Pandas Technical Analysis (Pandas TA) is an easy to use library that is built upon Python's Pandas library with more than 100 Indicators. 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'].
Features
Has 100+ indicators and utility functions.
Option to use multiprocessing when using df.ta.strategy(). See below.
Example Jupyter Notebook under the examples directory.
A new 'ta' method called 'strategy' that be default, 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.
Above (above)
Above Value (above_value)
Below (below)
Below Value (below_value)
Cross Value (cross_value)
User Added Indicators:
Aberration (aberration)
BRAR (brar)
Corrected Indicators:
Absolute Price Oscillator (apo)
Aroon & Aroon Oscillator (aroon)
* Fixed indicator and included oscillator in returned dataframe
Bollinger Bands (bbands)
Commodity Channel Index (cci)
Chande Momentum Oscillator (cmo)
Relative Vigor Index (rvgi)
Symmetric Weighted Moving Average (swma)
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.
importpandasaspdimportpandas_taasta# Load datadf=pd.read_csv('symbol.csv', sep=',')
# Calculate Returns and append to the df DataFramedf.ta.log_return(cumulative=True, append=True)
df.ta.percent_return(cumulative=True, append=True)
# New Columns with resultsdf.columns# Take a peekdf.tail()
# vv Continue Post Processing vv
Module and Indicator Help
importpandasaspdimportpandas_taasta# Help about this, 'ta', extensionhelp(pd.DataFrame().ta)
# List of all indicatorspd.DataFrame().ta.indicators()
# Help about the log_return indicatorhelp(ta.log_return)
New DataFrame Method: strategy with Multiprocessing
Strategy is a new Pandas (TA) method 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 a ta.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 Falsedf.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. Though the# default will usually be bestdf.ta.strategy(cores=4)
# 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 theredf.columns
New DataFrame Properties: reverse & datetime_ordered
# The 'reverse' is a helper property that returns the DataFrame# in reverse orderdf=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 return Falsetime_series_in_order=df.ta.datetime_ordered
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 Nonedf.ta.adjusted=None
Technical Analysis Indicators (by Category)
Candles (2)
Doji: cdl_doji
Heikin-Ashi: ha
Momentum (27)
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)
Overlap (26)
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)
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)
Describe the bug
When trying to add all indicators (ta.AllStrategy) to my dataframe I get:
Traceback (most recent call last):
File "C:\Users\hanna\Anaconda3\lib\multiprocessing\pool.py", line 119, in worker
result = (True, func(*args, **kwds))
File "C:\Users\hanna\Anaconda3\lib\multiprocessing\pool.py", line 44, in mapstar
return list(map(*args))
File "C:\Users\hanna\Anaconda3\lib\site-packages\pandas_ta\core.py", line 467, in _mp_worker
return getattr(self, method)(*args, **kwargs)
File "C:\Users\hanna\Anaconda3\lib\site-packages\pandas_ta\core.py", line 874, in cdl_pattern
result = cdl_pattern(open_=open_, high=high, low=low, close=close, name=name, offset=offset, **kwargs)
File "C:\Users\hanna\Anaconda3\lib\site-packages\pandas_ta\candles\cdl_pattern.py", line 64, in cdl_pattern
pattern_result = Series(pattern_func(open_, high, low, close, **kwargs) / 100 * scalar)
File "_abstract.pxi", line 352, in talib._ta_lib.Function.__call__
File "_abstract.pxi", line 383, in talib._ta_lib.Function.__call_function
File "C:\Users\hanna\Anaconda3\lib\site-packages\talib\__init__.py", line 24, in wrapper
return func(*args, **kwargs)
TypeError: Argument 'open' has incorrect type (expected numpy.ndarray, got NoneType)
As you can see it is probably due to cdl_pattern error.
Describe the bug
A clear and concise description of what the bug is.
The value of PSAR seems incorrect (as compared to TradingView).
--
Pandas_ta for 2020-12-31
PSARs_0.02_0.2 = 377.265728
TradingView for 2020-12-31
PSAR = 363.67
To Reproduce
Provide sample code.
from pandas_datareader import data
from IPython.display import display, HTML
import pandas as pd
import datetime
import pandas_ta as ta
start = datetime.datetime(2020, 1, 1)
end = datetime.datetime.now()
ticker = "SPY"
df = data.DataReader(ticker,
start=start,
end=end,
data_source='yahoo')
df.ta.psar(append=True)
display(HTML(df.sort_index(ascending=False).to_html()))
Expected behavior
A clear and concise description of what you expected to happen.
The value of PSAR should be as close as possible to TradingView
Screenshots
If applicable, add screenshots to help explain your problem.
Additional context
Add any other context about the problem here.
Hi ,
Thanks for a beutiful peice of code, it helps a lot.
I was looking for a Standard deviation indicator . Please guide how I can only add standard deviation 1,2,3 on a daily chart.
Again thanks for a beutiful peice of package ..... Very very good job here ..
Which version are you running? The lastest version is on Github. Pip is for major releases.
version v0.2.75
Running Windows 10
Describe the bug
I just installed the version 0.2.75 from github by downloading the .zip file, then installed using pip3 install pandas-ta-master.zip
Received a notification that I didn't have 'wheels' installed so it used legacy method of install, but installation was successful.
But when I tried to add the library I get the error shown below.
I uninstalled pandas-ta, then I installed wheels. I then reinstalled pandas-ta successfully:
C:\Users\chuck\Downloads>pip3 install pandas-ta-master.zip
<snip>a bunch of installation details....</snip>
Successfully built pandas-ta
Installing collected packages: pandas-ta
Successfully installed pandas-ta-0.2.75b0
C:\Users\chuck\Downloads>
=== Below is the result of simply trying to import the library =====
>>> import pandas_ta as pta
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import pandas_ta as pta
File "C:\Users\chuck\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_ta\__init__.py", line 116, in <module>
from pandas_ta.core import *
File "C:\Users\chuck\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_ta\core.py", line 4, in <module>
from pandas_ta.candles.cdl_pattern import ALL_PATTERNS
File "C:\Users\chuck\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_ta\candles\__init__.py", line 2, in <module>
from .cdl_doji import cdl_doji
File "C:\Users\chuck\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_ta\candles\cdl_doji.py", line 2, in <module>
from pandas_ta.overlap import sma
File "C:\Users\chuck\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_ta\overlap\__init__.py", line 6, in <module>
from .hilo import hilo
File "C:\Users\chuck\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_ta\overlap\hilo.py", line 4, in <module>
from .ma import ma
File "C:\Users\chuck\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_ta\overlap\ma.py", line 8, in <module>
from .linreg import linreg
File "C:\Users\chuck\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_ta\overlap\linreg.py", line 6, in <module>
from numpy.lib.stride_tricks import sliding_window_view
ImportError: cannot import name 'sliding_window_view' from 'numpy.lib.stride_tricks' (C:\Users\chuck\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\lib\stride_tricks.py)
>>>
Specifying specific categories work (['candles', 'momentum', 'overlap', 'performance', 'statistics', 'trend', 'volatility', 'volume'])
These have no effect on the result:
dataframe.ta.mp = True
dataframe.ta.mp = False
Error:
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "/usr/lib/python3.8/multiprocessing/pool.py", line 125, in worker
result = (True, func(*args, **kwds))
File "/usr/lib/python3.8/multiprocessing/pool.py", line 48, in mapstar
return list(map(*args))
File "/opt/tradebot/freqtrade/.env/lib/python3.8/site-packages/pandas_ta/core.py", line 432, in _mp_worker
return getattr(self, method)(*args, **kwargs)
TypeError: crossed() got an unexpected keyword argument 'append'
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "./.env/lib/python3.8/site-packages/pandas_ta/core.py", line 682, in strategy
[self._post_process(r, **kwargs) for r in results]
File "./.env/lib/python3.8/site-packages/pandas_ta/core.py", line 682, in <listcomp>
[self._post_process(r, **kwargs) for r in results]
File "/usr/lib/python3.8/multiprocessing/pool.py", line 448, in <genexpr>
return (item for chunk in result for item in chunk)
File "/usr/lib/python3.8/multiprocessing/pool.py", line 868, in next
raise value
TypeError: crossed() got an unexpected keyword argument 'append'
To Reproduce
Download sample data and try the above examples.
Expected behavior
All indicators added to dataframe.
Thanks for using Pandas TA!
Thanks for a great TA library!
Hi,
I am using 3.7.13 python without using TA lib in windows10.
I have used ta.macd for a while without any issue, but suddenly an error msg pop-up. After upgrade to "pip install -U git+https://github.com/twopirllc/[email protected]", there was not any data display. It displayed a while yesterday and disappeared again....
my coding:
df.ta.macd(close=df['Close'], fast=12, slow=26, signal=9, append=True)
I've upgraded to the development branch and while trying some custom indicator I get:
import_dir(ta_dir)
File "/opt/homebrew/lib/python3.9/site-packages/pandas_ta/custom.py", line 198, in import_dir
bind(module_name, _callable, _method_callable)
TypeError: bind() takes 2 positional arguments but 3 were given
In custom.py something doesn't look right as here we call bind with 3 arguments:
Perhaps it's an ongoing work but just to let you know! Thanks!
PS: I'm trying to use (and debug) the new vwap indicator. On my side all bands have the same values, but not sure if something is wrong on my side yet. I'm a bit stuck because trying the new vwap on the main branch is missing some methods like [X] An error occurred when attempting to load module vwapro: No module named 'pandas_ta._typing'
In development version, sometime I am getting RuntimeWarning: invalid value encountered in sqrt after searching about it, I found there is a _ui value with negative and doing sqrt with negative result the error. I do not know why I am getting negative! I have revise the data of close. it looks normal and no negative in close
d2 is not negative, but _ui sometime is negative. to fix it in development, I have added _ui = _ui.abs()