GithubHelp home page GithubHelp logo

twopirllc / pandas-ta Goto Github PK

View Code? Open in Web Editor NEW
5.0K 100.0 982.0 63.66 MB

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

Home Page: https://twopirllc.github.io/pandas-ta/

License: MIT License

Python 99.92% Makefile 0.08%
python3 pandas pandas-extension technical-analysis technical-analysis-indicators technical-analysis-library finance fundamental-analysis trading trading-algorithms

pandas-ta's Introduction

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/pandas-ta.git@development

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!

    • 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?
    • 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"

pandas-ta's People

Contributors

alexonab avatar allahyarzadeh avatar bizso09 avatar daikts avatar danlim-wz avatar delicateear avatar dependabot[bot] avatar dorren avatar drpaprikaa avatar edwardwang1 avatar ffhirata avatar gslinger avatar joeschr avatar lluissalord avatar locupleto avatar luisbarrancos avatar m6stafa avatar mihakralj avatar moritzgun avatar nkosenhleduma avatar olafos avatar pbrumblay avatar rengel8 avatar rluong003 avatar softdevdanial avatar twopirllc avatar twrobel avatar whubsch avatar yuvalwein avatar zlpatel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pandas-ta's Issues

Parallel Calculation of Indicators

Hi, thanks for the amazing library!

Is there a way to perform parallel processing of the technical indicators, especially if you are trying to calculate all of them, such as

df.ta.strategy(name='all')

Avoidable NaNs on Chaikin Money Flow (CMF)

Hi,

Using your (amazing) library, I have found that CMF is producing a lot of NaNs on my data. Checking which was the reason I have figured out that in my data there are a lot of cases where 'high' and 'low' price are exactly the same, hence it produces NaNs due to this part of the code:

hl_range = high - low
ad *= volume / hl_range

Hence my proposal is to add an epsilon component
from sys import float_info as sflt

ad *= volume / (hl_range + sflt.epsilon)

What is your opinion on that?

Thank you for all your work,
Lluis

ADD KDJ ,BRAR,Keltner Channel func

Hello my friend

Thank you very much for creating such a very convenient library.

I often use some indicators
KDJ, Brar and Aberration(Keltner channel) related libraries.

I implemented its algorithm using pandas.

so, I hope can be add to Panda-TA,
can you help me? thank you!

BRAR

    #BRAR

    df.columns = ['time','open','high','low','close','volume']
    df['HO']=df['high']-df['open']
    df['OL']=df['open']-df['low']
    df['HCY']=df['high']-df['close'].shift(1)
    df['CYL']=df['close'].shift(1)-df['low']
    df.loc[df['HCY']<0,'HCY']=0
    df.loc[df['CYL']<0,'CYL']=0
    df['ar']=df['HO'].rolling(26).sum()/df['OL'].rolling(26).sum()*100
    df['br']=df['HCY'].rolling(26).sum()/df['CYL'].rolling(26).sum()*100

BIAS

    df.columns = ['time','open','high','low','close','volume']
    result_MA=df.ta(kind='sma',length=MA_lengh)
    C=df['close']
    BIAS=(C-result_MA)/result_MA

KDJ

    #KDJ
    N=44
    M1=9
    H6['llv_low']=H6['low'].rolling(N).min()
    H6['hhv_high']=H6['high'].rolling(N).max()
    H6['rsv']=(H6['close']-H6['llv_low'])/(H6['hhv_high']-H6['llv_low'])
    H6['k']=H6['rsv'].ewm(adjust=False,alpha=1/M1).mean()
    H6['d']=H6['k'].ewm(adjust=False,alpha=1/M1).mean()
    H6['j']=3*H6['k']-2*H6['d']

Aberration

def Aberration(RAW,MA_lengh,ATR_lengh):
    df = pd.DataFrame(RAW)
    df.columns = ['time','open','high','low','close','volume']
    JG=(df['high']+df['low']+df['close'])/3
    ZG=df.ta(kind='sma',close=JG,length=MA_lengh)
    ATR=df.ta(kind='ATR',length=ATR_lengh)
    SG=ZG+ATR
    XG=ZG-ATR
   
    result = pd.concat([ZG,SG,XG,ATR], axis=1)

Donchian Indicator - Miscalculation

Hi, I think the Donchian Channels indicator (DC, a volatility indicator) isn't computing the right thing : the computation should be on the highest highs and the lowest lows, instead of on the closes. So the code therefore becomes :

Definition :

def donchian(high, low, lower_length=None, upper_length=None, offset=None, **kwargs):

line 15 :

# Calculate Result
lower = low.rolling(lower_length, min_periods=lower_min_periods).min()
upper = high.rolling(upper_length, min_periods=upper_min_periods).max()
mid = 0.5 * (lower + upper)

about cdl_doji and strategy()

Hi,
thanks a lot for your very useful library TA.
today I pip install it,and test it.
I found 2 problems.
1, in jupyter notebook and pycharm, I can import ha, but can not import cdl_doji.
2, df.ta.strategy() does not work.I tried df.ta.strategy(high), error exist yet.
just look at the photos.
ta
ta1
ta2
ta3

typo in kama

on line 28 of kama.py you have:
result = [npNaN for _ in range(0, length - 1)] + [0]

I think it's supposed to be:
result = [np.NaN for _ in range(0, length - 1)] + [0]

rolling calculations issue

Hi all , Hi Kevin

I have run in to the below error while applying a window calc to one of the features implemented within the lib

it goes as
df['roll_entp_10']= df_test.ENTP_10.rolling(10) which is a series , after explicitly turning in to a series still getting the same error

image

just for reference

pd.version 1.0.3

image

I have looked though in to the following as suggested
pandas-dev/pandas#11704
is there any additional guidance you can provide on that issue ?
best regards

How to plot Volume Profile?

apdict = [
        mpf.make_addplot(stck.VP,color='y',type = 'line', panel = 1)
        ]

#columns first uper like('Open,High,Low....')
#df.columns = map(str.title, df.columns)

#mpf.plot
mpf.plot(stck,style='yahoo',volume=False,type='candle',addplot=apdict,figratio=(16,8),title=ticker)

RETURNS:

Traceback (most recent call last):
  File "C:/Users/Srika/PycharmProjects/latest project/s&r.py", line 88, in <module>
    mpf.plot(stck,style='yahoo',volume=False,type='candle',addplot=apdict,figratio=(16,8),title=ticker)
  File "C:\Users\Srika\PycharmProjects\latest project\venv\lib\site-packages\mplfinance\plotting.py", line 501, in plot
    ax = _addplot_columns(panid,panels,ydata,apdict,xdates,config)
  File "C:\Users\Srika\PycharmProjects\latest project\venv\lib\site-packages\mplfinance\plotting.py", line 673, in _addplot_columns
    yd = [y for y in ydata if not math.isnan(y)]
  File "C:\Users\Srika\PycharmProjects\latest project\venv\lib\site-packages\mplfinance\plotting.py", line 673, in <listcomp>
    yd = [y for y in ydata if not math.isnan(y)]
TypeError: must be real number, not method

image

join ?

Hi,

I am discovering pandas_ta, and I was wondering why 'append' is an option in the API, but not join ?
It seems to me, naively, that join would be a useful option, especially to link an indicator with the time of the current dataframe...

About RSI question

hi。
when i use the RSI calc,it different with Tradingview。
the tradingview use RMA calc

url:https://www.tradingview.com/support/solutions/43000502338-relative-strength-index-rsi/

Calculation
RSI = 100 – 100/ (1 + RS)
RS = Average Gain of n days UP  / Average Loss of n days DOWN
For a practical example, the built-in Pine Script function rsi(), could be replicated in long form as follows.

change = change(close)
gain = change >= 0 ? change : 0.0
loss = change < 0 ? (-1) * change : 0.0
avgGain = rma(gain, 14)
avgLoss = rma(loss, 14)
rs = avgGain / avgLoss
rsi = 100 - (100 / (1 + rs))
"rsi", above, is exactly equal to rsi(close, 14).

so, Maybe you can view or update the calc code. ^_^

how to append new data frame?

let's say i have 100 rows in data frame, applied all strategies. Now, i want to add 1 more row, i don't want it to recalculate all the whole 101 rows instead only the last one.

momentum/stoch.py : column loss when slow_d = slow _k

In stoch.py lines 47 -> 50
fastk.name = f"STOCHF_{fast_k}" fastd.name = f"STOCHF_{slow_d}" slowk.name = f"STOCH_{slow_k}" slowd.name = f"STOCH_{slow_d}"
If slow_d = slow_k (or fast_k=slow_d) slow (or fast) stochastic names become identical. in this case the returned dataframe lose a column.
Thanks a lot for your work on this project ;)

Wrong calculation for CMO indicator between different versions

@twopirllc , I've just updated pandas-ta package to the latest version and it has updated my installed package to pandas_ta-0.1.63b.

I've run my one of the strategy, where I'm using CMO (Chande Momentum Oscillator) and fond that calculation are different than previous stable version of pandas_ta-0.1.39b0.

I didn't look into the recent commits, but checked README and observed that you have corrected CMO indicator too. Perhaps, the current change is not producing accurate results. I've validated it through some of the charting software.

Not sure, what's the correct value the current one (with pandas_ta-0.1.63b) or the previous version(pandas_ta-0.1.39b0)

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 ?

About add Stochastic RSI (STOCH RSI)

hi. When I studied the technical indicators, I found that Stochastic RSI is useful。
so,I modified the RSI code appropriately,But it's not perfect.
I want to add it to the code with your expertise。
Thanks!

calc in tradingview URL:
https://www.tradingview.com/support/solutions/43000502333-stochastic-rsi-stoch-rsi/

my code:

def stochrsi(close, length=None, scalar=None, drift=None,**kwargs):
    # Validate arguments
    length = int(length) if length and length > 0 else 14
    scalar = 100
    drift = int(drift) if drift and drift != 0 else 1

    # Calculate Result
    negative = close.diff(drift)
    positive = negative.copy()

    positive[positive < 0] = 0  # Make negatives 0 for the postive series
    negative[negative > 0] = 0  # Make postives 0 for the negative series
    
    alpha = (1.0 / length) if length > 0 else 0.5
    positive_avg = positive.ewm(alpha=alpha, adjust=False).mean()
    negative_avg = negative.ewm(alpha=alpha, adjust=False).mean().abs()

    rsi = scalar * positive_avg / (positive_avg + negative_avg)
    rsi_low   =  rsi.rolling(length).min()
    rsi_high =  rsi.rolling(length).max()

    fastk = 100 * (rsi - rsi_low) / (rsi_high-rsi_low)

    slowk = fastk.rolling(3).mean()
    slowd = slowk.rolling(3).mean()

    stochdf = pd.DataFrame(list(zip(rsi, slowk,slowd)))
    stochdf.columns=['rsi', 'stochrsi', 'stochrsi_3']

    return stochdf

Charts - with full data from day one

Currently the charts when displayed, start late, meaning ema15 starts after 15dats, etc..

typically we need full charts, where by we need to load previous data and display from the date we needed..

How can we get this thing done

IBM Watson juypter notebook import

The pip install works perfectly fine but the import pandas_ta as ta on the jupyter notebook version of ibm watson studio has this error below

AttributeError Traceback (most recent call last)
in
5 import numpy as np
6 import pandas as pd
----> 7 import pandas_ta as ta
8 import pandas_datareader.data as web
9 import datetime

C:\ProgramData\WatsonStudioDesktop\miniconda3\envs\desktop\lib\site-packages\pandas_ta_init_.py in
122
123 # DataFrame Extension
--> 124 from .core import *
125

C:\ProgramData\WatsonStudioDesktop\miniconda3\envs\desktop\lib\site-packages\pandas_ta\core.py in
25
26
---> 27 @pd.api.extensions.register_dataframe_accessor('ta')
28 class AnalysisIndicators(BasePandasObject):
29 """AnalysisIndicators is class that extends the Pandas DataFrame via

AttributeError: module 'pandas.api' has no attribute 'extensions'

error

I am running python 3.5

here is an error I got

File "C:/StockServer/TWSAPI/SuperTrendTest3.py", line 3, in
import pandas_ta as ta

File "C:\Users\googlecloud\Anaconda3\envs\py35\lib\site-packages\pandas_ta_init_.py", line 22, in
from .momentum.ao import ao

File "C:\Users\googlecloud\Anaconda3\envs\py35\lib\site-packages\pandas_ta\momentum\ao.py", line 33
ao.name = f"AO_{fast}_{slow}"
^
SyntaxError: invalid syntax

RSI/Stoch/ADX questions

Hi,

I have been using your library to understand TA. First off, thank you for the amazing work. It has been really useful to have!

Wherever possible, I have been double checking the indicator values calculated either on Yahoo Finance (YF) or StockCharts (SC). As such, I wanted to ask for some clarifications on couple of things:

  1. Using df.ta.rsi(length=14) gives me RSI results that are little bit off from YF or SC or manual calculation in excel. However, with df.ta.rsi(length=13), results pretty match with YF (Period 14) or manual work (again using 14 periods). I am not sure why there is a mismatch with ta.rsi default value of 14. Can you please check?

  2. In df.ta.stoch(), I noticed calling with default values gave different results from YF/SC. Digging deeper, in stoch.py, lines 18 & 19, I'm thinking shouldn't the value used be fast_k instead of slow_k. If I update the below to fast_k, I do get matching results with both sources mentioned. Maybe you had something else in mind while implementing?

Calculate Result

lowest_low   =  low.rolling(slow_k).min()
highest_high = high.rolling(slow_k).max()
  1. Using df.ta.adx(), I do get the ADX_14 value that matches with YF/SC but DMP_14 & DMN_14 are not matching. I was trying to understand your methodology of ADX calculation. I think the difference is due to smoothing techniques used. In adx.py, atr & rma calculations use ewm techniques. SC uses a different way of smoothing TR, +DM & -DM. For example:

First TR14 = Sum of first 14 periods of TR1
Second TR14 = First TR14 - (First TR14/14) + Current TR1
Subsequent Values = Prior TR14 - (Prior TR14/14) + Current TR1

as explained here:
https://school.stockcharts.com/doku.php?id=technical_indicators:average_directional_index_adx

I'm not sure what the above smoothing methodology is called but can you please comment on the difference? Also, is there way to use your existing functions to implement this smoothing method?

Sorry for the long post. I greatly appreciate your work and am trying to understand as much as possible. Any further help is greatly appreciated too!

[Enhancement] Naming of the Accumulation/Distribution Indicator

Hello,

Thank you for your great work.

Regarding the Accumulation/Distribution indicator, it's possible to have two versions of it: using close and open OR using close, high and low. However, if I'm not mistaken, as they would have the same name, it is impossible to have the two versions inside the same dataframe (without renaming).

Could you please dynamically name the series regarding the version chosen?

Thanks

VWAP indicator is calculating wrong vwap values for past days in dataframe

@twopirllc Thanks for creating this wonderful python module. I'm extensively using this module for my algos.

I found an issue with VWAP indicator when I ran it with my backtesting data. As per definition, VWAP should be calculated on daily data(Intraday).

Since, we pass series data, which contains past dates data as well. It calculates the cumulative sum incorrectly in that case. Each day's opening volume and hlc price will be different for sure.

Thus, the calculation for vwap should start with fresh data of each day. eg cumsum()

Note: Calculation is absolutely correct in a case of series data contains only 1-day data.

Maybe we could give a try to group a series data according to date and performing a calculation. It's just my thought. But, I would be happy to hear from you. As it's important for cross-checking strategies with backtesting data.

Adx not completely correct with tradingview

I've tried the ADX indicator like below
adx = ta.adx(df[ticker]['high'], df[ticker]['low'], df[ticker]['close'], length=14)
and returns close but not exactly the same results as trading view. The difference is about 1% up/down.

Sine Weighted Moving Average

I see on Tradingview script calc SWMA very simple, how to convert it to python use pandas ? : https://www.tradingview.com/script/6MWFvnPO-Sine-Weighted-Moving-Average/

PI = 2 * asin(1)
sum = 0.0
weightSum = 0.0

for i = 0 to length - 1
weight = sin((i + 1) * PI / (length + 1))
sum := sum + nz(src[i]) * weight
weightSum := weightSum + weight

swma = sum / weightSum


_Originally posted by @cbogithub in https://github.com/twopirllc/pandas-ta/issues/22#issuecomment-508996474_

ta.above append question

Hi Kevin,

Apologies in advance for a very stupid question. I updated the code base today. But I'm not sure what happened since then as using the 'above' function is not appending anymore.

Below line is not appending now but was working in a previous version
df.ta.above(df['MACD_12_26_9'], df['MACDs_12_26_9'], append=True)

This is appending just fine
df.ta.macd(fast=12, slow=26, signal=9, min_periods=None, append=True)

Can you take a look and tell me what I am doing wrong. Thanks in advance.

[Bug report] True range not calculated correctly

Hi Kevin,

While experimenting with the many indicators that you have implemented (big thanks for that!), I noticed a mistake in the calculation for the True Range.
I guess pandas_ta/volatility/true_range.py line 61 should be
ranges = [high - low, high - prev_close, prev_close - low]
instead of
ranges = [high - low, high - prev_close, low - prev_close]

Regards,
Wout

[bug] the ATR func use the RMA calc

@twopirllc Thanks for creating this wonderful python module.
I'm extensively using this module for my algos.

when i use the ATR func,the return different with tradingvew.
it mabe use rma to calc.
so the ATR=RMA(TA,lengh)

can you update it? Thanks !

Possible KST & TRIX enhancements

Hi KJ,

Can you look into kst.py and maybe update the naming for kst_signal? Reason is that if I call KST multiple times (short, medium and long term parameters), KSTS_9 gets overridden. Its not a big deal to handle but wondering if this was intentional or not on your part.
For example, following returns only one KSTS_9
df.ta.kst(append=True) #short-term
df.ta.kst(roc1=10, roc2=13, roc3=15, roc4=20, sma1=10, sma2=13, sma3=15, sma4=20, signal=9, append=True) #Medium term weekly
df.ta.kst(roc1=9, roc2=12, roc3=18, roc4=24, sma1=6, sma2=6, sma3=6, sma4=9, signal=9, append=True) #Long term monthly

Another enhancement request is adding a signal logic to TRIX .py (similar to KST)?

Thanks again for all of your work. This package is amazing!

[Enhancement] Consider Vectorize Algorithms

I recently stumbled upon your project (literally about 2 hours ago) and I've only had a chance to go through a few of your tools but I noticed a few of them that are ripe for vectorization. For example, looking at the WMA implementation you have (I've removed some fluff to conserve space since this is already a long post):

from pandas import Series
from numpy import arange

def wma(close, length):
    total_weight = 0.5 * length * (length + 1)
    weights_ = Series(arange(1, length + 1))
    def linear(w):
        def _compute(x):
            return (w * x).sum() / total_weight
        return _compute
    close_ = close.rolling(length, min_periods=length)
    wma = close_.apply(linear(weights), raw=True)
    return wma

Using convolution and Numpy's ability to operate on an entire array at the same time we can get a massive speedup over you method, albeit at the expense of ease of understanding. Here's what I came up with:

from numpy import arange
from scipy.ndimage import convolve1d as conv

def wma(close, length):
    weights = arange(1, length) / arange(1, length).sum()
    return conv(close, weights=weights, axis=0, mode='nearest')

Just as a quick test I pulled in the last 1000 5 minute time-frame tick marks from an exchange, then created a length 10, 100, and 1000 DataFrame on the closes. Here is the code:

import numpy as np, timeit
setup = '''
import pandas as pd
from numpy import arange
from pandas import Series
from scipy.ndimage import convolve1d as conv
def my_wma(dr, length):
    wts = arange(1, length) / arange(1, length).sum()
    return conv(dr, weights=wts, axis=0, mode='nearest')
def your_wma(close, length):
    total_weight = 0.5 * length * (length + 1)
    weights = Series(arange(1, length + 1))
    def linear(w):
        def _compute(x):
            return (w * x).sum() / total_weight
        return _compute
    close_ = close.rolling(length, min_periods=length)
    wma = close_.apply(linear(weights), raw=True)
    return wma
    
df = READ IN FROM CSV
df1 = df['close'].tail(10)
df2 = df['close'].tail(100)
df3 = df['close'].tail(1000)
'''
myt1 = timeit.repeat('my_wma(df1.values, 9)', setup=setup, number=100, repeat=10)
myt2 = timeit.repeat('my_wma(df2.values, 9)', setup=setup, number=100, repeat=10)
myt3 = timeit.repeat('my_wma(df3.values, 9)', setup=setup, number=100, repeat=10)
yourt1 = timeit.repeat('your_wma(df1, 9)', setup=setup, number=100, repeat=10)
yourt2 = timeit.repeat('your_wma(df2, 9)', setup=setup, number=100, repeat=10)
yourt3 = timeit.repeat('your_wma(df3, 9)', setup=setup, number=100, repeat=10)
print('Average Speed difference: {:0.01f}x'.format(np.mean(np.divide(yourt1, myt1))))
print('Average Speed difference: {:0.01f}x'.format(np.mean(np.divide(yourt2, myt2))))
print('Average Speed difference: {:0.01f}x'.format(np.mean(np.divide(yourt3, myt3))))

and the result was...

Average Speed difference: 29.2x
Average Speed difference: 613.0x
Average Speed difference: 5258.9x

I also ran

%timeit my_wma(df1.values, 9)
%timeit my_wma(df2.values, 9)
%timeit my_wma(df3.values, 9)
%timeit your_wma(df1, 9)
%timeit your_wma(df2, 9)
%timeit your_wma(df3, 9)

And got the results:

22.1 µs ± 58 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
22.7 µs ± 177 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
27.9 µs ± 42.5 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

664 µs ± 3.02 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
14.2 ms ± 20.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
150 ms ± 575 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

I realize that this is speedup would really be beneficial to someone who is calculating the averages for all historical points and that real time trading that the speed would probably not make a huge impact. However, it's clear to me that this method is much more efficient and IMO every bit of speedup helps, especially if one is back-testing.

Future data leak on DPO indicator

Thank you for this great library.

I've used the strategy method to add all indicators to a data frame. DPO_1 got a massive feature importance score and any models trained with that indicator had accuracy of 99 to 100% 😄.

It seems that when center=True (the default), this line leaks future data into the past.

default plot settings ?

It would be super convenient for end users ( especially people trying things in their jupyter environment) if the resulting dataframe, after calculating an indicator, had default plot settings already setup so that
myta_df.plot() plots a sensible graph...

What do you think ?

Specifying or detecting the order of data?

Hello,

First, thank you for this awesome package! It's nicely done!

I have the following issue - The data is in reverse order on my end, i.e. most recent candle is index 0.

For example:

>>> data.SPY
           date    open    high     low   close       volume
0    2020-05-06  288.04  288.45  283.87  284.34   67758728.0
1    2020-05-05  286.64  289.25  283.71  286.19   79330400.0
2    2020-05-04  280.74  283.90  279.13  283.57   80873200.0
3    2020-05-01  285.31  290.66  281.52  282.79  125063900.0
4    2020-04-30  291.71  293.32  288.59  290.48  122901700.0
...         ...     ...     ...     ...     ...          ...
6862 1993-02-04   44.97   45.09   44.47   45.00     531500.0
6863 1993-02-03   44.41   44.84   44.38   44.81     529400.0
6864 1993-02-02   44.22   44.38   44.13   44.34     201300.0
6865 1993-02-01   43.97   44.25   43.97   44.25     480500.0
6866 1993-01-29   43.97   43.97   43.75   43.94    1003200.0

[6867 rows x 6 columns]

And e.g. when I do atr, it seems that it goes in reverse order, filling most recent with NaN:

>>> data.SPY.ta.atr()
0            NaN
1            NaN
2            NaN
3            NaN
4            NaN
          ...   
6862    0.556601
6863    0.565054
6864    0.580380
6865    0.552330
6866    0.545352
Name: ATR_14, Length: 6867, dtype: float64

Now I know that the easiest thing in the world is to reverse the data with [::-1], but still... would be great if we could specify the order somehow, or even better - detect it form the date field.

invalid syntax error

when i run this, i get error

import pandas as pd
import pandas_ta as ta

# Help about this, 'ta', extension
help(pd.DataFrame().ta)

# List of all indicators
pd.DataFrame().ta.indicators()

# Help about the log_return indicator
help(ta.log_return)

# Help about the log_return indicator as a DataFrame Extension
help(pd.DataFrame().ta.log_return)

File "C:\Users\Rakesh\AppData\Local\Continuum\anaconda3\envs\zip355\lib\site-packages\pandas_ta\momentum\ao.py", line 33
ao.name = f"AO_{fast}_{slow}"
^
SyntaxError: invalid syntax

I am running the following
(zip355) C:\Users\Rakesh>pip install -U git+https://github.com/twopirllc/pandas-ta
Collecting git+https://github.com/twopirllc/pandas-ta
Cloning https://github.com/twopirllc/pandas-ta to c:\users\Rakesh\appdata\local\temp\pip-req-build-1l4j_eh8
Requirement not upgraded as not directly required: pandas in c:\users\Rakesh\appdata\local\continuum\anaconda3\envs\zip355\lib\site-packages (from pandas-ta==0.1.38b0) (0.22.0)
Requirement not upgraded as not directly required: python-dateutil>=2 in c:\users\Rakesh\appdata\local\continuum\anaconda3\envs\zip355\lib\site-packages (from pandas->pandas-ta==0.1.38b0) (2.8.1)
Requirement not upgraded as not directly required: pytz>=2011k in c:\users\Rakesh\appdata\local\continuum\anaconda3\envs\zip355\lib\site-packages (from pandas->pandas-ta==0.1.38b0) (2019.3)
Requirement not upgraded as not directly required: numpy>=1.9.0 in c:\users\Rakesh\appdata\local\continuum\anaconda3\envs\zip355\lib\site-packages (from pandas->pandas-ta==0.1.38b0) (1.14.2)
Requirement not upgraded as not directly required: six>=1.5 in c:\users\Rakesh\appdata\local\continuum\anaconda3\envs\zip355\lib\site-packages (from python-dateutil>=2->pandas->pandas-ta==0.1.38b0) (1.11.0)
Building wheels for collected packages: pandas-ta
Running setup.py bdist_wheel for pandas-ta ... done
Stored in directory: C:\Users\Rakesh\AppData\Local\Temp\pip-ephem-wheel-cache-bdcsthu0\wheels\64\67\96\15e918c3b53b4a323b5bd037c7f08be5ef6908141c50f07c76
Successfully built pandas-ta
jupyterlab-server 1.0.0 has requirement jsonschema>=3.0.1, but you'll have jsonschema 2.6.0 which is incompatible.
Installing collected packages: pandas-ta
Successfully installed pandas-ta-0.1.38b0

Filter indicators by category in strategy()

Hi,

I came across your library, it's awesome ! Especially the strategy() method, which allows to add all the indicators to a dataframe. Is there a way to add all the indicators for a specific category (momentum, statistics, trend...) only ? If not it would make a great feature !

Can not import talib

I am trying to test project files under tests directory
it shows the following error:

Collecting talib
Using cached talib-0.1.1.tar.gz (1.3 kB)
Using legacy setup.py install for talib, since package 'wheel' is not installed.
Installing collected packages: talib
Running setup.py install for talib: started
Running setup.py install for talib: finished with status 'error'

ERROR: Command errored out with exit status 1:
 command: 'D:\dev\projects\pandas-ta\venv\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\TAS01\\AppData\\Local\\Temp\\pycharm-packaging\\talib\\setup.py'"'"'; __file__='"'"'C:\\Users\\TAS01\\AppData\\Local\\Temp\\pycharm-packaging\\talib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\TAS01\AppData\Local\Temp\pip-record-4jfhoad9\install-record.txt' --single-version-externally-managed --compile --install-headers 'D:\dev\projects\pandas-ta\venv\include\site\python3.8\talib'
     cwd: C:\Users\TAS01\AppData\Local\Temp\pycharm-packaging\talib\
Complete output (14 lines):
running install
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\TAS01\AppData\Local\Temp\pycharm-packaging\talib\setup.py", line 32, in <module>
    setup(
  File "C:\Users\TAS01\AppData\Local\Programs\Python\Python38\lib\distutils\core.py", line 148, in setup
    dist.run_commands()
  File "C:\Users\TAS01\AppData\Local\Programs\Python\Python38\lib\distutils\dist.py", line 966, in run_commands
    self.run_command(cmd)
  File "C:\Users\TAS01\AppData\Local\Programs\Python\Python38\lib\distutils\dist.py", line 985, in run_command
    cmd_obj.run()
  File "C:\Users\TAS01\AppData\Local\Temp\pycharm-packaging\talib\setup.py", line 20, in run
    raise Exception("You probably meant to install and run ta-lib")
Exception: You probably meant to install and run ta-lib
----------------------------------------

ERROR: Command errored out with exit status 1: 'D:\dev\projects\pandas-ta\venv\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\TAS01\AppData\Local\Temp\pycharm-packaging\talib\setup.py'"'"'; file='"'"'C:\Users\TAS01\AppData\Local\Temp\pycharm-packaging\talib\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\TAS01\AppData\Local\Temp\pip-record-4jfhoad9\install-record.txt' --single-version-externally-managed --compile --install-headers 'D:\dev\projects\pandas-ta\venv\include\site\python3.8\talib' Check the logs for full command output.

Minor issue in the example notebook

The example notebook shows

e.ta.indicators()

but I think this needs to be

e().ta.indicators()

Or you need to assign e = pd.DataFrame() ... coders choice. :)

problem with lenght

hi mate,
i try to use your indicator but i have a problem when i use the parameter lenght:
sma=df.ta.sma(close=df['close'],lenght=10) print(df['close'].tail(3)) print(sma.tail(3))

and the output:

3922 8079.54
3923 8073.16
3924 8076.36
Name: close, dtype: float64
3922 8064.433
3923 8062.750
3924 8061.351
Name: SMA_10, dtype: float64

and if i put
sma=df.ta.sma(close=df['close'],lenght=20)

the output is
3922 8079.54
3923 8073.16
3924 8076.36
Name: close, dtype: float64
3922 8064.433
3923 8062.750
3924 8061.351
Name: SMA_10, dtype: float64

so not change anything..
where is my mistake ? because every time use the else condition

Validate Arguments

close = verify_series(close)
length = int(length) if length and length > 0 else 10
offset = get_offset(offset)

TA - all features generations

What's the best way to create all relevant features? I tried to use the df.ta.strategy(name='all')

Error:

`Index(['dt', 'open', 'high', 'low', 'close', 'volumn', 'trading_dt', 'stock'], dtype='object')

KeyError                                  Traceback (most recent call last)
D:\Anaconda\envs\py36\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2645             try:
-> 2646                 return self._engine.get_loc(key)
   2647             except KeyError:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'high'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-98-ce3fa983de61> in <module>
----> 1 ch_3 = ta_pd_v2(ch)

<ipython-input-77-d2409a027e53> in ta_pd_v2(df)
      8     df1["close-1"] = df1["close"].shift(1)
      9 
---> 10     df.ta.strategy(name='all')
     11     return df1

D:\Anaconda\envs\py36\lib\site-packages\pandas_ta\core.py in strategy(self, **kwargs)
    367         if name is None or name == "" or not isinstance(name, str): # Extra check
    368             name = "all"
--> 369         self._all(**kwargs) if name == "all" else None
    370 
    371 

D:\Anaconda\envs\py36\lib\site-packages\pandas_ta\core.py in _all(self, **kwargs)
    343         for kind in indicators:
    344             fn = getattr(self, kind)
--> 345             fn(append=append, **kwargs)
    346             print(f"[+] {kind}") if verbose else None
    347 

D:\Anaconda\envs\py36\lib\site-packages\pandas_ta\core.py in _wrapper(*class_methods, **method_kwargs)
     22     def _wrapper(*class_methods, **method_kwargs):
     23         cm = class_methods[0]
---> 24         result = method(cm, **method_kwargs)
     25 
     26         cm._add_prefix_suffix(result, **method_kwargs)

D:\Anaconda\envs\py36\lib\site-packages\pandas_ta\core.py in aberration(self, high, low, close, length, atr_length, offset, **kwargs)
   1067     @finalize
   1068     def aberration(self, high=None, low=None, close=None, length=None, atr_length=None, offset=None, **kwargs):
-> 1069         high = self._get_column(high, 'high')
   1070         low = self._get_column(low, 'low')
   1071         close = self._get_column(close, 'close')

D:\Anaconda\envs\py36\lib\site-packages\pandas_ta\core.py in _get_column(self, series, default)
    229         # Apply default if no series nor a default.
    230         elif series is None or default is None:
--> 231             return df[self.adjusted] if self.adjusted is not None else df[default]
    232         # Ok.  So it's a str.
    233         elif isinstance(series, str):

D:\Anaconda\envs\py36\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2798             if self.columns.nlevels > 1:
   2799                 return self._getitem_multilevel(key)
-> 2800             indexer = self.columns.get_loc(key)
   2801             if is_integer(indexer):
   2802                 indexer = [indexer]

D:\Anaconda\envs\py36\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2646                 return self._engine.get_loc(key)
   2647             except KeyError:
-> 2648                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2649         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2650         if indexer.ndim > 1 or indexer.size > 1:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'high'`

So, I used the customised feature generation script but run into error for certain features:

`def ta_pd_v2(df):
    df1 = df.copy()
    df1.columns = map(str.lower, df1.columns) 
    df1["open-1"] = df1["open"].shift(1)
    df1["high-1"] = df1["high"].shift(1)
    df1["low-1"] = df1["low"].shift(1)
    df1["close-1"] = df1["close"].shift(1)
    
    df1 = df1.ta.strategy(name='all')
    return df1

Example of error:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
D:\Anaconda\envs\py36\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2645             try:
-> 2646                 return self._engine.get_loc(key)
   2647             except KeyError:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'volume'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-28-5d947df895f7> in <module>
----> 1 ch.ta.strategy(name='all')

D:\Anaconda\envs\py36\lib\site-packages\pandas_ta\core.py in strategy(self, **kwargs)
    367         if name is None or name == "" or not isinstance(name, str): # Extra check
    368             name = "all"
--> 369         self._all(**kwargs) if name == "all" else None
    370 
    371 

D:\Anaconda\envs\py36\lib\site-packages\pandas_ta\core.py in _all(self, **kwargs)
    343         for kind in indicators:
    344             fn = getattr(self, kind)
--> 345             fn(append=append, **kwargs)
    346             print(f"[+] {kind}") if verbose else None
    347 

D:\Anaconda\envs\py36\lib\site-packages\pandas_ta\core.py in _wrapper(*class_methods, **method_kwargs)
     22     def _wrapper(*class_methods, **method_kwargs):
     23         cm = class_methods[0]
---> 24         result = method(cm, **method_kwargs)
     25 
     26         cm._add_prefix_suffix(result, **method_kwargs)

D:\Anaconda\envs\py36\lib\site-packages\pandas_ta\core.py in ad(self, high, low, close, volume, open_, signed, offset, **kwargs)
   1161         low = self._get_column(low, 'low')
   1162         close = self._get_column(close, 'close')
-> 1163         volume = self._get_column(volume, 'volume')
   1164 
   1165         result = ad(high=high, low=low, close=close, volume=volume, open_=open_, signed=signed, offset=offset, **kwargs)

D:\Anaconda\envs\py36\lib\site-packages\pandas_ta\core.py in _get_column(self, series, default)
    229         # Apply default if no series nor a default.
    230         elif series is None or default is None:
--> 231             return df[self.adjusted] if self.adjusted is not None else df[default]
    232         # Ok.  So it's a str.
    233         elif isinstance(series, str):

D:\Anaconda\envs\py36\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2798             if self.columns.nlevels > 1:
   2799                 return self._getitem_multilevel(key)
-> 2800             indexer = self.columns.get_loc(key)
   2801             if is_integer(indexer):
   2802                 indexer = [indexer]

D:\Anaconda\envs\py36\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2646                 return self._engine.get_loc(key)
   2647             except KeyError:
-> 2648                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2649         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2650         if indexer.ndim > 1 or indexer.size > 1:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'volume'

My another attempt:

`
import traceback
def ta_pd(df):
    df1 = df.copy()
    indicators = pd.DataFrame().ta.indicators(as_list=True)
    append = True
    df1.columns = map(str.lower, df1.columns)
    
    df1["open-1"] = df1["open"].shift(1)
    df1["high-1"] = df1["high"].shift(1)
    df1["low-1"] = df1["low"].shift(1)
    df1["close-1"] = df1["close"].shift(1)
    
    #print(len(indicators), "will be added.")
    for kind in indicators:
        try:
            print(kind)
            df1.ta(kind=kind, append=append)
        except Exception as e:
            print("\nError with indicator:", kind)
            print("") # print(".", end="")

    indicators2 = ["log_return", "percent_return", "trend_return"]
    for kind in indicators2:
        try:
            print(kind)
            df1.ta(kind=kind, append=append, cumulative=True)
        except Exception as e:
            print("\nError with indicator:", kind)
            print("") # print(".", end="")
    
    df1.drop(columns = ['dt', 'open', 'high', 'low', 'close', 'volumn', 'trading_dt', 'stock', 'open-1', 'high-1', 'low-1', 'close-1',
                           
    return df1
` 

and the error:

ad

Error with indicator: ad

adosc

Error with indicator: adosc

No module named 'pandas_ta.candles'

version: pandas-ta-0.1.65b0

$ python3.7
Python 3.7.7 (default, Apr 1 2020, 13:48:52)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
import pandas_ta as ta
Traceback (most recent call last):
File "", line 1, in
File "/lib/python3.7/site-packages/pandas_ta/init.py", line 21, in
from pandas_ta.core import *
File "/lib/python3.7/site-packages/pandas_ta/core.py", line 8, in
from pandas_ta.candles import *
ModuleNotFoundError: No module named 'pandas_ta.candles'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.