LEAN is the open source
algorithmic trading engine powering QuantConnect. Founded in 2013 LEAN has been built by a
global community of 80+ engineers and powers more than a dozen hedge funds today.
Alpha League Competition: $1,000 Weekly Prize Pool
Qualifying Alpha Streams Reentered Weekly Learn
more
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.
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.
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.
Tony Monaco
229
,
Sorry it will not allow me to attach a backtest
0
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.
1
Tony Monaco
229
,
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)
0
Alexandre Catarino
,
Please rerun the code. It was a data issue that has been fixed.
0
Amulya Jitendra Agarwal
410
,
Is any python example available for SMA crossover in futures?
1
Amulya Jitendra Agarwal
410
,
Also, why are you plotting the EMA based on equity rather than the futures?
1
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.
1
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.
3.9k
,
2nd the request for a Python version
1
Derek Melchin
STAFF
,
Hi Amulya and Brett,
I've translated the C# algorithm Alex published above. The python version is attached.
Best, Derek Melchin
2
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.
3.9k
,
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?
1
Derek Melchin
STAFF
,
Hi Brett,
Yes, scheduled events work with any asset class. With this algorithm, we can add the following line in Initialize
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
1
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
2.4k
,
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.
0
Shile Wen
63.4k
,
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
0
Brett C.
3.9k
,
Thanks Derek! Does SetHoldings work with futures? Don't think this algo is allocating 50% to SP and 50% to GC.
0
Derek Melchin
STAFF
,
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
1
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.
3.9k
,
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
0
Shile Wen
63.4k
,
Hi Brett,
This is the intended behavior.
For 10 year Treasuries, it would be Futures.Financials.Y10TreasuryNote instead of Futures.Financials.Y10TreasuryBond
See the attached backtest. To set the resolution of the contract rollover, change all instances of self.Time.resolutionto the desired resolution. For monthly rebalancing, we can update our contracts monthly, so the resolution in the backtest is monthly. However, if the contracts needed to be updated daily for any reason, we can change all instances of self.Time.month to self.Time.day.
Best, Shile Wen
0
Asdas
265
,
Hi Derek,
How would you compute the standard deviations of the futures in this case? I am looking for a Python implementation
2
Varad Kabade
STAFF
,
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
2
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.
Asdas
265
,
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
2
Varad Kabade
STAFF
,
Hi Asdas, To use the Standard Deviation indicator on the output of the Simple Moving Average indicator, we must use the IndicatorExtensions method refer to this doc. In the attached backtest, we have implemented this in our SymbolData class. Best, Varad Kabade
0
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.
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.
Loading...
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!