Back

SMA futures algorithm

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.

Update Backtest








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.


Sorry it will not allow me to attach a backtest

0


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.

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.


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

Please rerun the code. 
It was a data issue that has been fixed.

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.


Is any python example available for SMA crossover in futures?

0

Also, why are you plotting the EMA based on equity rather than the futures?

0

>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. 

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.


2nd the request for a Python version

0

Hi Amulya and Brett,

I've translated the C# algorithm Alex published above. The python version is attached.

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.


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?

        

0

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

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.


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

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

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.


Thanks Derek! Does SetHoldings work with futures? Don't think this algo is allocating 50% to SP and 50% to GC. 

0


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

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.


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


Hi Brett,

  1. This is the intended behavior. 
  2. For 10 year Treasuries, it would be Futures.Financials.Y10TreasuryNote instead of Futures.Financials.Y10TreasuryBond
  3. See the attached backtest. To set the resolution of the contract rollover, change all instances of self.Time.resolution to 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

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.


Update Backtest





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.


Loading...

This discussion is closed