Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
how could i buy at close and sell at next day open?

if there's no other rules, i just want to buy at close and sell at tomorrow open and do this everyday.
I thought i just need the last bar of today and the first bar of tomorrow?

How to do these things?
What if more general , Can i specify the time to buy and sell?

help plz.

16 responses

Usually to buy at the close for US equities you need to place an MOC order about 20 minutes before the close. I do not know know this fact affects the reality of backtests. I guess for a few shares it won;t but for big blocks of stock there will be an effect.

How about buy at specified time very close to 4:00 ? can we set it to 3:59?

And under this circumstance I think I don't need to send MOC orders. I just to send an market order before market close.

Hello Eric/Ricardo,

Although IB support MOC orders there are no plans that I am aware of for Quantopian to support them and so similar functionality will have to be implemented in the algo. In this thread https://www.quantopian.com/posts/intraday-strategy-gap-play-please-help Jess shows an example of trading at 9:31/15:59 ** although this does not take account of early closing days. Seong did some work on early closes here https://www.quantopian.com/posts/market-on-close-orders

AM has been looking at trading the close/open gap in the thread here https://www.quantopian.com/posts/how-do-i-shift-the-moving-average-of-an-imported-csv-chart through the use of a custom slippage model but he may now be of the view that he will have to look at a 'minutely' rather than 'daily' algo and check for the time of day.

P.

** Use sid(1406) for Celgene in place of sid(40207) if you clone this algo.

@ Peter, Are you really sure you would like to sell/buy at today's close and square off at tomorrow's opening. Do you plan to ingest data from the global financial markets during this interval? Even if you do, you would anyway take action next morning, and book your profit /loss regardless of what the data says. Seems a little dicey. Would you plan to do this everyday or would you like to figure out when it makes sens e to do this. The latter is a matter of calculating the probability of today's trend continuing overnight. While you can compute a number, the reliability of the number over different sets of data can vary. I would suggest computing the confidence interval along with the probability. If you are 95% confident, then the probability number is usable.

Hello Bharath,

I don't have a dog in this particular fight. I was just offering some relevant posts! Eric. Ricardo, AM, Kyu et al can no doubt offer insights on trading MOC, trading the gap etc.

P.

@Peter I appreciate that. My post was actually for Erik

@Anony The codes you post are very inspiring, thanks. But as u noted , when order being sent, it is executed tomorrow. So is it possible to buy @ today's close? I think maybe I need to specified time so that when it's 3:59 ,check if condition being met. Then my order will be executed by 4:00 and get today's close. But then the problem is how to set the open time. As I can't send an order @9:29 to execute @9:30 [market open at 9:30]....

@bharath there's lot of strategies built on trading the gap. Statistically u can make money.

Eric,

I won't say making money by trading the gaps is impossible. My only 2c was that probability of a sample is not enough. Confidence interval on the probability would come in handy. So will VaR, especially you are carrying overnight risk.

Hi Eric,

This reply might be too late to be useful, but here is a very simple algo that closes all positions as soon as you can after the open (9:31am) and opens positions as late in the day as we can (3:59pm). Doesn't handle early closes, but I'd be happy to add that if you'd like to see it, so currently if you ran this over a day with an early close you'd miss the day for buying.

It's true that given our setup right now we don't support MOO and MOC order types, so we can't simulate taking part in the open or close auction. Also, in order to get same day round-trip (Buy/Sell) you do need to run your algo in minute mode (which is how this example works).

Best, Jess

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.

Hi Jess and all,

I couple things to consider:

  • Rather than using a specific opening time, the open can be detected with code such as:
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  

This way, if the market happens to open late, you won't miss selling.

[EDIT] Woops...just looked mostly at Jess' code and not her comments about early closings...sorry for the redundancy (others pointed this out above, as well).

Best regards,

Grant

Grant,

My code runs at the open and 20 mins prior to close by doing:

schedule_function(HandleEntry,  
                      date_rule=date_rules.every_day(), time_rule=time_rules.market_open(minutes=1))  
schedule_function(HandleExit,  
                      date_rule=date_rules.every_day(),  
                      time_rule=time_rules.market_close(minutes=20))  

How can I still use the same fetch function, but use what you had posted above about different open and close times?

Hello Spencer,

I don't know if schedule_function takes early closes into account. One way to sort it out would be just to try it. Per http://www.insider-monitor.com/market-holidays.html:

The US stock markets will close early at 1:00 PM on Thursday, July 3, 2014, Friday, November 28, 2014, and Wednesday, December 24, 2014.

So, you'd just run your code over one or more of the early close days to see what it does. If 'HandleExit' doesn't get called, then post back.

Grant

That worked perfectly. It closed 3 hours earlier on Thursday and didn't do anything until the 7th after that.

I have another question though. So fetch_csv reads a csv file that I uploaded to dropbox. Let's say for example I have 15 securities listed under Monday, July 1st, 2014. How do I get the schedule_function to trade those securities on the next trading day. In this case it would be July 2nd, but for Fridays it would have to wait until Mondays.

I've never used fetcher. My understanding is that it loads overnight, but I'd check the help docs, and maybe confirm with Q support. --Grant

In Fetcher, the securities will automatically be rolled over each trading day. So your universe will be the same on July 1 and July 2, unless your file says to trade different stocks on July 2nd. Take a look at the API documentation: https://www.quantopian.com/help#overview-fetcher

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.