vistock package
Subpackages
- vistock.mpl package
- vistock.plotly package
- Submodules
- vistock.plotly.bull_draw module
- vistock.plotly.fig_utils module
- vistock.plotly.financials module
- vistock.plotly.ibd_rs module
- vistock.plotly.ibd_rs_cmp module
- vistock.plotly.mansfield module
- vistock.plotly.prf2s module
- vistock.plotly.prf4s module
- vistock.plotly.pv1s module
- vistock.plotly.pv2s module
- Module contents
Submodules
vistock.bull_draw_utils module
Utility Functons to calculate bull-run and drawdown.
- vistock.bull_draw_utils.calculate_bull_run(df)[source]
Calculate the bull-run for each ‘Close’ price in the dataframe.
- Parameters:
df (pandas.DataFrame) – DataFrame containing stock data with a ‘Close’ column.
- Returns:
Series representing the bull-run values.
- Return type:
pandas.Series
- vistock.bull_draw_utils.calculate_drawdown(df)[source]
Calculate the drawdown for each price in the dataframe.
- Parameters:
df (pandas.DataFrame) – DataFrame containing stock data with a ‘High’, ‘Close’ columns.
- Returns:
Series representing the drawdown values.
- Return type:
pandas.Series
- vistock.bull_draw_utils.calculate_drawdown_v2(df)[source]
Calculate the drawdown for each price in the dataframe.
- Parameters:
df (pandas.DataFrame) – DataFrame containing stock data with a ‘Close’ column.
- Returns:
Series representing the drawdown values.
- Return type:
pandas.Series
- vistock.bull_draw_utils.calculate_rolling_drawdown(data, window=60)[source]
Calculate the rolling drawdown for each price in the dataframe.
- Parameters:
df (pandas.DataFrame) – DataFrame containing stock data with a ‘High’, ‘Close’ columns.
window (int) – window size to rolling.
- Returns:
Series representing the rolling drawdown values.
- Return type:
pandas.Series
vistock.file_utils module
Common utility for file operations.
- vistock.file_utils.gen_fn_info(symbol, interval, date, module)[source]
Generate the information string for the output filename of a stock.
- Parameters:
symbol (str) – the stock symbol.
interval (str) – the interval of an OHLC item.
date (str) – last date of the stock data.
module (str) – filename of the module.
- Returns:
a filename concatenated above information.
- Return type:
str
Examples
>>> gen_fn_info('TSLA', '1d', '2023-02-17 00:00', 'plotly/pbv2s.py') 'TSLA_1d_20230217_0000_pbv2s'
- vistock.file_utils.make_dir(directory_path)[source]
Creates a directory at the given path and returns the original path string if it is valid. Returns an empty string if the path is invalid.
- Parameters:
directory_path (str) – A string representing the directory path.
- Returns:
A string representing the original directory path if it is valid, otherwise an empty string.
- Return type:
str
Examples
>>> make_dir("./out/") 'out' >>> make_dir(":") # ':' is not a valid character for directory names. ''
vistock.ibd 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
import vistock.stock_indices as si
code = 'SOX'
tickers = si.get_tickers(code)
stock_df = rankings(tickers,
rs_window=rs_window, rating_method=rating_method)
See Also:
- vistock.ibd.rankings(tickers, ticker_ref='^GSPC', period='2y', interval='1d', rs_window='12mo', rating_method='rank')[source]
Analyze stocks and generate a ranking table for individual stocks and industries based on Relative Strength (RS).
This function calculates Relative Strength (RS) for the given stocks compared to a reference index, then ranks both individual stocks and industries according to their RS values. It provides historical RS data and rating rankings.
- Parameters:
tickers (list of str) – A list of stock tickers to analyze.
ticker_ref (str, optional) – The ticker symbol for the reference index. Defaults to ‘^GSPC’ (S&P 500).
period (str, optional) – The period for which to fetch historical data. Defaults to ‘2y’ (two years).
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’.
rs_window (str, optional) – The time window (‘3mo’ or ‘12mo’) for calculating Relative Strength (RS). Defaults to ‘12mo’.
rating_method (str, optional) – The method to calculate ratings. Either ‘rank’ (based on relative ranking) or ‘qcut’ (based on quantiles). Defaults to ‘rank’.
- Returns:
A DataFrame containing stock rankings and RS ratings.
- Return type:
pd.DataFrame
- vistock.ibd.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)
- vistock.ibd.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
vistock.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:
- vistock.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
- vistock.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
- vistock.rsm.rankings(tickers, ticker_ref='^GSPC', period='2y', interval='1wk', ma='SMA', rating_method='rank')[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 index. Defaults to ‘^GSPC’ (S&P 500).
period (str, optional) – Period for retrieving historical data (‘6mo’, ‘1y’, ‘2y’, ‘5y’, ‘ytd’, ‘max’). Defaults to ‘2y’ (two years).
interval (str, optional) – Interval for historical data (‘1d’, ‘1wk’). Defaults to ‘1wk’ (one week).
ma (str, optional) – Moving average type (‘SMA’ for Simple Moving Average or ‘EMA’ for Exponential Moving Average). Defaults to ‘SMA’.
rating_method (str, optional) – Method for calculating stock ratings. Either ‘rank’ (based on relative ranking) or ‘qcut’ (based on quantiles). Defaults to ‘rank’.
- Returns:
A DataFrame containing ranked stock data with relative strength and other metrics.
- Return type:
pandas.DataFrame
vistock.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')
- vistock.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'
- vistock.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."
- vistock.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'
vistock.ta module
Technical Analysis
- vistock.ta.exponential_moving_average(values, window, min_periods=1, adjust=False)[source]
Calculate Exponential Moving Average (EMA) for given values and window size.
- Parameters:
values (pandas.Series) – Series of values for which to calculate the EMA.
window (int) – Number of periods over which to calculate the EMA.
adjust (bool, optional) – Whether to adjust the EMA calculation (default is False).
- Returns:
Series containing the calculated Exponential Moving Average (EMA) values.
- Return type:
pandas.Series
Examples
>>> import pandas as pd >>> values = pd.Series([100, 105, 110, 115, 120], ... index=pd.date_range(start='2024-01-01', periods=5, freq='D')) >>> exponential_moving_average(values, window=3) 2024-01-01 100.0000 2024-01-02 102.5000 2024-01-03 106.2500 2024-01-04 110.6250 2024-01-05 115.3125 Freq: D, dtype: float64
- vistock.ta.rsi(data, periods=14)[source]
Calculate the Relative Strength Index (RSI) for a given dataset.
RSI is a momentum oscillator that measures the speed and change of price movements. It oscillates between 0 and 100 and is typically used to identify overbought or oversold conditions in a market.
- Parameters:
data (pandas.Series) – A pandas Series containing the price data (typically closing prices) for which the RSI is to be calculated.
periods (int, optional, default: 14) – The number of periods to use for the RSI calculation. A typical value is 14.
- Returns:
A pandas Series containing the RSI values for the given data.
- Return type:
pandas.Series
Examples
>>> import pandas as pd >>> import yfinance as yf >>> df = yf.download('AAPL', start='2023-01-01', end='2024-01-01') >>> df['RSI'] = rsi(df['Close'], periods=14) >>> df['RSI'].tail() Date 2023-12-22 59.246142 2023-12-26 49.031934 2023-12-27 52.291513 2023-12-28 47.920430 2023-12-29 40.185177 Name: RSI, dtype: float64
- vistock.ta.simple_moving_average(values, window, min_periods=1)[source]
Calculate Simple Moving Average (SMA) for given values and window size.
- Parameters:
values (pandas.Series) – Series of values for which to calculate the SMA.
window (int) – Number of periods over which to calculate the SMA.
- Returns:
Series containing the calculated Simple Moving Average (SMA) values.
- Return type:
pandas.Series
Examples
>>> import pandas as pd >>> values = pd.Series([100, 105, 110, 115, 120], ... index=pd.date_range(start='2024-01-01', periods=5, freq='D')) >>> simple_moving_average(values, window=3) 2024-01-01 NaN 2024-01-02 NaN 2024-01-03 105.0 2024-01-04 110.0 2024-01-05 115.0 Freq: D, dtype: float64
vistock.tw module
tw.py - Module for handling Taiwan stock market data.
This module provides functionalities for interacting with various Taiwan Stock markets,including the Taiwan Stock Exchange (TWSE), Taipei Exchange (TPEx), and Emerging Stock Board (ESB). It supports converting stock symbols, fetching stock data, and retrieving ticker lists from these markets.
Main Features:
Convert Taiwan stock symbols to yfinance-compatible format.
Fetch historical and real-time stock data from TWSE, TPEx, and ESB.
Retrieve lists of tickers for TWSE, TPEx, and ESB.
Find stocks similar to a given name or code.
Usage Examples:
import tw
# Get the stock name from its code
name = tw.stock_name('2330.TW')
# Convert a stock symbol to yfinance format
yf_symbol = tw.as_yfinance('台積電')
# Find stocks similar to a given name or code
similar = tw.similar_stocks('印度')
# Get a list of tickers for the TWSE
twse_tickers = tw.get_twse_tickers()
# Get a list of tickers for a specified market
tickers = tw.get_tickers('TWSE')
- vistock.tw.as_yfinance(symbol)[source]
Convert a given stock symbol into yfinance compatible stock symbol.
This function handles different types of input:
If the input is already in yfinance format (ends with .TW or .TWO), it’s returned as is.
If the input is in Chinese, it’s treated as a stock name and converted to a code.
If the input starts with a digit, it’s treated as a Taiwan stock code and the appropriate suffix (.TW or .TWO) is added.
For other inputs (e.g., non-Taiwan stocks), the symbol is returned unchanged.
- Parameters:
symbol (str) – the input symbol.
- Returns:
the yfinance compatible stock symbol.
- Return type:
str
Examples
>>> as_yfinance('TSLA') 'TSLA' >>> as_yfinance('台積電') '2330.TW' >>> as_yfinance('2330') '2330.TW' >>> as_yfinance('元太') '8069.TWO' >>> as_yfinance('星宇航空') '2646.TWO'
- vistock.tw.get_esb_tickers()[source]
Fetch the list of tickers for companies listed on the Emerging Stock Board (ESB) of the Taipei Exchange.
Retrieves ticker symbols from the TPEx Open API.
- Returns:
A list of ESB ticker symbols.
- Return type:
list
Examples
>>> tickers = get_esb_tickers() >>> '2646.TWO' in tickers True >>> '6987.TWO' in tickers True
- vistock.tw.get_tickers(source)[source]
Retrieve a list of tickers for the specified exchange(s) in Taiwan, removing duplicates.
- Parameters:
source (str) –
The common abbreviation(s) for the exchange or market sector.
Possible values include:
’TWSE’: Taiwan Stock Exchange
’TPEX’: Taipei Exchange
’ESB’: Emerging Stock Board
Can also be combined with ‘+’ (e.g., ‘TWSE+TPEX’, ‘TWSE+TPEX+ESB’).
- Returns:
- A list of unique tickers for the given exchange(s) or market
sector(s).
- Return type:
list
- Raises:
KeyError – If any of the provided exchange abbreviations are not recognized.
Examples
>>> len(get_tickers('TWSE+TPEX')) >= 2000 True >>> len(get_tickers('ESB')) >= 300 True >>> len(get_tickers('TWSE+TPEX+ESB')) >= (1200 + 800 + 300) True >>> get_tickers('^UNKNOWN') Traceback (most recent call last): ... KeyError: "Exchange abbreviation '^UNKNOWN' not found."
- vistock.tw.get_tpex_tickers()[source]
Fetch the list of tickers for companies listed on the Taipei Exchange (TPEx).
Retrieves ticker symbols from the TPEx Open API.
- Returns:
A list of TPEx ticker symbols.
- Return type:
list
Examples
>>> tickers = get_tpex_tickers() >>> '8069.TWO' in tickers True
- vistock.tw.get_twse_tickers()[source]
Fetch the list of tickers for companies listed on the Taiwan Stock Exchange (TWSE).
Retrieves ticker symbols from the TWSE Open API.
- Returns:
A list of TWSE ticker symbols.
- Return type:
list
Examples
>>> tickers = get_twse_tickers() >>> print(tickers[:5]) ['0050.TW', '0051.TW', '0052.TW', '0053.TW', '0055.TW']
- vistock.tw.is_taiwan_stock(ticker)[source]
Check if the given ticker represents a Taiwan stock.
- Parameters:
ticker (str) – Stock ticker symbol.
- Returns:
True if it’s a Taiwan stock, False otherwise.
- Return type:
bool
Examples
>>> is_taiwan_stock('2330.TW') True >>> is_taiwan_stock('NVDA') False
- vistock.tw.similar_stocks(symbol)[source]
Get similar stock of a given stock.
- Parameters:
symbol (str) – a stock name or a stock code.
- Returns:
a list of stock name-code pairs.
- Return type:
[(str, str)]
Examples
>>> similar_stocks('印度') [('富邦印度', '00652'), ('富邦印度正2', '00653L'), ('富邦印度反1', '00654R')] >>> similar_stocks('永豐美國') [('永豐美國500大', '00858'), ('永豐美國科技', '00886')]
- vistock.tw.stock_name(code)[source]
Get stock name from its code.
- Parameters:
code (str) – a Taiwan stock code.
- Returns:
the Taiwan stock name.
- Return type:
str
Examples
>>> stock_name('2330.TW') '台積電' >>> stock_name('8069.TWO') '元太' >>> stock_name('2646.TWO') '星宇航空' >>> stock_name('2330') '台積電' >>> stock_name('8069') '元太' >>> stock_name('2646') '星宇航空'
vistock.utils module
Utility Functions for vistock package.
- class vistock.utils.MarketColorStyle(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
Enum
- AUTO = 'auto'
- EASTERN = 'eastern'
- WESTERN = 'western'
- vistock.utils.decide_market_color_style(ticker='TSLA', style=MarketColorStyle.AUTO)[source]
Determine the market color style based on the given ticker and specified style.
- Parameters:
ticker (str) – The stock ticker symbol. Default is ‘TSLA’.
style (MarketColorStyle) – The desired market color style. Default is MarketColorStyle.AUTO.
- Returns:
The determined market color style (EASTERN, WESTERN, or based on the ticker if AUTO is chosen).
- Return type:
Examples
>>> decide_market_color_style('TSLA') <MarketColorStyle.WESTERN: 'western'> >>> decide_market_color_style('2330.TW') <MarketColorStyle.EASTERN: 'eastern'> >>> decide_market_color_style('8069.TWO') <MarketColorStyle.EASTERN: 'eastern'>
vistock.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.
- vistock.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 (7,)
- vistock.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
- vistock.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.'
- vistock.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 vistock package.