Back to Community
SPY Monthly 1000$ with MA weight

def rebalance(context, data):
price_history = data.history(context.assets, "price", 500, "1d")
ma = price_history.mean()[0]
last_price = price_history.iloc[-1][0]
log.info("ma:" + str(ma) + " last price:" + str(last_price))
rate = last_price / ma - 1
price_history2 = data.history(context.assets, "price", 10, "1d")
average2 = price_history2.sum()[0]/len(price_history2)
amplitude = (price_history2.max()[0] / average2 - 1) - (price_history2.min()[0] / average2 - 1)
weight = 1.0
if rate >= 1.0:
weight = 0.6
elif rate >= 0.5:
weight = 0.7
elif rate >= 0.15:
weight = 0.8
elif rate >= 0.05:
weight = 0.9
elif rate < 0 and rate >= -0.05 and amplitude > 0.05:
weight = 0.6
elif rate < 0 and rate >=-0.05 and amplitude <= 0.05:
weight = 1.6
elif rate < -0.05 and rate >=-0.1 and amplitude > 0.05:
weight = 0.7
elif rate < -0.05 and rate >=-0.1 and amplitude <= 0.05:
weight = 1.7
elif rate < -0.1 and rate >=-0.2 and amplitude > 0.05:
weight = 0.8
elif rate < -0.1 and rate >=-0.2 and amplitude <= 0.05:
weight = 1.8
elif rate < -0.2 and rate >=-0.3 and amplitude > 0.05:
weight = 0.9
elif rate < -0.2 and rate >=-0.3 and amplitude <= 0.05:
weight = 1.9
elif rate < -0.3 and rate >=-0.4 and amplitude > 0.05:
weight = 1.0
elif rate < -0.3 and rate >=-0.4 and amplitude <= 0.05:
weight = 2.0
elif rate < -0.4 and amplitude > 0.5:
weight = 1.1
elif rate < -0.4 and amplitude <= 0.5:
weight = 2.1
log.info("amplitude:" + str(amplitude) + " weight:" + str(weight))
for i in range(0, len(context.assets)):
order_value(context.assets[i], 1000*weight)

Clone Algorithm
3
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 581d7ab7c4f1a2132d5b81e9
There was a runtime error.