Pandas TA - A Technical Analysis Library in Python 3
Pandas Technical Analysis (Pandas TA) is a free, Open Source, and easy to use Technical Analysis library with a Pandas DataFrame Extension. It has over 200 indicators, utility functions and TA Lib Candlestick Patterns. Beyond TA feature generation, it has a flat library structure, it's own DataFrame Extension (called ta), Custom Indicator Sets (called a Study) and Custom Directory creation. Lastly, it includes methods to help with Data Acquisition and Stochastic Sampling, Backtesting Support with Signal and Trend methods, and some basic Performance Metrics.
Contents
- Features
- Used By
- Sponsors
- Installation
- Quick Start
- Help
- Issues and Contributions
- Programming Conventions
- DataFrame Extension Properties
- DataFrame Extension Methods
- Indicators by Category
- Backtesting
- BETA
- TODO
- Sources
- Support
Features
Large & Lite Weight Library
- Over 200 Indicators, Statistics and Candlestick Patterns.
- Over 60 Candlestick Patterns with TA Lib indicator integration.
- Flat library structure similar to TA Lib.
- Single dependency: Pandas
Accuracy
- Indicators are highly correlated, r > 0.99, with TA Lib and builtin TradingView Indicators.
- 📈 Contributions are welcome for improved accuracy and performance.
Performance
- Pandas TA is fast, with or without TA Lib or Numba installed, but one is not penalized if they are installed.
- TA Lib computations are enabled by default. They can be disabled per indicator.
- The library includes a performance method,
help(ta.speed_test), to check runtime indicator performance for a given ohlcv DataFrame.
- Optionable Multiprocessing for a Pandas TA
Study. - Check Indicator Speeds on your system with the Indicator Speed Check Notebook.
Bulk Processing
- Easily process many indicators using the DataFrame Extension method
df.ta.study(). - Supports two kinds of Studies.
- Builtin: All, Categorical ("candles", "momentum", ...), and Common.
- Custom: User Defined
Study(formerlyStrategy).
Additional Features
- Examples
- Basic usage and workflows. See the Example Jupyter Notebooks.
- Creating Custom Studies using the Study Class.
- Study Customizations including, but not limited to, applying prefixes or suffixes or both to column/indicators names.
- Composition/Chained Studies like putting bbands on macd.
- Custom Indicators Directory
- Create and import a custom directory containing private indicators independent from the main library.
- Use
help(ta.import_dir)or read theimport_dirmethod in /pandas_ta/custom.py for more information.
- Data Acquisition
- Easily download ohlcv data from yfinance or with the Polygon API.
- See
help(ta.ticker),help(ta.yf),help(ta.polygon_api)and examples below.
- Stochastic Sample Generation BETA
- Built upon many of the Stochastic Processes from the stochastic package.
- See
help(ta.sample).
- Performance Metrics BETA
- A mini set of Performance Metrics.
- 📈 Contributions are welcome for improved accuracy and performance.
- A mini set of Performance Metrics.
- Backtesting Support BETA
- Easily generate Trading Signals for vectorbt using
ta.tsignals()orta.xsignals()methods.
- Easily generate Trading Signals for vectorbt using
Back to Contents
Used By
Pandas TA is used by Applications and Services like
Freqtrade
Freqtrade is a free and open source crypto trading bot written in Python. It is designed to support all major exchanges and be controlled via Telegram. It contains backtesting, plotting and money management tools as well as strategy optimization by machine learning.
Open BB
Previously Gamestonk Terminal
OpenBB is a leading open source investment analysis company. We represent millions of investors who want to leverage state-of-the-art data science and machine learning technologies to make sense of raw unrefined data. Our mission is to make investment research effective, powerful and accessible to everyone.
Tune TA
TuneTA optimizes technical indicators using a distance correlation measure to a user defined target feature such as next day return. Indicator parameter(s) are selected using clustering techniques to avoid "peak" or "lucky" values. The set of tuned indicators can be ...
VectorBT Pro
vectorbt PRO is the next-generation engine for backtesting, algorithmic trading, and research. It's a high-performance, actively-developed, commercial successor to the vectorbt library, one of the world's most innovative open-source backtesting engines. The PRO version extends the standard library with new impressive features and useful enhancements for professionals.
Sponsors
Thank you for your sponsorship of Pandas TA!
Installation
The minimum requirement is Pandas. Though not required, additional features may require numba, polygon, sklearn, statsmodels, stochastic, ta-lib, tqdm, vectorbt, or yfinance.
- Note:
vectorbtrequires many of the additional packages listed.
Pip
The pip version, 0.3.14b, is the last stable release. The next major release will occur when all the remaining Hilbert Transform indicators from TA Lib are included.
$ pip install pandas_ta
How about All?
$ pip install pandas_ta[full]
Development Version
The development version, 0.3.69b, includes numerous bug fixes, speed improvements and better documentation since release, 0.3.14b.
$ pip install -U git+https://github.com/twopirllc/pandas-ta.git@development
Back to Contents
Quick Start
Indicators return either a Pandas Series or DataFrame.
- Note: Volume Weighted Average Price (vwap) is the only indicator that requires a DatetimeIndex.
Simple Example
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
For a more descriptive Quick Start, please check out Michelangiolo Mazzeschi's Medium post: Technical Analysis with Python: Quickstart Guide for Pandas TA.
Help
import pandas as pd
import pandas_ta as ta
# Create a DataFrame so 'ta' can be used.
df = pd.DataFrame()
# Help about the DataFrame Extension: "ta"
help(df.ta)
# List of all indicators
df.ta.indicators()
# Help about an indicator such as adx
help(ta.adx)
Back to Contents
Issues and Contributions
Contributions, feedback, and bug squashing are integral to the success of this library. If you see something you can fix, please do. Your contributon helps us all!
- 🛑 Please DO NOT email me personally with Pandas TA Bugs, Issues or Feature Requests that are best handled with Github Issues.
Bugs, Indicators or Feature Requests
- Some bugs and features may already be be fixed or implemented in either the Latest Version or the the Development Version. Please try them first.
- If the Latest or Development Versions do not resolve the bug or address the Issue, try searching both Open and Closed Issues before opening a new Issue.
- When creating a new Issue, please be as detailed as possible with reproducible code, links if any, applicable screenshots, errors, logs, and data samples.
- You will be asked again for skipping form questions.
- Do you have correlation analysis to back your claim?
Contributors
Thank you for your contributions!
How to Contribute or what TODO?
Satisfaction or Suggestions? |
Feedback |
Knowledge and Experience? |
Info |
!hard |
Good First Issue |
| A little more challenging? | Bugs / Enhancements |
| Lonewolf? | Help Wanted |
Back to Contents
Programming Conventions
Pandas TA supports three Programming Conventions to make it easy to calculate or apply TA features. This includes the Standard, DataFrame Extension, and Pandas TA Study Conventions.
- Note: Each indicator either returns a Series or a DataFrame in Uppercase Underscore format regardless of style.
Standard
The Standard Convention is similar to TA Lib where one has to explicitly define the input arguments and manage the resultant Series or DataFrame.
sma10 = ta.sma(df["Close"], length=10)- Returns a Series with name:
SMA_10
- Returns a Series with name:
donchiandf = ta.donchian(df["HIGH"], df["low"], lower_length=10, upper_length=15)- Returns a DataFrame named
DC_10_15and column names:DCL_10_15, DCM_10_15, DCU_10_15
- Returns a DataFrame named
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.
DataFrame Extension
The DataFrame Extension "ta", extends the DataFrame with additional properties and methods specific to the library. Unlike the Standard Convention, df.ta uses the ohlcva columns as indicator arguments thus removing the need to specify the columns manually.
sma10 = df.ta.sma(length=10)- Returns a Series with name:
SMA_10
- Returns a Series with name:
ema10_ohlc4 = df.ta.ema(close=df.ta.ohlc4(), length=10, suffix="OHLC4")- Returns a Series with name:
EMA_10_OHLC4 - Chaining Indicators requires specifying the input like:
close=df.ta.ohlc4().
- Returns a Series with name:
donchiandf = df.ta.donchian(lower_length=10, upper_length=15)- Returns a DataFrame named
DC_10_15and column names:DCL_10_15, DCM_10_15, DCU_10_15
- Returns a DataFrame named
Same as the last three examples, but appending the results directly to the DataFrame df.
df.ta.sma(length=10, append=True)- Appends to
dfcolumn name:SMA_10.
- Appends to
df.ta.ema(close=df.ta.ohlc4(append=True), length=10, suffix="OHLC4", append=True)- Chaining Indicators requires specifying the input like:
close=df.ta.ohlc4().
- Chaining Indicators requires specifying the input like:
df.ta.donchian(lower_length=10, upper_length=15, append=True)- Appends to
dfwith column names:DCL_10_15, DCM_10_15, DCU_10_15.
- Appends to
Back to Contents
Pandas TA Study
🛑 The Strategy Class and strategy() are depreciated. Use Study Class and study() method instead.
The Study Dataclass can be used to name and group indicators and are executed by the Extension study() method. A Study can range from complex with Composition/Chaining to simple like a CommonStudy.
- Two premade Studies:
AllStudyandCommonStudy. - The
study()method automatically appends to the DataFrame.- Can be disabled by using the argument:
append=False.
- Can be disabled by using the argument:
- All Studies use mulitprocessing except when the cpu
coresare set to zero or when using thecol_namesargument (see below). - A Study will fail when consumed by Pandas TA if there is no
{"kind": "indicator name"}attribute. Remember to check your spelling. - For examples, see the Pandas TA Study Examples Notebook.
Required Arguments
- 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 Arguments
- cores: The number of cores to use for multiprocessing the Study. Default:
multiprocessing.cpu_count() - 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
# The Default Study: ta.AllStudy
# The following are equivalent:
df.ta.study()
df.ta.study("All")
df.ta.study(ta.AllStudy)
# CommonStudy
df.ta.study(ta.CommonStudy)
Categorical
# List of indicator categories
df.ta.categories
# Categorical Study requires a Category name
df.ta.study("Momentum") # Default values for all Momentum indicators
# Override all Overlap 'length' attributes
df.ta.study("overlap", length=42)
Custom
# Help
help(df.ta.study)
# Create a Custom Study
MyStudy = ta.Study(
name="DCSMA10",
description="SMA 50,200, BBANDS, RSI, MACD and Volume SMA 20",
ta=[
{"kind": "ohlc4"},
{"kind": "sma", "length": 10},
{"kind": "donchian", "lower_length": 10, "upper_length": 15},
{"kind": "ema", "close": "OHLC4", "length": 10, "suffix": "OHLC4"},
]
)
# Run it
df.ta.study(MyStudy, **kwargs)
Back to Contents
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.
- Multiprocessing isn't free, it comes with the cost of spinning up a Multiprocessing Pool, so lowering or disabling the
corescan improve bulk processing.
# 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 arguments.
# 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)
Back to Contents
DataFrame Extension 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
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
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
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
Back to Contents
DataFrame Extension Methods
These are some additional methods available to the DataFrame Extension.
categories
# Returns a List of Pandas TA categories.
df.ta.categories()
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]))
datetime_ordered
# The 'datetime_ordered' method 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()
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)
reverse
# The 'reverse' method returns the DataFrame in reverse order.
df.ta.reverse()
sample
Used to generate Stochastic Samples.
# The 'sample' method returns a stochastic sample
df.ta.sample(**kwargs)
# For list of arguments, see:
help(ta.sample)
study
The heart of Pandas TA DataFrame Extension; formerly strategy. See the Pandas TA Study section for more details.
# The 'study' method returns the DataFrame in reverse order.
df.ta.study(**kwargs)
# For list of arguments, see:
help(ta.study)
ticker
Yahoo Finance
# Download Chart history using yfinance. (pip install yfinance)
# It uses the same keyword arguments as yfinance (excluding start and end)
# Note: It automatically sets the index to be a DatetimeIndex
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
assets = {f"{t}_D": ta.df.ta.ticker(t, period="1y", cores=0, study=s, timed=True, returns=True, ds="yf") for t in tickers}
print(assets.keys())
spydf = assets["SPY_D"]
# For more info
help(ta.yf)
Polygon
# Download Chart history from Polygon. (pip install polygon)
polygon_api_key = # Your Polygon API Key
df = df.ta.ticker("aapl", ds="polygon", api_key=polygon_api_key) # Default ticker is "SPY"
# For more info
help(ta.polygon_api)
to_utc
# Sets the DataFrame index to UTC format.
df.ta.to_utc()
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"])
Back to Contents
Cycles (2)
- Even Better Sinewave: ebsw
- Reflex: reflex
- trendflex companion
| Even Better Sinewave (EBSW) |
|---|
![]() |
Momentum (41)
- 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)
- A wrapper for
- 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
- 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
- Default is John Carter's. Enable Lazybear's with
- Squeeze Pro: squeeze_pro
- Stochastic Oscillator: stoch
- Fast Stochastic Oscillator: stochf
- Stochastic RSI: stochrsi
- TD Sequential: td_seq
- Excluded from
df.ta.study().
- Excluded from
- Trix: trix
- True strength index: tsi
- Ultimate Oscillator: uo
- Williams %R: willr
| Moving Average Convergence Divergence (MACD) |
|---|
![]() |
Back to Contents
Overlap (35)
- 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=Falsedrops the Chikou Span Column to prevent potential data leak.
- Returns two DataFrames. For more information:
- Jurik Moving Average: jma
- Kaufman's Adaptive Moving Average: kama
- Linear Regression: linreg
- Ehler's MESA Adaptive Moving Average: mama
- Includes: fama
- 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
- Weighted Closing Price: wcp
- Weighted Moving Average: wma
- Zero Lag Moving Average: zlma
| Exponential Moving Averages (EMA) and Donchian Channels (KC) |
|---|
![]() |
Back to Contents
Performance (3)
Use parameter: cumulative=True for cumulative results.
- Draw Down: drawdown
- Log Return: log_return
- Percent Return: percent_return
| Log Returns (Cumulative) with Exponential Moving Average (EMA) |
|---|
![]() |
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
| Standard Deviation (STDEV) |
|---|
![]() |
Back to Contents
Transform (3)
- Cube Transform: cube
- Inverse Fisher Transform: ifisher
- ReMap: remap
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=Falseto disable centering and remove potential data leak.
- Set
- 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) |
|---|
![]() |
Utility (5)
- Above: above
- Above Value: above_value
- Below: below
- Below Value: below_value
- Cross: cross
Back to Contents
Volatility (15)
- Aberration: aberration
- Acceleration Bands: accbands
- Average True Range: atr
- Average True Range Trailing Stop: atrts
- 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) |
|---|
![]() |
Volume (19)
- 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
- Percentage Volume Oscillator: pvo
- Price-Volume: pvol
- Price Volume Rank: pvr
- Price Volume Trend: pvt
- Volume Profile: vp
- Volume Weighted Average Price: vwap
- Requires the DataFrame index to be a DatetimeIndex
- Volume Weighted Moving Average: vwma
- Worden Brothers Time Segmented Value: wb_tsv
| On-Balance Volume (OBV) |
|---|
![]() |
Back to Contents
Backtesting
While Pandas TA is not a backtesting application, it does provide two trend methods that generate trading signals for backtesting purposes: Trend Signals (ta.tsignals()) and Cross Signals (ta.xsignals()). Both Signal methods return a DataFrame with columns for the signal's Trend, Trades, Entries and Exits.
A simple manual backtest using Trend Signals can be found in the TA Analysis Notebook starting at Trend Creation cell.
Trend Signals
- Useful for signals based on trends or states.
- Examples
- Golden Cross:
df.ta.sma(length=50) > df.ta.sma(length=200) - Positive MACD Histogram:
df.ta.macd().iloc[:,1] > 0
- Golden Cross:
Cross Signals
- Useful for Signal Crossings or events.
- Examples
- RSI crosses above 30 and then below 70
- ZSCORE crosses above -2 and then below 2.
Vector BT
Ideally a backtesting application like vectorbt should be used. For an example comparing a Buy and Hold Strategy versus a TA Signal Strategy, see: VectorBT Backtest with Pandas TA Notebook.
Trend Signal Example
import pandas_ta as ta
import vectorbt as vbt
# requires 'yfinance' installed
df = ta.df.ta.ticker("AAPL", timed=True)
# Create the "Golden Cross"
df["GC"] = df.ta.sma(50, append=True) > df.ta.sma(200, append=True)
# Create Trend Signals
golden = df.ta.tsignals(df.GC, asbool=True, append=True)
# 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())
Cross Signal Example
import pandas_ta as ta
import vectorbt as vbt
# requires 'yfinance' installed
df = ta.df.ta.ticker("AAPL", timed=True)
# Signal when RSI crosses above 30 and later below 70
rsi = df.ta.rsi(append=True)
# Create Cross Signals
rsi_long = ta.xsignals(rsi, 20, 80, above=True)
# Create the Signals Portfolio
pf = vbt.Portfolio.from_signals(df.Close, entries=rsi_long.TS_Entries, exits=rsi_long.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())
Back to Contents
BETA
Pandas TA also includes features: Stochastic Processes and Performance Metrics.
- 📈 Contributions are welcome to improve and stablize them.
Stochastic Samples
Need fake data? Pandas TA can utilize the stochastic package to Generate Sample Processes. For additional arguments and features, use help(ta.sample)
Brief Example
# pip install stochastic
# 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)
Back to Contents
Performance Metrics
Performance Metrics are a new addition to the package.These metrics return a float and are not part of the DataFrame Extension. They are called using the Standard Convention.
import pandas_ta as ta
result = ta.cagr(df.close)
# Help
help(ta.cagr)
Metrics
The current metrics include:
- 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
Back to Contents
TODO
| Status | Remaining TA Lib Indicators |
|---|---|
| ☐ | Indicators: ht_dcperiod, ht_dcphase, ht_phasor, ht_sine, ht_trendline, ht_trendmode |
| ☐ | Numpy/Numba-ify base indicators |
| Status | Config System |
|---|---|
| ☐ | Candlesticks |
| ☐ | DataFrame Extension property: config |
| ☐ | JSON Config File |
| ☐ JSON Config File Format |
| Status | Data Acquisition |
|---|---|
| ✔ | Yahoo Finance Default |
| ✔ | Polygon |
| ☐ | AlphaVantage |
| ☐ | Financial Modeling Prep |
| Status | Stabilize |
|---|---|
| ☐ | Trading Signals |
| ☐ Trend Signals | |
| ☐ Cross Signals | |
| ☐ | Performance Metrics |
| ✔ | Better argument validation |
Back to Contents
Sources
Technical Analysis
Original TA-LIB | TradingView | Sierra Chart | MQL5 | FM Labs | Pro Real Code | User 42 | Technical Traders
Supplemental
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Support
Like the package, want more indicators and features? Continued Support?
- Donations help cover data and API costs so platform indicators (like TradingView) are accurate.
- I appreciate ALL of those that have bought me Coffee/Beer/Wine et al. I greatly appreciate it! 😎
Consider
Back to Contents









