Technical Analysis Library using Pandas and Numpy

Overview

CircleCI Documentation Status Coverage Status Code style: black Linter: Prospector PyPI PyPI - Downloads Donate PayPal

Technical Analysis Library in Python

It is a Technical Analysis library useful to do feature engineering from financial time series datasets (Open, Close, High, Low, Volume). It is built on Pandas and Numpy.

Bollinger Bands graph example

The library has implemented 42 indicators:

Volume

  • Money Flow Index (MFI)
  • Accumulation/Distribution Index (ADI)
  • On-Balance Volume (OBV)
  • Chaikin Money Flow (CMF)
  • Force Index (FI)
  • Ease of Movement (EoM, EMV)
  • Volume-price Trend (VPT)
  • Negative Volume Index (NVI)
  • Volume Weighted Average Price (VWAP)

Volatility

  • Average True Range (ATR)
  • Bollinger Bands (BB)
  • Keltner Channel (KC)
  • Donchian Channel (DC)
  • Ulcer Index (UI)

Trend

  • Simple Moving Average (SMA)
  • Exponential Moving Average (EMA)
  • Weighted Moving Average (WMA)
  • Moving Average Convergence Divergence (MACD)
  • Average Directional Movement Index (ADX)
  • Vortex Indicator (VI)
  • Trix (TRIX)
  • Mass Index (MI)
  • Commodity Channel Index (CCI)
  • Detrended Price Oscillator (DPO)
  • KST Oscillator (KST)
  • Ichimoku Kinkō Hyō (Ichimoku)
  • Parabolic Stop And Reverse (Parabolic SAR)
  • Schaff Trend Cycle (STC)

Momentum

  • Relative Strength Index (RSI)
  • Stochastic RSI (SRSI)
  • True strength index (TSI)
  • Ultimate Oscillator (UO)
  • Stochastic Oscillator (SR)
  • Williams %R (WR)
  • Awesome Oscillator (AO)
  • Kaufman's Adaptive Moving Average (KAMA)
  • Rate of Change (ROC)
  • Percentage Price Oscillator (PPO)
  • Percentage Volume Oscillator (PVO)

Others

  • Daily Return (DR)
  • Daily Log Return (DLR)
  • Cumulative Return (CR)

Documentation

https://technical-analysis-library-in-python.readthedocs.io/en/latest/

Motivation to use

How to use (Python 3)

$ pip install --upgrade ta

To use this library you should have a financial time series dataset including Timestamp, Open, High, Low, Close and Volume columns.

You should clean or fill NaN values in your dataset before add technical analysis features.

You can get code examples in examples_to_use folder.

You can visualize the features in this notebook.

Example adding all features

import pandas as pd
from ta import add_all_ta_features
from ta.utils import dropna


# Load datas
df = pd.read_csv('ta/tests/data/datas.csv', sep=',')

# Clean NaN values
df = dropna(df)

# Add all ta features
df = add_all_ta_features(
    df, open="Open", high="High", low="Low", close="Close", volume="Volume_BTC")

Example adding particular feature

import pandas as pd
from ta.utils import dropna
from ta.volatility import BollingerBands


# Load datas
df = pd.read_csv('ta/tests/data/datas.csv', sep=',')

# Clean NaN values
df = dropna(df)

# Initialize Bollinger Bands Indicator
indicator_bb = BollingerBands(close=df["Close"], window=20, window_dev=2)

# Add Bollinger Bands features
df['bb_bbm'] = indicator_bb.bollinger_mavg()
df['bb_bbh'] = indicator_bb.bollinger_hband()
df['bb_bbl'] = indicator_bb.bollinger_lband()

# Add Bollinger Band high indicator
df['bb_bbhi'] = indicator_bb.bollinger_hband_indicator()

# Add Bollinger Band low indicator
df['bb_bbli'] = indicator_bb.bollinger_lband_indicator()

# Add Width Size Bollinger Bands
df['bb_bbw'] = indicator_bb.bollinger_wband()

# Add Percentage Bollinger Bands
df['bb_bbp'] = indicator_bb.bollinger_pband()

Deploy and develop (for developers)

$ git clone https://github.com/bukosabino/ta.git
$ cd ta
$ pip install -r requirements-play.txt
$ make test

Sponsor

Logo OpenSistemas

Thank you to OpenSistemas! It is because of your contribution that I am able to continue the development of this open source library.

Based on

In Progress

  • Automated tests for all the indicators.

TODO

Changelog

Check the changelog of project.

Donation

If you think ta library help you, please consider buying me a coffee.

Credits

Developed by Darío López Padial (aka Bukosabino) and other contributors.

Please, let me know about any comment or feedback.

Also, I am a software engineer freelance focused on Data Science using Python tools such as Pandas, Scikit-Learn, Backtrader, Zipline or Catalyst. Don't hesitate to contact me if you need to develop something related with this library, Python, Technical Analysis, AlgoTrading, Machine Learning, etc.

Comments
  • Inaccurate Results with ADX

    Inaccurate Results with ADX

    Hi!

    Thanks for TA! Great job! It seems that i'm getting inaccurate data with ADX, at least data is different compared to cryptowatch and other sources. import krakenex import ta from pykrakenapi import KrakenAPI

    api = krakenex.API()
    k = KrakenAPI(api)
    df, last = k.get_ohlc_data("XXBTZEUR", ascending=True, interval=5)
    ohlc = ta.utils.dropna(df)
    print(ta.trend.adx(ohlc.high, ohlc.low, ohlc.close))
    

    and output is

    ...
    2018-09-25 17:35:00    22.381099
    Name: adx, Length: 720, dtype: float64
    

    while to ADX on website is for same interval/lenght is 12.54

    bug 
    opened by Zouuup 13
  • RSI has different results compared to Talib library

    RSI has different results compared to Talib library

    The RSI calculated from Ta library is different from the one that you get from Trading View. I compared the results between Ta library and Talib library and , Talib gives you the same results as in tradingview.

    bug 
    opened by asimsan 10
  • TypeError when defining MACD parameters

    TypeError when defining MACD parameters

    Hi, I am getting this error when using the parameter names 'window_slow', 'window_fast', and 'window_sign'. It works ok if I stop after the "close" parameter, but then I can't play with the window sizes. Is it something I've done wrong?

    --> 730 ind_MACD = ta.trend.MACD(close=df["close"], window_slow=26, window_fast=12, window_sign=9)

    TypeError: __init__() got an unexpected keyword argument 'window_slow'

    opened by MikeCas 9
  • API Requirements/Expectations

    API Requirements/Expectations

    Just curious on what sort of requirements or expectations you have regarding the API now and moving forward.

    • Limited to return a single Series? Is returning a DataFrame an option for indicators that return multiple series, such as MACD, BBANDs, et al?
    • Are the indicators to be decoupled and not rely on others for computation? For instance, MACD relying on SMAs?

    Thanks KJ

    opened by twopirllc 8
  • Error in MFI calculation

    Error in MFI calculation

    In your documentation, you have a link to MFI formula explanation and there you can see such text: "Money flow is positive when the typical price rises (buying pressure) and negative when the typical price declines (selling pressure)." So, you need to compare typical prices, not close prices.

    df.loc[(df['Close'] > df['Close'].shift(1, fill_value=df['Close'].mean())), 'Up_or_Down'] = 1
    df.loc[(df['Close'] < df['Close'].shift(1, fill_value=df['Close'].mean())), 'Up_or_Down'] = 2
    

    Here you need to make a comparison with tp.

    bug 
    opened by UnicornsExist 7
  • wrong cci calculation

    wrong cci calculation

    for cci calculation, we should use "mean absolute deviation (mad)" not standard deviation. please correct it. unfortunately, pandas rolling doesn't provide mad function. we have to find it by our own.

    here I'm posting my code which is used for cci calculation.

    pp = (data['CLOSE'] + data['LOW'] + data['HIGH'] )/3
    mad = lambda x : np.mean(np.abs(x-np.mean(x)))
    data['CCI']= (pp-pp.rolling(period).mean())/(0.015 * pp.rolling(period).apply(mad,True))
    
    bug 
    opened by angopinath 6
  • Parabolic Sar - feature-request

    Parabolic Sar - feature-request

    First: GREAT LIBRARY!!, @bukosabino! (better than all the others!!)

    And because of that I would be happy to find the parabolic sar from you in it. It's very complicated. I will try to code it for myself. If I'm ready with a good solution I will send it to you. But maybe you're faster! ;)

    enhancement 
    opened by TravelTrader 6
  • icichimoku future values missing?

    icichimoku future values missing?

    According to https://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ichimoku_cloud for icichimoku cloud the values are shifted forward. Where can I get these values, are they discarded?

    opened by bizso09 6
  • customize keltner channel ATRs

    customize keltner channel ATRs

    Allow users to define custom number of ATRs away from the central moving average

    https://school.stockcharts.com/doku.php?id=technical_indicators:keltner_channels

    opened by ludydoo 5
  • Add indicators and test data

    Add indicators and test data

    Adding Scheff Trend Cycle indicator Manually copy data from tradeview charts. Testing data round to 2 decimal places

    Adding Stoch RSI indicator, percentage volume oscillator, percentage price oscillator, ulcer index

    opened by lit26 5
  • VWAP Indicator Implementation

    VWAP Indicator Implementation

    From: https://medium.com/@neonguru/it-would-be-nice-if-it-included-vwap-22fa4e80584f

    It would be nice if it included VWAP.

    More info: https://school.stockcharts.com/doku.php?id=technical_indicators:vwap_intraday

    enhancement good first issue next version 
    opened by bukosabino 5
  • something like this

    something like this

    I fixed this indicator. It was completely wrong. Important things:

    1. Now it returns Series with NaN values by default unless new optional method parameter dropnans is not True OR you can specify self._check_fillna(self._vpt, value=-1) instead of value=0 to make it bfill, but I would not recommend it. Therefore it returns self._vpt with property self._vpt.shape[0] <= self.close.shape[0].
    2. Provided new optional method parameter smoothing_factor like in TradingView implementation of this indicator. But it's not used by default (like in pure definition of this indicator).
    3. Added some type|value checking, feel free to delete it. I added them to feel safe and didn't find a place with checkers.
    4. I didnt'find a place to add important comment about shifting and fill_value with series mean, so I did it in 273 line... Not in right place but ... whatever. It should be deleted, I guess.
    opened by Groni3000 2
  • FutureWarning (with pandas 1.5.1)

    FutureWarning (with pandas 1.5.1)

    trend.py:730: FutureWarning: The behavior of series[i:j] with an integer-dtype index is deprecated. In a future version, this will be treated as label-based indexing, consistent with e.g. series[i] lookups. To retain the old behavior, use series.iloc[i:j]. (...)

    Same thing on line 748 and 760. It's not really important at the moment but it's a quick fix (just add iloc after dropna), and because I don't like ignoring warnings I already have the pull request ready :)

    opened by i-gutierrez 0
  • Why does Bollinger Bands use ddof=0 instead of the default ddof=1?

    Why does Bollinger Bands use ddof=0 instead of the default ddof=1?

    This is not the standard calculation. It does not match the bb calculated from any other charting software I use, and the bands are now biased. What is the reasoning here?

    opened by matt-seaton 0
  • Add parameter

    Add parameter "exclude_ta_features" from add_all_ta_features.

    When coming across an error, I would be able to just remove the feature that was causing the error and process the rest.

    df_window = add_all_ta_features( df_window, open="open", high="high", low="low", close="close", volume="volume", )

    Would be something like this:

    df_window = add_all_ta_features( df_window, open="open", high="high", low="low", close="close", volume="volume", exclude_ta_features=["trend_dpo", "momentum_stoch_rsi"] )

    I'm getting this error below, so I would simply remove the feature that is causing it. In my case is probably indicator_adx or add_trend_ta is the feature probably causing it. That's why I think a parameter to pick which feature to process would be helpful.

    
    Traceback (most recent call last):
    
      File "C:\Users\artur\AppData\Local\Temp\ipykernel_7992\260366147.py", line 1, in <cell line: 1>
        df_window_pandas = add_all_ta_features(
    
      File "C:\Users\artur\miniforge3\envs\env_tsflex\lib\site-packages\ta\wrapper.py", line 585, in add_all_ta_features
        df = add_trend_ta(
    
      File "C:\Users\artur\miniforge3\envs\env_tsflex\lib\site-packages\ta\wrapper.py", line 343, in add_trend_ta
        df[f"{colprefix}trend_adx"] = indicator_adx.adx()
    
      File "C:\Users\artur\miniforge3\envs\env_tsflex\lib\site-packages\ta\trend.py", line 790, in adx
        adx_series[self._window] = directional_index[0: self._window].mean()
    
    IndexError: index 14 is out of bounds for axis 0 with size 9
    
    opened by arturdaraujo 0
Owner
Darío López Padial
Join us now and share the software. You'll be free.
Darío López Padial
Github.com/CryptoSignal - #1 Quant Trading & Technical Analysis Bot - 2,100 + stars, 580 + forks

CryptoSignal - #1 Quant Trading & Technical Analysis Bot - 2,100 + stars, 580 + forks https://github.com/CryptoSignal/Crypto-Signal Development state:

Github.com/Signal - 2,100 + stars, 580 + forks 4.2k Jan 1, 2023
Yahoo! Finance market data downloader (+faster Pandas Datareader)

Yahoo! Finance market data downloader Ever since Yahoo! finance decommissioned their historical data API, many programs that relied on it to stop work

Ran Aroussi 8.4k Jan 1, 2023
Supply a wrapper ``StockDataFrame`` based on the ``pandas.DataFrame`` with inline stock statistics/indicators support.

Stock Statistics/Indicators Calculation Helper VERSION: 0.3.2 Introduction Supply a wrapper StockDataFrame based on the pandas.DataFrame with inline s

Cedric Zhuang 1.1k Dec 28, 2022
Performance analysis of predictive (alpha) stock factors

Alphalens Alphalens is a Python Library for performance analysis of predictive (alpha) stock factors. Alphalens works great with the Zipline open sour

Quantopian, Inc. 2.5k Dec 28, 2022
Zipline, a Pythonic Algorithmic Trading Library

Zipline is a Pythonic algorithmic trading library. It is an event-driven system for backtesting. Zipline is currently used in production as the backte

Quantopian, Inc. 15.7k Jan 2, 2023
ffn - a financial function library for Python

ffn - Financial Functions for Python Alpha release - please let me know if you find any bugs! If you are looking for a full backtesting framework, ple

Philippe Morissette 1.4k Jan 1, 2023
An Algorithmic Trading Library for Crypto-Assets in Python

Service Master Develop CI Badge Catalyst is an algorithmic trading library for crypto-assets written in Python. It allows trading strategies to be eas

Enigma 2.4k Jan 5, 2023
Python library for backtesting trading strategies & analyzing financial markets (formerly pythalesians)

finmarketpy (formerly pythalesians) finmarketpy is a Python based library that enables you to analyze market data and also to backtest trading strateg

Cuemacro 3k Dec 30, 2022
High-performance TensorFlow library for quantitative finance.

TF Quant Finance: TensorFlow based Quant Finance Library Table of contents Introduction Installation TensorFlow training Development roadmap Examples

Google 3.5k Jan 1, 2023
Python Backtesting library for trading strategies

backtrader Yahoo API Note: [2018-11-16] After some testing it would seem that data downloads can be again relied upon over the web interface (or API v

DRo 9.8k Dec 30, 2022
Python Algorithmic Trading Library

PyAlgoTrade PyAlgoTrade is an event driven algorithmic trading Python library. Although the initial focus was on backtesting, paper trading is now pos

Gabriel Becedillas 3.9k Jan 1, 2023
Q-Fin: A Python library for mathematical finance.

Q-Fin A Python library for mathematical finance. Installation https://pypi.org/project/QFin/ pip install qfin Bond Pricing Option Pricing Black-Schol

Roman Paolucci 247 Jan 1, 2023
Beibo is a Python library that uses several AI prediction models to predict stocks returns over a defined period of time.

Beibo is a Python library that uses several AI prediction models to predict stocks returns over a defined period of time.

Santosh 54 Dec 10, 2022
Indicator divergence library for python

Indicator divergence library This module aims to help to find bullish/bearish divergences (regular or hidden) between two indicators using argrelextre

null 8 Dec 13, 2022
Find big moving stocks before they move using machine learning and anomaly detection

Surpriver - Find High Moving Stocks before they Move Find high moving stocks before they move using anomaly detection and machine learning. Surpriver

Tradytics 1.5k Dec 31, 2022
personal finance tracker, written in python 3 and using the wxPython GUI toolkit.

personal finance tracker, written in python 3 and using the wxPython GUI toolkit.

wenbin wu 23 Oct 30, 2022
Common financial risk and performance metrics. Used by zipline and pyfolio.

empyrical Common financial risk metrics. Table of Contents Installation Usage Support Contributing Testing Installation pip install empyrical Usage S

Quantopian, Inc. 1k Dec 26, 2022
Portfolio and risk analytics in Python

pyfolio pyfolio is a Python library for performance and risk analysis of financial portfolios developed by Quantopian Inc. It works well with the Zipl

Quantopian, Inc. 4.8k Jan 8, 2023
An open source reinforcement learning framework for training, evaluating, and deploying robust trading agents.

TensorTrade: Trade Efficiently with Reinforcement Learning TensorTrade is still in Beta, meaning it should be used very cautiously if used in producti

null 4k Dec 30, 2022