Back to Community
Weighted Moving Average

Hi all,

I'm trying to calculate a weighted moving average with this code:

    # get info  
    stock = sid(42950)  
    # calculate weighted moving averages  
    past9 = data.history(stock, 'close', 9, '1d')  
    past50 = data.history(stock, 'close', 50, '1d')  
    wma9 = np.ma.average(past9, weights=np.arange(1,9))  
    wma50 = np.ma.average(past50, weights=np.arange(1,50))  

But I keep getting this error:

ValueError: operands could not be broadcast together with shapes (9,)
(8,) There was a runtime error on line 23.

Does anyone know what would cause this?

1 response

Steven,

Hopefully this helps!

# WMA indicator

import talib as ta  
import numpy as np 

def initialize(context):  
    schedule_function(WMA_indicator, date_rules.every_day(), time_rules.market_close(minutes = 1)) 

def WMA_indicator(context, data):  
    stock, ma = symbol('SPY'), 200  

    price = data.current(stock, 'price')  
    prices = data.history(stock, 'price', ma, '1d')

    wma_np = np.ma.average(prices, weights = np.arange(1, ma + 1))  
    wma_ta = ta.WMA(prices, ma)[-1]

    record(price = price, wma_np = wma_np, wma_ta = wma_ta)