Sector Strategy with Beta Hedge

This is an example of a sector long vs. a beta hedge. The latter can be modified to make the portfolio long/short instead of market neutral (where both sides of the book are expected to produce results).

Can anyone explain the logic?

22
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
import numpy as np
import statsmodels.api as smapi

def initialize(context):
set_symbol_lookup_date('2016-10-21')
context.XLE = sid(8554)
context.stocks = symbols('TRGP','EOG','AR','APA','APC','BBG','CVX','COP','CXO','DVN','ESS','FANG','HAL','MRO','NE','SLB','PXD','VLO','XOM','OAS','HP')
set_benchmark(context.XLE)
schedule_function(myfunc,date_rule=date_rules.every_day(),time_rule=time_rules.market_close(minutes=30))

def handle_data(context, data):
record(l=context.account.leverage)
pass

def myfunc(context, data):
prices = history(20, "1d", "price")
prices = prices.dropna(axis=1)
prices = prices.drop([context.XLE], axis=1)
ret = prices.pct_change(5).dropna()
ret = np.log1p(ret).values
cumret = ret #np.cumsum(ret, axis=0)
xle = np.mean(cumret, axis=1)

i = 0
score = []
for sid in prices:
diff = np.diff(cumret[:,i])
Y = np.diff(cumret[:,i] - xle)
res = smapi.OLS(Y, X).fit()
if len(res.params) > 1:
score.append(res.params[1])
else:
score.append(0)
i += 1

netscore = np.sum(np.abs(score))

i = 0
wsum = 0
for sid in prices:
try:
#val = 10000000 * score[i] / netscore
val = context.portfolio.portfolio_value * score[i] / netscore
order_target_value(sid,  val)
wsum += val
except:
log.info("exception")
i += 1
continue

i += 1
order_target_value(context.XLE, -wsum/2)
There was a runtime error.