StockDataFrame works as a wrapper for pandas.DataFrame. Initialize it
with wrap or StockDataFrame.retype.
import pandas as pd
from stockstats import wrap
# from CSV
df = wrap(pd.read_csv('stock.csv'))
# from yfinance (disable multi-level index for compatibility)
import yfinance as yf
df = wrap(yf.download('AAPL', multi_level_index=False))
Your data should contain these columns (case-insensitive):
close: the close price of the period
: the highest price of the interval
high
low: the lowest price of the interval
volume: the volume of stocks traded during the interval
date: timestamp of the record, optional (used as index by default)
You can specify the index column name in wrap or retype. Use unwrap
to convert back to a plain pandas.DataFrame.
Access indicators
Indicators are calculated on first access. Delete a column to force
re-evaluation.
# indicators with default windows
rsi = df['rsi'] # 14-period RSI (default)
rsi6 = df['rsi_6'] # 6-period RSI
# moving averages on any column
sma = df['close_20_sma'] # 20-period SMA of close
ema = df['high_10_ema'] # 10-period EMA of high
Multi-line indicators
Some indicators generate multiple columns at once.
# MACD generates three columns at once
df.get('macd')
print(df[['macd', 'macds', 'macdh']].tail())
# Bollinger Bands
df.get('boll')
print(df[['boll', 'boll_ub', 'boll_lb']].tail())
Signal detection
# cross-over detection
golden_cross = df['close_10_sma_xu_close_50_sma'] # 10 SMA crosses above 50 SMA
# comparison operators
overbought = df['rsi_ge_70'] # True when RSI >= 70
Initialize all indicators with shortcuts
Some indicators, such as KDJ, BOLL, MFI, have shortcuts. Use df.init_all()
to initialize all these indicators.
This operation generates lots of columns. Please use it with caution.
Tutorial
Column naming patterns
Use pattern <column>_<window>_<indicator> for full control:
high_5_sma - 5 periods simple moving average of the high price
close_10_ema - 10 periods exponential moving average of the close
high_-1_d - 1 period delta of the high price (minus means looking backward)
Use pattern <indicator>_<window> when only the window varies:
rsi_6 - 6 periods RSI
cci_10 - 10 periods CCI
atr_13 - 13 periods ATR
Some indicators have default windows. Check their documentation for details.
Configurable parameters
Some statistics have configurable parameters. They are class-level fields. Changes
are global and won't affect existing results. Remove existing columns so that they
will be re-evaluated the next time you access them.
We use the close price to calculate the MACD lines.
df['macd'] is the difference between two exponential moving averages.
df['macds'] is the signal line.
df['macdh'] is the histogram line.
The period of short, long EMA and signal line can be tuned with
set_dft_window('macd', (short, long, signal)). The default
windows are 12 and 26 and 9.
Note: In July 2017 the code for MACDH was changed to drop an extra 2x multiplier
on the final value to align with calculation methods used in tools like
cryptowatch, tradingview, etc.
The Price Rate of Change (ROC) is a momentum-based technical indicator
that measures the percentage change in price between the current price
and the price a certain number of periods ago.
Formula:
ROC = (PriceP - PricePn) / PricePn * 100
Where:
PriceP: the price of the current period
PricePn: the price of the n periods ago
You need a column name and a period to calculate ROC.
Examples:
df['close_10_roc']: the ROC of the close price in 10 periods
df['high_5_roc']: the ROC of the high price in 5 periods
The Chande Momentum Oscillator (CMO) is a technical momentum
indicator developed by Tushar Chande.
The formula calculates the difference between the sum of recent
gains and the sum of recent losses and then divides the result
by the sum of all price movements over the same period.
The AO indicator is a good indicator for measuring the market dynamics,
it reflects specific changes in the driving force of the market, which
helps to identify the strength of the trend, including the points of
its formation and reversal.
Awesome Oscillator Formula
MEDIAN PRICE = (HIGH+LOW)/2
AO = SMA(MEDIAN PRICE, 5)-SMA(MEDIAN PRICE, 34)
Examples:
df['ao'] returns the Awesome Oscillator with default windows (5, 34)
df['ao_3,10'] returns the Awesome Oscillator with a window of 3 and 10
In financial markets, the concept of inertia was given by Donald Dorsey
in the 1995 issue of Technical Analysis of Stocks and Commodities
through the Inertia Indicator. The Inertia Indicator is moment-based
and is an extension of Dorsey's Relative Volatility Index (RVI).
Formula:
inertia = n periods linear regression of RVGI
Examples:
df['inertia'] retrieves the inertia of 20 periods linear regression of 14 periods RVGI
df['inertia_10'] retrieves the inertia of 10 periods linear regression of 14 periods RVGI
The Energy Index (Intermediate Willingness Index)
uses the relationship between the highest price, the lowest price and
yesterday's middle price to reflect the market's willingness to buy
and sell.
It contains 4 lines:
df['cr'] - the CR line
df['cr-ma1'] - StockDataFrame.CR_MA[0] periods of the CR moving average,
the default window is 5
df['cr-ma2'] - StockDataFrame.CR_MA[1] periods of the CR moving average,
the default window is 10
df['cr-ma3'] - StockDataFrame.CR_MA[2] periods of the CR moving average,
the default window is 20
The SSL Channel (Securement Stop Loss Channel), created by Erwin Beckers, is a
trend-following indicator that calculates dynamic support and resistance bands
using the simple moving averages of High and Low prices. The channel lines flip
positions based on whether the closing price crosses above the SMA of High
(bullish) or below the SMA of Low (bearish).
It has a parameter for window size. The default window is 10. Change it with
set_dft_window('ssl', n).
Examples:
df['ssl'] retrieves the 10-period SSL Channel line (defaults to SSL Up)
df['ssl_up'] retrieves the 10-period SSL Up line
df['ssl_down'] retrieves the 10-period SSL Down line
df['ssl_up_5'] retrieves the 5-period SSL Up line
df['ssl_down_5'] retrieves the 5-period SSL Down line
The default window of boll is 20.
You can also supply your window with df['boll_10']. It will also
generate the boll_ub_10 and boll_lb_10 column.
The default period of the Bollinger Band can be changed with
set_dft_window('boll', n). The width of the bands can be tuned with
StockDataFrame.BOLL_STD_TIMES. The default value is 2.
TR - True Range of Trading
TR is a measure of the volatility of a High-Low-Close series. It is used for
calculating the ATR.
The Efficiency Ratio (ER) is calculated by
dividing the price change over a period by the
absolute sum of the price movements that occurred
to achieve that change.
The resulting ratio ranges between 0 and 1 with
higher values representing a more efficient or
trending market.
The default column is close.
The default window is 10.
Formula:
window_change = ABS(close - close[n])
last_change = ABS(close-close[1])
volatility = moving sum of last_change in n
KER = window_change / volatility
Examples:
df['ker'] retrieves the 10 periods KER of the close price
df['high_5_ker'] retrieves 5 periods KER of the high price
The mean absolute deviation of a dataset is the average
distance between each data point and the mean. It gives
us an idea about the variability in a dataset.
Formula:
Calculate the mean.
Calculate how far away each data point is from the
mean using positive distances. These are called
absolute deviations.
Add those deviations together.
Divide the sum by the number of data points.
Example:
df['close_10_mad']: the MAD of the close price in 10 periods
The Pretty Good Oscillator indicator by Mark Johnson measures the
distance of the current close from its N-day simple moving average,
expressed in terms of an average true range over a similar period.
Formula:
PGO = (Close - SMA) / (EMA of TR)
Example:
df['pgo'] retrieves the PGO with default window 14.
The Percentage Volume Oscillator (PVO) is a momentum oscillator for volume.
The PVO measures the difference between two volume-based moving averages as
a percentage of the larger moving average.
Formula:
Percentage Volume Oscillator (PVO):
((12-day EMA of Volume - 26-day EMA of Volume)/26-day EMA of Volume) x 100
Signal Line: 9-day EMA of PVO
PVO Histogram: PVO - Signal Line
Example:
df['pvo'] derives from the difference of 2 exponential moving average.
df['pvos'] is the signal line.
df['pvoh'] is the histogram line.
The period of short, long EMA and signal line can be tuned with
set_dft_window('pvo', (short, long, signal)). The default
windows are 12 and 26 and 9.
On-Balance Volume (OBV) is a momentum indicator that uses volume flow to predict
changes in stock price. Joseph Granville developed the metric in 1963.
Formula:
If Close > Prior Close: OBV = Prior OBV + Volume
If Close < Prior Close: OBV = Prior OBV - Volume
If Close == Prior Close: OBV = Prior OBV
OBV[0] = 0
Examples:
df['obv'] retrieves the On-Balance Volume
df['obv_10_sma'] retrieves the 10-period SMA of OBV
df['obv_20_ema'] retrieves the 20-period EMA of OBV
The Qualitative Quantitative Estimation (QQE) indicator works like a smoother
version of the popular Relative Strength Index (RSI) indicator. QQE expands
on RSI by adding two volatility based trailing stop lines. These trailing
stop lines are composed of a fast and a slow moving Average True Range (ATR).
These ATR lines are smoothed making this indicator less susceptible to short
term volatility.
The Relative Vigor Index (RVI) is a momentum indicator
used in technical analysis that measures the strength
of a trend by comparing a security's closing price to
its trading range while smoothing the results using a
simple moving average (SMA).
Formula:
NUMERATOR= (a+(2xb)+(2xc)+d) / 6
DENOMINATOR= (e+(2xf)+(2xg)+h) / 6
RVI= SMA-N of DENOMINATOR / SMA-N of NUMERATOR
Signal Line = (RVI+(2xi)+(2xj)+k) / 6
where:
a=Close-Open
b=Close-Open One Bar Prior to a
c=Close-Open One Bar Prior to b
d=Close-Open One Bar Prior to c
e=High-Low of Bar a
f=High-Low of Bar b
g=High-Low of Bar c
h=High-Low of Bar d
i=RVI Value One Bar Prior
j=RVI Value One Bar Prior to i
k=RVI Value One Bar Prior to j
N=Minutes/Hours/Days/Weeks/Months
Examples:
df['rvgi'] retrieves the RVGI line of window 14
df['rvgis'] retrieves the RVGI signal line of window 14
df['rvgi_5'] retrieves the RVGI line of window 5
df['rvgis_5'] retrieves the RVGI signal line of window 5
The Gaussian Fisher Transform Price Reversals indicator, dubbed
FTR for short, is a stat based price reversal detection indicator
inspired by and based on the work of the electrical engineer
now private trader John F. Ehlers.
For example, if a stock is priced at 3.570 USD per share at the close on
one day, and at 3.575 USD per share at the close the next day, then the
logarithmic return is: ln(3.575/3.570) = 0.0014, or 0.14%.
Use df['log-ret'] to access this column.
Cross Upwards and Cross Downwards
Use the pattern <A>_xu_<B> to check when A crosses up B.
Use the pattern <A>_xd_<B> to check when A crosses down B.
Use the pattern <A>_x_<B> to check when A crosses B.
Examples:
kdjk_x_kdjd returns a series that marks the cross of KDJK and KDJD
kdjk_xu_kdjd returns a series that marks where KDJK crosses up KDJD
kdjk_xd_kdjd returns a series that marks where KDJD crosses down KDJD
Comparisons
Use patterns <A>_le_<B>, <A>_ge_<B>, <A>_lt_<B>, <A>_gt_<B>,
<A>_eq_<B>, <A>_ne_<B> for comparing two columns.
Count of Non-Zero Value
Count non-zero values of a specific range. It requires a column and a window.
Examples:
Count how many typical prices are larger than close in the past 10 periods
Technical Analysis Indicators - Pandas TA Classic is an easy to use Python 3 Pandas Extension with a comprehensive collection of indicators and TA-Lib patterns.
An easy to use Python 3 Pandas Extension with 130+ Technical Analysis Indicators. Can be called from a Pandas DataFrame or standalone like TA-Lib. Correlation tested with TA-Lib.