rs_rating package

Submodules

rs_rating.ibd_fin module

IBD Financial Analysis Module

This module provides functions for financial data analysis and comparison, using methods inspired by those used by Investors Business Daily (IBD).

Key Features:

  • Calculation of relative strength for various financial metrics (e.g., EPS, Revenue) against benchmarks such as the S&P 500.

  • Creation of comparative DataFrames that rank stocks based on their financial metrics and performance.

  • Sorting and analysis of financial performance across multiple stocks using custom ranking methods.

Usage:

Import this module to access functions for analyzing and ranking financial data. For example:

from ibd_fin import financial_metric_ranking

# Example usage
ranking_df = financial_metric_ranking(stock_data)
rs_rating.ibd_fin.financial_metric_ranking(tickers)[source]
rs_rating.ibd_fin.metric_strength_vs_benchmark(quarterly_metric, annual_metric, quarterly_bench, annual_bench)[source]

Calculate the relative strength of a financial metric series versus a benchmark.

This function calculates the weighted YoY growth for both the financial metric and the benchmark, and then computes the relative strength by comparing the two.

Parameters:
  • quarterly_metric (pd.Series) – Quarterly financial metric series.

  • annual_metric (pd.Series) – Annual financial metric series.

  • quarterly_bench (pd.Series) – Quarterly benchmark series.

  • annual_bench (pd.Series) – Annual benchmark series.

Returns:

Series containing the relative strength values, calculated as the difference in weighted YoY growth between the metric and the benchmark, multiplied by 100.

Return type:

pd.Series

rs_rating.ibd_rs module

IBD RS (Relative Strength) Rating Module

This module provides tools for analyzing and ranking stocks based on their relative strength compared to a benchmark index, inspired by the Investor’s Business Daily (IBD) methodology.

Key Features:

  • Relative strength calculation

  • Stock and industry ranking generation

  • Rating-based filtering of rankings

Usage:

import ibd_res as ibd

# Generate rankings for a list of stocks
tickers = ['MSFT', 'NVDA', 'AAPL', 'GOOGL', 'AMZN', 'TSLA']
stock_rankings, industry_rankings = ibd.rankings(tickers)

# Calculate relative strength for a single stock
stock_rs = ibd.relative_strength(stock_closes, index_closes)

# Filter rankings based on a minimum rating
min_rating = 80
top_stocks = stock_rankings[stock_rankings["Rating"] >= min_rating]

See Also:

rs_rating.ibd_rs.rankings(tickers, ticker_ref='^GSPC', period='2y', interval='1d', rating_method='rank', rs_window='12mo')[source]

Generates stock and industry ranking tables based on Relative Strength (RS) compared to a reference index.

Parameters:
  • tickers (list) – List of stock tickers to analyze.

  • ticker_ref (str, optional) – The reference index ticker symbol. Default is ‘^GSPC’ (S&P 500).

  • period (str, optional) – Duration for fetching historical stock data. Default is ‘2y’ (two years).

  • interval (str, optional) – Time interval between data points. Can be ‘1d’ (daily), ‘1wk’ (weekly), or ‘1mo’ (monthly). Default is ‘1d’.

  • rating_method (str, optional) – Method for calculating stock ratings. Can be either ‘rank’ or ‘qcut’. Default is ‘rank’.

  • rs_window (str, optional) – Period for calculating RS. Either ‘3mo’ or ‘12mo’. Default is ‘12mo’.

Returns:

  1. Stock Rankings DataFrame:
    • ’Rank’: Stock rank based on RS

    • ’Ticker’: Stock ticker

    • ’Price’: Latest stock price

    • ’Sector’: Sector of the stock

    • ’Industry’: Industry of the stock

    • ’RS’: Current RS value

    • ’1 Month Ago’: RS value one month ago

    • ’3 Months Ago’: RS value three months ago

    • ’6 Months Ago’: RS value six months ago

    • ’Rating’: Current rating

    • ’Rating (1 Month Ago)’: Rating one month ago

    • ’Rating (3 Months Ago)’: Rating three months ago

    • ’Rating (6 Months Ago)’: Rating six months ago

  2. Industry Rankings DataFrame:
    • ’Rank’: Industry rank based on RS

    • ’Industry’: Industry name

    • ’Sector’: Sector name

    • ’RS’: Current RS value

    • ’1 Month Ago’: RS value one month ago

    • ’3 Months Ago’: RS value three months ago

    • ’6 Months Ago’: RS value six months ago

    • ’Tickers’: List of stock tickers in the industry

    • ’Rating’: Current rating

    • ’Rating (1 Month Ago)’: Rating one month ago

    • ’Rating (3 Months Ago)’: Rating three months ago

    • ’Rating (6 Months Ago)’: Rating six months ago

Return type:

tuple of pd.DataFrame

rs_rating.ibd_rs.relative_strength(closes, closes_ref, interval='1d')[source]

Calculate the relative strength of a stock compared to a reference index.

Relative Strength (RS) is a metric used to evaluate the performance of a stock relative to a benchmark index. A higher RS rating indicates that the stock has outperformed the index, while a lower RS rating suggests underperformance.

This function calculates the RS rating by comparing the quarter-weighted growth of the stock’s closing prices to the quarter-weighted growth of the reference index’s closing prices over the past year. The formula is as follows:

growth = (current - previous) / previous
gf = current/previous = growth + 1
relative_rate = gf_stock / gf_index
relative_strength = relative_rate * 100

Here gf means “growth factor”, i.e., “price ratio”

The quarter-weighted growth is calculated using the weighted_growth function.

Parameters:
  • closes (pd.Series) – Closing prices of the stock.

  • closes_ref (pd.Series) – Closing prices of the reference index.

  • interval (str, optional) – The frequency of the data points. Must be one of ‘1d’ for daily data, ‘1wk’ for weekly data, or ‘1mo’ for monthly data. Defaults to ‘1d’.

Returns:

Relative strength values for the stock.

Return type:

pd.Series

Example

>>> stock_closes = pd.Series([100, 102, 105, 103, 107])
>>> index_closes = pd.Series([1000, 1010, 1015, 1005, 1020])
>>> rs = relative_strength(stock_closes, index_closes)
rs_rating.ibd_rs.relative_strength_3m(closes, closes_ref, interval='1d')[source]

Calculate the 3-Month Relative Strength of a stock compared to a reference index, based on price performance (growths).

The 3-Month Relative Strength Rating (RS Rating) measures the stock’s price performance against a benchmark index over a recent three-month period. This rating is designed to help investors quickly gauge the strength of a stock’s performance relative to the market.

Parameters:
  • closes (pd.Series) – Closing prices of the stock.

  • closes_ref (pd.Series) – Closing prices of the reference index.

  • interval (str, optional) – The frequency of the data points. Must be one of ‘1d’ for daily data, ‘1wk’ for weekly data, or ‘1mo’ for monthly data. Defaults to ‘1d’.

Returns:

3-Month relative strength values for the stock, rounded to two decimal places. The values represent the stock’s performance relative to the benchmark index, with 100 indicating parity.

Return type:

pd.Series

rs_rating.rsm module

Mansfield Relative Strength (RSM) Module

This module provides functions for calculating and ranking stocks based on Mansfield Relative Strength (RSM) and related metrics. It includes methods to compute Dorsey Relative Strength (RSD), Mansfield Relative Strength (RSM) using both Simple Moving Average (SMA) and Exponential Moving Average (EMA), as well as functionality to rank stocks against a benchmark index.

Examples:

To calculate RSM for a list of stock tickers and rank them:

>>> tickers = ['AAPL', 'MSFT', 'GOOGL']
>>> rank = ranking(tickers, period='2y', interval='1wk', window=52)
>>> print(rank.head())

To compute Mansfield Relative Strength using SMA for specific close prices:

>>> closes = pd.Series([...])  # Example closing prices
>>> closes_index = pd.Series([...])  # Example index closing prices
>>> rsm = mansfield_relative_strength(closes, closes_index, window=52)
>>> print(rsm)

See Also:

rs_rating.rsm.dorsey_relative_strength(closes, closes_index)[source]

Calculate Dorsey Relative Strength (RSD) for given close prices and index close prices.

Parameters:
  • closes (pandas.Series) – Series of closing prices for the stock.

  • closes_index (pandas.Series) – Series of closing prices for the benchmark index.

Returns:

Series containing the calculated Dorsey Relative Strength (RSD) values.

Return type:

pandas.Series

rs_rating.rsm.mansfield_relative_strength(closes, closes_index, window, ma='SMA')[source]

Calculate Mansfield Relative Strength (RSM) for given close prices, index close prices, and window size using a given moving average method (‘SMA’ or ‘EMA’).

Parameters:
  • closes (pandas.Series) – Series of closing prices for the stock.

  • closes_index (pandas.Series) – Series of closing prices for the benchmark index.

  • window (int) – Window size for calculating the Simple Moving Average of the Dorsey Relative Strength.

  • ma (str, optional) – Moving average type (‘SMA’, ‘EMA’). Default to ‘SMA’.

Returns:

Series containing the calculated Mansfield Relative Strength (RSM) values with given moving average method.

Return type:

pandas.Series

Examples

>>> stock_closes = pd.Series([100, 105, 110],
...     index=pd.date_range(start='2024-01-01', periods=3, freq='D'))
>>> index_closes = pd.Series([2000, 2050, 2100],
...     index=pd.date_range(start='2024-01-01', periods=3, freq='D'))
>>> mansfield_relative_strength(stock_closes, index_closes, window=2)
2024-01-01    5.000000
2024-01-02    5.097847
2024-01-03    5.238095
dtype: float64
>>> mansfield_relative_strength_with_ema(stock_closes, index_closes,
...     window=2, ma='EMA')
2024-01-01    5.000000
2024-01-02    5.097847
2024-01-03    5.238095
dtype: float64
rs_rating.rsm.ranking(tickers, ticker_ref='^GSPC', period='2y', interval='1wk', ma='SMA')[source]

Rank stocks based on their Mansfield Relative Strength (RSM) against an index benchmark.

Parameters:
  • tickers (list of str) – List of stock tickers to rank.

  • ticker_ref (str, optional) – Ticker symbol of the benchmark. Default to ‘^GSPC’ (S&P 500)

  • period (str, optional) – Period for historical data (‘6mo’, ‘1y’, ‘2y’, ‘5y’, ‘ytd’, ‘max’). Default to ‘2y’ (two years).

  • interval (str, optional) – Interval for historical data (‘1d’, ‘1wk’). Default to ‘1wk’ (one week).

  • ma (str, optional) – Moving average type (‘SMA’, ‘EMA’). Default to ‘SMA’.

Returns:

DataFrame containing the ranked stocks.

Return type:

pandas.DataFrame

rs_rating.stock_indices module

Functions for retrieving and managing stock market indices data.

This module provides functions for retrieving ticker symbols for various stock market indices and identifying index names from their ticker symbols. It supports querying index tickers from specified sources and obtaining the name of an index based on its symbol.

Main Functions:

  • get_tickers(source): Retrieve ticker symbols for a specified stock market index source.

  • get_name(index_symbol): Retrieve the name of an index from its ticker symbol.

  • ticker_from_name(name): Get the ticker symbol of an index from its long name.

Usage Examples:

from stock_indices import get_tickers, get_name

# Get tickers for the S&P 500 index
spx_tickers = get_tickers('SPX')

# Get tickers for the Philadelphia Semiconductor
sox_tickers = get_tickers('SOX')

# Get tickers for the SPX and the SOX
tickers = get_tickers('SPX+SOX')

# Get the name of an index from its symbol
index_name = get_name('^NDX')
rs_rating.stock_indices.get_name(index_symbol)[source]

Return the name of the index based on the provided symbol.

Parameters:

index_symbol (str) –

The ticker symbol or common abbreviation for the index.

  • Yahoo Finance ticker symbols (e.g., ‘^GSPC’ for S&P 500, ‘^NDX’ for NASDAQ-100).

  • Common abbreviations (e.g., ‘SPX’ for S&P 500, ‘NDX’ for NASDAQ-100).

Possible values include:

  • ’^GSPC’, ‘SPX’: S&P 500

  • ’^DJI’, ‘DJIA’: Dow Jones Industrial Average

  • ’^NDX’, ‘NDX’: NASDAQ 100

  • ’^IXIC’, ‘COMP’: NASDAQ Composite

  • ’^RUI’, ‘RUI’, ‘R1000’: Russell 1000

  • ’^RUT’, ‘RUT’, ‘R2000’: Russell 2000

  • ’^SOX’, ‘SOX’: PHLX Semiconductor

  • ’^NYA’, ‘NYA’: NYSE Composite

  • ’^MID’, ‘MID’: S&P MidCap 400

  • ’^TWII’, ‘TWII’: Taiwan Weighted Index

  • ’^W5000’, ‘W5000’: Wilshire 5000 Total Market Index

  • ’USLS’: U.S. Listed Stocks

  • ’^STOXX50E’: Euro Stoxx 50

  • ’^FTSE’: FTSE 100

  • ’^GDAXI’: DAX

  • ’^FCHI’: CAC 40

  • ’^GSPTSE’: S&P/TSX Composite

  • ’^N225’: Nikkei 225

  • ’^HSI’: Hang Seng Index

Returns:

The name of the index if found. If not found, returns the original index_symbol.

Return type:

str

Examples

>>> get_name('SPX')
'S&P 500'
>>> get_name('^GSPC')
'S&P 500'
>>> get_name('^DJI')
'Dow Jones Industrial Average'
>>> get_name('^IXIC')
'NASDAQ Composite'
>>> get_name('^NDX')
'NASDAQ 100'
>>> get_name('^RUI')
'Russell 1000'
>>> get_name('^RUT')
'Russell 2000'
>>> get_name('^SOX')
'PHLX Semiconductor'
>>> get_name('^W5000')
'Wilshire 5000 Total Market Index'
>>> get_name('^TWII')
'Taiwan Weighted Index'
>>> get_name('^HSI')
'Hang Seng Index'
>>> get_name('SOXX')
'iShares Semiconductor ETF'
>>> get_name('AAPL')
'AAPL'
rs_rating.stock_indices.get_tickers(source)[source]

Retrieve a list of tickers for the specified index or combined indices.

Parameters:

source (str) –

The ticker symbol or common abbreviation for the index or indices.

  • Yahoo Finance ticker symbols (e.g., ‘^GSPC’ for S&P 500, ‘^NDX’ for NASDAQ-100).

  • Common abbreviations (e.g., ‘SPX’ for S&P 500, ‘NDX’ for NASDAQ-100).

  • Multiple indices can be combined using ‘+’ (e.g., ‘^GSPC+^NDX’).

Possible values include:

  • ’^GSPC’, ‘SPX’: S&P 500

  • ’^DJI’, ‘DJIA’: Dow Jones Industrial Average

  • ’^NDX’, ‘NDX’: NASDAQ-100

  • ’^RUI’, ‘RUI’: Russell 1000

  • ’^RUT’, ‘RUT’: Russell 2000

  • ’^SOX’, ‘SOX’: PHLX Semiconductor

  • ’^W5000’, ‘W5000’: Wilshire 5000 Total Market Index

  • ’U.S. listed’: U.S. listed stocks

Returns:

A list of tickers for the specified source.

Return type:

list

Raises:

KeyError – If the provided source is not recognized or does not correspond to a known index.

Examples

>>> len(get_tickers('SPX')) >= 500
True
>>> len(get_tickers('^GSPC')) >= 500
True
>>> len(get_tickers('^NDX')) >= 100
True
>>> len(get_tickers('^RUI')) >= 1000
True
>>> len(get_tickers('^RUT')) > 1900
True
>>> len(get_tickers('^W5000')) > 5000
True
>>> len(get_tickers('U.S.Listed')) > 5000
True
>>> len(get_tickers('USLS')) > 5000
True
>>> 500 < len(get_tickers('^GSPC+^NDX')) < (500+100)
True
>>> 500 < len(get_tickers('SPX+SOX+NDX')) < (500+30+100)
True
>>> get_tickers('^UNKNOWN')
Traceback (most recent call last):
    ...
KeyError: "Index symbol '^UNKNOWN' not found."
rs_rating.stock_indices.ticker_from_name(name)[source]

Get ticker symbol of an index from its long name.

Parameters:

name (str) – The long name of a ticker.

Returns:

The ticker symbol.

Return type:

str

Examples

>>> ticker_from_name('S&P 500')
'^GSPC'
>>> ticker_from_name('Dow Jones Industrial Average')
'^DJI'
>>> ticker_from_name('NASDAQ 100')
'^NDX'
>>> ticker_from_name('Russell 1000')
'^RUI'
>>> ticker_from_name('Wilshire 5000 Total Market Index')
'^W5000'
>>> ticker_from_name('Taiwan Weighted Index')
'^TWII'

rs_rating.yf_utils module

Utility functions for working with Yahoo Finance data.

This module contains various utility functions for retrieving and processing stock data using the Yahoo Finance API via the yfinance library.

rs_rating.yf_utils.calc_weighted_metric(financials, tickers_info, metric, weight_field, threshold=0.7)[source]

Calculate the weighted average of a specified financial metric for all stock symbols in the provided dataset using NumPy. The weights can be based on any specified field (e.g., market capitalization or shares outstanding).

Parameters:
  • financials (dict) – A dictionary where each key is a stock ticker and the value is a DataFrame of the ticker’s quarterly financials.

  • tickers_info (dict) – A dictionary where each key is a stock ticker and the value is a dictionary of the ticker’s info, including market cap, shares outstanding, etc.

  • metric (str) – The name of the financial metric to calculate (e.g., ‘Basic EPS’, ‘Total Revenue’, ‘Operating Revenue’).

  • weight_field (str) – The field name to use for weighting (e.g., ‘marketCap’, ‘sharesOutstanding’).

  • threshold (float, optional) – The minimum percentage of the total possible weight required for a valid weighted average (default is 0.7, meaning 70%).

Returns:

The weighted average of the specified metric over the specified number of quarters (or years).

Return type:

numpy.ndarray

Examples

>>> tickers = ['AAPL', 'MSFT', 'GOOG']
>>> financials = download_financials(tickers, ['Basic EPS'])
...                             
[...**********************100%**********************]
3 of 3 financials downloaded
>>> tickers_info = {
...     'AAPL': {'marketCap': 3357369434112,
...              'sharesOutstanding': 15204100096},
...     'MSFT': {'marketCap': 2985852141568,
...              'sharesOutstanding': 7433039872},
...     'GOOG': {'marketCap': 1864140193792,
...              'sharesOutstanding': 5584999936},
... }
>>> weighted_eps = calc_weighted_metric(financials, tickers_info,
...                                     'Basic EPS', 'sharesOutstanding')
>>> type(weighted_eps)
<class 'numpy.ndarray'>
>>> weighted_eps.shape
(6,)
rs_rating.yf_utils.download_financials(symbols, fields=None, frequency='quarterly', max_workers=8, progress=True)[source]

Downloads the financials (quarterly or annual) of multiple stocks and returns the specified fields.

Parameters:
  • symbols (list of str) – List of ticker symbols, e.g., [‘AAPL’, ‘MSFT’, ‘TSLA’].

  • fields (list, optional) – List of fields to return. If None, all fields will be returned. Defaults to None.

  • frequency (str, optional) – The frequency of the financial data to fetch. Options are ‘quarterly’ or ‘annual’. Defaults to ‘quarterly’.

  • max_workers (int, optional) – Maximum number of threads to use for parallel requests. Defaults to 8.

  • progress (bool, optional) – Whether to show a progress bar. Defaults to True.

Returns:

A dictionary where each key is a stock ticker, and the value is a DataFrame of the specified fields.

Return type:

dict

Examples

>>> symbols = ['AAPL', 'MSFT', 'TSLA', 'GOOG', 'AMZN']
>>> financials = download_financials(symbols, frequency='annual')
...                             
[...*******************100%**********************]
  5 of 5 financials downloaded
>>> epses = financials['AAPL']['Basic EPS']
>>> type(epses)
<class 'pandas.core.series.Series'>
>>> len(epses) >= 4
True
rs_rating.yf_utils.download_tickers_info(symbols, fields=None, max_workers=8, progress=True)[source]

Downloads the basic information of multiple stocks and returns the specified fields.

Parameters:
  • symbols (list of str) – List of ticker symbols, e.g., [‘AAPL’, ‘MSFT’, ‘TSLA’]

  • fields (list, optional) – List of fields to return. If None, all fields will be returned.

  • max_workers (int) – Maximum number of threads to use for parallel requests

  • progress (bool) – Whether to show a progress bar

Returns:

A dictionary where each key is a stock ticker, and the value is a dictionary of the specified fields.

Return type:

dict

Examples

>>> symbols = ['AAPL', 'MSFT', 'TSLA', 'GOOG', 'AMZN']
>>> info = download_tickers_info(symbols) 
...                                       
[...*******************100%**********************]  5 of 5 info downloaded
>>> info['AAPL']['longName']
'Apple Inc.'
rs_rating.yf_utils.fetch_financials(symbol, fields=None, frequency='quarterly')[source]

Fetch the financials for a single ticker symbol using yfinance.

Parameters:
  • symbol (str) – Ticker symbol as a string

  • fields (list, optional) – List of fields to return. If None, all fields will be returned. Defaults to None.

  • frequency (str) – The frequency of the financial data (‘quarterly’ or ‘annual’).

Returns:

DataFrame containing the ticker’s financials

Return type:

DataFrame

Module contents

Initialize widgetify package.