Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to take indicator (such as SMA, RSI, EMA etc.) and feed into them stocks from context.portfolio.positions ?

Hi,

I'm interested in how to take indicator such as Simple moving average, RSI or EMA etc. and feed into them stock from context.portfolio.positions. Simply take Dictionary: A dictionary of all the open positions, keyed by security ID. Convert them to array and use this in for loop to value all open positions. I want to used it in my algorithm for exiting positions. I tried this code, but doesn't works and I don't know why...


for stock in context.portfolio.positions:  

    SMA_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],window_length=10,mask=stock)  
    SMA_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],window_length=30,mask=stock)  
    bSell = SMA_10 > SMA_30  
    print('Sell stock: ' , bSell)  

    if bSell and data.can_trade(stock):  
        order_target_percent(stock,0)

Thanks,
Michael

1 response

I found solution. So here is answer for someone with same question:

I import talib library

def record_SMA(context, data):  

    fast = 10  
    slow = 30  


    for stock in context.portfolio.positions:  
          prices = data.history(stock, 'close', slow, '1d')  
          SMA_fast = talib.SMA(prices, fast)[-1]  
          SMA_slow = talib.SMA(prices, slow)[-1]  
          bClose = SMA_slow < SMA_fast  

          if bClose and data.can_trade(stock):  
            order_target_percent(stock,0)  
            print('close position for stock:' , stock)