Im obviously new at this, as this probably is not hard to do. Im trying to set up a backtest where I sell SPY if data from external CSV file rise above 20-day SMA, and vice versa. Problem is I get an error in line 16, where I open orders. Hope any of you can point me in the right direction?
def initialize(context):
#Set up SPY and High-Yield Spreads from external CSV file as my universe
context.securities = [sid(8554),
fetch_csv("https://fred.stlouisfed.org/graph/fredgraph.csv?chart_type=line&recession_bars=on&log_scales=&bgcolor=%23e1e9f0&graph_bgcolor=%23ffffff&fo=Open+Sans&ts=12&tts=12&txtcolor=%23444444&show_legend=yes&show_axis_titles=yes&drp=0&cosd=2012-03-30&coed=2017-03-29&height=450&stacking=&range=Custom&mode=fred&id=BAMLH0A0HYM2&transformation=lin&nd=1996-12-31&ost=-99999&oet=99999&lsv=&lev=&mma=0&fml=a&fgst=lin&fgsnd=2009-06-01&fq=Daily%2C+Close&fam=avg&vintage_date=&revision_date=&line_color=%234572a7&line_style=solid&lw=2&scale=left&mark_type=none&mw=2&width=1168",date_column ='DATE',symbol="BAMLH0A0HYM2", date_format = '%Y-%m-%d')]
schedule_function(ma_handling, date_rules.every_day(), time_rules.market_open(hours=1))
#I want to buy SPY when HY-spreads rise above 20-day SMA
def spreadwidening(context, data):
price_history = data.history(BAMLH0A0HYM2, 20, "1d")
sma_20 = hist.mean()
open_orders =get_open_orders()
if BAMLH0A0HYM2 > sma_20:
if context.spy not in open_orders:
order_target_percent(context.spy, -1.0)
else BAMLH0A0HYM2 < sma_20:
if context.spy not in open_orders:
order_target_percent(context.spy, +1.0)
record(leverage = context.account.leverage)