Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

stockstats

> 编程语言
Open source

Supply a wrapper ``StockDataFrame`` based on the ``pandas.DataFrame`` with inline stock statistics/indicators support.

1.5K stars0 likes0 views
WebsiteGitHub

About

Supply a wrapper ``StockDataFrame`` based on the ``pandas.DataFrame`` with inline stock statistics/indicators support.

Stock Statistics/Indicators Calculation Helper

Introduction

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

Installation

pip install stockstats

Compatibility

Requires Python 3.9+. CI tests against Python 3.10, 3.11, 3.12, and 3.13.

License

BSD-3-Clause License

Quick Start

Load and wrap data

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
  • high: the highest price of the interval
  • 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.

Statistics/Indicators

Summary

Name Access Pattern Default Window Description SMA 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

Moving Averages

Simple Moving Average

Follow the pattern <columnName>_<window>_sma to retrieve a simple moving average.

Exponential Moving Average

Follow the pattern <columnName>_<window>_ema to retrieve an exponential moving average.

SMMA - Smoothed 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 - Triple Exponential Moving Average

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.

LRMA - Linear Regression Moving Average

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 10

KAMA - Kaufman's Adaptive Moving Average

Kaufman's Adaptive Moving Average is designed to account for market noise or volatility.

It has 2 optional parameters and 2 required parameters:

  • fast - optional, the parameter for fast EMA smoothing, default to 5
  • slow - optional, the parameter for slow EMA smoothing, default to 34
  • column - required, the column to calculate
  • window - required, rolling window size

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 = 30
  • df['close_2_kama'] retrieves 2 periods KAMA of the close price with default fast and slow

VWMA - Volume Weighted Moving Average

It'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 VWMA
  • df['vwma_6'] retrieves the 6 periods VWMA

DMA - Difference of Moving Average

df['dma'] retrieves the difference of 10 periods SMA of the close price and the 50 periods SMA of the close price.

Moving Standard Deviation

Follow the pattern <columnName>_<window>_mstd to retrieve the moving STD.

Moving Variance

Follow the pattern <columnName>_<window>_mvar to retrieve the moving VAR.


Momentum

RSI - Relative Strength Index

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 periods
  • df['rsi_6']: retrieve the RSI of 6 periods

Stochastic RSI

Stochastic 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 periods
  • df['stochrsi_6']: retrieve the Stochastic RSI of 6 periods

MACD - Moving Average Convergence Divergence

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.

PPO - Percentage Price Oscillator

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.

KDJ Indicator

The stochastic oscillator is a momentum indicator that uses support and resistance levels.

It includes three lines:

  • df['kdjk'] - K series
  • df['kdjd'] - D series
  • df['kdjj'] - J series

The 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)

ROC - Rate of Change

The Price Rate of C

GitHub Issues· 12 open

View all on GitHub
  • #204

    Shift of data does not produce NaN at the beginning of data

    Updated Mar 21, 2026
  • #179

    import Error "TypeError: 'type' object is not subscriptable"

    Updated Jul 1, 2024
  • #182

    Different results in DMI indicators (ex: adx_X_ema) between 0.5.X and 0.6.X.

    Updated Nov 3, 2023
  • #180

    WMA and Hull MA

    Updated Oct 13, 2023
  • #122

    Error calculating the number of prices greater than the close of the last 10 periods

    Updated Nov 17, 2022
  • #125

    Supertrend indicator seems to incorrectly change orientation

    Updated Nov 16, 2022
  • #119

    SSL Channel add

    Updated Apr 18, 2022
  • #118

    DMI指标使用有疑问

    Updated Apr 10, 2022
  • #112

    Document Enhancements.

    enhancementUpdated Jan 7, 2022
  • #29

    Add weighted moving average

    wait on originatorUpdated Jan 1, 2022

Highlights

  • •close: the close price of the period
  • •high: the highest price of the interval
  • •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)
  • •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)
  • •rsi_6 - 6 periods RSI
  • •cci_10 - 10 periods CCI

> Tags

Python

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言