question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Issues with MACD Calculations

See original GitHub issue

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

import pandas_ta as ta
print(ta.version)

0.3.14b0

Do you have TA Lib also installed in your environment?

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

Did you upgrade? Did the upgrade resolve the issue?

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

I upgraded…

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

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

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

A clear and concise description of what the bug is.

To Reproduce

Provide sample code. Sample code above.

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

Screenshots image

Additional context Data csv below

Thanks for using Pandas TA!

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:17 (7 by maintainers)

github_iconTop GitHub Comments

1reaction
twopirllccommented, Feb 18, 2022

@schwaa,

The TV data and Alpaca data are always different. It is hard to know which to trust.

I’m not keen on Alpaca data. But any broker is subject to misprints and missing values when live streaming and even post-hoc. But whomever the broker is that you are placing actual transactions with, whether it’s IB, Alpaca, TDA, et al., you will have to trust their data at some point.

That said … these are too far off for algo trading, meaning a false cross up on the MACD causes a trade that shouldn’t happen, so I’m very motivated to figure out how to not get false positives and I understand it could be me that’s messing it up.

I understand.

However I am unconvinced that PTA is the issue here as it’s indicator values are consistent with TA Lib, primary purpose of PTA, and core TV indicators, ancillary. So when I see claims that an indicator, especially a core one, is not working, I get nervous. 😓 Don’t forget, for some indicators, that you need a larger set of bars to avoid the Unstable Period; you will have to figure out what is the minimum necessary bars to get expected values. I am using the max bars, 10235, I could get from TV for this comparison, but certainly you can converge with much less.


Your Data

schwaa_file = "schwaa-macd.csv"
df = pd.read_csv(schwaa_file, index_col="timestamp")
df.drop(columns=["trade_count", "vwap"], errors="ignore", inplace=True)
df.index.name = "datetime"

sch_macddf = df.iloc[:,-3:]
print(f"bars {df.shape[0]} from {df.index[0]}")
df.close.plot(figsize=(16,8), color=["black"], grid=True)
# df

Screen Shot 2022-02-18 at 7 46 47 AM

sch_macddf.plot(figsize=(16,2.5), color=["black", "blue", "purple"], grid=True).axhline(0, color="black")

Screen Shot 2022-02-18 at 7 46 58 AM

More Data (Max from TV)

CSV: BATS_SQQQ_30_schwaa_macd_max

# Max bars I could get from TV with tv.macd
schwaa_file = "BATS_SQQQ_30_schwaa_macd_max.csv"
df = pd.read_csv(schwaa_file, index_col="datetime")
df.drop(columns=["volume ma"], errors="ignore", inplace=True)
df.index.name = "datetime"
# print(df.columns)

# MACDs
_k = 3
sch_macddf = df.iloc[:,-_k:]
df.ta.macd(talib=False, presma=False, append=True)
pta_macddf = df.iloc[:,-_k:]
schwaa_pta_df = df.iloc[:,-2 * _k:]

# Last _m=39 bars
_m = 39
df = df.iloc[-_m:]
sch_macddf = sch_macddf.iloc[-_m:]
pta_macddf = pta_macddf.iloc[-_m:]
schwaa_pta_df = schwaa_pta_df.iloc[-_m:]


print(f"bars {df.shape[0]} from {df.index[0]}")
df.close.plot(figsize=(16,8), color=["black"], grid=True)

Screen Shot 2022-02-18 at 7 52 59 AM

Sanity Plots

sch_macddf.plot(figsize=(16,2.5), color=["blue", "black", "purple"], grid=True).axhline(0, color="black")

Screen Shot 2022-02-18 at 7 53 06 AM

pta_macddf.plot(figsize=(16,2.5), color=["black", "blue", "purple"], grid=True).axhline(0, color="black")

Screen Shot 2022-02-18 at 7 53 15 AM

Correlation

def highlight_top(s, v=0.98):
    return ["background-color: lightgreen" if cell else "" for cell in s > v]

schwaa_pta_corr = schwaa_pta_df.corr()
schwaa_pta_corr.style.apply(highlight_top)

Screen Shot 2022-02-18 at 7 58 19 AM

Row wise Comparison

schwaa_pta_df.iloc[:40].style.background_gradient()

Screen Shot 2022-02-18 at 7 53 50 AM


Hope this helps!

KJ

1reaction
schwaacommented, Feb 16, 2022

I also checked that my bars in the CSV match the bars in the Alpaca Graphic. But they get a very different result. Thank you

So, the CSV ohlcv values are not equal bar by bar with Alpaca?

The OHLCV data values ARE equal bar by bar with Alpaca. Both the chart and the data are coming from Alpaca. And I verified and handful of spot bars visually.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Why MACD Divergence Can Be an Unreliable Signal
One of the main problems with divergence is that it often signals a (possible) reversal but no actual reversal occurs—a false positive. The...
Read more >
Don't Trade Based on MACD Divergence Until You Read This
MACD divergence is highly inaccurate; why and under what conditions it is likely to produce false signals?
Read more >
You Just Misused the MACD Indicator For Your Trade
We calculate the MACD based on subtraction of the 26-period exponential moving average(EMA) over the 12-period EMA.
Read more >
MACD Indicator Explained | How Does It Work? - Finbold
One of the divergence problems is that it can signal a reversal, but it is a false positive. The other is that the...
Read more >
Two Great MACD Trading Signals - Incredible Charts
The problem with regular signals is that MACD is prone to whipsaws in the same way as the underlying moving averages on which...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found