Pandas TA

Pandas TA - A Technical Analysis Library in Python 3

license Python Version PyPi Version Package Status Downloads Stars Forks Used By Contributors Issues Closed Issues Buy Me a Coffee


Example Chart

Pandas Technical Analysis (Pandas TA) is an easy to use library that leverages the Pandas package with more than 140 Indicators and Utility functions and more than 60 TA Lib Candlestick Patterns. Many commonly used indicators are included, such as: Candle Pattern (cdl_pattern), 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.

Note: TA Lib must be installed to use all the Candlestick Patterns. pip install TA-Lib. If TA Lib is not installed, then only the builtin Candlestick Patterns will be available.


Table of contents



Features

  • Over 140 indicators and utility functions.
  • TA Lib indicators (pip install ta-lib).
    • TA Lib's 63 Chart Patterns
    • Python Indicators are tightly correlated with the de facto TA Lib.
    • TA Lib computations are by default enabled. They can be disabled disabled per indicator by using the argument talib=False.
      • For example to disable TA Lib calculation for stdev: ta.stdev(df["close"], length=30, talib=False).
  • Stochastic Sample Realizations with the stochastic package (pip install stochastic). See the Stochastic Samples section below.
  • External Custom Indicators Directory independent of the builtin Pandas TA indicators. For more information, see import_dir documentation under /pandas_ta/custom.py.
  • Example Jupyter Notebooks with vectorbt Portfolio Backtesting with Pandas TA's ta.tsignals method.
  • Multiprocessing Support for Sets of Indicators called Study (formerly Strategy) when using the DataFrame Extension method df.ta.study().
    • Have the need for speed? By using the DataFrame study method, you get multiprocessing for free! Conditions permitting.
  • Study Customizations like applying prefixes or suffixes or both to column/indicators names. Useful for Custom Chained Studies.
  • Example Jupyter Notebooks under the examples directory, including how to create Custom Studies using the new Study Class

Under Development

Pandas TA can also leverage other common or popular trading packages you may have installed in your environment. Current packages include: TA Lib, Vector BT, YFinance, Polygon API, and Stochastic. Much is experimental.

  • Easily download ohlcv data from yfinance or Polygon API.
    • See help(ta.ticker), help(ta.yf), help(ta.polygon_api) and examples below.
  • Some Common Performance Metrics

Installation

Stable

The pip version is the last stable release. Version: 0.3.14b

$ pip install pandas_ta

Latest Version

Best choice! Version: 0.3.45b

  • Includes all fixes and updates between pypi and what is covered in this README.
$ pip install -U git+https://github.com/twopirllc/pandas-ta

Cutting Edge

This is the Development Version which could have bugs and other undesireable side effects. Use at own risk!

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

Quick Start

import pandas as pd
import pandas_ta as ta

df = pd.DataFrame() # Empty DataFrame

# Load data
df = pd.read_csv("path/to/symbol.csv", sep=",")
# OR if you have yfinance installed
df = df.ta.ticker("aapl")

# VWAP requires the DataFrame index to be a DatetimeIndex.
# Replace "datetime" with the appropriate column from your DataFrame
df.set_index(pd.DatetimeIndex(df["datetime"]), inplace=True)

# 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

Help

Some indicator arguments have been reordered for consistency. Use help(ta.indicator_name) for more information or make a Pull Request to improve documentation.

import pandas as pd
import pandas_ta as ta

# Create a DataFrame so 'ta' can be used.
df = pd.DataFrame()

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

# List of all indicators
df.ta.indicators()

# Help about an indicator such as bbands
help(ta.bbands)

Issues and Contributions

Thanks for using Pandas TA!

  • Comments and Feedback

    • Have you read 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 Studies with the Study Class?
    • Documentation could always be improved. Can you help contribute?
  • Bugs, Indicators or Feature Requests

    • First, search the Closed Issues before you Open a new Issue; it may have already been solved.
    • Please be as detailed as possible with reproducible code, links if any, applicable screenshots, errors, logs, and data samples. You will be asked again if you provide nothing.
      • 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.
        • Do you have correlation analysis to back your claim?
        • Can you contribute?
    • 🛑 Please DO NOT personally email me Pandas TA questions that are best handled with Github Issues.

Contributors

Thank you for your contributions!


Programming Conventions

Pandas TA has three primary "styles" of processing Technical Indicators for your use case and/or requirements. They are: Standard, DataFrame Extension, and the Pandas TA Study. Each with increasing levels of abstraction for ease of use. As you become more familiar with Pandas TA, the simplicity and speed of using a Pandas TA Study may become more apparent. Furthermore, you can create your own indicators through Chaining or Composition. Lastly, each indicator either returns a Series or a DataFrame in Uppercase Underscore format regardless of style.


Standard

You explicitly define the input columns and take care of the output.

  • sma10 = ta.sma(df["Close"], length=10)
    • Returns a Series with name: SMA_10
  • donchiandf = ta.donchian(df["HIGH"], df["low"], lower_length=10, upper_length=15)
    • Returns a DataFrame named DC_10_15 and column names: DCL_10_15, DCM_10_15, DCU_10_15
  • ema10_ohlc4 = ta.ema(ta.ohlc4(df["Open"], df["High"], df["Low"], df["Close"]), length=10)
    • Chaining indicators is possible but you have to be explicit.
    • Since it returns a Series named EMA_10. If needed, you may need to uniquely name it.

Pandas TA DataFrame Extension

Calling df.ta will automatically lowercase OHLCVA to ohlcva: open, high, low, close, volume, adj_close. By default, df.ta will use the ohlcva for the indicator arguments removing the need to specify input columns directly.

  • sma10 = df.ta.sma(length=10)
    • Returns a Series with name: SMA_10
  • ema10_ohlc4 = df.ta.ema(close=df.ta.ohlc4(), length=10, suffix="OHLC4")
    • Returns a Series with name: EMA_10_OHLC4
    • Chaining Indicators require specifying the input like: close=df.ta.ohlc4().
  • donchiandf = df.ta.donchian(lower_length=10, upper_length=15)
    • Returns a DataFrame named DC_10_15 and column names: DCL_10_15, DCM_10_15, DCU_10_15

Same as the last three examples, but appending the results directly to the DataFrame df.

  • df.ta.sma(length=10, append=True)
    • Appends to df column name: SMA_10.
  • df.ta.ema(close=df.ta.ohlc4(append=True), length=10, suffix="OHLC4", append=True)
    • Chaining Indicators require specifying the input like: close=df.ta.ohlc4().
  • df.ta.donchian(lower_length=10, upper_length=15, append=True)
    • Appends to df with column names: DCL_10_15, DCM_10_15, DCU_10_15.

Pandas TA Study

A Pandas TA Study is a named group of indicators to be run by the study method. All Studies use mulitprocessing except when using the col_names parameter (see below). There are different types of Studies listed in the following section.


Here are the previous Styles implemented using a Study Class:

# (1) Create the Study
MyStudy = ta.Study(
    name="DCSMA10",
    ta=[
        {"kind": "ohlc4"},
        {"kind": "sma", "length": 10},
        {"kind": "donchian", "lower_length": 10, "upper_length": 15},
        {"kind": "ema", "close": "OHLC4", "length": 10, "suffix": "OHLC4"},
    ]
)

# (2) Run the Study
df.ta.study(MyStudy, **kwargs)



Pandas TA Studies

  • 🛑 The Study Class and corresponding method have replaced the Strategy Class and method.

The Study Class is a simple way to name and group your favorite TA Indicators by using a Data Class. Pandas TA comes with two prebuilt basic Studies to help you get started: AllStudy and CommonStudy. A Study can be as simple as the CommonStudy or as complex as needed using Composition/Chaining.

  • When using the study method, all indicators will be automatically appended to the DataFrame df.
  • You are using a Chained Study when you have the output of one indicator as input into one or more indicators in the same Study.
  • Note: Use the 'prefix' and/or 'suffix' keywords to distinguish the composed indicator from it's default Series.

See the Pandas TA Study Examples Notebook for examples including Indicator Composition/Chaining.

Study 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
  • Note: A Study will fail when consumed by Pandas TA if there is no {"kind": "indicator name"} attribute. Remember to check your spelling.

Optional Parameters

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

Types of Studies

Builtin

# Running the Builtin CommonStudy as mentioned above
df.ta.study(ta.CommonStudy)

# The Default Study is the ta.AllStudy. The following are equivalent:
df.ta.study()
df.ta.study("All")
df.ta.study(ta.AllStudy)

Categorical

# List of indicator categories
df.ta.categories

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

Custom

# Create your own Custom Study
CustomStudy = ta.Study(
    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 Study"
df.ta.study(CustomStudy)

Multiprocessing

The Pandas TA study method utilizes multiprocessing for bulk indicator processing of all Study types with ONE EXCEPTION! When using the col_names parameter to rename resultant column(s), the indicators in ta array will be ran in order.

# VWAP requires the DataFrame index to be a DatetimeIndex.
# * Replace "datetime" with the appropriate column from your DataFrame
df.set_index(pd.DatetimeIndex(df["datetime"]), inplace=True)

# Runs and appends all indicators to the current DataFrame by default
# The resultant DataFrame will be large.
df.ta.study()
# Or the string "all"
df.ta.study("all")
# Or the ta.AllStudy
df.ta.study(ta.AllStudy)

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

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

# Choose the number of cores to use. Default is all available cores.
# For no multiprocessing, set this value to 0.
df.ta.cores = 4

# Maybe you do not want certain indicators.
# Just exclude (a list of) them.
df.ta.study(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.study(fast=10, slow=50, verbose=True)

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

Custom Study without Multiprocessing

Remember These will not be utilizing multiprocessing

NonMPStudy = ta.Study(
    name="EMAs, BBs, and MACD",
    description="Non Multiprocessing Study by rename Columns",
    ta=[
        {"kind": "ema", "length": 8},
        {"kind": "ema", "length": 21},
        {"kind": "bbands", "length": 20, "col_names": ("BBL", "BBM", "BBU")},
        {"kind": "macd", "fast": 8, "slow": 21, "col_names": ("MACD", "MACD_H", "MACD_S")}
    ]
)
# Run it
df.ta.study(NonMPStudy)



DataFrame Properties

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

categories

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

cores

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

# Set the number of cores to 0 for no multiprocessing.
df.ta.cores = 0

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

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.
df.ta.datetime_ordered

ds

# Gets the Data Source (ds). Default: "yf"
df.ta.ds

# Set the Data Source (ds) so that df.ta.ticker() can download ohlcv data.
# Available Data Sources: "yf", "polgon"
df.ta.ds = "yf"

exchange

# Sets the Exchange to use when calculating the last_run property. Default: "NYSE"
df.ta.exchange

# Set the Exchange.
# Available Exchanges: "ASX", "BMF", "DIFX", "FWB", "HKE", "JSE", "LSE", "NSE", "NYSE", "NZSX", "RTS", "SGX", "SSE", "TSE", "TSX"
df.ta.exchange = "LSE"

last_run

# Returns the time Pandas TA was last run as a string.
df.ta.last_run

reverse

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

prefix & suffix

# Applying a prefix to the name of an indicator.
prehl2 = df.ta.hl2(prefix="pre")
print(prehl2.name)  # "pre_HL2"

# Applying a suffix to the name of an indicator.
endhl2 = df.ta.hl2(suffix="post")
print(endhl2.name)  # "HL2_post"

# Applying a prefix and suffix to the name of an indicator.
bothhl2 = df.ta.hl2(prefix="pre", suffix="post")
print(bothhl2.name)  # "pre_HL2_post"

time_range

# Returns the time range of the DataFrame as a float.
# By default, it returns the time in "years"
df.ta.time_range

# Available time_ranges include: "years", "months", "weeks", "days", "hours", "minutes". "seconds"
df.ta.time_range = "days"
df.ta.time_range # prints DataFrame time in "days" as float

to_utc

# Sets the DataFrame index to UTC format.
df.ta.to_utc



DataFrame Methods

These are some additional methods available to the DataFrame Extension (ta).


constants

import numpy as np

# Add constant '1' to the DataFrame
df.ta.constants(True, [1])
# Remove constant '1' to the DataFrame
df.ta.constants(False, [1])

# Adding constants for charting
chart_lines = np.append(np.arange(-4, 5, 1), np.arange(-100, 110, 10))
df.ta.constants(True, chart_lines)
# Removing some constants from the DataFrame
df.ta.constants(False, np.array([-60, -40, 40, 60]))

indicators

# Prints the indicators and utility functions
df.ta.indicators()

# Returns a list of indicators and utility functions
ind_list = df.ta.indicators(as_list=True)

# Prints the indicators and utility functions that are not in the excluded list
df.ta.indicators(exclude=["cg", "pgo", "ui"])
# Returns a list of the indicators and utility functions that are not in the excluded list
smaller_list = df.ta.indicators(exclude=["cg", "pgo", "ui"], as_list=True)

ticker

Yahoo Finance (default)

# Download Chart history using yfinance. (pip install yfinance) https://github.com/ranaroussi/yfinance
# It uses the same keyword arguments as yfinance (excluding start and end)
df = df.ta.ticker("aapl") # Default ticker is "SPY"

# Period is used instead of start/end
# Valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max
# Default: "max"
df = df.ta.ticker("aapl", period="1y") # Gets this past year

# History by Interval by interval (including intraday if period < 60 days)
# Valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo
# Default: "1d"
df = df.ta.ticker("aapl", period="1y", interval="1wk") # Gets this past year in weeks
df = df.ta.ticker("aapl", period="1mo", interval="1h") # Gets this past month in hours

# A Ticker & DataFrame Dictionary with a Study applied
tickers = ["SPY", "AAPL", "SQ"]
s = ta.CommonStudy
asset = {f"{t}_D": ta.df.ta.ticker(t, cores=0, study=s, ds="yf") for t in tickers}
print(asset.keys())
spydf = asset["SPY_D]

# BUT WAIT!! THERE'S MORE!!
help(ta.yf)

Polygon

# Download Chart history from Polygon. (pip install polygon) https://github.com/pssolanki111/polygon
polygon_api_key = # Your Polygon API Key
df = df.ta.ticker("aapl", ds="polygon", api_key=polygon_api_key) # Default ticker is "SPY"

# BUT WAIT!! THERE'S MORE!!
help(ta.polygon_api)



Indicators (by Category)

Candles (64)

Patterns that are not bold, require TA-Lib to be installed: pip install TA-Lib

  • 2crows
  • 3blackcrows
  • 3inside
  • 3linestrike
  • 3outside
  • 3starsinsouth
  • 3whitesoldiers
  • abandonedbaby
  • advanceblock
  • belthold
  • breakaway
  • closingmarubozu
  • concealbabyswall
  • counterattack
  • darkcloudcover
  • doji
  • dojistar
  • dragonflydoji
  • engulfing
  • eveningdojistar
  • eveningstar
  • gapsidesidewhite
  • gravestonedoji
  • hammer
  • hangingman
  • harami
  • haramicross
  • highwave
  • hikkake
  • hikkakemod
  • homingpigeon
  • identical3crows
  • inneck
  • inside
  • invertedhammer
  • kicking
  • kickingbylength
  • ladderbottom
  • longleggeddoji
  • longline
  • marubozu
  • matchinglow
  • mathold
  • morningdojistar
  • morningstar
  • onneck
  • piercing
  • rickshawman
  • risefall3methods
  • separatinglines
  • shootingstar
  • shortline
  • spinningtop
  • stalledpattern
  • sticksandwich
  • takuri
  • tasukigap
  • thrusting
  • tristar
  • unique3river
  • upsidegap2crows
  • xsidegap3methods
  • Heikin-Ashi: ha
  • Z Score: cdl_z

# Get all candle patterns (Default)
df = df.ta.cdl_pattern(name="all")

# Get only one pattern
df = df.ta.cdl_pattern(name="doji")

# Get some patterns
df = df.ta.cdl_pattern(name=["doji", "inside"])

Cycles (2)

  • Even Better Sinewave: ebsw
  • Reflex: reflex
    • trendflex companion

Momentum (42)

  • Awesome Oscillator: ao
  • Absolute Price Oscillator: apo
  • Bias: bias
  • Balance of Power: bop
  • BRAR: brar
  • Commodity Channel Index: cci
  • Chande Forecast Oscillator: cfo
  • Center of Gravity: cg
  • Chande Momentum Oscillator: cmo
  • Coppock Curve: coppock
  • Correlation Trend Indicator: cti
    • A wrapper for ta.linreg(series, r=True)
  • Directional Movement: dm
  • 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
  • Quantitative Qualitative Estimation: qqe
  • Rate of Change: roc
  • Relative Strength Index: rsi
  • Relative Strength Xtra: rsx
  • Relative Vigor Index: rvgi
  • Schaff Trend Cycle: stc
  • Slope: slope
  • SMI Ergodic smi
  • Squeeze: squeeze
    • Default is John Carter's. Enable Lazybear's with lazybear=True
  • Squeeze Pro: squeeze_pro
  • Stochastic Oscillator: stoch
  • Fast Stochastic Oscillator: stochf
  • Stochastic RSI: stochrsi
  • TD Sequential: td_seq
    • Excluded from df.ta.study().
  • Trix: trix
  • True strength index: tsi
  • Ultimate Oscillator: uo
  • Williams %R: willr
Moving Average Convergence Divergence (MACD)
Example MACD

Overlap (36)

  • Bill Williams Alligator: alligator
  • Arnaud Legoux Moving Average: alma
  • 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
  • Holt-Winter Moving Average: hwma
  • Ichimoku Kinkō Hyō: ichimoku
    • Returns two DataFrames. For more information: help(ta.ichimoku).
    • lookahead=False drops the Chikou Span Column to prevent potential data leak.
  • Jurik Moving Average: jma
  • Kaufman's Adaptive Moving Average: kama
  • Linear Regression: linreg
  • McGinley Dynamic: mcgd
  • Midpoint: midpoint
  • Midprice: midprice
  • Open-High-Low-Close Average: ohlc4
  • Pascal's Weighted Moving Average: pwma
  • WildeR's Moving Average: rma
  • Sine Weighted Moving Average: sinwma
  • Simple Moving Average: sma
  • Smoothed Moving Average: smma
  • Ehler's Super Smoother Filter: ssf
  • Ehler's Super Smoother Filter (3 Poles): ssf3
  • Supertrend: supertrend
  • Symmetric Weighted Moving Average: swma
  • T3 Moving Average: t3
  • Triple Exponential Moving Average: tema
  • Triangular Moving Average: trima
  • Variable Index Dynamic Average: vidya
  • Volume Weighted Average Price: vwap
    • Requires the DataFrame index to be a DatetimeIndex
  • 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.

  • Draw Down: drawdown
  • Log Return: log_return
  • Percent Return: percent_return
Percent Return (Cumulative) with Simple Moving Average (SMA)
Example Cumulative Percent Return

Statistics (11)

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

Trend (19)

  • Average Directional Movement Index: adx
    • Also includes dmp and dmn in the resultant DataFrame.
  • Archer Moving Averages Trends: amat
  • Aroon & Aroon Oscillator: aroon
  • Choppiness Index: chop
  • Chande Kroll Stop: cksp
  • Decay: decay
    • Formally: linear_decay
  • Decreasing: decreasing
  • Detrended Price Oscillator: dpo
    • Set lookahead=False to disable centering and remove potential data leak.
  • Increasing: increasing
  • Long Run: long_run
  • Parabolic Stop and Reverse: psar
  • Q Stick: qstick
  • Short Run: short_run
  • Trendflex: trendflex
    • reflex companion
  • Trend Signals: tsignals
  • TTM Trend: ttm_trend
  • Vertical Horizontal Filter: vhf
  • Vortex: vortex
  • Cross Signals: xsignals
Average Directional Movement Index (ADX)
Example ADX

Utility (5)

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

Volatility (14)

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

Volume (16)

  • 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
  • Klinger Volume Oscillator: kvo
  • Money Flow Index: mfi
  • Negative Volume Index: nvi
  • On-Balance Volume: obv
  • Positive Volume Index: pvi
  • Price-Volume: pvol
  • Price Volume Rank: pvr
  • Price Volume Trend: pvt
  • Volume Profile: vp
  • Worden Brothers Time Segmented Value: wb_tsv
On-Balance Volume (OBV)
Example OBV



Backtesting

Vector BT

For easier integration with vectorbt's Portfolio from_signals method, the ta.trend_return method has been replaced with ta.tsignals method to simplify the generation of trading signals. For a comprehensive example, see the example Jupyter Notebook VectorBT Backtest with Pandas TA in the examples directory.

  • See the vectorbt website more options and examples.

Brief example

import pandas as pd
import pandas_ta as ta
import vectorbt as vbt

df = pd.DataFrame().ta.ticker("AAPL") # requires 'yfinance' installed

# Create the "Golden Cross" 
df["GC"] = df.ta.sma(50, append=True) > df.ta.sma(200, append=True)

# Create boolean Signals(TS_Entries, TS_Exits) for vectorbt
golden = df.ta.tsignals(df.GC, asbool=True, append=True)

# Sanity Check (Ensure data exists)
print(df)

# Create the Signals Portfolio
pf = vbt.Portfolio.from_signals(df.close, entries=golden.TS_Entries, exits=golden.TS_Exits, freq="D", init_cash=100_000, fees=0.0025, slippage=0.0025)

# Print Portfolio Stats and Return Stats
print(pf.stats())
print(pf.returns_stats())

Performance Metrics   BETA

Performance Metrics are a new addition to the package and consequentially are likely unreliable. Use at your own risk. These metrics return a float and are not part of the DataFrame Extension. They are called the Standard way. For Example:

import pandas_ta as ta
result = ta.cagr(df.close)

Available Metrics

  • Compounded Annual Growth Rate: cagr
  • Calmar Ratio: calmar_ratio
  • Downside Deviation: downside_deviation
  • Jensen's Alpha: jensens_alpha
  • Log Max Drawdown: log_max_drawdown
  • Max Drawdown: max_drawdown
  • Pure Profit Score: pure_profit_score
  • Sharpe Ratio: sharpe_ratio
  • Sortino Ratio: sortino_ratio
  • Volatility: volatility

Stochastic Samples   BETA

Pandas TA can utilize the stochastic package (pip install stochastic) to Generate Sample Processes. For arguments and features, see help(ta.sample)

In short, when you create a Stochastic Sample,

# Returns a Sample Realization Object
sp = ta.sample() # Sample Process Object
print(sp)

# List of Object properties and methods
print(", ".join([x for x in dir(sp) if not x.startswith('_')]))

print(sp.np) # Return process as Numpy ndarray
print(sp.df) # Return process as Pandas DataFrame

# List of available processes
print(sp.processes)
# Returns type of process used
print(sp.process)

# List of available noises
print(sp.noises)
# Returns type of noise used
print(sp.noise)

# See the help for more options and examples
help(ta.sample)



Changes

General

  • A Study Class to help name and group your favorite indicators.
  • If a TA Lib is already installed, Pandas TA will run TA Lib's version. (BETA)
  • Some indicators have had their mamode kwarg updated with more moving average choices with the Moving Average Utility function ta.ma(). For simplicity, all choices are single source moving averages. This is primarily an internal utility used by indicators that have a mamode kwarg. This includes indicators: accbands, amat, aobv, atr, bbands, bias, efi, hilo, kc, natr, qqe, rvi, and thermo; the default mamode parameters have not changed. However, ta.ma() can be used by the user as well if needed. For more information: help(ta.ma)
    • Moving Average Choices: dema, ema, fwma, hma, linreg, midpoint, pwma, rma, sinwma, sma, swma, t3, tema, trima, vidya, wma, zlma.
  • An experimental and independent Watchlist Class located in the Examples Directory that can be used in conjunction with the new Study Class.
  • Linear Regression (linear_regression) is a new utility method for Simple Linear Regression using Numpy or Scikit Learn's implementation.
  • Added utility/convience function, to_utc, to convert the DataFrame index to UTC. See: help(ta.to_utc) Now as a Pandas TA DataFrame Property to easily convert the DataFrame index to UTC.

Breaking / Depreciated Indicators

  • Arnaud Legoux Moving Average (alma) Updated accuracy and speed with new default length=9 and argument distribution_offset renamed to dist_offset. See help(ta.alma).
  • Trend Return (trend_return) has been removed and replaced with tsignals. When given a trend Series like close > sma(close, 50) it returns the Trend, Trade Entries and Trade Exits of that trend to make it compatible with vectorbt by setting asbool=True to get boolean Trade Entries and Exits. See help(ta.tsignals)
  • Volume Profile (vp) is no longer part of the DataFrame Extension since it does not return a Time Series.
  • Zero Lag Moving Average (zlma) now using available Moving Averages from ta.ma. See help(ta.zlma) and help(ta.ma).

New Indicators

  • Bill Williams Alligator (alligator) attempts to identify if an asset is trending. See help(ta.alligator)
  • Cross Signals (xsignals) is a wrapper of Trend Signals (help(ta.tsignals)) that returns Trends, Trades, Entries and Exits. Cross Signals are commonly used for bbands, rsi, zscore crossing some value either above or below two values at different times. See help(ta.xsignals)
  • Directional Movement (dm) developed by J. Welles Wilder in 1978 attempts to determine which direction the price of an asset is moving. See help(ta.dm)
  • Jurik Moving Average (jma) attempts to eliminate noise to see the "true" underlying activity. See: help(ta.jma)
  • Smoothed Moving Average (smma) can be used to confirm trends and define areas of support and resistance. See: help(ta.smma)
  • Fast Stochastic Oscillator (stochf) is related to stoch but is less rarely used since it is more volatile. See: help(ta.stochf)
  • Squeeze Pro (squeeze_pro) is an extended version of "TTM Squeeze" from John Carter. See help(ta.squeeze_pro)
  • Tom DeMark's Sequential (td_seq) attempts to identify a price point where an uptrend or a downtrend exhausts itself and reverses. Currently exlcuded from df.ta.study() for performance reasons. See help(ta.td_seq)
  • Think or Swim Standard Deviation All (tos_stdevall) indicator which returns the standard deviation of data for the entire plot or for the interval of the last bars defined by the length parameter. See help(ta.tos_stdevall)
  • Worden Brothers Time Segmented Value (wb_tsv) is an oscillator indicator that attempts to indentify money flow in a stock, similar to On Balance Volume (obv). See help(ta.wb_tsv)

Updated Indicators

  • Average True Range (atr): The default mamode is now "RMA" and with the same mamode options as TradingView. See help(ta.atr).
  • Exponential Moving Average (ema): The argument sma has been renamed presma`` to avoid potential name collision. When presma=True, then the Pandas TA version will bootstrap **ema** like TA Lib. See help(ta.ema)```.
  • Kaufman Adaptive Moving Average (kama): An mamode as been added with default "SMA" to properly boostrap kama. Note: Not all MAs are usable. See help(ta.kama).
  • Linear Regression (linreg): Checks numpy's version to determine whether to utilize the as_strided method or the newer sliding_window_view method. This should resolve Issues with Google Colab and it's delayed dependency updates as well as TensorFlow's dependencies as discussed in Issues #285 and #329.
  • Ehler's Super Smoother Filter (ssf): Some new arguments (pi, sqrt2) were added to control the precision of the calculation since it varies by author and user. Additionally, the poles argument has been removed. For 3 Poles, see help(ta.ssf3). See help(ta.ssf).
  • Ehler's Super Smoother Filter (3 Poles) (ssf3): Was split from ta.ssf and also has addtional arguments arguments (pi, sqrt3). See help(ta.ssf3).
  • Standard Deviation (stdev): To use ddof argument, also set talib=False. The ddof argument is not available if you have TA Lib installed in your environment. Same goes for variance. See help(ta.stdev).
  • Variance (variance): To use ddof argument, also set talib=False. The ddof argument is not available if you have TA Lib installed in your environment. Same goes for stdev. See help(ta.variance).
  • Volume Profile (vp): Calculation improvements. See Pull Request #320 See help(ta.vp).

Sources

Original TA-LIB | TradingView | Sierra Chart | MQL5 | FM Labs | Pro Real Code | User 42 | Technical Traders


Support

Feeling generous, like the package or want to see it become more a mature package?

  • Donations help cover data and API costs so platform indicataors (like TradingView) are accurate.
  • I appreciate ALL of those that have bought me Coffee/Beer/Wine et al. I greatly appreciate it! 😎

Consider

"Buy Me A Coffee"

S
Description
Technical Analysis Indicators - Pandas TA is an easy to use Python 3 Pandas Extension with 130+ Indicators
Readme MIT 62 MiB
Languages
Python 99.9%