Pandas Technical Analysis (Pandas TA) is an easy to use library that leverages the Pandas library with more than 120 Indicators and Utility functions. 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.
The pip
version is the last most stable release.
$ pip install pandas_ta
Best choice!
$ pip install -U git+https://github.com/twopirllc/pandas-ta
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
import pandas as pd
import pandas_ta as ta
# Load data
df = pd.read_csv("path/to/symbol.csv", sep=",")
# 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
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 the log_return indicator
help(ta.log_return)
Thanks for using Pandas TA!
$ pip install -U git+https://github.com/twopirllc/pandas-ta
Thank you for your contributions!
alexonab | allahyarzadeh | codesutras | daikts | DrPaprikaa | FGU1 | lluissalord | maxdignan | NkosenhleDuma | pbrumblay | RajeshDhalange | rengel8 | rluong003 | SoftDevDanial | tg12 | twrobel | whubsch | YuvalWein
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 Strategy. 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 Strategy 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.
You explicitly define the input columns and take care of the output.
sma10 = ta.sma(df["Close"], length=10)
SMA_10
donchiandf = ta.donchian(df["HIGH"], df["low"], lower_length=10, upper_length=15)
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)
EMA_10
. If needed, you may need to uniquely name it.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)
SMA_10
ema10_ohlc4 = df.ta.ema(close=df.ta.ohlc4(), length=10, suffix="OHLC4")
EMA_10_OHLC4
close=df.ta.ohlc4()
.donchiandf = df.ta.donchian(lower_length=10, upper_length=15)
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)
df
column name: SMA_10
.df.ta.ema(close=df.ta.ohlc4(append=True), length=10, suffix="OHLC4", append=True)
close=df.ta.ohlc4()
.df.ta.donchian(lower_length=10, upper_length=15, append=True)
df
with column names: DCL_10_15, DCM_10_15, DCU_10_15
.A Pandas TA Strategy is a named group of indicators to be run by the strategy method. All Strategies use mulitprocessing except when using the col_names
parameter (see below). There are different types of Strategies listed in the following section.
# (1) Create the Strategy
MyStrategy = ta.Strategy(
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 Strategy
df.ta.strategy(MyStrategy, **kwargs)
The Strategy 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 Strategies to help you get started: AllStrategy and CommonStrategy. A Strategy can be as simple as the CommonStrategy or as complex as needed using Composition/Chaining.
df
.See the Pandas TA Strategy Examples Notebook for examples including Indicator Composition/Chaining.
{"kind": "indicator name"}
attribute. Remember to check your spelling.# 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()
df.ta.strategy("All")
df.ta.strategy(ta.AllStrategy)
# 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=42) # Override all Overlap '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)
The Pandas TA strategy method utilizes multiprocessing for bulk indicator processing of all Strategy 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.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)
# Choose the number of cores to use. Default is all available cores.
df.ta.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 there
df.columns
Remember These will not be utilizing multiprocessing
NonMPStrategy = ta.Strategy(
name="EMAs, BBs, and MACD",
description="Non Multiprocessing Strategy 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.strategy(NonMPStrategy)
# 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
# List of Pandas TA categories.
df.ta.categories
# 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
# 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
# The 'reverse' is a helper property that returns the DataFrame
# in reverse order.
df.ta.reverse
# 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"
lazybear=True
Moving Average Convergence Divergence (MACD) |
---|
Simple Moving Averages (SMA) and Bollinger Bands (BBANDS) |
---|
Use parameter: cumulative=True for cumulative results.
Percent Return (Cumulative) with Simple Moving Average (SMA) |
---|
Z Score |
---|
centered=False
to remove potential data leak.Average Directional Movement Index (ADX) |
---|
Average True Range (ATR) |
---|
On-Balance Volume (OBV) |
---|
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)
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)
to_utc
, to convert the DataFrame index to UTC. See: help(ta.to_utc)
help(ta.bbands)
help(ta.drawdown)
help(ta.hilo)
help(ta.mcgd)
help(ta.pvr)
help(ta.qqe)
article in the June, 1994 issue of Technical Analysis of Stocks & Commodities Magazine. See: help(ta.pvr)
help(ta.rsx)
help(ta.ssf)
help(ta.thermo)
help(ta.ttm_trend)
help(ta.vidya)
mamode
is now "RMA" and with the same mamode
options as TradingView. See help(ta.atr)
.strict
checks if the series is continuously decreasing over period length
. Default: False
. See help(ta.decreasing)
.strict
checks if the series is continuously increasing over period length
. Default: False
. See help(ta.increasing)
.anchor
. Default: "D" for "Daily". See Timeseries Offset Aliases for additional options. Requires the DataFrame index to be a DatetimeIndex此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。