accessibility of daily moving average: Issue to get the current(today data if period is day) data ?
lf263820 Posts: 17
I have created a daily moving average variable. But I could not get the current moving average data when the period is day. I am able to get yesterday moving average. Here is below for the code.
def on_start(self, md, order, service, account): daily_bars = md.bar.daily(start=-200) ###moving average 0 for simple, 1 for ema dclose = daily_bars.close self.realSMA21 = talib.MA(dclose , timeperiod=21, matype=0) self.realSMA50 = talib.MA(dclose , timeperiod=50, matype=0)
I can get access to self.realSMA21[-1] (yesterday MA) but self.realSMA21 gives NAN so how to get access to today MA data?
A daily moving average is based on close prices..
So a 20 day MA price is the moving average of the previous 20 days.
It is super simple to calculate, you do not need TALIB, just sum the close prices for the last 20 days and divide by 20 (make sure you have 20 items in your list!!).
If you want it for the day before that, sum the close prices for the 20 days prior to that and divide by 20, easy.
Most of the time, for model decision making, when using a 20 day MA you are looking at something like.. current price is above or below the 20 day moving average price. ie the MA of the PREVIOUS 20 days.. You can't include today because you don't know today's close price until 4pm.
At the start of any day you do not have a close price for that day. If you did you would be forward-looking, that's a no, no.
So asking for the MA price for today is mute...
Now, saying that, there is a way of getting a 20 day MA including today.. live... you simply fold in the last traded price, put it as the last price in the list before you do your calculation.
But your code shows you are doing the calculation in on_start.. and depending on when you start your script and what type of symbol you are looking at you may not have a LAST price.
I am assuming you are doing some kind of beginning of the day calcuation.. if the price today is above or below the 20 day MA price then do this.
Hopefully this helps!
run on 12/23/2018 that that outputs the previous 20 days SPY close prices as follows...