Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Simple Moving Average Indicator to Buy or Short

I've been researching the forums and am trying to find an example of a strategy I'm trying to build but haven't had any luck yet.

The parameters of the strategy are fairly simple:
1. Three tickers (MSFT, AAPL, SPY)
2. Use Moving Average (Close, SMA, 50) as the analysis tool to buy or short based on below conditions
3. In order for initial trade to start, the Price must cross above/below the SMA

1D:5M

either A or B can occur first:

A. If price is currently BELOW the SMA line, and then crosses ABOVE the SMA line, a BUY order is placed with total shares equaling (total investment capital of $1,000,000) / (Current Share Price). This position is held until B occurs, at which point the bought shares are sold (so the position is closed.

B. If price is currently ABOVE the SMA line, and then crosses BELOW the SMA line, a SHORT SALE order is placed with total shares equaling (total investment capital of $1,000,000) / (Current Share Price). This position is held until A occurs, at which point the shorted shares are ‘covered’ (so the position is closed.

A will always be followed by B, and vice versa (i.e.: as soon as one position is closed, the opposite position will be opened). It is crucial that the previous position be closed before the next position can be opened (i.e.: if a stock was bought, it must be sold before it is then shorted…….and if a stock was previously shorted, it must be covered before a buy order is made.

It's a very simple strategy but will show a few key parts in the algorithm:
- How to build an algorithm using multiple tickers
- How to build an algorithm that combines both buying and shorting
- Requiring a previous position to be closed before a new position is immediately opened thereafter on the same security.

If there's an existing available algorithm built, or if someone could take the time to show how this could be built, I'd very much appreciate it.

Thanks

4 responses

I presented a framework two weeks ago with an implementation of the exact strategy you're describing. You can find it here. All you would need to do is to create AlphaGeneratorsMA with len_short_ma 1 (to get last price) (len_long_ma is 50 by default). To get it implemented clone the algorithm and replace line 159-162 by

# creation of alpha generators  
alpha_ma_msft = AlphaGeneratorMa(sid_stock=sid(5061), len_short_ma=1)  
alpha_ma_aapl = AlphaGeneratorMa(sid_stock=sid(24), len_short_ma=1)  
alpha_ma_spy = AlphaGeneratorMa(sid_stock=sid(8554), len_short_ma=1)  
# alpha generators are added to the portfolio manager  
context.p_manager.list_alpha.append(alpha_ma_mfst)  
context.p_manager.list_alpha.append(alpha_ma_aapl)  
context.p_manager.list_alpha.append(alpha_ma_spy)  

It will allocate a third of your portfolio to each strategy. You can add as many securities as you want, all you have to do is to create alpha generators and add them to the portfolio manager. You can change the window length of your sma with parameter len_long_ma when you create the alpha generator.

The only small difference I see with your description is that the algo will trade from day one (long if price is above sma and short if price is below) and will not wait for the first cross. You should be able to modify the alpha generator with a boolean to add the constraint.

Thank you for your help with this, Matthieu. I appreciate it.

Where I'm still somewhat unclear is how to define that a buy order be placed upon certain conditions (IE: price moves above MAVG(30)), and in the opposite condition (IE: Price moves below MAVG(30)), the same quantity be shorted (and initial amount is sold). The move to 'Quantity 0' is clear, but the opposite action (a short after a buy....with one closing the position before the other begins) isn't something I understand.

Is there an existing algo written that you know of?

AR, here's a sample algo that trades based on the security price and moving average: https://www.quantopian.com/help#sample-basic

You can also try searching the forums for more intricate examples, people have shared well thought-out algos!

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.

AR L,

In the framework you don't micromanage orders at the alpha level, all you need to take care is the allocation you request to the portfolio manager.

When you want to be long on one security this means you want 100% of the allocation on this security hence an allocation of 1. When you want to be short you want an allocation of -1 to get negative exposure at the level of your portfolio. Depending on the position of the price from the sma the allocation asked will be either 1 if you want to be long or -1 if you want to be short (l.104-107).

Then the equi-weight porfolio manager will compute the target allocation which will depend on the number of alpha generators it handles. If you want to apply the strategy on three securities (ie the portfolio manager handles three alpha generators) each strategy will get 1/3 of the allocation asked and in the target portfolio their weight will be either +0.33 or -0.33.

Lastly the execution handler takes care of the orders to reach the target. I you stay long nothing will change but if you go from long to short, allocation will move from +0.33 in the actual portfolio to -0.33 in the target portfolio and the execution handler will compute the order to close your previous position and open a short one in the same time. (if you were long 50 shares for example, the execution handler will produce market order to sell 100 shares. It will close your long 50 shares position and open a short 50 shares position)

I hope it is more clear now.