from QuantConnect.Data.Market import TradeBar
from datetime import timedelta
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
import decimal as d
class MyAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2017, 9, 11) # Set Start Date
self.SetEndDate(2017, 9, 13)
self.SetCash(100000) # Set Strategy Cash
self.symbolData = dict()
for ticker in ["SPY", "AAPL", "NVDA", "FB", "BABA", "MU", "MYL", "JD", "TEVA", "TVIX", "AMD"]:
symbol = self.AddEquity(ticker, Resolution.Second).Symbol
consolidator_daily = TradeBarConsolidator(timedelta(1))
consolidator_daily.DataConsolidated += self.OnDailyData
self.SubscriptionManager.AddConsolidator(symbol, consolidator_daily)
consolidator_minute = TradeBarConsolidator(60)
consolidator_minute.DataConsolidated += self.OnMinuteData
self.SubscriptionManager.AddConsolidator(symbol, consolidator_minute)
self.symbolData[symbol] = SymbolData()
#self.Schedule.On(self.DateRules.EveryDay(),
# self.TimeRules.AfterMarketOpen('SPY', 1),
# Action(self.one_minute_after_open_market))
#self.Schedule.On(self.DateRules.EveryDay(),
# self.TimeRules.AfterMarketOpen('SPY', 5),
# Action(self.before_close_market))
#self.Schedule.On(self.DateRules.EveryDay(),
# self.TimeRules.Every(timedelta(seconds=10)),
# Action(self.Tensec))
# Add daily bar to daily rolling window
def OnDailyData(self, sender, bar):
self.symbolData[bar.Symbol].daily_rw.Add(bar)
def OnMinuteData(self, sender, bar):
self.symbolData[bar.Symbol].minute_rw.Add(bar)
def OnData(self, data):
for symbol in data.Keys:
self.Log(str(symbol))
if data[symbol] is None: continue
# Create local variable to readability
window = self.symbolData[symbol].window
# Update the window. If not ready, continue
window.Add(data[symbol])
minute = self.symbolData[symbol].minute_rw
if not (window.IsReady and minute.IsReady): continue
if self.Portfolio[symbol].Invested:
last_close = window[0].Close
last_min_open = minute[1].Open
last_min_close = minute[1].Close
last_bar = minute[1].Close - minute[1].Open
second_bar = minute[2].Close - minute[2].Open
fourth_bar = minute[4].Close - minute[4].Open
self.Log(str(symbol)+str(last_min_open)+", "+str(last_close))
if (last_close > last_min_close):
self.Log(str(last_min_open)+", "+str(last_close))
self.Liquidate(symbol)
self.Log('LIQUIDATE AT THRESHOLD REACHED.')
if not self.Portfolio[symbol].Invested:
last_bar = minute[1].Close - minute[1].Open
second_bar = minute[2].Close - minute[2].Open
third_bar = minute[3].Close - minute[3].Open
fourth_bar = minute[4].Close - minute[4].Open
last_close = window[0].Close
last_min_open = minute[1].Open
last_min_close = minute[1].Close
#self.Log(str(last_bar)+", "+", "+str(second_bar)+", "+str(third_bar)+", "+str(last_close)+", "+str(minute[0].Open))
if (last_bar < 0 and last_min_close - last_close > d.Decimal(0.05)):
self.SetHoldings(symbol, -1.0/3.0)
self.Log('shorting')
#def Tensec(self):
# for symbol in self.symbolData:
# Create local variable to readability
# window = self.symbolData[symbol].window
# Update the window. If not ready, continue
# minute = self.symbolData[symbol].minute_rw
# if not (window.IsReady and minute.IsReady): continue
def OnEndOfDay(self):
self.Plot("Portfolio", "MarginRemaining", self.Portfolio.MarginRemaining)
def OnEndOfAlgorithm(self):
self.Liquidate()
self.Log('LIQUIDATE AT End Of Algorithm.')
class SymbolData(object):
def __init__(self):
self.daily_rw = RollingWindow[TradeBar](5)
self.minute_rw = RollingWindow[TradeBar](5)
self.window = RollingWindow[TradeBar](5)
Hello Alexandre,
thank you for your help again. Thanks to you I finally got to the point where I can test things without getting errors every 10 minutes. I still got a new problem though. This next algorithm I'm working on is simpler. It should iterate through a list of stock every second. If not invested and the last minute bar was negative and the difference between the current price and the last minute's closing price is more than 0.05, it should make a short position. If the stock is invested and the last price is bigger than the last minute's close, it should close the position. This has been working if I iterate in OnData for the rolling windows and in another method which I had called every ten seconds for making the positions. When I put it all in OnData I get the following error:
Runtime Error: Python.Runtime.PythonException: ArgumentOutOfRangeException : Must be between 0 and -1
Parameter name: i
Actual value was 1.
at QuantConnect.Indicators.RollingWindow`1[T].get_Item (System.Int32 i) [0x0004c] in <38253e1f0adf48debed06f8d2e7759e5>:0
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in <dca3b561b8ad4f9fb10141d81b39ff45>:0
at Python.Runtime.PyObject.Invoke (Python.Runtime.PyTuple args, Python.Runtime.PyDict kw) [0x00033] in <387056c9810b431d9b668f2df5d6c027>:0
at Python.Runtime.PyObject.InvokeMethod (System.String name, Python.Runtime.PyTuple args, Python.Runtime.PyDict kw) [0x00007] in <387056c9810b431d9b668f2df5d6c027>:0
at Python.Runtime.PyObject.TryInvokeMember (System.Dynamic.InvokeMemberBinder binder, System.Object[] args, System.Object& result) [0x0003e] in <387056c9810b431d9b668f2df5d6c027>:0
at (wrapper dynamic-method) System.Object:CallSite.Target (System.Runtime.CompilerServices.Closure,System.Runtime.CompilerServices.CallSite,object,QuantConnect.Data.Slice)
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1] (System.Runtime.CompilerServices.CallSite site, T0 arg0, T1 arg1) [0x00128] in <63992662b765477a898ef49cdcc99ee2>:0
at QuantConnect.AlgorithmFactory.Python.Wrappers.AlgorithmPythonWrapper.OnData (QuantConnect.Data.Slice slice) [0x000c6] in <a4a88fb3668b4590893c272615df630f>:0
at QuantConnect.Lean.Engine.AlgorithmManager.Run (QuantConnect.Packets.AlgorithmNodePacket job, QuantConnect.Interfaces.IAlgorithm algorithm, QuantConnect.Lean.Engine.DataFeeds.IDataFeed feed, QuantConnect.Lean.Engine.TransactionHandlers.ITransactionHandler transactions, QuantConnect.Lean.Engine.Results.IResultHandler results, QuantConnect.Lean.Engine.RealTime.IRealTimeHandler realtime, QuantConnect.Lean.Engine.Server.ILeanManager leanManager, System.Threading.CancellationToken token) [0x012d0] in <b6042ddb9cf849bda5636f8ee179370d>:0 (Open Stacktrace)
Also I've noticed that the algorithm is crashing if I remove the SPY from the stock list. Why is that?
Kind regards,
Christian Lauer