Hi Quantpians,
I am making my very early steps creating the algorithms, and getting stuck with some very very simple stuff, which drives me completely nuts, so any help would be really really appreciated.
I was trying to build an extremely simply algorithm, not for the sake of its functionality, but just to make sure that the code works, and this is where I got stuck. I have two securities and the idea is to buy those when the weighted average momentum for four periods (month, 3 months, 6 months, year) is positive. Portfolio rebalances once a month.
This is the code I tried (which is very similar to a functional code which I saw in one of the tutorials).
def initialize(context):
context.security_list = [sid(24), sid(5061)]
schedule_function(handle_data, date_rules.month_start(0), time_rules.market_open(minutes = 30))
def compute_weights(context, data):
hist = data.history(context.security_list, 'close', 240, '1d')
m1 = hist.pct_change(20)
m3 = hist.pct_change(60)
m6 = hist.pct_change(120)
m12 = hist.pct_change(240)
momentum_13612 = (m1*12 + m3*4 + m6*2 + m12)/4
if momentum_13612 > 0:
weight = 0.5
else:
weight = 0
return weight
def handle_data(context, data):
wt = compute_weights(context, data)
for security in context.security_list:
if data.can_trade(security):
order_target_percent(security, wt[security])
The error that I am receiving is the following:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
There was a runtime error on line 31. ("wt = compute_weights(context, data)")
Can anyone please suggest what I am doing wrong?
Many thanks in advance!