And some other options.
Since record() resolution is daily, can also be done in before_trading_start to catch yesterday's ending values if scheduling becomes a chore.
(in this case since the values are daily history)
Also showing some debugger output here.
'''
https://www.quantopian.com/posts/how-can-i-plot-moving-average-over-1-week-1-month-etc-for-multiple-stocks
Couple of charting examples
'''
def initialize(context):
c = context
c.stocks = symbols('AAPL', 'NFLX')
c.slow_ma = 21 # number of average trading days per month
c.fast_ma = 7
def before_trading_start(context,data):
c = context
hst = data.history(c.stocks, 'price', c.slow_ma, '1d')
'''
hst
DataFrame:
Equity(24 [AAPL]) Equity(23709 [NFLX])
2018-05-15 00:00:00+00:00 186.46 326.13
2018-05-16 00:00:00+00:00 188.19 328.32
2018-05-17 00:00:00+00:00 187.00 325.22
2018-05-18 00:00:00+00:00 186.29 324.18
2018-05-21 00:00:00+00:00 187.62 331.82
...
'''
ma_fast = hst[-c.fast_ma:].mean() # last 7
ma_slow = hst[:] .mean() # [:] meaning all
'''
> ma_fast
ma_fast: Series
Equity(24 [AAPL]): 192.364285714
Equity(23709 [NFLX]): 365.792857143
> ma_slow
ma_slow: Series
Equity(24 [AAPL]): 189.473809524
Equity(23709 [NFLX]): 349.997142857
> ma_fast[c.stocks[0]]
float64: 192.364285714
> ma_fast[c.stocks[1]]
float64: 365.792857143
'''
''' Charting '''
typical = 0
if typical: # hardcoded keys
# Custom chart can take 5 items.
# Since its resolution is daily, it doesn't hurt to run from here (before market open)
record(
aapl_ma_f = ma_fast[c.stocks[0]],
aapl_ma_s = ma_slow[c.stocks[0]],
nflx_ma_f = ma_fast[c.stocks[1]],
nflx_ma_s = ma_slow[c.stocks[1]],
aapl_prc = hst[c.stocks[0]][-1], # most recent value, same as data.current(c.stocks[0], 'price')
#nflx_prc = hst[c.stocks[1]][-1],
)
else: # Automatic keys in chart
# In this case ... for a bit more flexibility.
# There's a way to automatically assign symbols in chart legend
count = 0 # Have to keep count
for s in c.stocks:
record(**{s.symbol + '_f' : ma_fast[s]}) ; count += 1 # fast
if count == 5: break
record(**{s.symbol + '_s' : ma_slow[s]}) ; count += 1 # slow
if count == 5: break
# and just the latest price
record(**{s.symbol + '_prc' : hst[s][-1]}) ; count += 1
if count == 5: break