Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Problems using MaximizeAlpha

Hi!
I want to develop a strategy that simply rebalances every year at the end of june according to the latest data available on companies' mkt caps and just for the top 1000 stocks.
The weight that every stock should have is proportional to their mkt cap, so if a company has a mkt cap of 10 B and another of 5 B, the latter should have half the allocation of the former.

I used TargetWeights to have an equal weighting and it seems to have worked, now can I use opt.MaximizeAlpha?

In the attached backtest it gives me an error..
Anyway does opt.MaximizeAlpha follow my logic (if a company has a mkt cap of 10 B and another of 5 B, the latter should have half the allocation of the former)

8 responses

The MaximizeAlpha objective always requires some constraint(s). Typically, at least a MaxGrossExposure constraint to limit the leverage should be added. One difference with the MaximizeAlpha objective is that it, obviously, is trying to maximize the values. It will dutifully do this and order an infinite number shares which isn't really very realistic. That needs to be constrained somehow. So this will work

order_optimal_portfolio(objective = objective, constraints = [opt.MaxGrossExposure(1.0)])

Other constraints can be used but I would typically start with at least limiting the gross exposure (ie leverage). Good luck.

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.

solved the problem, thanks Dan!

Now what I would like to know is if this backtest fullfills my desire to give a weight to every stock I buy directly proportional to its mkt cap.
Let's imagine that just 3 stocks are in my universe (in this case they are 1000), when I rebalance if stock A has mkt cap 20B, stock B has mkt cap 10B and stock C has mkt cap 5 B and I have 1 000 000 dollars to use, I want to buy roughly 570 000 $ securities worth of stock A, 285 714$ worth of stock B and 142857$ of stock C.

Does this algo work this way? Do I need to build this logic on my own, or use other ways to place my orders?

To weight each stock proportional to its market cap use the TargetWeightWeights objective. You know the weights you want to assign so that is the objective to use and not MaximizeAlpha.

The MaximizeAlpha objective is best used when you have a factor which one feels is proportional to the outcome one wants. If one wants high returns then that factor should be proportional to returns, If one wants a high sharpe ratio then that factor should be proportional to the sharpe ratio. Typically this objective starts with the highest alpha value, orders as much of that until some constraint is reached, and then begins ordering the second highest alpha and so forth. It generally will end up ordering only a small subset of the universe.

One can set the weight as a percent of the total market cap inside the pipeline definition by using the recently added summary methods (see the docs here) Something like this

def make_pipeline():  
    # Gets the latest market cap.  
    mkt_cap = morningstar.valuation.market_cap.latest  
    screen = mkt_cap.top(1000, mask=(QTradableStocksUS()))  
    # Weight each of the top 1000 by their market cap  
    total_market_cap = mkt_cap.sum(mask=screen)  
    weight = mkt_cap / total_market_cap  
    return Pipeline(  
    columns={  
        'mkt_cap': mkt_cap,  
        'weight': weight,  
    },  
    domain=US_EQUITIES,  
    screen=screen,  
)

Then simply use the 'weight' column as the target weight in TargetWeightWeights objective. See the attached backtest. Good luck.

thank you Dan! I've developed a model very similar to yours.
The question that I have now is...this model does not deal with cash left free from companies going private, bankrupt etc, doesn't it?

P.S.: your comment

# yearly rebalancing, happens every January month end  

is wrong, it's every June month end

Whenever a company becomes un-tradable (ie data.can_trade is False) the backtester will automatically close out the position and increase cash by the position value as of the last tradable date. This happens every day even if the portfolio is being rebalanced less frequently. It's actually very similar to what one would see in a live broker account.

@Emiliano Fraticelli So, a question... how do you want to 'deal' with this cash? It will currently remain as cash but then be redistributed the next time the portfolio is rebalanced. Several ideas. Perhaps rebalance more frequently, or rebalance when cash is greater than some amount. Note that one can check for the universe on an annual basis but rebalance at a different interval. Simply save the universe to a context variable (perhaps annually) but then rebalance based upon that saved list more frequently (but of course exclude any stocks which cannot trade).

Attached is a backtest which logs the number of portfolio positions each day. Looking at the logs one can see the desired 1000 positions are always opened but steadily, as the year passes, anywhere from 15-50 stocks are dropped from the portfolio. This represent from 1-5% of the portfolio not being invested at some times.

There's actually the possibility of the opposite also happening. Stocks can be added to the portfolio as a result of a corporate action (eg a spinoff). It's not obvious if this occurs here but it is something to consider. More than likely any such added positions would be closed at rebalancing.

thank you @Dan Whitnable !

Well I have to think about how to treat these companies, but I think I would treat them just as Russell 1000 index does.
I'll have to do some research about it, do you have any suggestions?

I took at quick look at Wikipedia (the source of all knowledge) and found this regarding how the Russel 1000 handles delisted stocks.

The Russell indexes do not immediately replace a company that merges with another firm or has its stock delisted.

That doesn't tell the whole story though. The Russel 1000, being an index and not an actual portfolio, wouldn't typically include cash in the index calculation. So, even though the stocks being tracked may not be updated, the remaining stock weights may change to reflect the total market cap having been reduced?