Back to Community
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?

Clone Algorithm
22
Loading...
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('XLE','AAPL','AAP','ABC','ADS','AGN','ALXN','AMG','AMGN','AMP','AMZN','ANTM','APD','AVB','AZO','BA','BCR','BDX','BIIB','BLK','BMRN','BRK.B','BXP','CB','CELG','CF','CHTR','CI','CLX','CME','CMG','CMI','COST','CVS','CVX','CXO','DIS','ECL','EQIX','ESS','EW','FDX','FB','FLT','GD','GILD','GMCR','GS','GWW','GOOG','GOOGL','HBI','HD','HON','HSIC','HSY','HUM','IBM','IEP','ILMN','ISRG','IVV','KMB','KSU','LLL','LMT','MCK','MHFI','MHK','MJN','MKL','MMM','MNST','MON','MPC','MTB','NEE','NFLX','NOC','NSC','ORLY','PANW','PCLN','PCP','PCYC','PH','PII','PLL','PPG','PSA','PX','PXD','REGN','RL','ROK','ROP','RTN','SBAC','SHW','SIAL','SJM','SLG','SPG','SRCL','SRE','STZ','TDG','TMO','TRV','TRW','TSLA','TWC','UHS','UNH','UNP','UPS','UTX','V','VNO','VRTX','WDC','WHR','WYNN','ITW','JAZZ','ZBH','CBOE','ADBE','XLU')
    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])
        X = smapi.add_constant(diff, prepend=True)
        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.