One problem is how you calculate the moving average. The history
function returns a pandas.DataFrame
, which is a table with columns representing securities and rows representing timestamps (objects containing a date and time). Applying the .mean()
method produces either a pandas.Series
with entries indexed by securities and containing the mean for each security, ie. the 200-day simple moving average, which is what you want; or a pandas.Series
with entries indexed by timestamps and containing the average price at that time of the 4 securities you chose. I don't remember how pandas
applies its .mean
method. You can control this by specifying the axis=
keyword argument in your .mean
call. Or, to be safer, do what James does and first extract the column representing your security, then calculate its mean, which can be combined into sma = prices[stock].mean()
, if you first set prices = history(200,'1d','price')
.
The second problem is, as James mentioned, integer division. In Python and almost all other languages, 2/4
evaluates to 0. A time-honored hack is to either set one of the two operands to a floating-point value, here context.long_leverage = 2.0
, or explicitly convert one, eg. float(len(context.stocks))
; then the other operand is implicitly converted to a float
and floating-point division applied, yielding 0.5
.
Another minor thing is that you set context.long_leverage
to a fixed value and never change it. It would be more informative to record your actual leverage: record(context.account.leverage)
.
I also see that you never sell. Some of your stocks may grow beyond your desired allocation. You might want to add at the end something like
elif price > sma * 1.05:
order_target_percent(float(context.long_leverage)/len(context.stocks))