Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Moving Average based algorithm help

Hello,

I just found this incredible place and I am looking to put a (hopefully simple) script together...

I would like to buy a nominal $10,000 amount worth of stock X, with buys (total shares roughly 10,000/market price) occurring as close as possible to market open and sell of position occurring as close as possible to market close (day trade time only).

The trade will be triggered by the volume of the previous day exceeding the prior two day volume average.

Thanks for any suggestions!

5 responses

Hello DL,

Definitely doable. A few brief notes:

  • You'll need to run on minute bars (no access to buy at the open and sell prior to close with daily data).
  • I suggest looking into the history API (see the help page) for access to the trailing data.
  • The preferred method to catch the open is to detect the opening bar with code like this (context.prior_datetime initialized to None):
if context.prior_datetime == None or context.prior_datetime.day != get_datetime().day:  
        context.prior_datetime = get_datetime()  
    else:  
        context.prior_datetime = get_datetime()  
        return  
  • For the close, it is a little trickier, because sometimes the market closes early, per a schedule. You can get a feel for how to handle this on https://www.quantopian.com/posts/get-early-closes-function.
  • Initially, you might want to turn off commissions and slippage (set_commission(commission.PerShare(cost=0)), set_slippage(slippage.FixedSlippage(spread=0.00)), and then add them in once you get the algorithm running.

There's a bit of a learning curve...I suggest a simple algorithm to explore the history API for starters. Note that history will return natively a Python pandas dataframe, which is quite handy.

The best way to get help is to post as much code as you can to the forum, either by attaching a completed backtest (preferred) or by pasting the code into the dialog box.

Grant

Thank you, Grant! As an old fundamental investor with modest experience writing code, I am looking forward to learning a lot around here! I will work through your post and will follow up with progress.

Hi DL,

Welcome to Quantopian!

Here is a simple script that executes your strategy. It buys close to the market open (9:31AM) where the trade is triggered by the volume of the previous day exceeding the prior two day volume average. It will purchase $10,000 worth of stock and then close the position at the end of day (3:59PM).

This is a very basic program and doesn't cover early market closes or cases where there is no trade data available. You can click the "clone algorithm" button to get your own copy. When you're experimenting with the code, it would be useful to look at the slippage and commissions, as Grant mentioned, and also log and record your variables to understand the behavior of your algo.

Here are some useful threads you might be interested in:
https://www.quantopian.com/posts/market-on-close-orders
https://www.quantopian.com/posts/sending-mkt-and-moc-orders-before-markets-open-on-daily-bars

Cheers,
Alisa

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.

Thanks Alisa. I was not able to get the same results that I had in my Excel model for the stock in my analysis though I am much closer after factoring in Tesla above...

Just to be clear, I am looking at buying at open of current day, based on volume yesterday exceeding average volume of the days two and three days back of present- for instance, buying at open on Friday morning based upon Thursday volume exceeding the average of Tuesday-Wednesday. Is that the same assumption built into your code data set and index? I see a sum of a period, divided by a count, and then an index within the series- but I am not sure of the directional flow up or down the x axis in a source table, etc., or whether history includes day 1 etc. I will immerse myself into the FAQs again!

Hi DL,

Yes I used those same volume conditions to construct the algo above. I'll use the example you mentioned above of trading on the Friday open to explain the steps in my code:

vol_hist = history(4, '1d', 'volume') :
This will return the return the daily volume history for Tuesday, Wednesday, Thursday and Friday (which is the current day). Vol_hist is a dataframe with 4 values.

prior_VolAvg = sum(vol_hist.ix[0:2])/len(vol_hist.iloc[0:2]):
This calculates the average volume of Tuesday-Wednesday. It is using the formula that average = sum of the terms/ # of terms. This snippet of code uses pandas for indexing into dataframes. The notation [0:2] indicates the start and end values that we want. This means we're grabbing everything from 0 until (but not including) 2. Thus, we are getting the 0 and 1 position in the dataframe, which corresponds to the "Tuesday" and"Wednesday" volume respectively.

yest_vol = vol_hist.iloc[2:] :
This is the volume for the 2nd position, which is Thursday (yseterday) in our example.

Now we get to the meat of the algo!

if exchange_time.hour== 9 and exchange_time.minute == 31 :
Only enter the position at 9:31AM, which is the closest you can trade in Quantopian to the market open.

if yest_vol > prior_VolAvg: order_target_value(context.tsla, 10000) :
If Thursday's volume is greater than the average of Tuesday-Wednesday volume, then order $10,000 worth of Tesla stock.

elif exchange_time.hour==15 and exchange_time.minute == 59: if context.portfolio.positions[context.tsla].amount != 0: order_target_percent(context.tsla,0)
If we have any positions in the algo, sell them at 3:59PM, which is the market close.

Hope this helped break down the steps of the algo. If something is amiss or unexpected, let me know and I'll take a another look!

Alisa