Pandas Technical Analysis (Pandas TA) is an easy to use library that is built upon Python's Pandas library with more than 100 Indicators and Utility functions. These indicators are commonly used for financial time series datasets with columns or labels similar to: 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) and more.
This version contains both the orignal code branch as well as a newly refactored branch with the option to use Pandas DataFrame Extension mode. All the indicators 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'].
- Has 100+ indicators and utility functions.
- Option to use multiprocessing when using df.ta.strategy(). See below.
- 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.
- Abbreviated Indicator names as listed below.
- Extended Pandas DataFrame as 'ta'.
- Easily add prefixes or suffixes or both to columns names.
- Categories similar to TA-lib and tightly correlated with TA Lib in testing.
- 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.
- Improved the calculation performance of indicators: Exponential Moving Averagage and Weighted Moving Average.
- Removed internal core optimizations when running
df.ta.strategy('all')
with multiprocessing. See theta.strategy()
method for more details.
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.
$ pip install pandas_ta
$ pip install -U git+https://github.com/twopirllc/pandas-ta
import pandas as pd
import pandas_ta as ta
# Load data
df = pd.read_csv('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
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)
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.
- See the Pandas TA Strategy Examples Notebook for more Examples including Indicator Composition/Chaining.
- 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
- 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.
- A Strategy will fail when consumed by Pandas TA if there is no {"kind": "indicator name"} attribute. Remember to check your spelling.
# Builtin All Default Strategy
AllStrategy = Strategy(
name="All",
description="All the indicators with their default settings. Pandas TA default.",
ta=None
)
# Builtin Default (Example) Strategy.
CommonStrategy = 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"},
]
)
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.
- The
ta.strategy()
method is still under development. Future iterations will allow you to load ata.json
config file with your specific strategy name and parameters to automatically run you bulk indicators.
# This property only effects df.ta.strategy(). When set to True,
# it enables multiprocessing when processing "ALL" the indicators.
# Default is False
df.ta.mp = True
# Runs and appends all indicators to the current DataFrame by default
# The resultant DataFrame will be large.
df.ta.strategy()
# Or equivalently use name='all'
df.ta.strategy(name='all')
# 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)
# You can change the number of cores to use. The default is the the number of
# cpus you have. Not utilizing all your cores will result in quicker results.
# For instance if you have 4 CPUs, then cores=2 will be quicker.
df.ta.strategy(cores=2)
# 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 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(name="All")
df.ta.strategy()
# List of available categories
ta.categories
# Running a Categorical Strategy only requires the Category name
df.ta.strategy(name="Momentum") # Default values for all Momentum indicators
df.ta.strategy(name="overlap", length=27) # Override all 'length' attributes
# 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)
# Or pass in the name and ta atributes of the "Custom Strategy"
df.ta.strategy(name=CustomStrategy.name, ta=CustomStrategy.ta)
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"
# The 'reverse' is a helper property that returns the DataFrame
# in reverse order
df = df.ta.reverse
# 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
# 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
- Doji: cdl_doji
- Heikin-Ashi: ha
- 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
- Fisher Transform: fisher
- Inertia: inertia
- KDJ: kdj
- KST Oscillator: kst
- Moving Average Convergence Divergence: macd
- Momentum: mom
- 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
- Stochastic Oscillator: stoch
- Trix: trix
- True strength index: tsi
- Ultimate Oscillator: uo
- Williams %R: willr
Moving Average Convergence Divergence (MACD) |
---|
- Double Exponential Moving Average: dema
- Exponential Moving Average: ema
- Fibonacci's Weighted Moving Average: fwma
- 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) |
---|
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) |
---|
- Entropy: entropy
- Kurtosis: kurtosis
- Mean Absolute Deviation: mad
- Median: median
- Quantile: quantile
- Skew: skew
- Standard Deviation: stdev
- Variance: variance
- Z Score: zscore
Z Score |
---|
- 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
- Vortex: vortex
Average Directional Movement Index (ADX) |
---|
- Above: above
- Above Value: above_value
- Below: below
- Below Value: below_value
- Cross: cross
- 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
Average True Range (ATR) |
---|
- 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) |
---|
- TradingView: http://www.tradingview.com
- Original TA-LIB: http://ta-lib.org/
Please leave any comments, feedback, suggestions, or indicator requests.