Technical Analysis Indicators - Pandas TA is an easy to use Python 3 Pandas Extension with 130+ Indicators

Overview

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 130 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

  • Has 130+ indicators and utility functions.
    • BETA Also Pandas TA will run TA Lib's version, this includes TA Lib's 63 Chart Patterns.
  • Indicators in Python are tightly correlated with the de facto TA Lib if they share common indicators.
  • If TA Lib is also installed, TA Lib computations are enabled by default but can be disabled disabled per indicator by using the argument talib=False.
    • For instance to disable TA Lib calculation for stdev: ta.stdev(df["close"], length=30, talib=False).
  • NEW! Include External Custom Indicators independent of the builtin Pandas TA indicators. For more information, see import_dir documentation under /pandas_ta/custom.py.
  • Example Jupyter Notebook with vectorbt Portfolio Backtesting with Pandas TA's ta.tsignals method.
  • Have the need for speed? By using the DataFrame strategy method, you get multiprocessing for free! Conditions permitting.
  • Easily add prefixes or suffixes or both to columns names. Useful for Custom Chained Strategies.
  • Example Jupyter Notebooks under the examples directory, including how to create Custom Strategies using the new Strategy Class
  • Potential Data Leaks: dpo and ichimoku. See indicator list below for details. Set lookahead=False to disable.

Under Development

Pandas TA checks if the user has some common trading packages installed including but not limited to: TA Lib, Vector BT, YFinance ... Much of which is experimental and likely to break until it stabilizes more.

  • If TA Lib installed, existing indicators will eventually get a TA Lib version.
  • Easy Downloading of ohlcv data using yfinance. See help(ta.ticker) and help(ta.yf) 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.14b

  • 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/[email protected]

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 Strategies with the Strategy 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?
    • You will be asked to fill out an Issue even if you email my personally.

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 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.


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 Strategy

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.


Here are the previous Styles implemented using a Strategy Class:

# (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)



Pandas TA Strategies

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.

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

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

Strategy 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 Strategy 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 Strategy tries to capture. Default: None
  • created: At datetime string of when it was created. Default: Automatically generated.

Types of Strategies

Builtin

# 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)

Categorical

# 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

Custom

# 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)

Multiprocessing

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.
# 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.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

Custom Strategy without Multiprocessing

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)



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 strategy 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

exchange

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

# Set the Exchange to use.
# 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

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
import numpy as np
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

# 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

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



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 (This is the default behaviour)
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 (1)

  • 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)
  • 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
  • Stochastic RSI: stochrsi
  • TD Sequential: td_seq
    • Excluded from df.ta.strategy().
  • Trix: trix
  • True strength index: tsi
  • Ultimate Oscillator: uo
  • Williams %R: willr
Moving Average Convergence Divergence (MACD)
Example MACD

Overlap (33)

  • 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
  • Ehler's Super Smoother Filter: ssf
  • 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 (18)

  • 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
  • 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 (15)

  • 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
On-Balance Volume (OBV)
Example OBV



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

Backtesting with vectorbt

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.


Brief example

  • See the vectorbt website more options and examples.
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())



Changes

General

  • A Strategy 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 Strategy 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

  • 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)

New Indicators

  • Arnaud Legoux Moving Average (alma) uses the curve of the Normal (Gauss) distribution to allow regulating the smoothness and high sensitivity of the indicator. See: help(ta.alma) trading account, or fund. See help(ta.drawdown)
  • Candle Patterns (cdl_pattern) If TA Lib is installed, then all those Candle Patterns are available. See the list and examples above on how to call the patterns. See help(ta.cdl_pattern)
  • Candle Z Score (cdl_z) normalizes OHLC Candles with a rolling Z Score. See help(ta.cdl_z)
  • Correlation Trend Indicator (cti) is an oscillator created by John Ehler in 2020. See help(ta.cti)
  • Cross Signals (xsignals) was created by Kevin Johnson. It is a wrapper of Trade Signals 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)
  • Even Better Sinewave (ebsw) measures market cycles and uses a low pass filter to remove noise. See: help(ta.ebsw)
  • Jurik Moving Average (jma) attempts to eliminate noise to see the "true" underlying activity.. See: help(ta.jma)
  • Klinger Volume Oscillator (kvo) was developed by Stephen J. Klinger. It is designed to predict price reversals in a market by comparing volume to price.. See help(ta.kvo)
  • Schaff Trend Cycle (stc) is an evolution of the popular MACD incorportating two cascaded stochastic calculations with additional smoothing. See help(ta.stc)
  • 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.strategy() 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)
  • Vertical Horizontal Filter (vhf) was created by Adam White to identify trending and ranging markets.. See help(ta.vhf)

Updated Indicators

  • Acceleration Bands (accbands) Argument mamode renamed to mode. See help(ta.accbands).
  • ADX (adx): Added mamode with default "RMA" and with the same mamode options as TradingView. New argument lensig so it behaves like TradingView's builtin ADX indicator. See help(ta.adx).
  • Archer Moving Averages Trends (amat): Added drift argument and more descriptive column names.
  • Average True Range (atr): The default mamode is now "RMA" and with the same mamode options as TradingView. See help(ta.atr).
  • Bollinger Bands (bbands): New argument ddoff to control the Degrees of Freedom. Also included BB Percent (BBP) as the final column. Default is 0. See help(ta.bbands).
  • Choppiness Index (chop): New argument ln to use Natural Logarithm (True) instead of the Standard Logarithm (False). Default is False. See help(ta.chop).
  • Chande Kroll Stop (cksp): Added tvmode with default True. When tvmode=False, cksp implements “The New Technical Trader” with default values. See help(ta.cksp).
  • Chande Momentum Oscillator (cmo): New argument talib will use TA Lib's version and if TA Lib is installed. Default is True. See help(ta.cmo).
  • Decreasing (decreasing): New argument strict checks if the series is continuously decreasing over period length with a faster calculation. Default: False. The percent argument has also been added with default None. See help(ta.decreasing).
  • Increasing (increasing): New argument strict checks if the series is continuously increasing over period length with a faster calculation. Default: False. The percent argument has also been added with default None. See help(ta.increasing).
  • Klinger Volume Oscillator (kvo): Implements TradingView's Klinger Volume Oscillator version. See help(ta.kvo).
  • 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.
  • Moving Average Convergence Divergence (macd): New argument asmode enables AS version of MACD. Default is False. See help(ta.macd).
  • Parabolic Stop and Reverse (psar): Bug fix and adjustment to match TradingView's sar. New argument af0 to initialize the Acceleration Factor. See help(ta.psar).
  • Percentage Price Oscillator (ppo): Included new argument mamode as an option. Default is sma to match TA Lib. See help(ta.ppo).
  • True Strength Index (tsi): Added signal with default 13 and Signal MA Mode mamode with default ema as arguments. See help(ta.tsi).
  • Volume Profile (vp): Calculation improvements. See Pull Request #320 See help(ta.vp).
  • Volume Weighted Moving Average (vwma): Fixed bug in DataFrame Extension call. See help(ta.vwma).
  • Volume Weighted Average Price (vwap): Added a new parameter called anchor. Default: "D" for "Daily". See Timeseries Offset Aliases for additional options. Requires the DataFrame index to be a DatetimeIndex. See help(ta.vwap).
  • Volume Weighted Moving Average (vwma): Fixed bug in DataFrame Extension call. See help(ta.vwma).
  • Z Score (zscore): Changed return column name from Z_length to ZS_length. See help(ta.zscore).

Sources

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


Support

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

Consider

"Buy Me A Coffee"

Comments
  • Problem with strategy (all)

    Problem with strategy (all)

    Which version are you running? The lastest version is on Github. Pip is for major releases.

    import pandas_ta as ta
    print(ta.version)
    

    0.3.14b0

    Do you have TA Lib also installed in your environment?

    $ pip list
    

    Yes TA-Lib 0.4.17

    Upgrade.

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

    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.

    When I switch to ta.CommonStrategy I get:

    Index(['open', 'high', 'low', 'close', 'volume', 'SMA_10', 'SMA_20', 'SMA_50', 'SMA_200', 'VOL_SMA_20'],

    I get 6 indicators(sma) added to my dataframe. Is this the expected behavior? Only 6 common indicators?

    question wontfix info 
    opened by hn2 26
  • PSAR indicator - Incorrect value

    PSAR indicator - Incorrect value

    Which version are you running? The lastest version is on Github. Pip is for major releases.

    import pandas_ta as ta
    print(ta.version)
    

    0.2.28b0

    Upgrade.

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

    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.

    Thanks for using Pandas TA!

    bug help wanted 
    opened by mtvu 23
  • NameError: name 'watchlist' is not defined

    NameError: name 'watchlist' is not defined

    NameError: name 'watchlist' is not defined Which version are you running? The lastest version is on Github. Pip is for major releases.

    import pandas_ta as ta
    print(ta.version)
    

    Upgrade.

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

    Describe the bug A clear and concise description of what the bug is.

    To Reproduce Provide sample code.

    Expected behavior A clear and concise description of what you expected to happen.

    Screenshots If applicable, add screenshots to help explain your problem.

    Additional context Add any other context about the problem here.

    Thanks for using Pandas TA!

    question info 
    opened by ravijvora 23
  • Standard Deviation feature request

    Standard Deviation feature request

    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 ..

    Thanks, Manoj

    info 
    opened by manojjenago 21
  • Numpy ImportError: cannot import name 'sliding_window_view' from 'numpy.lib.stride_tricks'

    Numpy ImportError: cannot import name 'sliding_window_view' from 'numpy.lib.stride_tricks'

    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)
    >>> 
    
    duplicate info 
    opened by ctilly 18
  • Error with df.ta.strategy(

    Error with df.ta.strategy("All")

    Which version are you running? The lastest version is on Github. Pip is for major releases.

    Python: 3.8.6
    pandas-ta: 0.2.23b0
    

    Upgrade.

    done
    

    Describe the bug A clear and concise description of what the bug is.

    These examples fails on the latest version:

    The Default Strategy is the ta.AllStrategy. The following are equivalent:

    df.ta.strategy() df.ta.strategy("All") df.ta.strategy(ta.AllStrategy)

    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!

    help wanted info 
    opened by Fredrik81 18
  • Pandas TA strategy method goes into infinite loop: Windows Freeze Support Error

    Pandas TA strategy method goes into infinite loop: Windows Freeze Support Error

    @twopirllc I was trying to run the below code on a dataframe

    df.ta.strategy("Momentum")
    print(df)
    

    It goes into infinite loop and consumes all CPU on my windows 10 laptop. Then I need to kill all VSCodium and python exes. Could you please help?

    Originally posted by @rahulmr in https://github.com/twopirllc/pandas-ta/issues/138#issuecomment-751864255

    question info 
    opened by twopirllc 18
  • Issues with MACD Calculations

    Issues with MACD Calculations

    Which version are you running? The lastest version is on Github. Pip is for major releases.

    import pandas_ta as ta
    print(ta.version)
    

    0.3.14b0

    Do you have TA Lib also installed in your environment?

    $ pip list
    
    Package                       Version
    ---------------------------------------
    alpaca-trade-api              1.4.3
    dataclasses                   0.8
    graphviz                      0.19.1
    ipykernel                     6.7.0
    ipython                       8.0.0
    ipython-genutils              0.2.0
    joblib                        1.1.0
    jsonschema                    4.4.0
    jupyter-client                7.1.1
    jupyter-core                  4.9.1
    jupyterlab-pygments           0.1.2
    matplotlib                    3.5.1
    matplotlib-inline             0.1.3
    numpy                         1.22.1
    pandas                        1.3.5
    pandas-datareader             0.10.0
    pandas-ta                     0.3.14b0
    requests                      2.27.1
    scikit-learn                  1.0.2
    scipy                         1.7.3
    seaborn                       0.11.2
    setuptools                    60.5.0
    six                           1.16.0
    sklearn                       0.0
    

    Did you upgrade? Did the upgrade resolve the issue?

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

    I upgraded..

    Describe the bug The bug is probably me... but it doesn't make sense. I'm using the same data which I will provide, I hope via attachment. The code is simple -

    # get data from Alpaca - SIP feed and calc MACD, MACDs
    symbol='SQQQ'
    mdf = api.get_bars(symbol, TimeFrame(30, TimeFrameUnit.Minute), "2022-02-14", "2022-02-15", adjustment='raw').df
    mdf.ta.macd(append=True)
    

    When I do this. the values for 2-15 15:00 are Negative. 13:00 to 15:00 Rising. But SQQQ was running up into 13:00 and then reversed Down at 14:00. So my computation is the complete opposite.? I have it negative going to positive instead of positive going to negative.

    A clear and concise description of what the bug is.

    To Reproduce

    Provide sample code. Sample code above.

    Expected behavior I did verify the data in the Alpaca produced chart is the same as the data I'm using.

    Screenshots image

    Additional context Data csv below

    Thanks for using Pandas TA!

    bug 
    opened by schwaa 17
  • Elders Thermometer Indicator

    Elders Thermometer Indicator

    Which version are you running? The lastest version is on Github. Pip is for major releases.

    import pandas_ta as ta
    print(ta.version)
    

    Version 0.2.01b

    Upgrade.

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

    Is your feature request related to a problem? Please describe. No

    Describe the solution you'd like Elders Thermometer Psuedocode Elders Thermometer by LazyBear MQL5 Description

    Describe alternatives you've considered None at this time

    Additional context None

    Thanks for using Pandas TA! 😎

    enhancement good first issue 
    opened by twopirllc 17
  • custom ta.Strategy does not work when df.ta.mp = True

    custom ta.Strategy does not work when df.ta.mp = True

    If we create a custom strategy like this one: custom_a = ta.Strategy(name="A", ta=[{"kind": "sma", "length": 50}, {"kind": "sma", "length": 200}]) and call df.ta.mp = True df.ta.strategy(custom_a, cores=3)

    Indicators are not added.

    enhancement 
    opened by umit77 17
  • Parameters in strategy()'s ta

    Parameters in strategy()'s ta

    Hi @twopirllc,

    I'm playing with the new improved strategy() method, it's quite an improvement nice work ! You should push it to pip ;)

    In my workflow, I'm computing a bunch of data on the indicators and then select the relevant ones. However, I don't know a priori which ones nor their parameters, and they are not always the same.

    Since all the indictors don't have the same number of parameters, they would be passed as a list of floats, instead of their explicit names. For example :

    CustomStrategy = ta.Strategy(name="MyStrat",
    	                     ta=[{'kind':'sma',    'params':[30]}, 
                                     {'kind':'bbands', 'params':[20,2]}},
                                     {'kind':'macd',   'params':[8,21]}, 
                                    ],
    	                     )
    

    This way, the code would be more modular. Is it possible to implement that ?

    enhancement 
    opened by DrPaprikaa 16
  • Streaming API

    Streaming API

    Which version are you running? The lastest version is on Github. Pip is for major releases.

    import pandas_ta as ta
    print(ta.version)
    

    0.4.14b0

    Do you have TA Lib also installed in your environment?

    $ pip list
    

    yes

    Upgrade.

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

    Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] I find it frustrating to recalculate a techincal indicator for the entire data set for every new data point when operating in a real-time setting.

    Describe the solution you'd like A clear and concise description of what you want to happen. Currently if you are using this library for streaming data, real time updates require you to append the data to your dataframe and calculate the technical indicator for the entire history. It would be nice to have a streaming API that allows you to give just the latest piece of data and get the updated value for the technical indicator.

    For example, let's say you have 100,000 rows of data and you are calculating the 200 EMA. For backtesting, you can just calculate the 200 EMA for every row and move forward with your back test. With the streaming API feature, if you had the 100,001st data point, you would need to append it to your historical data and then calculate the 200 EMA for every data point, which is slow and redundant.

    Similar to this: https://github.com/mrjbq7/ta-lib#streaming-api

    Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered. I've considered only keeping X number of historic data points so recalculating the newest technical indicator value is fast but this is a pain to implement.

    Additional context Add any other context or screenshots about the feature request here. I'm a software engineer and would be happy to help build this with others. I'm curious if there is much interest out there for this feature though before putting in a bunch of work to pull it off.

    Thanks for using Pandas TA!

    enhancement 
    opened by michaelto20 0
  • One test fails: tests/test_strategy.py:199: AssertionError

    One test fails: tests/test_strategy.py:199: AssertionError

    Which version are you running? The lastest version is on Github. Pip is for major releases. 0.3.14

    ========================================================================================== FAILURES ==========================================================================================
    _____________________________________________________________________________ TestStrategyMethods.test_custom_a ______________________________________________________________________________
    
    self = <tests.test_strategy.TestStrategyMethods testMethod=test_custom_a>
    
        def test_custom_a(self):
            self.category = "Custom E"
        
            amat_logret_ta = [
                {"kind": "amat", "fast": 20, "slow": 50 },  # 2
                {"kind": "log_return", "cumulative": True},  # 1
                {"kind": "ema", "close": "CUMLOGRET_1", "length": 5} # 1
            ]
        
            custom = pandas_ta.Strategy(
                "AMAT Log Returns",  # name
                amat_logret_ta,  # ta
                "AMAT Log Returns",  # description
            )
            self.data.ta.strategy(custom, verbose=verbose, timed=strategy_timed, ordered=True)
            self.data.ta.tsignals(trend=self.data["AMATe_LR_20_50_2"], append=True)
    >       self.assertEqual(len(self.data.columns), 13)
    E       AssertionError: 101 != 13
    
    tests/test_strategy.py:199: AssertionError
    ====================================================================================== warnings summary ======================================================================================
    pandas_ta/utils/_core.py:14
      /usr/ports/finance/py-pandas-ta/work-py39/pandas-ta-0.3.14/pandas_ta/utils/_core.py:14: DeprecationWarning: invalid escape sequence \g
        return re_.sub("([a-z])([A-Z])","\g<1> \g<2>", x).title()
    
    ../../../../../local/lib/python3.9/site-packages/pytest_freezegun.py:17: 706 warnings
      /usr/local/lib/python3.9/site-packages/pytest_freezegun.py:17: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead.
        if LooseVersion(pytest.__version__) < LooseVersion('3.6.0'):
    
    tests/test_ext_indicator_overlap_ext.py::TestOverlapExtension::test_mcgd_ext
    tests/test_strategy.py::TestStrategyMethods::test_all_no_multiprocessing
    tests/test_indicator_overlap.py::TestOverlap::test_mcgd
      /usr/ports/finance/py-pandas-ta/work-py39/pandas-ta-0.3.14/pandas_ta/overlap/mcgd.py:24: FutureWarning: The series.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
        mcg_ds = close[:1].append(mcg_cell[1:])
    
    -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
    ================================================================================== short test summary info ===================================================================================
    SKIPPED [1] tests/test_indicator_momentum.py:487: Skipped
    SKIPPED [1] tests/test_strategy.py:89: verbose mode only
    SKIPPED [1] tests/test_strategy.py:85: verbose mode only
    SKIPPED [1] tests/test_utils.py:152: Skipped
    SKIPPED [1] tests/test_utils.py:57: Skipped
    SKIPPED [1] tests/test_utils.py:156: Skipped
    SKIPPED [1] tests/test_utils.py:160: Skipped
    SKIPPED [1] tests/test_ext_indicator_momentum.py:231: Skipped
    ============================================================= 1 failed, 344 passed, 8 skipped, 710 warnings in 143.67s (0:02:23) =============================================================
    

    Python-3.9 FreeBSD 13.1

    bug 
    opened by yurivict 0
  • Difference in EMA values between pandas-ta and tradingview

    Difference in EMA values between pandas-ta and tradingview

    Which version are you running? The lastest version is on Github. Pip is for major releases. 0.3.14b0

    Do you have TA Lib also installed in your environment? Yes

    Have you tried the development version? Did it resolve the issue? No

    Describe the bug I am trying to calculate 200 days ema but the ema from ta is way off.

    To Reproduce

    import yfinance as yf
    import pandas_ta as ta
    
    x = yf.download('ABB.NS', start = "2021-12-08", progress = False)['Close']
    
    ema= ta.ema(x, 200)[-1]
    

    Expected behavior expected 200 days ema = 2720.93

    Additional context 20 days and 50 days ema are matching with TradingView but not 100 and 200 days.

    I tried to use help(ta.ema) but not sure which number to use for the offset argument

    bug info 
    opened by thecpshah 3
  • CMO (Chande Momentum Oscillator) calculation

    CMO (Chande Momentum Oscillator) calculation

    Original CMO explanation from Chande's book: 206595953-ab02f2ce-514e-4941-a711-76298c174bf4 206595986-af72ad1e-f8a1-4786-bf6c-b17d3f82aa73

    To Reproduce

    df = ta.DataFrame({'close': [101.0313, 101.125, 101.9687, 102.7813, 103, 102.9687, 103.0625, 102.9375, 102.7188, 102.75, 102.9063, 102.9687 ]})
    df['cmo'] = ta.cmo(close = ff['close'], length=10)
    df
    

    Expected behavior This should generate THREE cmo values - for the last three rows of data, equivalent to what is in the book. Instead, we get:

    close   | cmo
    101.031 | NaN
    101.125 | NaN
    101.969 | NaN
    102.781 | NaN
    103.000 | NaN
    102.969 | NaN
    103.062 | NaN
    102.938 | NaN
    102.719 | NaN
    102.750 | NaN
    102.906 | 60.091
    102.969 | 61.928
    

    Remark: TA-LIB also mis-calculates CMO and returns different results from the book (and different results from Pandas-TA)...

    bug enhancement help wanted good first issue 
    opened by mihakralj 2
  • Most of the indicators returns NaN.

    Most of the indicators returns NaN.

    Pandas_ta version: 0.3.14b0 Python version: Python 3.8.10 Ta-Lib is installed. Ta-Lib version: 0.4.24

    Most of the indicators return Nan. Only a few indicators work.

    import numpy as np
    import pandas as pd
    import pandas_ta as ta
    
    data=np.genfromtxt("b15.csv",delimiter=",")
    df=pd.DataFrame(data,columns=["Time","Open","High","Low","Close","Volume"])
    e=ta.momentum.macd(close=df["Close"])
    print(e)
    
                                MACD_12_26_9  MACDh_12_26_9  MACDs_12_26_9
    Time                                                                  
    1970-01-01 00:26:17.836800           NaN            NaN            NaN
    1970-01-01 00:26:17.837700           NaN            NaN            NaN
    1970-01-01 00:26:17.838600           NaN            NaN            NaN
    1970-01-01 00:26:17.839500           NaN            NaN            NaN
    1970-01-01 00:26:17.840400           NaN            NaN            NaN
    ...                                  ...            ...            ...
    1970-01-01 00:27:47.256300           NaN            NaN            NaN
    1970-01-01 00:27:47.257200           NaN            NaN            NaN
    1970-01-01 00:27:47.258100           NaN            NaN            NaN
    1970-01-01 00:27:47.259000           NaN            NaN            NaN
    1970-01-01 00:27:47.259900           NaN            NaN            NaN
    
    [98980 rows x 3 columns]
    

    Vortex works:

    e=ta.trend.vortex(close=df["Close"],high=df["High"],low=df["Low"])
    print(e)
    
                                 VTXP_14   VTXM_14
    Time                                          
    1970-01-01 00:26:17.836800       NaN       NaN
    1970-01-01 00:26:17.837700       NaN       NaN
    1970-01-01 00:26:17.838600       NaN       NaN
    1970-01-01 00:26:17.839500       NaN       NaN
    1970-01-01 00:26:17.840400       NaN       NaN
    ...                              ...       ...
    1970-01-01 00:27:47.256300  1.157145  0.864892
    1970-01-01 00:27:47.257200  1.152978  0.886676
    1970-01-01 00:27:47.258100  1.184268  0.856069
    1970-01-01 00:27:47.259000  1.219873  0.828368
    1970-01-01 00:27:47.259900  1.238993  0.761392
    
    [98980 rows x 2 columns]
    
    
    good first issue info 
    opened by benimadimkadir 5
  • Wrong/Missing output of PVI Positive Volume Index

    Wrong/Missing output of PVI Positive Volume Index

    Which version are you running? The lastest version is on Github. Pip is for major releases.

    0.3.79b0
    

    Do you have TA Lib also installed in your environment?

    0.4.25
    

    Have you tried the development version? Did it resolve the issue?

    It didn't
    

    Describe the bug

    By definition, Positive Volume Index should return two things: PVT and 255 MA of PVT. It produces only a single value and that is too wrong.

    To Reproduce

    import pandas as pd
    import pandas_ta as ta
    
    df = pd.DataFrame() # Empty DataFrame
    
    # Load data
    # OR if you have yfinance installed
    df = df.ta.ticker("aapl")
    
    
    # New Columns with results
    df.ta.pvi(append=True);
    
    # Take a peek
    print(df.tail())
    
    
    // Output 
                                     Open        High         Low       Close     Volume  Dividends  Stock Splits        PVI_1
    Date                                                                                                                      
    2022-11-25 00:00:00-05:00  148.309998  148.880005  147.119995  148.110001   35195900        0.0           0.0  1966.006190
    2022-11-28 00:00:00-05:00  145.139999  146.639999  143.380005  144.220001   69246000        0.0           0.0  1963.379764
    2022-11-29 00:00:00-05:00  144.289993  144.809998  140.350006  141.169998   83763800        0.0           0.0  1961.264938
    2022-11-30 00:00:00-05:00  141.399994  148.720001  140.550003  148.029999  111224400        0.0           0.0  1966.124328
    2022-12-01 00:00:00-05:00  148.210007  149.130005  146.615005  148.309998   71250416        0.0           0.0  1966.124328
    

    Expected behavior

    There should be two values PVI_1 and PVI_SIGNAL_1 (or whatever like PVI_255_S_1)

                                     Open        High         Low       Close     Volume  Dividends  Stock Splits        PVI_1        PVT_SIGNAL_1
    Date 
    ...
               
    2022-11-29 00:00:00-05:00  144.289993  144.809998  140.350006  141.169998   83763800        0.0           0.0  931.75          941.01
    2022-11-30 00:00:00-05:00  141.399994  148.720001  140.550003  148.029999  111224400        0.0           0.0  936.61          940.97
    2022-12-01 00:00:00-05:00  148.210007  149.130005  146.615005  148.309998   71250416        0.0           0.0  936.61          940.94
    

    This is the definition https://www.investopedia.com/terms/p/pvi.asp

    Probable solution?

    I also found a probable solution https://github.com/voice32/stock_market_indicators/blob/master/indicators.py#L457

    My experience in python is not so much like in days not weeks - I copied and paste the codes but it looks like df it expects is kind of outdated. Although, the formula matches, it has an "if" conditions depending on if current volume is > the previous volume. It also has 255 written. So my hopes are high it will work.

    Screenshots

    image

    Additional context

    You can use TradingView chart as shown above to see correct output.

    Thanks for using Pandas TA!

    bug help wanted good first issue 
    opened by VarunBatraIT 1
Releases(0.3.14)
  • 0.3.14(Jul 28, 2021)

    New:

    • Include External Custom Indicators independent of builtin Pandas TA indicators.
    • Jurik MA indicator included.

    Updated:

    • Google Colab numpy dependencies differences fix #285.
    • TA Lib integration improvements.
    • Enable/Disable TA Lib functions with talib argument. See indicator help().

    Other:

    • Misc. Refactoring.
    Source code(tar.gz)
    Source code(zip)
  • v0.3.02(Jul 2, 2021)

    Updated:

    • Added tos_stdevall indicator
    • Volume Profile vp Improvements

    Other:

    • Minor Refactoring
    • Accepts a string for a single column when using 'col_names'
    Source code(tar.gz)
    Source code(zip)
  • v0.2.93(Jun 20, 2021)

  • v0.2.86(May 30, 2021)

  • v0.2.83(May 27, 2021)

    Added:

    • Users get TA Lib speeds if TA Lib is installed. (Most but not all TA Lib indicators are included)

    Other:

    • Updated Notebooks
    • Refactoring
    Source code(tar.gz)
    Source code(zip)
[CVPR 2021] Involution: Inverting the Inherence of Convolution for Visual Recognition, a brand new neural operator

involution Official implementation of a neural operator as described in Involution: Inverting the Inherence of Convolution for Visual Recognition (CVP

Duo Li 1.3k Dec 28, 2022
level1-image-classification-level1-recsys-09 created by GitHub Classroom

level1-image-classification-level1-recsys-09 ❗ 주제 설명 COVID-19 Pandemic 상황 속 마스크 착용 유무 판단 시스템 구축 마스크 착용 여부, 성별, 나이 총 세가지 기준에 따라 총 18개의 class로 구분하는 모델 ?

6 Mar 17, 2022
the official implementation of the paper "Isometric Multi-Shape Matching" (CVPR 2021)

Isometric Multi-Shape Matching (IsoMuSh) Paper-CVF | Paper-arXiv | Video | Code Citation If you find our work useful in your research, please consider

Maolin Gao 9 Jul 17, 2022
[CVPR 2022 Oral] Crafting Better Contrastive Views for Siamese Representation Learning

Crafting Better Contrastive Views for Siamese Representation Learning (CVPR 2022 Oral) 2022-03-29: The paper was selected as a CVPR 2022 Oral paper! 2

249 Dec 28, 2022
Weakly Supervised Scene Text Detection using Deep Reinforcement Learning

Weakly Supervised Scene Text Detection using Deep Reinforcement Learning This repository contains the setup for all experiments performed in our Paper

Emanuel Metzenthin 3 Dec 16, 2022
This repo is the code release of EMNLP 2021 conference paper "Connect-the-Dots: Bridging Semantics between Words and Definitions via Aligning Word Sense Inventories".

Connect-the-Dots: Bridging Semantics between Words and Definitions via Aligning Word Sense Inventories This repo is the code release of EMNLP 2021 con

12 Nov 22, 2022
Dynamic Attentive Graph Learning for Image Restoration, ICCV2021 [PyTorch Code]

Dynamic Attentive Graph Learning for Image Restoration This repository is for GATIR introduced in the following paper: Chong Mou, Jian Zhang, Zhuoyuan

Jian Zhang 84 Dec 09, 2022
Official implementation of "GS-WGAN: A Gradient-Sanitized Approach for Learning Differentially Private Generators" (NeurIPS 2020)

GS-WGAN This repository contains the implementation for GS-WGAN: A Gradient-Sanitized Approach for Learning Differentially Private Generators (NeurIPS

46 Nov 09, 2022
An implementation of the [Hierarchical (Sig-Wasserstein) GAN] algorithm for large dimensional Time Series Generation

Hierarchical GAN for large dimensional financial market data Implementation This repository is an implementation of the [Hierarchical (Sig-Wasserstein

11 Nov 29, 2022
PPO is a very popular Reinforcement Learning algorithm at present.

PPO is a very popular Reinforcement Learning algorithm at present. OpenAI takes PPO as the current baseline algorithm. We use the PPO algorithm to train a policy to give the best action in any situat

Rosefintech 11 Aug 23, 2021
Unsupervised Representation Learning by Invariance Propagation

Unsupervised Learning by Invariance Propagation This repository is the official implementation of Unsupervised Learning by Invariance Propagation. Pre

FengWang 15 Jul 06, 2022
✔️ Visual, reactive testing library for Julia. Time machine included.

PlutoTest.jl (alpha release) Visual, reactive testing library for Julia A macro @test that you can use to verify your code's correctness. But instead

Pluto 68 Dec 20, 2022
TACTO: A Fast, Flexible and Open-source Simulator for High-Resolution Vision-based Tactile Sensors

TACTO: A Fast, Flexible and Open-source Simulator for High-Resolution Vision-based Tactile Sensors This package provides a simulator for vision-based

Facebook Research 255 Dec 27, 2022
PyTorch code accompanying our paper on Maximum Entropy Generators for Energy-Based Models

Maximum Entropy Generators for Energy-Based Models All experiments have tensorboard visualizations for samples / density / train curves etc. To run th

Rithesh Kumar 135 Oct 27, 2022
ScriptProfilerPy - Module to visualize where your python script is slow

ScriptProfiler helps you track where your code is slow It provides: Code lines t

Lucas BLP 3 Jun 02, 2022
Learning Neural Painters Fast! using PyTorch and Fast.ai

The Joy of Neural Painting Learning Neural Painters Fast! using PyTorch and Fast.ai Blogpost with more details: The Joy of Neural Painting The impleme

Libre AI 72 Nov 10, 2022
The codes and related files to reproduce the results for Image Similarity Challenge Track 2.

ISC-Track2-Submission The codes and related files to reproduce the results for Image Similarity Challenge Track 2. Required dependencies To begin with

Wenhao Wang 89 Jan 02, 2023
PyTorch implementation of PP-LCNet

PP-LCNet-Pytorch Pre-Trained Models Google Drive p018 Accuracy Models Top1 Top5 PPLCNet_x0_25 0.5186 0.7565 PPLCNet_x0_35 0.5809 0.8083 PPLCNet_x0_5 0

24 Dec 12, 2022
Experiments on Flood Segmentation on Sentinel-1 SAR Imagery with Cyclical Pseudo Labeling and Noisy Student Training

Flood Detection Challenge This repository contains code for our submission to the ETCI 2021 Competition on Flood Detection (Winning Solution #2). Acco

Siddha Ganju 108 Dec 28, 2022
A simple image/video to Desmos graph converter run locally

Desmos Bezier Renderer A simple image/video to Desmos graph converter run locally Sample Result Setup Install dependencies apt update apt install git

Kevin JY Cui 339 Dec 23, 2022