Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help with an SP&500 ATR Strategy

Hi,
I am new in Quantopian and appreciate help coding a specific ATR strategy. My coding skills are zero, any help will be appreciated.

Brief explanation: The market has its highest volatilatility intraday period from 9.30 to 10.15-10.30am aprox. I have seen that many stocks overshoot up/down in that volatile period and when vol. recedes around 10.30am those stocks tend to rebound to the opposite overshooting side. I know a prop trader that operated with a similar strategy with huge success.

Strategy to backtest: Tracking all 500 stocks from SP&500 index, at 10.20am I would like to go long 50 stocks from that index that has the highest negative [ (current price - open price) / ATR (14) ] and at the same time go short 50 stocks from that index that has the highest positive [ (current price - open price) / $ATR (14) ]. I will close those trades at 11.30am. The basic explanation is going long the 50 stocks that went down the hardest compared to its ATR and go short the 50 stocks that went up the most. The objective is betting on a reversion, at 11.30 when volatility has receded and market "corrected" overshooting anomalies.

I do not know if Quantopian allows to backtest buy/sell order at specific times of the day.

Thanks!,
Federico.

15 responses

Hi Federico,

There is a limitation of maximum 100 securities which can be used in one algorithm. So, using 500 S&P500 stocks is not possible as far as I know.

Regards,
Ed

Ed,
Thanks for your answer. Maybe we can use 100 random securities from the SP&500 index and instead of buying 50 and shorting 50, we reduce that amount to 10/10.
Regards,
F

Hi Federico,

Would it be better to use S&P100 instead of randomly picking something from SP&500?

Regards,
Ed

"I do not know if Quantopian allows to backtest buy/sell order at specific times of the day?" I'm also wondering this

E.g. buy security xyz at time 12.00 a.m. at the first day of the month then hold until close

Federico, here is a draft implementation of your idea. It doesn't look very impressive, but it's just a draft and can contain bugs. Please, check it out, play with it, ask questions.

Patrick, sure, it's possible to create orders at specific time of the day. You can look at this implementation as an example. It creates orders at 10:20 a.m. every trading day.

Thanks Ed!

Thanks Ed !!
Certainly the backtest result does not look impressive, I will play it out and let you know any observations.

Ed:
Considering the algo backtest results were bad, what could happen if we change the order rules: instead of buying the lowest and selling the highest, do the opposite. I assume with those changes the backtest should yield great results.

I noticed in the code the positions are being closed out after just ten minutes. Federico, I think your original intention was to hold them until 11:30, not 10:30, right?

I changed the code for 11.30 but the results are also poor. I am not an expert in coding, maybe if you know you can tweak it for 11.30 (which was the main intention).

In addition, if the backtest is not attractive under this rules, what could happen if we do do opposite ? buying the highest and shorting the lowest ?

Hi guys,

Thank you for your interest to this topic!

Unfortunately I don't have much time for this, so my apologies for being slow. However, as you are interested I'll try to dedicate more time to it.

Let me first give you some more details about my implementation:
It uses subset of S&P100 index. I excluded some stocks because they caused errors in back testing. I can give more details later if needed.
In the latest version I've moved strategy parameters(amount of shares to buy/sell and amount of stocks with min/max ratio to use) to context, so you can tweak them.
My code does the following:
1. At 9:31(first available candle) it saves open prices for all securities to context.opens for future use
2. At 10:29(last candle before 10:30) it calculates (price - open)/atr14 ratio for every security and picks up equal amount(context.nstocks) of most negative and most positive securities for the trade.
3. It creates market orders to buy/sell equal amount(context.shares) of picked up securities. They are executed on the next candle(10:30 a.m.) as was asked by Federico.
4. At 11:29(last candle before 11:30) it creates closing orders for all open positions. They will be executed on the next candle(11:30 a.m).

Please, look at the code, try to understand it and ask questions. I want you to collaborate and learn :)

I fixed time to close positions from 10:29 to 11:29, but it didn't help much as Federico mentioned.
To change algorithm to the opposite you can set context.shares to negative number, i.e. context.shares = -50 would mean that 50 shares will be sold for the stocks with lowest ratio and 50 shares will be bought for the stocks with the highest ratio.
However, the results don't differ much for some reason. Probably due to the bug in the code. Let's try to find it.

Regards,
Ed.

Hello Ed,

The algo starts on 2013-09-01 but if you look at 'ratios' you will see this has NaN values until 2013-09-23 i.e. the 15th day of the algo when the ATR time period is 14. This makes me think that the ATR is calculated on daily data but I assume you want the minutely ATR of the prices from 09:31 to 10:19.

If my interpretation is correct I'm not sure what the answer is. I have a feeling that a batch transform - which is the obvious solution - has issues in minutely backtests. Then the only answer is to wait for the 'history' function.

P.

Hi Guys,

I wanted to chime in with an explanation on why you will not see a sign inversion on your returns when you flipped the buys and sells in the algo you are working on.

By default Quantopian's backtester applies commission costs and slippage to your strategy. You can modify these settings, but if you do not specify another option the defaults are commissions of $0.03/share and a volume share slippage model that simulates price impact based on the size of your order (bigger orders result in bigger price moves).

If you want to look at performance in the absence of any simulated t-costs (knowing that this would be unrealistic in terms of execution) you can set these options both to zero by adding the following two lines to your initialize method:

set_slippage(slippage.FixedSlippage(spread = 0.00))
set_commission(commission.PerTrade(0.00))

I've attached a backtest run on this algo with these changes here as well.

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.

Jessica, thank you for the explanations. I somehow thought that backtests use zero commissions and slippage by default. I should've read Quantopian documenpitation more carefully :)
Peter, I also noticed that daily ATR was used for some reason, but I'm not sure if minute ATR(14) should be used as it was not mentioned in the strategy explanations. Federico, can you elaborate on this?

Just wanted to chime in here... off-topic. This is only my second post here, I've just signed up at Quantopian yesterday and I have to say I am incredibly impressed with the community here so far. Very helpful, encouraging and knowledgeable folks seem to have congregated here. I am just starting out, trying to learn Python for the first time and will definitely stick around. Great site, great ideas, great community.