Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Quantopian Lecture Series: The Art of Not Following the Market

Algorithms that do not follow the market are very attractive to investors. We will discuss some approaches for reducing correlation to a benchmark and discuss why returns aren’t everything. Please find some algorithms demonstrating concepts in this notebook in the replies to this post.

In addition, we have released a notebook primer on linear regression here. Linear regression is used in determining beta for beta hedging, so those who are a little rusty may want to check it out first.

This is the first in Quantopian’s Summer Lecture Series. We are currently developing a quant finance curriculum and will be releasing clone-able notebooks and algorithms to teach key concepts. This notebook will be presented at this meetup. Stay tuned for more.

Credit for the notebooks goes to Jenny Nitishinskaya, and credit for the algorithms goes to David Edwards.

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

14 responses

Nice! I'd be curious to see how TSLA hedged using a Kalman filter beta estimator looks.

Here is an example of an algorithm which holds a long-only portfolio based on earnings yield, and does not implement any hedging or risk management. Notice its performance over the 08-09 period.

Here is the same long-only earnings yield strategy, but with a beta hedge implemented. Because we can never actually know beta, only estimate it, the reduction in beta is significant, but not great. The performance is better and it doesn't take the same hit as the first.

Here is an example of the same earnings yield strategy implemented as long short equity. In this case we long the top 50 equities ranked by earnings yield and short the bottom 50. We are betting on the returns spread of our ranking and the beta in this strategy is very low.

Finally, here is the same long short equity strategy but with beta hedging turned on. Because the beta is already so low, the impact is negligible.

@Simon A Kalman filter is definitely a great choice to estimate any moving quantity like beta, sharpe ratio, or equity price. I'm sure that adding a Kalman filter instead of a point-in-time estimate would improve the quality of these strategies. We will definitely go over Kalman filters and parameter estimation during a future lecture, and maybe re-release versions of these algorithms with Kalman filters added.

Hello!

We will be hosting a live webinar for this first lecture in our summer series, "The Art of Not Following the Market" on July 9th at 12pm ET. You can register to attend here: http://bit.ly/DontFollowTheMarket. We will also share the recording with the community afterwards.

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Hello,

The video from "The Art of Not Following the Market" is now available: http://bit.ly/DontFollowtheMarketVideo. Our next webinar in the summer lecture series, "The Good, the Bad, and the Correlated" is being held this Thursday, at 12pm EDT. If you would like to join, please RSVP here.

We will also share the recording in the community forum.

Kelly

@Delaney Granizo-Mackenzie
Hi, in the beta hedging algorithm, function get_alphas_and_betas, why do you use index_returns as y, asset_return as X? Thanks

Hi Ryan,
Good catch, there is no reason to use the asset returns as X, that's a mistake on my part for sure. Here is the updated algorithm.

The algorithms in this thread may cease working briefly as we're doing maintenance during the switch to Q2. Please let me know if this causes any issues.

@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

  1. 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
  2. Selecting [1:] in the returns and index_returns to avoid the nan in the first position, in get_alphas_and_betas
  3. 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
  4. 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'])  

Hello German,

Generally a failed beta calculation will occur when there are NaNs in the returns data. This is somewhat unavoidable as data sources will always have some degree of dirt in them. The hope with a strategy like this is that you are invested in enough positions that failing on a few positions doesn't affect the overall beta of the strategy. Also, it's generally a good idea to exit/not enter the positions if we can't compute a reasonable beta.

You can check out the beta calculation in the backtester source code here: https://github.com/quantopian/zipline/blob/master/zipline/finance/risk/cumulative.py

We are working on an updated version of this algo and hope to release it soon.

Thanks,
Delaney

For some reason, the algo is shorting 10X the portfolio value despite the input is .

order_target_percent(asset, 0.01)

The symbol is EEQ on 8/4 to 8/18

Can anyone confirm this?