Alpaca stock data averaging issue resolved.

ByJames Burnett

As I’m sitting here coding a new Swing Trading Python bot with the Alpaca API I noticed that one of my simple moving average values isn’t calculating correctly. My SMA function uses the built in pandas rolling mean function, dataframe.rolling(n).mean(). For some reason the moving average for my 120 window average does not match the moving average from any of my brokerage tools (ThinkOrSwim and Webull). All my other data aligns right up, RSI, SMA(20) but not my SMA(120).

I spent a good deal of time looking for my coding error. Knowing that I’ve had issues with Alpaca data in the past I decided to check the actual data being returned by the Alpaca trading API. Sure enough there is a problem with the Alpaca data stream. As you can see below the data in after hours is populated with a 0 which is throwing off my moving averages.

2021-03-02 14:15:00-05:00 85.38
2021-03-02 14:30:00-05:00 0
2021-03-02 14:45:00-05:00 0
2021-03-02 15:00:00-05:00 85.27
2021-03-02 15:15:00-05:00 84.94
2021-03-02 15:30:00-05:00 84.73
2021-03-02 15:45:00-05:00 84.12
2021-03-03 08:15:00-05:00 0
2021-03-03 08:30:00-05:00 0
2021-03-03 08:45:00-05:00 0
2021-03-03 09:00:00-05:00 0
2021-03-03 09:15:00-05:00 0
2021-03-03 09:30:00-05:00 83.92
2021-03-03 09:45:00-05:00 83.23
2021-03-03 10:00:00-05:00 82.47
2021-03-03 10:15:00-05:00 82.7
2021-03-03 10:30:00-05:00 82.7

My Fix.

To fix, I simply ignore any rows of data that has a closing price of zero.

        for bar in self.barset[symbol]:
            if bar.c > 0:
                timestamp.append(bar.t)   
                close.append(bar.c)
                volume.append(bar.v)
                open.append(bar.o)
                low.append(bar.l)
                high.append(bar.h)
%d bloggers like this: