How do I calculate the moving average from yesterday

Good people,

Essentially, I'm trying to get the moving average from yesterday as opposed to from today (using .mavg)
I tried history function and iloc, which both don't get the job done.

Help would be appreciated!

Edit:
I want to take the difference between today's and yesterday's MA.
This is how I get today MA (it's in a loop).
moving_average = data[stock].mavg(200)

2 responses

Did you happen to solve the problem? I am looking to do the same thing.

You'll want to use pipeline to fetch data and calculate factors. The 'data' method is deprecated.

To get the average of the previous 200 days close prices simply use the built in factor SimpleMovingAverage...

from quantopian.pipeline.factors import SimpleMovingAverage
sma_200 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=200)



There isn't a built in factor for getting yesterdays value. So, one would need to write a simple custom factor. Maybe something like this.


from quantopian.pipeline import CustomFactor
import numpy as np

class SMA_200_Yesterday(CustomFactor):
inputs = [USEquityPricing.close]
# set the window length to 1 plus the moving average window
window_length = 201

def compute(self, today, assets, out, close):
# Take the mean of previous days but exclude the latest date
out[:] = np.nanmean(close[0:-1], axis=0)

sma_200_yesterday = SMA_200_Yesterday()



With these two factors you could get the difference like this

sma_delta = sma_200 - sma_200_yesterday



This difference could also be calculated directly in a single custom factor. Perhaps like this..


from quantopian.pipeline import CustomFactor
import numpy as np

class SMA_200_Yesterday_Diff(CustomFactor):
inputs = [USEquityPricing.close]
# set the window length to 1 plus the moving average window
window_length = 201

def compute(self, today, assets, out, close):
# Take the mean of previous days but exclude the latest date
out[:] = np.nanmean(close[1:], axis=0) - np.nanmean(close[0:-1], axis=0)