-
-
Save Duk2/0a5ae1861e21f176e299b7cb3841d7f2 to your computer and use it in GitHub Desktop.
LeveragedETF_Algo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import math | |
ratios = [] | |
for weight in np.arange(0.00,1.10, 0.10): | |
ratios.append([weight, 1 - weight]) | |
lookback = 84 | |
sd_power = 2.5 | |
def initialize(context): | |
#avoid not executed orders | |
set_slippage(slippage.FixedSlippage(spread=0.00001)) | |
#set commissions | |
set_commission(commission.PerShare(cost=0.05, min_trade_cost=1.25)) | |
# ETFs | |
context.symbols = [sid(37514), # SPXL | |
sid(38294)] # TMF | |
# Rebalance | |
schedule_function( | |
reallocate, | |
date_rules.month_end(), | |
time_rules.market_close(minutes = 15) | |
) | |
def reallocate(context, data): | |
price_history = data.history(context.symbols,'price',lookback,'1d') | |
returns = (price_history - price_history.shift(1)) / price_history.shift(1) | |
# Random initial values | |
ratio = [0, 1] | |
max_sharpe = -1000 | |
# Loop through each ratio | |
for c in range(len(ratios)): | |
temp_returns = returns.iloc[:, 0] * ratios[c][0] + returns.iloc[:, 1] * ratios[c][1] | |
cum_return = np.prod(1 + temp_returns) - 1 | |
ann_return = cum_return ** (252 / lookback) | |
ann_sd = temp_returns.std() * math.sqrt(252) | |
sharpe = ann_return / (ann_sd ** sd_power) | |
if sharpe > max_sharpe: | |
ratio = ratios[c] | |
max_sharpe = sharpe | |
order_target_percent(context.symbols[0], ratio[0]) | |
order_target_percent(context.symbols[1], ratio[1]) | |
record(context.symbols[0], ratio[0]) | |
record(context.symbols[1], ratio[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment