Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
anilb: How can I plot moving average over 1 week, 1 month, etc. for multiple stocks?

This code below does not seem to plot Apple, and Netflix stocks.
Please advice.

def initialize(context):  
    context.security = symbols("AAPL","NFLX")

def getMovingAvg(data, security, n):  
    price_hist = data.history(security, 'price', n, '1d')  
    return(price_hist.mean())

def handle_data(context, data):  
    for security in context.security:  
        if security in data:  
            mvavg7 = getMovingAvg(data, security, 7)  # 1 week mvg  
            mvavg30 = getMovingAvg(data, security, 30)  # 1 month mvg  
            current_price = data[security].price

            record(MA_WK=mvavg7,  
                   MA_Mnth=mvavg30,  
                   Price= current_price)  
3 responses

Anil ,

Try this way:

# --------------------------------------------------------  
stocks = symbols('AAPL','NFLX'); slow_ma = 30; fast_ma = 7  
# --------------------------------------------------------  
def initialize(context):  
    schedule_function(record_mavg, date_rules.every_day(), time_rules.market_close())

def record_mavg(context,data):    

    ma_fast = data.history(stocks, 'price', fast_ma, '1d').mean()  
    ma_slow = data.history(stocks, 'price', slow_ma, '1d').mean()    

    record(aapl_ma_f = ma_fast[0],  
           aapl_ma_s = ma_slow[0],  
           nflx_ma_f = ma_fast[1],  
           nflx_ma_s = ma_slow[1],  
           )  

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  

Thanks a ton, Vladimir, and Blue Seahawk.