@Delaney Granizo-Mackenzie, David Edwards and Ryan Chen
I am testing the migrated code of long short equity strategy with beta hedging adding couple of changes
- Replacing order_by(fundamentals.valuation_ratios.earning_yield.desc()) with order_by(fundamentals.valuation_ratios.earning_yield.desc()).limit(num_stocks), in before_trading_start
- Selecting [1:] in the returns and index_returns to avoid the nan in the first position, in get_alphas_and_betas
- Adding an if asset != context.index: inside the for to make sure the linreg is not applied to the SPY position that is not included in factors, in get_alphas_and_betas
- Replacing X = returns linreg(X, index_returns,y) with y = returns linreg(index_returns,y), in get_alphas_and_betas , as noted by Ryan Chen and David Edwards
Now the beta is reduced to 0.07 from 0.29, but I still get tons of WARNs like
2008-03-03 get_alphas_and_betas:105 WARN [Failed Beta Calculation] asset = HFC
2008-03-03 get_alphas_and_betas:105 WARN [Failed Beta Calculation] asset = UNT
2008-03-03 get_alphas_and_betas:105 WARN [Failed Beta Calculation] asset = TCB
2008-03-03 get_alphas_and_betas:105 WARN [Failed Beta Calculation] asset = RGC
2008-03-03 get_alphas_and_betas:105 WARN [Failed Beta Calculation] asset = WCC
Some times this happens for almost all the assets in the portfolio
Why is this happening?
How does this affect the beta hedging?
How can this be avoided or corrected?
How is beta calculated in the backtester(zipline) and how is that beta related with the beta hedging factor?
def get_alphas_and_betas(context, data):
prices = data.history(context.all_assets, 'price', context.lookback, '1d')
returns = prices.pct_change()[1:]
index_returns = data.history(context.index, 'price', context.lookback, '1d').pct_change()[1:]
factors = {}
for asset in context.portfolio.positions :
if asset != context.index:
try:
y = returns[asset]
factors[asset] = linreg(index_returns,y)
except:
log.warn("[Failed Beta Calculation] asset = %s"%asset.symbol)
return pd.DataFrame(factors, index=['alpha', 'beta'])