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(2013,10,07) #Set Start Date self.SetEndDate(2013,10,11) #Set End Date self.SetCash(100000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data equity = self.AddEquity("SPY", Resolution.Second) self.spy = equity.Symbol start_date = to_python_datetime(self.StartDate) end_date = to_python_datetime(self.EndDate) self.mid_datetime = start_date + (end_date - start_date)/2
def OnData(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' if data.ContainsKey(self.spy): currentTime = to_python_datetime(self.Time) if self.IsRoundHour(currentTime): negative = 1 if currentTime < self.mid_datetime else -1 self.LimitOrder(self.spy, negative*10, data[self.spy].Price)
def OnData(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' if self.Transactions.OrdersCount == 0: self.MarketOrder(self.spy, 100) for kvp in data.Delistings: self.__delistedSymbols.append(kvp.Key) pyTime = to_python_datetime(self.Time) if pyTime.date == datetime(2014, 4, 7): self.Liquidade() return if self.__changes is None: return for security in self.__changes.AddedSecurities: if security.Symbol in data: self.Log("{0}: Added Security: {1}".format( pyTime, security.Symbol)) self.MarketOnOpenOrder(security.Symbol, 100) for security in self.__changes.RemovedSecurities: if security.Symbol in data: self.Log("{0}: Removed Security: {1}".format( pyTime, security.Symbol)) if security.Symbol not in self.__delistedSymbols: self.Log("Not in delisted: {0}:".format(security.Symbol)) self.MarketOnOpenOrder(security.Symbol, -100)
def MarketOnOpenOrders(self): '''MarketOnOpenOrders are always executed at the next market's opening price. The only properties that can be updated are the quantity and order tag properties.''' if self.TimeIs(8, 12 + 2, 0): self.Log("Submitting MarketOnOpenOrder") # its EOD, let's submit a market on open order to short even more! newTicket = self.MarketOnOpenOrder(self.spy, 50) self.__openMarketOnOpenOrders.append(newTicket) if len(self.__openMarketOnOpenOrders) == 1 and to_python_datetime( self.Time).minute == 59: ticket = self.__openMarketOnOpenOrders[0] # check for fills if ticket.Status == OrderStatus.Filled: self.__openMarketOnOpenOrders = [] return quantity = ticket.Quantity + 1 self.Log("Updating quantity - New Quantity: {0}".format(quantity)) # we can update the quantity and tag updateOrderFields = UpdateOrderFields() updateOrderFields.Quantity = Nullable[int](quantity) updateOrderFields.Tag = "Update #{0}".format( ticket.UpdateRequests.Count + 1) ticket.Update(updateOrderFields)
def OnData(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' # wait for our macd to fully initialize if not self.__macd.IsReady: return pyTime = to_python_datetime(self.Time) # only once per day if self.__previous.date() == pyTime.date(): return # define a small tolerance on our checks to avoid bouncing tolerance = 0.0025 holdings = self.Portfolio[self.spy].Quantity signalDeltaPercent = ( self.__macd.Current.Value - self.__macd.Signal.Current.Value) / self.__macd.Fast.Current.Value # if our macd is greater than our signal, then let's go long if holdings <= 0 and signalDeltaPercent > tolerance: # 0.01% # longterm says buy as well self.SetHoldings(self.spy, 1.0) # of our macd is less than our signal, then let's go short elif holdings >= 0 and signalDeltaPercent < -tolerance: self.Liquidate(self.spy) # plot both lines self.Plot("MACD", self.__macd.Current.Value) self.Plot("MACD", self.__macd.Signal.Current.Value) self.Plot(str(self.spy), self.__macd.Fast.Current.Value) self.Plot(str(self.spy), self.__macd.Slow.Current.Value) self.__previous = pyTime
def OnData(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' pyTime = to_python_datetime(self.Time) if pyTime.date() != self.__last.date( ): # each morning submit a market on open order self.__submittedMarketOnCloseToday = False self.MarketOnOpenOrder(self.equity.Symbol, 100) self.__last = pyTime if not self.__submittedMarketOnCloseToday and self.equity.Exchange.ExchangeOpen: # once the exchange opens submit a market on close order self.__submittedMarketOnCloseToday = True self.MarketOnCloseOrder(self.equity.Symbol, -100)
def OnData(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' # we are only using warmup for indicator spooling, so wait for us to be warm then continue if self.IsWarmingUp: return for sd in self.__sd.values(): lastPriceTime = to_python_datetime(sd.Close.Current.Time) if self.RoundDown(lastPriceTime, sd.Security.SubscriptionDataConfig.Increment): sd.Update()
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(2013,10,07) #Set Start Date self.SetEndDate(2013,10,11) #Set End Date self.SetCash(10000000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data self.AddEquity("SPY", Resolution.Tick) self.AddEquity("BAC", Resolution.Minute) self.AddEquity("AIG", Resolution.Hour) self.AddEquity("IBM", Resolution.Daily) self.__lastTradeTicks = to_python_datetime(self.StartDate) self.__lastTradeTradeBars = self.__lastTradeTicks self.__tradeEvery = timedelta(minutes=1)
def OnData(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' try: pyTime = to_python_datetime(self.Time) # the first time we come through here we'll need to do some # things such as allocation and initializing our symbol data if self.__first: self.__first = False self.__lastRotationTime = pyTime return delta = pyTime - self.__lastRotationTime if delta > self.__rotationInternal: self.__lastRotationTime = pyTime for x in self.SymbolData: x.Update() # pick which one is best from growth and safety symbols orderedObjScores = sorted(self.SymbolData, key=lambda x: x.ObjectiveScore, reverse=True) for orderedObjScore in orderedObjScores: self.Log(">>SCORE>>{0}>>{1}".format( orderedObjScore.Symbol, orderedObjScore.ObjectiveScore)) bestGrowth = orderedObjScores[0] if bestGrowth.ObjectiveScore > 0: if self.Portfolio[bestGrowth.Symbol].Quantity == 0: self.Log("PREBUY>>LIQUIDATE>>") self.Liquidate() qty = int(self.Portfolio.Cash / self.Securities[bestGrowth.Symbol].Close) self.Log(">>BUY>>{0}@{1}".format( bestGrowth.Symbol, (100.0 * bestGrowth.OneMonthPerformance.Current.Value))) self.MarketOrder(bestGrowth.Symbol, qty) else: # if no one has a good objective score then let's hold cash this month to be safe self.Log(">>LIQUIDATE>>CASH") self.Liquidate() except: self.Error("OnTradeBar: Error")
def OnData(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' pyTime = to_python_datetime(self.Time) if pyTime - self.__lastTradeTradeBars < self.__tradeEvery: return self.__lastTradeTradeBars = pyTime for kvp in data.Bars: period = kvp.Value.Period.TotalSeconds if self.roundTime(pyTime, period) != pyTime: pass symbol = kvp.Key holdings = self.Portfolio[symbol] if not holdings.Invested: self.MarketOrder(symbol, 10) else: self.MarketOrder(symbol, -holdings.Quantity)
def MarketOnCloseOrders(self): '''MarketOnCloseOrders are always executed at the next market's closing price. The only properties that can be updated are the quantity and order tag properties.''' if self.TimeIs(9, 12, 0): self.Log("Submitting MarketOnCloseOrder") # open a new position or triple our existing position qty = self.Portfolio[self.spy.Value].Quantity qty = 100 if qty == 0 else 2 * qty newTicket = self.MarketOnCloseOrder(self.spy, qty) self.__openMarketOnCloseOrders.append(newTicket) if len(self.__openMarketOnCloseOrders) == 1 and to_python_datetime( self.Time).minute == 59: ticket = self.__openMarketOnCloseOrders[0] # check for fills if ticket.Status == OrderStatus.Filled: self.__openMarketOnCloseOrders = [] return quantity = ticket.Quantity + 1 self.Log("Updating quantity - New Quantity: {0}".format(quantity)) # we can update the quantity and tag updateOrderFields = UpdateOrderFields() updateOrderFields.Quantity = Nullable[int](quantity) updateOrderFields.Tag = "Update #{0}".format( ticket.UpdateRequests.Count + 1) ticket.Update(updateOrderFields) if self.TimeIs(self.EndDate.Day, 12 + 3, 45): self.Log( "Submitting MarketOnCloseOrder to liquidate end of algorithm") self.MarketOnCloseOrder(self.spy, -self.Portfolio[self.spy.Value].Quantity, "Liquidate end of algorithm")
def OnData(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' if not data.ContainsKey(self.__Symbol): return pyTime = to_python_datetime(self.Time) if pyTime.month != self.__LastMonth: # we'll submit the next type of order from the queue orderType = self.__orderTypesQueue.Dequeue() #Log(""); self.Log("\r\n--------------MONTH: {0}:: {1}\r\n".format( pyTime.strftime("%B"), orderType)) #Log("") self.__LastMonth = pyTime.month self.Log("ORDER TYPE:: {0}".format(orderType)) isLong = self.__Quantity > 0 stopPrice = d.Decimal(1 + self.__StopPercentage) * data[ self.__Symbol].High if isLong else d.Decimal( 1 - self.__StopPercentage) * data[self.__Symbol].Low limitPrice = d.Decimal(1 - self.__LimitPercentage ) * stopPrice if isLong else d.Decimal( 1 + self.__LimitPercentage) * stopPrice if orderType == OrderType.Limit: limitPrice = d.Decimal(1 + self.__LimitPercentage) * data[ self.__Symbol].High if not isLong else d.Decimal( 1 - self.__LimitPercentage) * data[self.__Symbol].Low request = SubmitOrderRequest(orderType, self.__Symbol.SecurityType, self.__Symbol, self.__Quantity, stopPrice, limitPrice, self.Time, str(orderType)) ticket = self.Transactions.AddOrder(request) self.__tickets.append(ticket) elif len(self.__tickets) > 0: ticket = self.__tickets[-1] if pyTime.day > 8 and pyTime.day < 14: if ticket.UpdateRequests.Count == 0 and ticket.Status is not OrderStatus.Filled: self.Log("TICKET:: {0}".format(ticket)) updateOrderFields = UpdateOrderFields() updateOrderFields.Quantity = Nullable[int]( ticket.Quantity + copysign(self.__DeltaQuantity, self.__Quantity)) updateOrderFields.Tag = "Change quantity: {0}".format( pyTime) ticket.Update(updateOrderFields) elif pyTime.day > 13 and pyTime.day < 20: if ticket.UpdateRequests.Count == 1 and ticket.Status is not OrderStatus.Filled: self.Log("TICKET:: {0}".format(ticket)) updateOrderFields = UpdateOrderFields() updateOrderFields.LimitPrice = Nullable[Decimal]( self.__Security.Price * d.Decimal(1 - copysign( self.__LimitPercentageDelta, ticket.Quantity))) updateOrderFields.StopPrice = Nullable[Decimal]( self.__Security.Price * d.Decimal(1 + copysign( self.__StopPercentageDelta, ticket.Quantity))) updateOrderFields.Tag = "Change prices: {0}".format(pyTime) ticket.Update(updateOrderFields) else: if ticket.UpdateRequests.Count == 2 and ticket.Status is not OrderStatus.Filled: self.Log("TICKET:: {0}".format(ticket)) ticket.Cancel("{0} and is still open!".format(pyTime)) self.Log("CANCELLED:: {0}".format(ticket.CancelRequest))
def TimeIs(self, day, hour, minute): pyTime = to_python_datetime(self.Time) return pyTime.day == day and pyTime.hour == hour and pyTime.minute == minute