Giter Club home page Giter Club logo

ta's Introduction

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 43 indicators:

Volume

ID Name Class defs
1 Money Flow Index (MFI) MFIIndicator money_flow_index
2 Accumulation/Distribution Index (ADI) AccDistIndexIndicator acc_dist_index
3 On-Balance Volume (OBV) OnBalanceVolumeIndicator on_balance_volume
4 Chaikin Money Flow (CMF) ChaikinMoneyFlowIndicator chaikin_money_flow
5 Force Index (FI) ForceIndexIndicator force_index
6 Ease of Movement (EoM, EMV) EaseOfMovementIndicator ease_of_movement
sma_ease_of_movement
7 Volume-price Trend (VPT) VolumePriceTrendIndicator volume_price_trend
8 Negative Volume Index (NVI) NegativeVolumeIndexIndicator negative_volume_index
9 Volume Weighted Average Price (VWAP) VolumeWeightedAveragePrice volume_weighted_average_price

Volatility

ID Name Class defs
10 Average True Range (ATR) AverageTrueRange average_true_range
11 Bollinger Bands (BB) BollingerBands bollinger_hband
bollinger_hband_indicator
bollinger_lband
bollinger_lband_indicator
bollinger_mavg
bollinger_pband
bollinger_wband
12 Keltner Channel (KC) KeltnerChannel keltner_channel_hband
keltner_channel_hband_indicator
keltner_channel_lband
keltner_channel_lband_indicator
keltner_channel_mband
keltner_channel_pband
keltner_channel_wband
13 Donchian Channel (DC) DonchianChannel donchian_channel_hband
donchian_channel_lband
donchian_channel_mban
donchian_channel_pband
donchian_channel_wband
14 Ulcer Index (UI) UlcerIndex ulcer_index

Trend

ID Name Class defs
15 Simple Moving Average (SMA) SMAIndicator sma_indicator
16 Exponential Moving Average (EMA) EMAIndicator ema_indicator
17 Weighted Moving Average (WMA) WMAIndicator wma_indicator
18 Moving Average Convergence Divergence (MACD) MACD macd
macd_diff
macd_signal
19 Average Directional Movement Index (ADX) ADXIndicator adx
adx_neg
adx_pos
20 Vortex Indicator (VI) VortexIndicator vortex_indicator_neg
vortex_indicator_pos
21 Trix (TRIX) TRIXIndicator trix
22 Mass Index (MI) MassIndex mass_index
23 Commodity Channel Index (CCI) CCIIndicator cci
24 Detrended Price Oscillator (DPO) DPOIndicator dpo
25 KST Oscillator (KST) KSTIndicator kst
kst_sig
26 Ichimoku Kinkō Hyō (Ichimoku) IchimokuIndicator ichimoku_a
ichimoku_b
ichimoku_base_line
ichimoku_conversion_line
27 Parabolic Stop And Reverse (Parabolic SAR) PSARIndicator psar_down
psar_down_indicator
psar_up
psar_up_indicator
28 Schaff Trend Cycle (STC) STCIndicator stc
29 Aroon Indicator AroonIndicator aroon_down
aroon_up

Momentum

ID Name Class defs
30 Relative Strength Index (RSI) RSIIndicator rsi
31 Stochastic RSI (SRSI) StochRSIIndicator stochrsi
stochrsi_d
stochrsi_k
32 True strength index (TSI) TSIIndicator tsi
33 Ultimate Oscillator (UO) UltimateOscillator ultimate_oscillator
34 Stochastic Oscillator (SR) StochasticOscillator stoch
stoch_signal
35 Williams %R (WR) WilliamsRIndicator williams_r
36 Awesome Oscillator (AO) AwesomeOscillatorIndicator awesome_oscillator
37 Kaufman's Adaptive Moving Average (KAMA) KAMAIndicator kama
38 Rate of Change (ROC) ROCIndicator roc
39 Percentage Price Oscillator (PPO) PercentagePriceOscillator ppo
ppo_hist
ppo_signal
40 Percentage Volume Oscillator (PVO) PercentageVolumeOscillator pvo
pvo_hist
pvo_signal

Others

ID Name Class defs
41 Daily Return (DR) DailyReturnIndicator daily_return
42 Daily Log Return (DLR) DailyLogReturnIndicator daily_log_return
43 Cumulative Return (CR) CumulativeReturnIndicator cumulative_return

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.

ta's People

Contributors

alexgorbachev avatar bastianzim avatar bbriegel avatar bpradana avatar bukosabino avatar christian-janiake-movile avatar cjaniake avatar cobrobrown avatar codeninja avatar codyharris-circle avatar coire avatar d5lewis avatar devenygaard avatar groni3000 avatar i-gutierrez avatar innaky avatar lit26 avatar mcmartins avatar michelmetran avatar mnr73 avatar monism123 avatar mprivat avatar reesh19 avatar riless avatar sam-kleiner avatar sblackstone avatar twopirllc avatar yarimiz 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

ta's Issues

Issue in the calculation of the EMA

I might be wrong here, but i think the calculation of the EMA is not entirely correct.

Current code:

def ema(series, periods):
    sma = series.rolling(window=periods, min_periods=periods).mean()[:periods]
    rest = series[periods:]
    return pd.concat([sma, rest]).ewm(span=periods, adjust=False).mean()

Analysis:
Assuming that periods=5. (for easier explanation)
The first line of code results in the first 4 rows to be NaN
and the 5th row to be the SMA of the first 5 rows.
Then you fuse that together with the rest of the series.
This causes the 6th row to be the result of the EMA of:
[None, None, None, None, SMA for first 5 rows, EMA of(4xNone+SMA for first 5 rows)]

Problems:
The 5th row is an SMA.
The following rows are still not a calculation of the expected 5 prices,
but instead of NaN, the SMA and then the actual prices.

I made a quick Jupyter Notebook for a better explanation:
https://colab.research.google.com/drive/1aPb0qPoeNWVLIk_ErhvoZTk1ImNzznCO

My proposition:

def ema(series, periods, fillna=False):
    if fillna is True:
        return series.ewm(span=periods, min_periods=0, adjust=False).mean()

    return series.ewm(span=periods, min_periods=periods, adjust=False).mean()

ADX pos,ADX neg and adx giving always 20.

Hi,
Toady, i ran adx again by fresh install of your ta ,
looks like recently you have performed changes ta lib and adx functionality is not working.

df['adx_pos']=trend.adx_pos( df['high'], df['low'], df['close'], n=8    , fillna=True)
df['adx_neg']=trend.adx_neg(df['high'], df['low'], df['close'], n=8, fillna=True)
df['adx']=trend.adx(df['high'], df['low'], df['close'], n=8,fillna=True)

could you please resolve this issue ASAP. looks like some return get_min_max function not proper.

        adx_pos  adx_neg   adx    high     low    SYMBOL   close   macd  macd_signal    rsi   3_ema  14_ema

date
2019-04-05 0.0 0.0 0.0 768.75 756.10 AXISBANK 762.20 0.00 0.00 50.00 762.20 762.20
2019-04-08 0.0 0.0 0.0 768.00 748.55 AXISBANK 754.60 -0.17 -0.09 0.00 757.64 758.13
2019-04-09 0.0 0.0 0.0 766.00 751.00 AXISBANK 763.40 0.06 -0.03 57.19 760.37 760.14
2019-04-10 0.0 0.0 0.0 767.90 758.00 AXISBANK 760.85 0.07 0.00 48.01 760.57 760.36
2019-04-11 0.0 0.0 0.0 761.35 747.00 AXISBANK 752.30 -0.27 -0.08 29.62 757.39 758.26
2019-04-12 0.0 0.0 0.0 766.75 751.60 AXISBANK 764.35 0.05 -0.05 56.63 759.94 759.67
2019-04-15 0.0 0.0 0.0 770.20 760.00 AXISBANK 762.85 0.18 0.01 53.68 760.97 760.34
2019-04-16 0.0 0.0 0.0 776.00 765.10 AXISBANK 771.10 0.66 0.17 65.21 764.48 762.44
2019-04-18 0.0 0.0 0.0 779.00 769.00 AXISBANK 771.20 0.99 0.36 65.33 766.78 764.05
2019-04-22 20.0 20.0 0.0 768.90 750.55 AXISBANK 755.50 0.40 0.37 40.11 762.95 762.56
2019-04-23 20.0 20.0 0.0 759.30 749.00 AXISBANK 753.25 -0.15 0.25 37.70 759.68 760.99
2019-04-24 20.0 20.0 0.0 755.70 738.35 AXISBANK 752.85 -0.58 0.07 37.25 757.39 759.67
2019-04-25 20.0 20.0 0.0 758.55 738.55 AXISBANK 740.90 -1.56 -0.27 26.25 751.86 756.70
2019-04-26 20.0 20.0 0.0 765.15 747.25 AXISBANK 759.90 -1.18 -0.46 52.16 754.55 757.20
2019-04-30 20.0 20.0 0.0 769.70 755.80 AXISBANK 766.85 -0.46 -0.46 58.34 758.66 758.65
2019-05-02 20.0 20.0 20.0 767.80 748.05 AXISBANK 752.35 -0.79 -0.53 44.50 756.55 757.72
2019-05-03 20.0 20.0 20.0 763.80 753.45 AXISBANK 757.30 -0.72 -0.57 49.25 756.80 757.66
2019-05-06 20.0 20.0 20.0 753.40 744.10 AXISBANK 747.45 -1.28 -0.71 41.17 753.68 756.18
2019-05-07 20.0 20.0 20.0 755.50 740.00 AXISBANK 741.85 -2.06 -0.98 37.17 749.74 754.14
2019-05-08 20.0 20.0 20.0 744.75 733.35 AXISBANK 735.50 -3.04 -1.40 32.98 744.99 751.50
2019-05-09 20.0 20.0 20.0 740.50 729.40 AXISBANK 731.00 -4.07 -1.94 30.20 740.33 748.63
2019-05-10 20.0 20.0 20.0 738.50 729.50 AXISBANK 735.05 -4.54 -2.46 35.82 738.57 746.74
2019-05-13 20.0 20.0 20.0 742.85 730.00 AXISBANK 732.10 -5.05 -2.98 33.55 736.41 744.71
2019-05-14 20.0 20.0 20.0 738.50 722.50 AXISBANK 731.35 -5.44 -3.48 32.94 734.72 742.87
2019-05-15 20.0 20.0 20.0 737.70 716.10 AXISBANK 721.95 -6.34 -4.05 26.05 730.47 740.00
2019-05-16 20.0 20.0 20.0 735.00 718.70 AXISBANK 731.85 -6.26 -4.50 41.03 730.93 738.89
2019-05-17 20.0 20.0 20.0 752.15 727.20 AXISBANK 748.95 -4.92 -4.58 57.99 736.93 740.26
2019-05-20 20.0 20.0 20.0 790.65 760.20 AXISBANK 782.40 -1.42 -3.95 74.52 752.09 745.98
2019-05-21 20.0 20.0 20.0 791.80 771.05 AXISBANK 772.95 0.64 -3.03 66.05 759.04 749.63
2019-05-22 20.0 20.0 20.0 784.00 770.20 AXISBANK 779.15 2.69 -1.88 68.74 765.75 753.62
2019-05-23 20.0 20.0 20.0 804.30 770.60 AXISBANK 776.40 4.07 -0.69 66.06 769.30 756.70
2019-05-24 20.0 20.0 20.0 795.90 778.50 AXISBANK 793.20 6.33 0.71 73.38 777.26 761.61
2019-05-27 20.0 20.0 20.0 816.40 787.20 AXISBANK 813.90 9.56 2.48 79.62 789.48 768.65
2019-05-28 20.0 20.0 20.0 822.10 801.00 AXISBANK 808.40 11.56 4.30 74.28 795.78 773.99
2019-05-29 20.0 20.0 20.0 813.00 802.10 AXISBANK 804.70 12.72 5.98 70.60 798.76 778.11
2019-05-30 20.0 20.0 20.0 814.20 803.25 AXISBANK 807.55 13.69 7.52 71.84 801.69 782.06
2019-05-31 20.0 20.0 20.0 818.70 793.20 AXISBANK 808.30 14.35 8.89 72.20 803.89 785.58
2019-06-03 20.0 20.0 20.0 814.65 803.10 AXISBANK 812.65 15.03 10.12 74.37 806.81 789.20
2019-06-04 20.0 20.0 20.0 827.75 805.50 AXISBANK 822.80 16.16 11.33 78.81 812.14 793.70
2019-06-06 20.0 20.0 20.0 825.95 805.80 AXISBANK 807.70 15.71 12.20 60.73 810.66 795.57
2019-06-07 20.0 20.0 20.0 813.25 801.30 AXISBANK 804.00 14.89 12.74 57.03 808.44 796.70
2019-06-10 20.0 20.0 20.0 816.75 807.40 AXISBANK 814.15 14.86 13.17 63.98 810.34 799.03
2019-06-11 20.0 20.0 20.0 821.45 807.00 AXISBANK 814.80 14.72 13.48 64.40 811.83 801.14
2019-06-12 20.0 20.0 20.0 815.75 809.10 AXISBANK 813.55 14.34 13.65 62.76 812.40 802.80
2019-06-13 20.0 20.0 20.0 823.40 810.75 AXISBANK 820.15 14.39 13.80 67.77 814.99 805.11
2019-06-14 20.0 20.0 20.0 823.10 797.45 AXISBANK 801.20 12.80 13.60 46.87 810.39 804.59
2019-06-17 20.0 20.0 20.0 801.00 775.10 AXISBANK 777.70 9.57 12.79 32.52 799.49 801.00
2019-06-18 20.0 20.0 20.0 784.85 770.10 AXISBANK 775.75 6.78 11.59 31.60 791.58 797.63
2019-06-19 20.0 20.0 20.0 789.00 763.35 AXISBANK 770.70 4.13 10.10 29.12 784.62 794.04
2019-06-20 20.0 20.0 20.0 775.45 758.85 AXISBANK 771.40 2.06 8.49 30.00 780.21 791.02
2019-06-21 20.0 20.0 20.0 778.25 762.80 AXISBANK 771.05 0.39 6.87 29.78 777.16 788.35
2019-06-24 20.0 20.0 20.0 775.25 761.00 AXISBANK 762.85 -1.57 5.18 24.99 772.39 784.95
2019-06-25 20.0 20.0 20.0 783.00 756.55 AXISBANK 781.65 -1.61 3.82 47.39 775.48 784.51
2019-06-26 20.0 20.0 20.0 792.00 781.70 AXISBANK 788.60 -1.08 2.84 53.33 779.85 785.06
2019-06-27 20.0 20.0 20.0 806.85 781.60 AXISBANK 800.45 0.29 2.33 61.82 786.72 787.11
2019-06-28 20.0 20.0 20.0 812.90 793.30 AXISBANK 808.55 1.99 2.26 66.61 793.99 789.97
2019-07-01 20.0 20.0 20.0 819.00 807.45 AXISBANK 810.45 3.45 2.50 67.71 799.48 792.70
2019-07-02 20.0 20.0 20.0 812.55 800.75 AXISBANK 802.60 3.93 2.79 58.54 800.52 794.02
2019-07-03 20.0 20.0 20.0 811.50 801.50 AXISBANK 806.20 4.55 3.14 61.31 802.41 795.64
2019-07-04 20.0 20.0 20.0 813.20 804.30 AXISBANK 808.85 5.20 3.55 63.39 804.56 797.41
2019-07-05 20.0 20.0 20.0 812.95 801.30 AXISBANK 806.10 5.42 3.93 59.56 805.07 798.57
2019-07-08 20.0 20.0 20.0 803.65 778.65 AXISBANK 782.90 3.70 3.88 37.50 797.68 796.48
2019-07-09 20.0 20.0 20.0 788.80 776.40 AXISBANK 786.20 2.57 3.62 41.08 793.85 795.11
2019-07-10 20.0 20.0 20.0 790.00 764.55 AXISBANK 769.25 0.32 2.96 30.67 785.65 791.66
2019-07-11 20.0 20.0 20.0 773.50 763.00 AXISBANK 766.40 -1.68 2.03 29.23 779.24 788.29
2019-07-12 20.0 20.0 20.0 768.60 751.00 AXISBANK 755.80 -4.07 0.81 24.33 771.42 783.96
2019-07-15 20.0 20.0 20.0 759.65 744.00 AXISBANK 749.75 -6.37 -0.62 21.92 764.20 779.40
2019-07-16 20.0 20.0 20.0 763.20 747.55 AXISBANK 761.05 -7.20 -1.94 35.69 763.15 776.95
2019-07-17 20.0 20.0 20.0 765.55 750.05 AXISBANK 752.60 -8.45 -3.24 30.97 759.63 773.70
2019-07-18 20.0 20.0 20.0 755.00 734.60 AXISBANK 740.40 -10.29 -4.65 25.39 753.22 769.26
2019-07-19 20.0 20.0 20.0 746.80 723.30 AXISBANK 729.25 -12.51 -6.22 21.33 745.23 763.93
2019-07-22 20.0 20.0 20.0 738.50 720.00 AXISBANK 727.45 -14.24 -7.83 20.71 739.30 759.06
2019-07-23 20.0 20.0 20.0 739.30 726.10 AXISBANK 728.00 -15.40 -9.34 21.51 735.54 754.92
2019-07-24 20.0 20.0 20.0 732.80 709.35 AXISBANK 712.30 -17.37 -10.95 16.15 727.79 749.24
2019-07-25 20.0 20.0 20.0 726.25 706.35 AXISBANK 723.15 -17.86 -12.33 30.06 726.24 745.76
2019-07-26 20.0 20.0 20.0 732.00 719.20 AXISBANK 729.85 -17.51 -13.37 37.45 727.45 743.64
2019-07-29 20.0 20.0 20.0 740.00 710.00 AXISBANK 720.25 -17.79 -14.25 31.88 725.05 740.52
2019-07-30 20.0 20.0 20.0 728.00 701.00 AXISBANK 707.60 -18.82 -15.17 26.00 719.23 736.13
2019-07-31 20.0 20.0 20.0 694.90 657.80 AXISBANK 674.10 -22.08 -16.55 16.63 704.19 727.86
2019-08-01 20.0 20.0 20.0 680.75 662.65 AXISBANK 669.30 -24.76 -18.19 15.69 692.56 720.05
2019-08-02 20.0 20.0 20.0 681.65 661.60 AXISBANK 673.85 -26.22 -19.80 20.58 686.32 713.89

for adx (n=30) getting index 30 is out of bounds for axis 0 with size 11

Hi,
I am getting exception, when adx(df['close],]n=30,True) is called, please see attached file for dataframe.
adx_30_index_bound_error.txt

Traceback (most recent call last):
File "./algo_trade_signals.py", line 3499, in
do_identify_multibagger_on_monthly_charts(datetime_object_from_datetime,datetime_object_to_datetime,df)
File "./algo_trade_signals.py", line 2115, in do_identify_multibagger_on_monthly_charts
df['adx']=trend.adx(df['high'], df['low'], df['close'], n=30,fillna=True)
File "/usr/local/lib/python2.7/dist-packages/ta/trend.py", line 179, in adx
adx[n] = dx[0:n].mean()
IndexError: index 30 is out of bounds for axis 0 with size 11
Q2: why adx values initially for dataframe begining, zeros for more than 30 columns??

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! ;)

Error in ATR calculation

Thank you for all the work that you've put into this library. It is very useful! I was just using the ATR function and believe I found a minor error in the calculation. After calculating the TRs, the first ATR is set using the mean TR from the entire period which would not be able to be calculated point in time:

atr[0] = tr[1::].mean()

The effect of this only lasts for the length of the rolling window but shouldn't we set the first ATR value to just the first TR?

I emailed you an example as well.

EMA keeps changing

Dear Developer,

Let me first express my gratitude for your project. I believe this is one of the best technical indicator library for python.

However, over the past couple of weeks, I have been having trouble with regression test. At first, the library had "ema_fast" and "ema_slow" functions, which were then replaced by a single "ema." This ema function had the default period of 14. However, the default value was removed as of version 2.

This results in code breaking down everytime the library is upgraded. This would make it difficult to use this library for a production code. I would like to suggest that you should not change the function signature outright, but rather show "deprecation warning" for a few versions first. So, people can migrate their codes.

Thank you very much.

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

Ease of Movement (EMV) (ta.volume)

A few minor things:

  1. The Ease function takes closing price as a positional argument, but the closing price isn't actually needed in the calculation.

2: The calculation itself is mostly correct, but is missing one step: It needs to be multiplied by 10^8 or 100,000,000.

3: The default n is 20, but I've only ever seen EMV calculated with n=14

TypeError: unsupported operand type(s) for -: 'str' and 'str' or KeyError: "['3,161.25' '3,147.20' '2,975.20' ... '10,600.25' '10,616.45' '10,619.55'] not in index"

df = pd.read_csv('D:/GLIM/Empirical/Data/NIFTY_ta.csv')

df.head()
Out[132]:
Date Open High Low Close Volume
0 10-Nov-08 2,973.30 3,161.25 2,973.30 3,148.25 25,07,00,000
1 11-Nov-08 3,147.20 3,147.20 2,919.45 2,938.65 22,16,54,000
2 12-Nov-08 2,937.90 2,975.20 2,794.95 2,848.45 25,04,60,000
3 14-Nov-08 2,848.00 2,938.80 2,778.80 2,810.35 25,67,42,000
4 17-Nov-08 2,813.40 2,835.70 2,694.50 2,799.55 25,12,20,000

Error 1

df2 = add_all_ta_features(df2, "Open", "High", "Low", "Close", "Volume", fillna=True)
Traceback (most recent call last):

File "", line 1, in
df2 = add_all_ta_features(df2, "Open", "High", "Low", "Close", "Volume", fillna=True)

File "D:\Setup Files\Anaconda3\lib\site-packages\ta\wrapper.py", line 185, in add_all_ta_features
df = add_volume_ta(df, high, low, close, volume, fillna=fillna)

File "D:\Setup Files\Anaconda3\lib\site-packages\ta\wrapper.py", line 26, in add_volume_ta
df[volume], fillna=fillna)

File "D:\Setup Files\Anaconda3\lib\site-packages\ta\volume.py", line 31, in acc_dist_index
clv = ((close - low) - (high - close)) / (high - low)

File "D:\Setup Files\Anaconda3\lib\site-packages\pandas\core\ops.py", line 1066, in wrapper
result = safe_na_op(lvalues, rvalues)

File "D:\Setup Files\Anaconda3\lib\site-packages\pandas\core\ops.py", line 1034, in safe_na_op
lambda x: op(x, rvalues))

File "pandas_libs\algos_common_helper.pxi", line 1212, in pandas._libs.algos.arrmap_object

File "D:\Setup Files\Anaconda3\lib\site-packages\pandas\core\ops.py", line 1034, in
lambda x: op(x, rvalues))

TypeError: unsupported operand type(s) for -: 'str' and 'str'

Error 2

df2 = add_all_ta_features(df2, df2['Open'], df2['High'], df2['Low'], df2['Close'], df2['Volume'], fillna=True)
Traceback (most recent call last):

File "", line 1, in
df2 = add_all_ta_features(df2, df2['Open'], df2['High'], df2['Low'], df2['Close'], df2['Volume'], fillna=True)

File "D:\Setup Files\Anaconda3\lib\site-packages\ta\wrapper.py", line 185, in add_all_ta_features
df = add_volume_ta(df, high, low, close, volume, fillna=fillna)

File "D:\Setup Files\Anaconda3\lib\site-packages\ta\wrapper.py", line 25, in add_volume_ta
df['volume_adi'] = acc_dist_index(df[high], df[low], df[close],

File "D:\Setup Files\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2679, in getitem
return self._getitem_array(key)

File "D:\Setup Files\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2723, in _getitem_array
indexer = self.loc._convert_to_indexer(key, axis=1)

File "D:\Setup Files\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1327, in _convert_to_indexer
.format(mask=objarr[mask]))

KeyError: "['3,161.25' '3,147.20' '2,975.20' ... '10,600.25' '10,616.45' '10,619.55'] not in index"

Can you add Stochastic RSI ?

There is already a stochastic oscillator indicator, but can you also add Stochastic RSI indicator ? It would be of great help. I haven't found a single Stochastic RSI indicator, that matches with the one from Trading view.

On Balance Volume calculation error

EDIT: I updated my original answer because I think this might be better

Thanks for the hard work on the library. I noticed a bug in the calculation for On Balance Volume.

In the code:

` df = pd.DataFrame([close, volume]).transpose()

df['OBV'] = 0

c1 = close < close.shift(1)

c2 = close > close.shift(1)

if c1.any():

    df.loc[c1, 'OBV'] = - volume

if c2.any():

    df.loc[c2, 'OBV'] = volume

obv = df['OBV']

if fillna:

    obv = obv.replace([np.inf, -np.inf], np.nan).fillna(0)

return pd.Series(obv, name='obv')`

the lines:

if c1.any():

    df.loc[c1, 'OBV'] = - volume

if c2.any():

    df.loc[c2, 'OBV'] = volume`

don't seem to allow the OBV value to propagate through time. It is resetting obv = volume every time the close price is higher than the previous period, and obv = - volume every time the price closes lower.

If you initialize the OBV for period zero to be equal to volume at period zero then you should be able to apply a cumulative sum with cumsum . ex:

df.loc[0,'OBV'] = df.loc[0,'Volume']

Then assuming you keep the code you have, you can apply cumsum to what we currently have as the OBV column:

df.loc[:,'OBV']= df['OBV'].cumsum()

This should keep the cumulative sum as needed with as little effort as possible IMO.

can you please add divergences for each indicators

Hi,
you can reach me on: [email protected]
When i read the documentation, and investopedia, i found that, even though indicators calculation is fine, but finding bullish divergences, bearish divergences, bullish failover, brearing failover are very and most important than, just finding techincal indicators.
please let me know if you need my help in python code development for the same.
I am a programmer from india, and very much liked your library.
i can contribute to your python lib, for divergences as a seperate library /method call for each technical indicator.

ADX results in all nan when index of dataframe does not start at 1

The dataframe I passed into the adx method had been resampled and the indexes were something like 60,120,180.

On line 144:
trs[0] = tr.dropna()[0:n].sum()

Due to my index starting at sixty, the series had no values after slicing and the sum was 0. This caused a divide by zero and created a nan. This caused din and dip to have the first value in the series be nan, which then resulted in all adx values being nan.

On line 145 there is a reset index. If this was moved prior to the sum for trs[0] it would resolve the issue. I'm not sure if there are other implications of doing that.

About Adding Weighted Moving Average

Hi!

First of all, really appreciate your effort in making TA calculation a lot easier in Python!

I just have one little request, can you add weighted moving average (WMA) in the library? Since simple moving average and exponential moving average are already in, WMA is also quite useful.

rsi with n=30 days value calc

Hi,
I would like to calculate rsi for monthly performance, to get long term investment indicators using your rsi indicator.
Q: I would like to calculate rsi on daily stock market data with n=30 input parameter to your function: rsi(close, n=30, fillna=True),
will it work?.
Q: will this equiavalent to calculation of rsi(14) on monthly stock market data?
or what i mean is:
will rsi(30) on daily data in dataframe == rsi(14) on monthly data in dataframe?.

ADX gives nans

In adx calculation you have:
pdm = high.combine(cs, lambda x1, x2: get_min_max(x1, x2, 'max'))
pdn = low.combine(cs, lambda x1, x2: get_min_max(x1, x2, 'min'))

The get_min_max function is not returning the max and min. I believe you forgot to add the returns, i.e.
return max(x1, x2)
return min(x1, x2)

please add cci

@bukosabino

Hi

Please can you add CCI (Commodity Channel Index) indicator too?

If you don't know, there are three different Momentum base formulas in TA : MACD, TSI, and CCI.

You already have two of them why not adding the last one please?

Data from future

Hi

I wanted to ask if the add_all_ta_features uses data from future candles or just current and past only
Thanks
P.S. Great work

LSTM model code for df

Hi bukosabino,

As you are doing a great work, on ta using python.
Is it possible for you to make , a LSTM(Long short term memory model) using machine learning/data science to predict the stock market prices?.
I heard that, LSTM model is excellent model close to ~90% prediction rate for timeseries data of stocks.

Please let me know, if you need more information.

Problem calculating average true range

Hola,

First thank you for making this library available to the rest of us, second I have problem using the average_true_range function. As an example, I just tried to calculate the same values of the example you put as a reference:

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

But I couldn't get the same result as the refered page. I made sure my values were right, and finally I think the problem lies in the utils.ema function, and the way it calls pandas.ewm function.

I got it to produce the desired values, by calling the ewm function and specify the decay in terms of center of mass, like this:

return pd.concat([sma, rest]).ewm(com=(self.periods-1), adjust=False).mean()

instead of calling it like:

return pd.concat([sma, rest]).ewm(span=periods, adjust=False).mean()

why do you have the calculation of the average using the decay in terms of span?

Received error using ADX 'str' object has no attribute 'shift'

I received an error when attempting to use the ADX feature using the code below:

df_data = pd.DataFrame()
df_data = pd.read_csv(text_response,names=fieldnames)
df_data= df_data.set_index('Date')
df_data['ADX']=ta.trend.adx('High','Low','Close',n=25,fillna=True)

These are the error messages that I received:

`
  File "<ipython-input-140-f9e022ae3a9c>", line 1, in <module>
    runfile('/home/tim/python/fx_related/fx_import.py', wdir='/home/tim/python/fx_related')

  File "/home/tim/anaconda3/lib/python3.6/site-packages/spyder_kernels/customize/spydercustomize.py", line 668, in runfile
    execfile(filename, namespace)

  File "/home/tim/anaconda3/lib/python3.6/site-packages/spyder_kernels/customize/spydercustomize.py", line 108, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/home/tim/python/fx_related/fx_import.py", line 36, in <module>
    df_data['ADX']=ta.trend.adx('High','Low','Close',n=25,fillna=True)

  File "/home/tim/anaconda3/lib/python3.6/site-packages/ta/trend.py", line 137, in adx
    cs = close.shift(1)

AttributeError: 'str' object has no attribute 'shift'
```

Is anyone else having this problem?
Thanks

Installation error

While installing I get following error -
I am on Python 2.7.10

pip install ta Collecting ta Using cached https://files.pythonhosted.org/packages/68/29/e2b9a4ad5f8710a0913d9fc1abb52c5b89ecf7ea036f8a8d8e4e73b08009/ta-0.1.4.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 20, in <module> File "/private/var/folders/53/3syytbw50fnc0stv_tz8s7qwmcg7vv/T/pip-build-ESKw_I/ta/setup.py", line 21, in <module> classifiers = [], File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 124, in setup dist.parse_config_files() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 390, in parse_config_files parser.read(filename) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ConfigParser.py", line 305, in read self._read(fp, filename) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ConfigParser.py", line 546, in _read raise e ConfigParser.ParsingError: File contains parsing errors: setup.cfg [line 2]: ' description-file = README.md\n'

fillna - fill last known value

Hey there!

While working with the library I dug through the library and found for instance for RSI that you just fill N/A values with 50:
momentum.py:48

if fillna:
        rsi = rsi.fillna(50)

is there any possible way to use pandas default fill-options like ffill on the df to just get the last known value if a new one cannot be established?

Pandas problem

Hi I have problem to generate average_true_range.

It looks that there is problem in pandas.

I using python 3.6, pandas 0.23.4

(ta_2) c:\repos\ta_test\ta-master\examples_to_use>python all_features_example.py
Index(['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume_BTC',
'Volume_Currency', 'Weighted_Price'],
dtype='object')
Traceback (most recent call last):
File "all_features_example.py", line 17, in
fillna=True)
File "C:\Users\nxa18933\AppData\Local\Continuum\anaconda3\envs\ta_2\lib\site-packages\ta\wrapper.py", line 190, in add_all_ta_features
df = add_volatility_ta(df, high, low, close, fillna=fillna)
File "C:\Users\nxa18933\AppData\Local\Continuum\anaconda3\envs\ta_2\lib\site-packages\ta\wrapper.py", line 54, in add_volatility_ta
n=14, fillna=fillna)
File "C:\Users\nxa18933\AppData\Local\Continuum\anaconda3\envs\ta_2\lib\site-packages\ta\volatility.py", line 44, in average_true_range
atr[i] = (atr[i-1] * (n-1) + tr[i]) / n
File "C:\Users\nxa18933\AppData\Local\Continuum\anaconda3\envs\ta_2\lib\site-packages\pandas\core\series.py", line 767, in getitem
result = self.index.get_value(self, key)
File "C:\Users\nxa18933\AppData\Local\Continuum\anaconda3\envs\ta_2\lib\site-packages\pandas\core\indexes\base.py", line 3118, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas_libs\index.pyx", line 106, in pandas._libs.index.IndexEngine.get_value
File "pandas_libs\index.pyx", line 114, in pandas._libs.index.IndexEngine.get_value
File "pandas_libs\index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\hashtable_class_helper.pxi", line 958, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas_libs\hashtable_class_helper.pxi", line 964, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 3

I can not install ta with pip help plss

Hey this is the error I get, would be really happy if someone can help me, thankss

Collecting ta
Using cached https://files.pythonhosted.org/packages/ba/09/149cb10cbd6b98cbcbaa6f74169b4f1f2ce6df144335bea0df0eaa9e1b01/ta-0.4.2.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "/private/var/folders/hc/b2dnskds513b2dxjnv8m3g_40000gn/T/pip-install-ceehcvvi/ta/setup.py", line 14, in
install_requires=open('requirements.txt').readlines(),
FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt'

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

Wrong Bollinger Band?!

Hi
I have the whole 1 hour candle data of bitcoin from bitmex, you can't say they are wrong.
Then i replace nan with epsilon values
Collecting the data from index one forward
using the same code you showed in the read me for bollinger

the bollingers are,... anything but bollinger ! they are more like a spike every now and then between 0 and 1 !!!

http://prntscr.com/nbdmz4

the correct function call should be bollinger_lband for the bollinger bands themselves, maybe you could correct the ream me file. I understand that you are calculating something different for bollinger band indicator method. but showing an image of bollinger in read me, then putting those two function calls as example, will confuse users.

Also, a little file that showed all the available functions with their parameters as a reference would be nice. if you want, i can put near an hour and make that list for you

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

ADX Method Divide by Zero Error (ta 0.3.7)

I've seen an issue the trs[i] value can equal zero giving this error:

/usr/local/lib/python3.6/dist-packages/ta/trend.py:170: RuntimeWarning: invalid value encountered in double_scalars
  dip[i] = 100 * (dip_mio[i]/trs[i])
/usr/local/lib/python3.6/dist-packages/ta/trend.py:174: RuntimeWarning: invalid value encountered in double_scalars
  din[i] = 100 * (din_mio[i]/trs[i])

I've checked the pandas series sent to adx, and there are no np.nan, or None values in them.

It needs to be handled in some way. The code doesn't crash, it just gives a warning.

ta version 0.3.7

Naming of Indicators

Hey there! I just fiddled around with your library and I really like it. One thing that feels kinda strange: when applying all indicators, the header just states "trend1" and so on, not the name of the actual indicator. This makes working with it quite tough.

Any chance that I missed something here?

Thank you!

Bug with ADI calculation

ta/ta/volume.py

Lines 33 to 34 in 953be3d

ad = clv * volume
ad = ad + ad.shift(1)

I believe this not calculating the ADI correctly.

Per wikipedia the ADI should be ADI(prev) + volume X CLV
What those lines above are doing is (volume x CLV)(prev) + (volume x CLV)

So it's not propagating the previous ADI value to calculate the next ADI value, but rather the previous (volume x CLV) value.

Some features report no value for some latest candles

Hey there, me again :D

So I ran some tests and watched the data and encountered some of the features giving me 0.0 as value. Some others suddenly lock in at strange fixed values also. (on the right in the screenshot, kcc at 7023.3 as an example)

I will attach a screenshot as well as the csv file that got created from my data.
(CSV is not supported by Github upload so I will attach a PDF)
output.pdf

bildschirmfoto 2018-07-18 um 01 33 59

Allow option to mitigate NaNs and 0.0s at the top of returned dataframe

I have seen this issue about seeing NaNs and 0.0s at the top of the returned dataframe when certain functions are used. Would it be possible to include the option to mitigate these NaNs and 0.0s? I am not referring to the fillna strategy, but rather something related to the calculation.
For example, I noticed that the cause of many of these NaNs and 0.0s are due to the use of pandas functions df.rolling(), df.shift() and df.diff(). The fixes would be to include parameters df.rolling(min_periods=0) and df.shift(fill_value=x) where x is some fill strategy like df.mean() or df.median(). Maybe this would not be a true representation of the calculation, but when using these functions for live data, they can provide some predictive power to any model as long as there are values (and not NaNs or 0.0s).
I can work on the implementation as this library has already proved extraordinarily useful and I would like to contribute. But I have not contributed to another project yet, so it might take some hand-holding.

Tests

Hey there,

Nice job with this library!

Can I ask why you have no (unit) tests to verify the correctness of the implementation of the indicators ?

I may be able to contribute there.

Cheers,

Missing sklearn module dependency

pip3 install ta succeeds.

>>> import pandas as pd
>>> from ta import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/ta/__init__.py", line 11, in <module>
    from .pipeline_wrapper import *
  File "/usr/local/lib/python3.6/dist-packages/ta/pipeline_wrapper.py", line 2, in <module>
    from sklearn.base import TransformerMixin, BaseEstimator
ModuleNotFoundError: No module named 'sklearn'

So it looks like the 'ta' package is missing sklearn as a dependency.

pip3 install sklearn

Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from ta import *
>>> 

Incorrect Bollinger low and high calculation

Bollinger low and high calculate the standard deviation as follows:

mstd = close.rolling(n, min_periods=0).std()

According to the Pandas documentation, std() uses (N - ddof) as the denominator, where ddof defaults to 1, unlike numpy std().

StockCharts has an example of Bollinger in Excel which, unsurprisingly, uses N as the denominator. Wikipedia explains that N - 1 is used if the sd is being calculated from a sample of the population, rather than the whole. As this is rolling, and a very small set of numbers, I assume Pandas is calculating the actual sd from all the data fed to it, therefore we should use N.

The high and low band Bollinger calcs should be:

mstd = close.rolling(n, min_periods=0).std(ddof=0)

The same applies to the Bollinger indicators.

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.

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.

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.