/pandas-ta

Technical Analysis Indicators - Pandas TA is an easy to use Python 3 Pandas Extension with 120+ Indicators

Primary LanguagePythonMIT LicenseMIT

Python Version PyPi Version Package Status Downloads

Pandas TA

Pandas Technical Analysis Library in Python 3

Example Chart

Pandas Technical Analysis (Pandas TA) is an easy to use library that is built upon Python's Pandas library with more than 120 Indicators and Utility functions. These indicators are commonly used for financial time series datasets with columns or labels: datetime, open, high, low, close, volume, et al. Many commonly used indicators are included, such as: Simple Moving Average (sma) Moving Average Convergence Divergence (macd), Hull Exponential Moving Average (hma), Bollinger Bands (bbands), On-Balance Volume (obv), Aroon & Aroon Oscillator (aroon), Squeeze (squeeze) and many more.

Pandas TA has three different ways of processing Technical Indicators as described below. The primary requirement to run indicators in Pandas DataFrame Extension mode, is that open, high, low, close, volume are lowercase. Depending on the indicator, they either return a named Series or a DataFrame in uppercase underscore parameter format. For example, MACD(fast=12, slow=26, signal=9) will return a DataFrame with columns: ['MACD_12_26_9', 'MACDh_12_26_9', 'MACDs_12_26_9'].

Pandas TA Issues, Ideas and Contributions

Thanks for trying Pandas TA!

Please take a moment to read this and the rest of this README before posting any issue.

  • Comments and Feedback

    • Have you read the rest of this document?
    • Are you running the latest version?
      • pip install -U git+https://github.com/twopirllc/pandas-ta
    • Have you tried the Examples?
      • Did they help?
      • What is missing?
      • Could you help improve them?
    • Did you know you can easily build Custom Strategies with the Strategy Class?
    • Documentation could always use improvement. Can you contribute?
  • Indicator or Feature Requests & Contributions

    • Please be as detailed as possible. Links, screenshots, and sometimes data samples are welcome.
      • You want a new indicator not currently listed.
      • You want an alternate version of an existing indicator.
      • The indicator does not match another website, library, broker platform, language, et al.
        • Can you contribute?

Features

  • Has 120+ indicators and utility functions.
  • Easily add prefixes or suffixes or both to columns names. Useful for building Custom Strategies.
  • Extended Pandas DataFrame as 'ta'.
  • Indicators are tightly correlated with the de facto TA Lib if they share common indicators.
  • Example Jupyter Notebooks under the examples directory, including how to create Custom Strategies using the new Strategy Class
  • A new 'ta' method called 'strategy'. By default, it runs all the indicators or equivalent ta.AllStrategy.

Recent Changes

  • A Strategy Class to help name and group your favorite indicators.
  • An experimental and independent Watchlist Class located in the Examples Directory that can be used in conjunction with the new Strategy Class. and Weighted Moving Average.
  • Multiprocessing is automatically applied to df.ta.strategy() for All indicators or a chosen Category of indicators.
  • Improved the calculation performance of indicators: Exponential Moving Averagage
  • Updated trend_return utility to return a more pertinenet trade info for a trend. Example can be found in the AI Example Notebook. The notebook is still a work in progress and open to colloboration.

Breaking Indicators

  • Stochastic Oscillator (stoch): Now in line with Trading View's calculation. See: help(ta.stoch)

New Indicators

  • Squeeze (squeeze). A Momentum indicator. Both John Carter's TTM and Lazybear's TradingView versions are implemented. The default is John Carter's, or lazybear=False. Set lazybear=True to enable Lazybear's.
  • TTM Trend (ttm_trend). A trend indicator inspired from John Carter's book "Mastering the Trade".
  • SMI Ergodic (smi) Developed by William Blau, the SMI Ergodic Indicator is the same as the True Strength Index (TSI) except the SMI includes a signal line and oscillator.
  • Gann High-Low Activator (hilo) The Gann High Low Activator Indicator was created by Robert Krausz in a 1998 issue of Stocks & Commodities Magazine. It is a moving average based trend indicator consisting of two different simple moving averages.
  • Stochastic RSI (stochrsi) "Stochastic RSI and Dynamic Momentum Index" was created by Tushar Chande and Stanley Kroll. In line with Trading View's calculation. See: help(ta.stochrsi)
  • Inside Bar (cdl_inside) An Inside Bar is a bar contained within it's previous bar's high and low See: help(ta.cdl_inside)

Updated Indicators

  • Fisher Transform (fisher): Added Fisher's default ema signal line. To change the length of the signal line, use the argument: signal=5. Default: 5
  • Fisher Transform (fisher) and Kaufman's Adaptive Moving Average (kama): Fixed a bug where their columns were not added to final DataFrame when using the strategy method.
  • Trend Return (trend_return): Returns a DataFrame now instead of Series.
  • Average True Range (atr): Added option to return atr as a percentage. See: help(ta.atr)

What is a Pandas DataFrame Extension?

A Pandas DataFrame Extension, extends a DataFrame allowing one to add more functionality and features to Pandas to suit your needs. As such, it is now easier to run Technical Analysis on existing Financial Time Series without leaving the current DataFrame. This extension by default returns the Indicator result or it can append the result to the existing DataFrame by including the parameter 'append=True' in the method call. Examples below.

Getting Started and Examples

Installation (python 3)

$ pip install pandas_ta

Latest Version

$ pip install -U git+https://github.com/twopirllc/pandas-ta

Quick Start using the DataFrame Extension

import pandas as pd
import pandas_ta as ta

# Load data
df = pd.read_csv("path/symbol.csv", sep=",")

# Calculate Returns and append to the df DataFrame
df.ta.log_return(cumulative=True, append=True)
df.ta.percent_return(cumulative=True, append=True)

# New Columns with results
df.columns

# Take a peek
df.tail()

# vv Continue Post Processing vv

Module and Indicator Help

import pandas as pd
import pandas_ta as ta

# Help about this, 'ta', extension
help(pd.DataFrame().ta)

# List of all indicators
pd.DataFrame().ta.indicators()

# Help about the log_return indicator
help(ta.log_return)

New Class: Strategy

What is a Pandas TA Strategy?

A Strategy is a simple way to name and group your favorite TA indicators. Technically, a Strategy is a simple Data Class to contain list of indicators and their parameters. Note: Strategy is experimental and subject to change. Pandas TA comes with two basic Strategies: AllStrategy and CommonStrategy.

Strategy Requirements:

  • name: Some short memorable string. Note: Case-insensitive "All" is reserved.
  • ta: A list of dicts containing keyword arguments to identify the indicator and the indicator's arguments

Optional Requirements:

  • description: A more detailed description of what the Strategy tries to capture. Default: None
  • created: At datetime string of when it was created. Default: Automatically generated.

Things to note:

  • A Strategy will fail when consumed by Pandas TA if there is no {"kind": "indicator name"} attribute. Remember to check your spelling.

Brief Examples

# The Builtin All Default Strategy
ta.AllStrategy = ta.Strategy(
    name="All",
    description="All the indicators with their default settings. Pandas TA default.",
    ta=None
)

# The Builtin Default (Example) Strategy.
ta.CommonStrategy = ta.Strategy(
    name="Common Price and Volume SMAs",
    description="Common Price SMAs: 10, 20, 50, 200 and Volume SMA: 20.",
    ta=[
        {"kind": "sma", "length": 10},
        {"kind": "sma", "length": 20},
        {"kind": "sma", "length": 50},
        {"kind": "sma", "length": 200},
        {"kind": "sma", "close": "volume", "length": 20, "prefix": "VOL"}
    ]
)

# Your Custom Strategy or whatever your TA composition
CustomStrategy = ta.Strategy(
    name="Momo and Volatility",
    description="SMA 50,200, BBANDS, RSI, MACD and Volume SMA 20",
    ta=[
        {"kind": "sma", "length": 50},
        {"kind": "sma", "length": 200},
        {"kind": "bbands", "length": 20},
        {"kind": "rsi"},
        {"kind": "macd", "fast": 8, "slow": 21},
        {"kind": "sma", "close": "volume", "length": 20, "prefix": "VOLUME"},
    ]
)

DataFrame Method: strategy with Multiprocessing

The new Pandas (TA) method strategy is used to facilitate bulk indicator processing. By default, running df.ta.strategy() will append all applicable indicators to DataFrame df. Utility methods like above, below et al are not included, however they can be included with Custom Strategies.

  • The ta.strategy() method is still under development and subject to change until stable.
# Runs and appends all indicators to the current DataFrame by default
# The resultant DataFrame will be large.
df.ta.strategy()
# Or the string "all"
df.ta.strategy("all")
# Or the ta.AllStrategy
df.ta.strategy(ta.AllStrategy)

# Use verbose if you want to make sure it is running.
df.ta.strategy(verbose=True)

# Use timed if you want to see how long it takes to run.
df.ta.strategy(timed=True)

# Maybe you do not want certain indicators.
# Just exclude (a list of) them.
df.ta.strategy(exclude=["bop", "mom", "percent_return", "wcp", "pvi"], verbose=True)

# Perhaps you want to use different values for indicators.
# This will run ALL indicators that have fast or slow as parameters.
# Check your results and exclude as necessary.
df.ta.strategy(fast=10, slow=50, verbose=True)

# Sanity check. Make sure all the columns are there
df.columns

Running a Builtin, Categorical or Custom Strategy

Builtin

# Running the Builtin CommonStrategy as mentioned above
df.ta.strategy(ta.CommonStrategy)

# The Default Strategy is the ta.AllStrategy. The following are equivalent
# df.ta.strategy(ta.AllStrategy)
# df.ta.strategy("All")
df.ta.strategy()

Categorical

# List of indicator categories
df.ta.categories

# Running a Categorical Strategy only requires the Category name
df.ta.strategy("Momentum") # Default values for all Momentum indicators
df.ta.strategy("overlap", length=27) # Override all 'length' attributes

Custom

# Create your own Custom Strategy
CustomStrategy = ta.Strategy(
    name="Momo and Volatility",
    description="SMA 50,200, BBANDS, RSI, MACD and Volume SMA 20",
    ta=[
        {"kind": "sma", "length": 50},
        {"kind": "sma", "length": 200},
        {"kind": "bbands", "length": 20},
        {"kind": "rsi"},
        {"kind": "macd", "fast": 8, "slow": 21},
        {"kind": "sma", "close": "volume", "length": 20, "prefix": "VOLUME"},
    ]
)
# To run your "Custom Strategy"
df.ta.strategy(CustomStrategy)

DataFrame Property: categories

# List of Pandas TA categories
df = df.ta.categories

DataFrame Property: cores

# Set the number of cores to use for strategy multiprocessing
# Defaults to the number of cpus you have
df.ta.cores = 4

# Returns the number of cores you set or your default number of cpus.
df.ta.cores

DataFrame Properties: reverse & datetime_ordered

# The 'datetime_ordered' property returns True if the DataFrame
# index is of Pandas datetime64 and df.index[0] < df.index[-1]
# Otherwise it returns False
time_series_in_order = df.ta.datetime_ordered

# The 'reverse' is a helper property that returns the DataFrame
# in reverse order
df = df.ta.reverse

DataFrame Property: adjusted

# Set ta to default to an adjusted column, 'adj_close', overriding default 'close'
df.ta.adjusted = "adj_close"
df.ta.sma(length=10, append=True)

# To reset back to 'close', set adjusted back to None
df.ta.adjusted = None

DataFrame kwargs: prefix and suffix

prehl2 = df.ta.hl2(prefix="pre")
print(prehl2.name)  # "pre_HL2"

endhl2 = df.ta.hl2(suffix="post")
print(endhl2.name)  # "HL2_post"

bothhl2 = df.ta.hl2(prefix="pre", suffix="post")
print(bothhl2.name)  # "pre_HL2_post"

Technical Analysis Indicators (by Category)

Candles (3)

  • Doji: cdl_doji
  • Inside Bar: cdl_inside
  • Heikin-Ashi: ha

Momentum (33)

  • Awesome Oscillator: ao
  • Absolute Price Oscillator: apo
  • Bias: bias
  • Balance of Power: bop
  • BRAR: brar
  • Commodity Channel Index: cci
  • Center of Gravity: cg
  • Chande Momentum Oscillator: cmo
  • Coppock Curve: coppock
  • Efficiency Ratio: er
  • Elder Ray Index: eri
  • Fisher Transform: fisher
  • Inertia: inertia
  • KDJ: kdj
  • KST Oscillator: kst
  • Moving Average Convergence Divergence: macd
  • Momentum: mom
  • Pretty Good Oscillator: pgo
  • Percentage Price Oscillator: ppo
  • Psychological Line: psl
  • Percentage Volume Oscillator: pvo
  • Rate of Change: roc
  • Relative Strength Index: rsi
  • Relative Vigor Index: rvgi
  • Slope: slope
  • SMI Ergodic smi
  • Squeeze: squeeze
    • Default is John Carter's. Enable Lazybear's with lazybear=True
  • Stochastic Oscillator: stoch
  • Stochastic RSI: stochrsi
  • Trix: trix
  • True strength index: tsi
  • Ultimate Oscillator: uo
  • Williams %R: willr
Moving Average Convergence Divergence (MACD)
Example MACD

Overlap (27)

  • Double Exponential Moving Average: dema
  • Exponential Moving Average: ema
  • Fibonacci's Weighted Moving Average: fwma
  • Gann High-Low Activator: hilo
  • High-Low Average: hl2
  • High-Low-Close Average: hlc3
    • Commonly known as 'Typical Price' in Technical Analysis literature
  • Hull Exponential Moving Average: hma
  • Ichimoku Kinkō Hyō: ichimoku
    • Use: help(ta.ichimoku). Returns two DataFrames.
  • Kaufman's Adaptive Moving Average: kama
  • Linear Regression: linreg
  • Midpoint: midpoint
  • Midprice: midprice
  • Open-High-Low-Close Average: ohlc4
  • Pascal's Weighted Moving Average: pwma
  • William's Moving Average: rma
  • Sine Weighted Moving Average: sinwma
  • Simple Moving Average: sma
  • Supertrend: supertrend
  • Symmetric Weighted Moving Average: swma
  • T3 Moving Average: t3
  • Triple Exponential Moving Average: tema
  • Triangular Moving Average: trima
  • Volume Weighted Average Price: vwap
  • Volume Weighted Moving Average: vwma
  • Weighted Closing Price: wcp
  • Weighted Moving Average: wma
  • Zero Lag Moving Average: zlma
Simple Moving Averages (SMA) and Bollinger Bands (BBANDS)
Example Chart

Performance (3)

Use parameter: cumulative=True for cumulative results.

  • Log Return: log_return
  • Percent Return: percent_return
  • Trend Return: trend_return
Percent Return (Cumulative) with Simple Moving Average (SMA)
Example Cumulative Percent Return

Statistics (9)

  • Entropy: entropy
  • Kurtosis: kurtosis
  • Mean Absolute Deviation: mad
  • Median: median
  • Quantile: quantile
  • Skew: skew
  • Standard Deviation: stdev
  • Variance: variance
  • Z Score: zscore
Z Score
Example Z Score

Trend (15)

  • Average Directional Movement Index: adx
  • Archer Moving Averages Trends: amat
  • Aroon & Aroon Oscillator: aroon
  • Choppiness Index: chop
  • Chande Kroll Stop: cksp
  • Decreasing: decreasing
  • Detrended Price Oscillator: dpo
  • Increasing: increasing
  • Linear Decay: linear_decay
  • Long Run: long_run
  • Parabolic Stop and Reverse: psar
  • Q Stick: qstick
  • Short Run: short_run
  • TTM Trend: ttm_trend
  • Vortex: vortex
Average Directional Movement Index (ADX)
Example ADX

Utility (5)

  • Above: above
  • Above Value: above_value
  • Below: below
  • Below Value: below_value
  • Cross: cross

Volatility (12)

  • Aberration: aberration
  • Acceleration Bands: accbands
  • Average True Range: atr
  • Bollinger Bands: bbands
  • Donchian Channel: donchian
  • Keltner Channel: kc
  • Mass Index: massi
  • Normalized Average True Range: natr
  • Price Distance: pdist
  • Relative Volatility Index: rvi
  • True Range: true_range
  • Ulcer Index: ui
Average True Range (ATR)
Example ATR

Volume (13)

  • Accumulation/Distribution Index: ad
  • Accumulation/Distribution Oscillator: adosc
  • Archer On-Balance Volume: aobv
  • Chaikin Money Flow: cmf
  • Elder's Force Index: efi
  • Ease of Movement: eom
  • Money Flow Index: mfi
  • Negative Volume Index: nvi
  • On-Balance Volume: obv
  • Positive Volume Index: pvi
  • Price-Volume: pvol
  • Price Volume Trend: pvt
  • Volume Profile: vp
On-Balance Volume (OBV)
Example OBV

Contributors

Inspiration