Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Keyerror 'SAR', can't figure it out, please hlep, thanks!

hi, all,
I'm trying to add a list to context object as context.SAR to store the last number from ta_sar. when I run the code, I kept getting "run time error, key error 'SAR' ".
I just can't figure it out, can some one shed a light on it?
many thanks!

def SAR_handling(context, data):
global c

H = data.history(context.stock,'high', 20, '1d').dropna()  
L = data.history(context.stock,'low', 20, '1d').dropna()  


ta_sar = talib.SAR(H, L, acceleration=0.02, maximum=0.2)  
context.SAR[c]=ta_sar[-1]  
c=c+1  
3 responses

I defined a global list SAR and changed the code to be:

H = data.history(context.stock,'high', 20, '1d').dropna()
L = data.history(context.stock,'low', 20, '1d').dropna()

ta_sar = talib.SAR(H, L, acceleration=0.02, maximum=0.2)
SAR.append(ta_sar[-1] )

this worked, but I still don't know why can't I attach the list to context object as context.SAR
I'm looking forward to an answer.
thanks again!

Try this:

import numpy as np  
import talib

def initialize(context):  
    schedule_function(trade, date_rules.every_day(), time_rules.market_close(minutes = 15))  
    context.SAR = [] 

def trade(context, data):  
    stock = symbol('SPY'); period = 20  

    price = data.current(stock,'price')  
    H = data.history(stock,'high', period, '1d').dropna()  
    L = data.history(stock,'low', period, '1d').dropna()

    ta_sar = talib.SAR(H, L, 0.02, 0.2)  
    # context.SAR = np.append(context.SAR, ta_sar[-1])  
    context.SAR.append(ta_sar[-1])  

    record(price = price, SAR = context.SAR[-1])  

it worked ! thank you Vladimir.
my problem was that i didn't declare context.SAR.
thank you for clear it our for me!