Supply a wrapper ``StockDataFrame`` based on the ``pandas.DataFrame`` with inline stock statistics/indicators support.
Supply a wrapper ``StockDataFrame`` based on the ``pandas.DataFrame`` with inline stock statistics/indicators support.
Supply a wrapper StockDataFrame for pandas.DataFrame with inline stock
statistics/indicators support.
Supported statistics/indicators are:
Moving Averages: SMA, EMA, SMMA, TEMA, LRMA, KAMA, VWMA, DMA
Momentum: RSI, StochRSI, MACD, PPO, KDJ, ROC, CMO, KST, Coppock, AO, BOP, CTI, Inertia, PSL
Trend: Supertrend, Aroon, Ichimoku, CR, DMI (+DI/-DI/ADX/ADXR), TRIX, WT
Volatility: Bollinger Bands, ATR, TR, CCI, WR, CHOP, KER, Z-Score, MAD, PGO
Volume: VR, MFI, PVO, VWMA
Oscillators: QQE, RVGI, ERI, FTR
Utilities: delta, shift, log return, cross/cross-up/cross-down, comparisons (le/ge/lt/gt/eq/ne), count, max/min in range, permutation
pip install stockstats
Requires Python 3.9+. CI tests against Python 3.10, 3.11, 3.12, and 3.13.
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 periodhigh: the highest price of the intervallow: the lowest price of the intervalvolume: the volume of stocks traded during the intervaldate: 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.
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
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())
# 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
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.
Use pattern <column>_<window>_<indicator> for full control:
high_5_sma - 5 periods simple moving average of the high priceclose_10_ema - 10 periods exponential moving average of the closehigh_-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 RSIcci_10 - 10 periods CCIatr_13 - 13 periods ATRSome indicators have default windows. Check their documentation for details.
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.
close_20_sma
-
Simple Moving Average
EMA
close_20_ema
-
Exponential Moving Average
SMMA
close_7_smma
-
Smoothed Moving Average
TEMA
tema
5
Triple Exponential Moving Average
LRMA
close_10_lrma
-
Linear Regression Moving Average
KAMA
close_2_kama
10, 5, 34
Kaufman's Adaptive Moving Average
VWMA
vwma
14
Volume Weighted Moving Average
DMA
dma
10, 50
Difference of Moving Average
RSI
rsi
14
Relative Strength Index
StochRSI
stochrsi
14
Stochastic RSI
MACD
macd
12, 26, 9
Moving Average Convergence Divergence
PPO
ppo
12, 26, 9
Percentage Price Oscillator
KDJ
kdjk
9
Stochastic Oscillator
ROC
close_10_roc
-
Rate of Change
CMO
cmo
14
Chande Momentum Oscillator
KST
kst
-
Know Sure Thing
Coppock
coppock
10, 11, 14
Coppock Curve
AO
ao
5, 34
Awesome Oscillator
BOP
bop
-
Balance of Power
CTI
cti
12
Correlation Trend Indicator
Inertia
inertia
20, 14
Inertia Indicator
PSL
psl
12
Psychological Line
Supertrend
supertrend
14
Supertrend indicator
Aroon
aroon
25
Aroon Oscillator
Ichimoku
ichimoku
9, 26, 52
Ichimoku Cloud
CR
cr
26
Energy Index
DMI
pdi, ndi, adx
14
Directional Movement Index
TRIX
trix
12
Triple Exponential Average
WT
wt1, wt2
10, 21
Wave Trend
Bollinger
boll
20
Bollinger Bands
ATR
atr
14
Average True Range
TR
tr
-
True Range
CCI
cci
14
Commodity Channel Index
WR
wr
14
Williams %R
CHOP
chop
14
Choppiness Index
KER
ker
10
Kaufman's Efficiency Ratio
Z-Score
close_75_z
-
Z-Score
MAD
close_10_mad
-
Mean Absolute Deviation
PGO
pgo
14
Pretty Good Oscillator
VR
vr
26
Volume Variation Index
MFI
mfi
14
Money Flow Index
PVO
pvo
12, 26, 9
Percentage Volume Oscillator
QQE
qqe
14, 5
Quantitative Qualitative Estimation
RVGI
rvgi
14
Relative Vigor Index
ERI
eribull, eribear
13
Elder-Ray Index
FTR
ftr
9
Gaussian Fisher Transform
Follow the pattern <columnName>_<window>_sma to retrieve a simple moving average.
Follow the pattern <columnName>_<window>_ema to retrieve an exponential moving average.
It requires column and window.
For example, use df['close_7_smma'] to retrieve the 7 periods smoothed moving
average of the close price.
TEMA is another implementation for the triple exponential moving average.
TEMA = (3 x EMA) - (3 x EMA of EMA) + (EMA of EMA of EMA)
It takes two parameters, column and window. By default, the column is close,
the window is 5.
Use set_dft_window('tema', n) to change the default window.
Examples:
df['tema'] stands for 5 periods TEMA for the close price.df['middle_10_tema'] stands for the 10 periods TEMA for the typical price.Linear regression works by taking various data points in a sample and providing a "best fit" line to match the general trend in the data.
Implementation reference:
https://github.com/twopirllc/pandas-ta/blob/main/pandas_ta/overlap/linreg.py
Examples:
df['close_10_lrma'] linear regression of close price with window size 10Kaufman's Adaptive Moving Average is designed to account for market noise or volatility.
It has 2 optional parameters and 2 required parameters:
The default value for window, fast and slow can be configured with
set_dft_window('kama', (10, 5, 34))
Examples:
df['close_10,2,30_kama'] retrieves 10 periods KAMA of the close
price with fast = 2 and slow = 30df['close_2_kama'] retrieves 2 periods KAMA of the close price
with default fast and slowIt's the moving average weighted by volume.
It has a parameter for window size. The default window is 14. Change it with
set_dft_window('vwma', n).
Examples:
df['vwma'] retrieves the 14 periods VWMAdf['vwma_6'] retrieves the 6 periods VWMAdf['dma'] retrieves the difference of 10 periods SMA of the close price and
the 50 periods SMA of the close price.
Follow the pattern <columnName>_<window>_mstd to retrieve the moving STD.
Follow the pattern <columnName>_<window>_mvar to retrieve the moving VAR.
RSI charts the current and historical strength or weakness of a stock. It takes a window parameter.
The default window is 14. Use set_dft_window('rsi', n) to tune it.
Examples:
df['rsi']: retrieve the RSI of 14 periodsdf['rsi_6']: retrieve the RSI of 6 periodsStochastic RSI gives traders an idea of whether the current RSI value is overbought or oversold. It takes a window parameter.
The default window is 14. Use set_dft_window('stochrsi', n) to tune it.
Examples:
df['stochrsi']: retrieve the Stochastic RSI of 14 periodsdf['stochrsi_6']: retrieve the Stochastic RSI of 6 periodsWe 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 Percentage Price Oscillator includes three lines.
df['ppo'] derives from the difference of 2 exponential moving average.df['ppos'] is the signal line.df['ppoh'] is the histogram line.The period of short, long EMA and signal line can be tuned with
set_dft_window('ppo', (short, long, signal)). The default
windows are 12 and 26 and 9.
The stochastic oscillator is a momentum indicator that uses support and resistance levels.
It includes three lines:
df['kdjk'] - K seriesdf['kdjd'] - D seriesdf['kdjj'] - J seriesThe default window is 9. Use set_dft_window('kdjk', n) to change it.
Use df['kdjk_6'] to retrieve the K series of 6 periods.
KDJ also has two configurable parameters named StockDataFrame.KDJ_PARAM.
The default value is (2.0/3.0, 1.0/3.0)
The Price Rate of C
Shift of data does not produce NaN at the beginning of data
import Error "TypeError: 'type' object is not subscriptable"
Different results in DMI indicators (ex: adx_X_ema) between 0.5.X and 0.6.X.
WMA and Hull MA
Error calculating the number of prices greater than the close of the last 10 periods
Supertrend indicator seems to incorrectly change orientation
SSL Channel add
DMI指标使用有疑问
Document Enhancements.
Add weighted moving average