Back

Schedule.On and Futures.Indices.SP500EMini

Hi,

consider the following script, it simply buy Futures at 10UTC and sell at 17UTC:

import numpy as np
from System import *
from NodaTime import DateTimeZone

from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Data import *
from datetime import timedelta



class ScheduledEventsAlgorithm(QCAlgorithm):
'''Basic template algorithm simply initializes the date range and cash'''

def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

self.SetStartDate(2019, 6, 1) #Set Start Date
self.SetEndDate(2020, 6, 1) #Set End Date
self.SetCash(100000) #Set Strategy Cash
#Timezone Setting
self.SetTimeZone(DateTimeZone.Utc)
#


# Setup Interactive Broker
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage)

#Adding Instruments
self.futureES = self.AddSecurity(SecurityType.Future, Futures.Indices.SP500EMini, Resolution.Hour);
self.futureES.SetFilter(timedelta(0), timedelta(182))

#Logging / Debugs
self.Logging_On = True
self.Debug_On = False

# Set Schedule to buy and sell
self.Schedule.On(self.DateRules.EveryDay(self.futureES.Symbol), self.TimeRules.At(10, 0), self.ESBuy)
self.Schedule.On(self.DateRules.EveryDay(self.futureES.Symbol), self.TimeRules.At(13, 0), self.ESSell)


def OnData(self, data):
# If we haven't already stored the front contract, we need to find it
pass

def ESBuy(self):
if self.Debug_On:
self.Debug("ESBuy: Fired at : {0}".format(self.Time))
self.MarketOrder(self.futureES.Symbol, 1)


def ESSell(self):
if self.Debug_On:
self.Debug("ESSell: Fired at : {0}".format(self.Time))
self.Liquidate

It fails with the following error:

The security with symbol '/ES' is marked as non-tradable.

what is the best way to implement such a simple strategy with this asset?

 

 

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.


The problem from the error message isn't the schedule you're trying to implement, but the contract you're trying to trade.

'/ES' is the abstract e-Mini Future, not a specific tradeable instrument. It's used for determining the market hours, tick sizes, etc that are all the same for each of the expiries related to this contract.

To add a specific expiry for the e-Mini, you need to do the following:

var symbol = QuantConnect.Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, expiryDate);
var future = AddFutureContract(symbol);

Noting the expiry date at the end of the first line.

Alternatively, take a look at the documentation around Universe Selection. This will help with automagically making sure you're using the right contract, but is a higher barrier to get to

0

Hi Islander,

As Adam pointed out above, the symbol the algorithm is trying to trade is the canonical symbol. See the attached backtest logs for reference.

To trade futures, we need to select an individual contract to trade. I recommend reviewing our Bootcamp lesson on futures for more information and examples.

Going forward, please attach a backtest of an algorithm instead of embedding the code in the message body.

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 Adam May  and Derek Melchin .

Consider the attached backtest, I would like to adjust this algo in the way it trades every day and it opens a position at 16:00UTC and it closes at 17:00UTC. Could you please indicate me what parts I need to change?

0


Hi Islander,

To have the algorithm open positions at 16:00UTC and close them at 17:00UTC, we need to adjust our alpha model initializer to be

self.SetAlpha(ConstantFutureContractAlphaModel(InsightType.Price, InsightDirection.Up, timedelta(minutes=59)))

and add the following conditional to the ShouldEmitInsights method

if not (utcTime.hour == 16 and utcTime.minute == 0):
return False

To ensure the positions are closed when insights have expired, we need to adjust the definition of the CreateTargets method inside the SingleSharePortfolioConstructionModel. 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.


Ok Thanks Derek Melchin 

I assume that timedelta(minutes=59)) gives how long it should keep the position open. Please clarify. Thanks.

But suppose now that when I generate insights I would like to evaluate time as in your example but also some indicators in another symbol.

Something like the following:

fastPeriod = 20
slowPeriod = 60
self._tolerance = 1 + 0.001
self.IsUpTrend = False
self.IsDownTrend = False
self.SetWarmUp(max(fastPeriod, slowPeriod))

# Adds SPY to be used in our EMA indicators
equity = self.AddEquity("SPY", Resolution.Daily)
self._fast = self.EMA(equity.Symbol, fastPeriod, Resolution.Daily)
self._slow = self.EMA(equity.Symbol, slowPeriod, Resolution.Daily)

Where exactly should I put this code and how can I pass to ShouldEmitInsight ?

 

0

Hi Islander,

Yes, the timedelta states how long to hold the position for. Review our documentation on insights for more information.

To take the EMA factors into account when generating the insights, I recommend replacing the current alpha model with a custom one. We place the code in the constructor. Note that we warm up the EMAs before using them too.

class MyAlphaModel(AlphaModel):
def __init__(self, algorithm):
fastPeriod = 20
slowPeriod = 60
self._tolerance = 1 + 0.001
self.IsUpTrend = False
self.IsDownTrend = False

symbol = algorithm.AddEquity("SPY", Resolution.Daily).Symbol
self._fast = algorithm.EMA(symbol, fastPeriod, Resolution.Daily)
self._slow = algorithm.EMA(symbol, slowPeriod, Resolution.Daily)

# Warm up history
history = algorithm.History(symbol, slowPeriod, Resolution.Daily).loc[symbol]
for idx, row in history.iterrows():
self._fast.Update(idx, row.close)
self._slow.Update(idx, row.close)

def Update(self, algorithm, slice):
if not (algorithm.UtcTime.hour == 16 and algorithm.UtcTime.minute == 0 and algorithm.UtcTime.second == 0):
return []

insights = []
for symbol in slice.Keys:
if symbol.SecurityType != SecurityType.Future:
continue
insights.append(Insight.Price(symbol, timedelta(minutes=59), InsightDirection.Up))

return insights

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.


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