Hello, I am currently having problem with my futures algoirthm. It is just a basic buy and sell based on sma crossover. I am only dealing with the s and p 500 mini futures but am just trying to understand the basics with it first before I go onto more complex methods. Also, we are using indicators from SPY and applying it to trade S&P future since it is easier to get this data.
I seem to get runtime errors with different starting dates. Try running it from the beginning of the year and then try running it more recent. I think the main problems with it are the calendars used between regular US equities and futures. Thank you for the help I appreciate it.
Tony Monaco
Sorry it will not allow me to attach a backtest
Alexandre Catarino
I have written a simple algorithm as an example.
Basically, it will look for the sma cross and buy/sell the nearest futures contract and liquidate the position at the end of the day.
The SMA Cross will just define the quantity:
var quantity = _sma5 > _sma9 ? 2 : -2;
since the logics for entering the trade is similar.
Tony Monaco
Thanks so much for the response. I ran your code and ran into this problem and wanted to see if you were aware of it.
The begining it runs correctly and chooses the right future contract (ESH17) shown in the first pic. Though, in march when it switches to ESM17 it flatlines and keeps buying and selling at the same price for a loss. I attached the pictures to show. Let me know what you think. Thanks again
Here is the overview picture and you can see in march where the first contract expire it stops working correctly
Below is the ESH17 and everything looks right
Below is the ESM17 contract and when it is supposed to switch to this one the program runs into the problem and behaves as in the picture below (buys and sells about 25 cents apart and does not follow the price of the futures contract)
Alexandre Catarino
Please rerun the code.
It was a data issue that has been fixed.
Amulya Jitendra Agarwal
Is any python example available for SMA crossover in futures?
Amulya Jitendra Agarwal
Also, why are you plotting the EMA based on equity rather than the futures?
Jared Broad
>EMA based on equity rather than the futures?
Alex did this because its easier and doesn't require re-creating the SMA with each new contract listed.
>SMA crossover in futures
I'll see if we can publish an easy one for you to follow.
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 QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect 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. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Brett C.
2nd the request for a Python version
Derek Melchin
Hi Amulya and Brett,
I've translated the C# algorithm Alex published above. The python version is attached.
Best,
Derek Melchin
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 QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect 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. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Brett C.
Thanks Derek. Do futures work with scheduled events? How would you change the code to run once a day during a scheduled event rather than continuously with OnData?
Derek Melchin
Hi Brett,
Yes, scheduled events work with any asset class. With this algorithm, we can add the following line in Initialize
self.Schedule.On(self.DateRules.EveryDay("SPY"), \ self.TimeRules.AfterMarketOpen(equity.Symbol, 10), \ self.Trade)
Then we just move all the logic of OnData into a method called Trade and change
for chain in data.FutureChains:
to
for chain in self.CurrentSlice.FutureChains:
See the attached backtest for reference.
Best,
Derek Melchin
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 QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect 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. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
P Chen
Hi Derek,
Thanks for the examples - I had a question related to the ones posted here so far. How would you extend the logic of your last example to work with custom data points? Say for example, I wanted to do an SMA crossover, but have the fast and slow EMA indicators take a custom value instead of the last bar's close.
Shile Wen
Hi P Chen,
Please see the “Manual Update” section of the Custom Period Indicators documentation on how to use custom values with indicators. Please note you will initialize the EMA with ExponentialMovingAverage instead of self.EMA. As for using custom data, this strategy tutorial is good if using Quandl data.
Best,
Shile Wen
Brett C.
Thanks Derek! Does SetHoldings work with futures? Don't think this algo is allocating 50% to SP and 50% to GC.
Derek Melchin
Hi Brett,
Yes, the SetHoldings method works with futures contract. There are just a few issues with the algorithm above.
Firstly, both the `Trade_spfut` and `Trade_goldfut` methods trade gold and SPY futures, despite their method names. To resolve this, we just need to remove the loop with
if self.fut_sp.Symbol not in self.CurrentSlice.FutureChains: return chain = self.CurrentSlice.FutureChains[self.fut_sp.Symbol]
in the `Trade_spfut` method for instance.
Secondly, the algorithm will run into bugs if none of the contracts have a positive open interest. We can fix this with
sp = [sp for sp in chain if sp.OpenInterest > 0] if len(sp) == 0: if self.prev_sp_contract is not None: self.Liquidate(self.prev_sp_contract.Symbol) return
Lastly, the algorithm doesn't handle roll overs when the selected contract switches. We can implement this with
if self.prev_sp_contract is None: self.prev_sp_contract = trade_sp if self.prev_sp_contract.Symbol != trade_sp.Symbol: self.Liquidate(self.prev_sp_contract.Symbol) self.prev_sp_contract = trade_sp self.SetHoldings(trade_sp.Symbol, 0.5)
See the attached backtest for reference.
Best,
Derek Melchin
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 QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect 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. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Brett C.
Derek, this is so helpful - thank you! A few follow ups:
1. I did some testing and SetHoldings with futures seems to allocate a percent of Margin (vs Portfolio Equity as with equities). Can you confirm?
2. I want to add more markets, but the Treasury futures (2yr, 5yr, 10yr, 30yr) cause an error. I pulled the syntax from the documentation. Any ideas what this message refers to... **During the algorithm initialization, the following exception has occurred: AttributeError : type object 'Financials' has no attribute 'Y10TreasuryBond'** ?
3. If I shift to monthly rebalance, then I should check daily for the contract with the most Open Interest and roll the futures into the most active., which I attempted. What's the best way to do that?
Best,
Brett
Shile Wen
Hi Brett,
Best,
Shile Wen
Asdas
Hi Derek,
How would you compute the standard deviations of the futures in this case? I am looking for a Python implementation
Varad Kabade
Hi Asdas,
To compute Standard deviations for futures, we can either select a contract and create an indicator using its symbol and warming up the indicator so it is ready for use. Alternatively, we can assign indicators to all contracts in the OnSecuritiesChanged event handler. We can create a SymbolData class to store the indicator and use a dictionary keyed by the contract symbol. Refer to the attached backtest
Best,
Varad Kabade
Asdas
Great thanks Varad. How would combine both the SMA and the standard deviations calculations? Ideally I would like to use both the SMA of a given future and it's respective standard deviations
Tony Monaco
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 QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect 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. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!