This algo is basically a Frankenstein of code that I've cobbled together, but is currently broken and will not run. Would one of you guys with more experience then I have take a look at it and see if it can be fixed?
# Import the libraries that will be used in the algorithm
import statsmodels.api as sm
import talib
# "initialize(context)" is a required setup method for initializing state or
# other bookkeeping. This method is called only once at the beginning of your
# algorithm. "context" is an augmented Python dictionary used for maintaining
# state during your backtest or live trading session. "context" should be used
# instead of global variables in the algorithm. Properties can be accessed
# using dot notation (ex. "context.some_property").
def initialize(context):
# Ensure that only long positions are held in the portfolio
set_long_only()
# Define the securities that will be used within each portfolio variant.
context.aggressive = [
sid(25902), # Vanguard Consumer Discretionary ETF
sid(25903), # Vanguard Consumer Staples ETF
sid(26667), # Vanguard Energy ETF
sid(25904), # Vanguard Financials ETF
sid(25906), # Vanguard Health Care ETF
sid(26668), # Vanguard Industrials ETF
sid(25905), # Vanguard Information Technology ETF
sid(25898), # Vanguard Materials ETF
sid(26669), # Vanguard REIT ETF
sid(26670), # Vanguard Telecommunication Services ETF
sid(25908) # Vanguard Utilities ETF
]
context.defensive = [
sid(22887), # Vanguard Extended Duration Treasury ETF
sid(33650), # Vanguard Intermediate-Term Bond ETF
sid(38984), # Vanguard Intermediate-Term Government Bond ETF
sid(33649), # Vanguard Long-Term Bond ETF
sid(38988), # Vanguard Long-Term Government Bond ETF
sid(38983), # Vanguard Mortgage-Backed Securities ETF
sid(33651), # Vanguard Short-Term Bond ETF
sid(38986), # Vanguard Short-Term Government Bond ETF
sid(43529), # Vanguard Short-Term Inflation-Protected Securities ETF
sid(33652), # Vanguard Total Bond Market ETF
sid(38987), # Vanguard Intermediate-Term Corporate Bond ETF
sid(38982), # Vanguard Long-Term Corporate Bond ETF
sid(38985), # Vanguard Short-Term Corporate Bond ETF
sid(49366), # Vanguard Tax-Exempt Bond ETF
]
# Define the benchmark security the algorithm will use to guage the overall
# direction of the market.
context.benchmark = sid(8554) # SPDR S&P 500 ETF Trust
# Define the leverage that the algorithm will use. The inverse of the defined
# amount will be held as cash.
context.leverage = 0.9 # Hold 10% of the total portfolio value as cash
# Define the lookback period (in days) that the algorithm will use to calculate
# RSI.
context.fast_lookback = 100
context.slow_lookback = 200
# Define the rebalance schedule that the algorithm will use.
schedule_function(rebalance, date_rule = date_rules.week_start(days_offset = 2), time_rule = time_rules.market_open(minutes = 90)) # Rebalance every Wednesday 90 minutes after market open
# Define the regression calculation that the algorithm will use.
def regression(context, data, price):
X = range(len(price))
A = sm.add_constant(X)
Y = price.values
result = sm.OLS(Y, A).fit()
(b, a) = result.params
slope = a / b * 252.0
return slope
# Define the parameters used to calculate RSI that the algorithm will use.
def find_rsi(context, price):
fast_rsi = []
slow_rsi = []
rsi = talib.RSI(price, timeperiod = 20)
for i in range(1, context.fast_lookback + 1):
fast_rsi.append(rsi[-i])
for i in range(1, context.slow_lookback + 1):
slow_rsi.append(rsi[-i])
fast = sum(fast_rsi) / len(fast_rsi)
slow = sum(slow_rsi) / len(slow_rsi)
return {'fast':fast, 'slow':slow}
# Calculate the RSI of the benchmark security in order to guage the overall
# direction of the market.
def check_benchmark_rsi(context, data):
price = data.history(context.benchmark, 'price', 250, '1d')
rsi = find_rsi(context, price)
fast_rsi = rsi['fast']
slow_rsi = rsi['slow']
if fast_rsi > 50:
return True
elif slow_rsi < 50:
return False
else:
return True
# Define the rules and weights for each portfolio variant during rebalancing
# that the algorithm will use.
def rebalance(context, data):
if check_benchmark_rsi(context, data) == True:
price = data.history(context.aggressive, 'price', 250, '1d')
momentum_list = []
momentum_dict = {}
for s in context.aggressive:
momentum = regression(context, data, price[s])
momentum_list.append(momentum)
momentum_dict[s] = momentum
momentum_list.sort()
for s in context.aggressive:
if momentum_dict[s] == momentum_list[-1]:
order_target_percent(s, context.leverage * 0.25)
elif momentum_dict[s] == momentum_list[-2]:
order_target_percent(s, context.leverage * 0.25)
elif momentum_dict[s] == momentum_list[-3]:
order_target_percent(s, context.leverage * 0.25)
elif momentum_dict[s] == momentum_list[-4]:
order_target_percent(s, context.leverage * 0.25)
if check_benchmark_rsi(context, data) == False:
price = data.history(context.defensive, 'price', 250, '1d')
momentum_list = []
momentum_dict = {}
for s in context.defensive:
momentum = regression(context, data, price[s])
momentum_list.append(momentum)
momentum_dict[s] = momentum
momentum_list.sort()
for s in context.defensive:
if momentum_dict[s] == momentum_list[-1]:
order_target_percent(s, context.leverage * 0.25)
elif momentum_dict[s] == momentum_list[-2]:
order_target_percent(s, context.leverage * 0.25)
elif momentum_dict[s] == momentum_list[-3]:
order_target_percent(s, context.leverage * 0.25)
elif momentum_dict[s] == momentum_list[-4]:
order_target_percent(s, context.leverage * 0.25)