Modifies python example algorithms to show implicit convertion benefits

This commit is contained in:
AlexCatarino
2017-06-15 18:40:34 +01:00
parent 6ca9d7cf14
commit 6242706342
22 changed files with 189 additions and 212 deletions
@@ -31,7 +31,7 @@ class AddRemoveSecurityRegressionAlgorithm(QCAlgorithm):
self.SetEndDate(2013,10,11) #Set End Date
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.spy = self.AddEquity("SPY")
self.AddEquity("SPY")
self._lastAction = None
@@ -42,22 +42,22 @@ class AddRemoveSecurityRegressionAlgorithm(QCAlgorithm):
return
if not self.Portfolio.Invested:
self.SetHoldings(self.spy.Symbol, .5)
self.SetHoldings("SPY", .5)
self._lastAction = self.Time
if self.Time.weekday() == 1:
self.aig = self.AddEquity("AIG")
self.bac = self.AddEquity("BAC")
self.AddEquity("AIG")
self.AddEquity("BAC")
self._lastAction = self.Time
if self.Time.weekday() == 2:
self.SetHoldings(self.aig.Symbol, .25)
self.SetHoldings(self.bac.Symbol, .25)
self.SetHoldings("AIG", .25)
self.SetHoldings("BAC", .25)
self._lastAction = self.Time
if self.Time.weekday() == 3:
self.RemoveSecurity(self.aig.Symbol)
self.RemoveSecurity(self.bac.Symbol)
self.RemoveSecurity("AIG")
self.RemoveSecurity("BAC")
self._lastAction = self.Time
def OnOrderEvent(self, orderEvent):
+6 -9
View File
@@ -11,16 +11,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import clr
clr.AddReference("System")
clr.AddReference("QuantConnect.Algorithm")
clr.AddReference("QuantConnect.Indicators")
clr.AddReference("QuantConnect.Common")
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
import numpy as np
@@ -34,8 +32,7 @@ class BasicTemplateAlgorithm(QCAlgorithm):
self.SetEndDate(2013,10,11) #Set End Date
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
equity = self.AddSecurity(SecurityType.Equity, "SPY", Resolution.Second)
self.spy = equity.Symbol
self.AddEquity("SPY", Resolution.Second)
print "numpy test: print np.pi" , np.pi
def OnData(self, data):
@@ -45,4 +42,4 @@ class BasicTemplateAlgorithm(QCAlgorithm):
data: Slice object keyed by symbol containing the stock data
'''
if not self.Portfolio.Invested:
self.SetHoldings(self.spy, 1)
self.SetHoldings("SPY", 1)
+3 -4
View File
@@ -31,13 +31,12 @@ class CustomBenchmarkAlgorithm(QCAlgorithm):
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.AddEquity("SPY", Resolution.Second)
self.spy = equity.Symbol
self.SetBenchmark(self.spy);
self.SetBenchmark("SPY");
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 self.Portfolio.Invested:
self.SetHoldings(self.spy, 1)
self.SetHoldings("SPY", 1)
self.Debug("Purchased Stock");
+13 -9
View File
@@ -11,12 +11,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import clr
clr.AddReference("System")
clr.AddReference("System.Collections")
clr.AddReference("QuantConnect.Algorithm")
clr.AddReference("QuantConnect.Indicators")
clr.AddReference("QuantConnect.Common")
from clr import AddReference
AddReference("System")
AddReference("System.Collections")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Indicators")
AddReference("QuantConnect.Common")
from System import *
from System.Collections.Generic import List
@@ -34,7 +34,7 @@ class CustomChartingAlgorithm(QCAlgorithm):
self.SetStartDate(2016,1,1)
self.SetEndDate(2017,1,1)
self.SetCash(100000)
self.spy = self.AddEquity("SPY", Resolution.Minute).Symbol
self.AddEquity("SPY", Resolution.Daily)
# In your initialize method:
# Chart - Master Container for the Chart:
@@ -56,7 +56,11 @@ class CustomChartingAlgorithm(QCAlgorithm):
self.resamplePeriod = (self.EndDate - self.StartDate) / 2000
def OnData(self, slice):
self.lastPrice = slice[self.spy].Close
if slice["SPY"] is None:
self.lastPrice = 0
return
self.lastPrice = slice["SPY"].Close
if self.fastMA == 0: self.fastMA = self.lastPrice
if self.slowMA == 0: self.slowMA = self.lastPrice
self.fastMA = (d.Decimal(0.01) * self.lastPrice) + (d.Decimal(0.99) * self.fastMA);
@@ -69,7 +73,7 @@ class CustomChartingAlgorithm(QCAlgorithm):
# On the 5th days when not invested buy:
if not self.Portfolio.Invested and self.Time.day % 13 == 0:
self.Order(self.spy, (int)(self.Portfolio.MarginRemaining / self.lastPrice))
self.Order("SPY", (int)(self.Portfolio.MarginRemaining / self.lastPrice))
self.Plot("Trade Plot", "Buy", self.lastPrice)
elif self.Time.day % 21 == 0 and self.Portfolio.Invested:
self.Plot("Trade Plot", "Sell", self.lastPrice)
@@ -41,18 +41,17 @@ class CustomDataBitcoinAlgorithm(QCAlgorithm):
# Define the symbol and "type" of our generic data:
self.AddData(Bitcoin, "BTC")
self.btc = self.Securities["BTC"].Symbol
def OnData(self, data):
if self.btc not in data: return
if "BTC" not in data: return
close = data[self.btc].Close
close = data["BTC"].Close
# If we don't have any weather "SHARES" -- invest"
if not self.Portfolio.Invested:
# Weather used as a tradable asset, like stocks, futures etc.
self.SetHoldings(self.btc, 1)
self.SetHoldings("BTC", 1)
self.Debug("Buying BTC 'Shares': BTC: {0}".format(close))
self.Debug("Time: {0} {1}".format(datetime.now(), close))
+15 -19
View File
@@ -41,27 +41,23 @@ class CustomDataNIFTYAlgorithm(QCAlgorithm):
# Define the symbol and "type" of our generic data:
self.AddData(DollarRupee, "USDINR")
self.rupee = self.Securities["USDINR"].Symbol
self.AddData(Nifty, "NIFTY")
self.nifty = self.Securities["NIFTY"].Symbol
self.AddEquity("SPY", Resolution.Daily)
self.minimumCorrelationHistory = 50
self.today = CorrelationPair()
self.prices = []
def OnData(self, data):
if self.rupee in data:
if "USDINR" in data:
self.today = CorrelationPair(self.Time)
self.today.CurrencyPrice = data[self.rupee].Close
self.today.CurrencyPrice = data["USDINR"].Close
if self.nifty not in data: return
if "NIFTY" not in data: return
self.today.NiftyPrice = data[self.nifty].Close
self.today.NiftyPrice = data["NIFTY"].Close
if self.today.date() == data[self.nifty].Time.date():
if self.today.date() == data["NIFTY"].Time.date():
self.prices.append(self.today)
if len(self.prices) > self.minimumCorrelationHistory:
self.prices.pop(0)
@@ -69,17 +65,17 @@ class CustomDataNIFTYAlgorithm(QCAlgorithm):
# Strategy
if self.Time.weekday() != 2: return
cur_qnty = self.Portfolio[self.nifty].Quantity
quantity = math.floor(self.Portfolio.TotalPortfolioValue * decimal.Decimal(0.9) / data[self.nifty].Close)
cur_qnty = self.Portfolio["NIFTY"].Quantity
quantity = math.floor(self.Portfolio.MarginRemaining * decimal.Decimal(0.9) / data["NIFTY"].Close)
hi_nifty = max(price.NiftyPrice for price in self.prices)
lo_nifty = min(price.NiftyPrice for price in self.prices)
if data[self.nifty].Open >= hi_nifty:
code = self.Order(self.nifty, quantity - cur_qnty)
self.Debug("LONG {0} Time: {1} Quantity: {2} Portfolio: {3} Nifty: {4} Buying Power: {5}".format(code, self.Time.ToShortDateString(), quantity, self.Portfolio[self.nifty].Quantity, data[self.nifty].Close, self.Portfolio.TotalPortfolioValue))
elif data[self.nifty].Open <= lo_nifty:
code = self.Order(self.nifty, -quantity - cur_qnty)
self.Debug("SHORT {0} Time: {1} Quantity: {2} Portfolio: {3} Nifty: {4} Buying Power: {5}".format(code, self.Time.ToShortDateString(), quantity, self.Portfolio[self.nifty].Quantity, data[self.nifty].Close, self.Portfolio.TotalPortfolioValue))
if data["NIFTY"].Open >= hi_nifty:
code = self.Order("NIFTY", quantity - cur_qnty)
self.Debug("LONG {0} Time: {1} Quantity: {2} Portfolio: {3} Nifty: {4} Buying Power: {5}".format(code, self.Time, quantity, self.Portfolio["NIFTY"].Quantity, data["NIFTY"].Close, self.Portfolio.TotalPortfolioValue))
elif data["NIFTY"].Open <= lo_nifty:
code = self.Order("NIFTY", -quantity - cur_qnty)
self.Debug("SHORT {0} Time: {1} Quantity: {2} Portfolio: {3} Nifty: {4} Buying Power: {5}".format(code, self.Time, quantity, self.Portfolio["NIFTY"].Quantity, data["NIFTY"].Close, self.Portfolio.TotalPortfolioValue))
class Nifty(PythonData):
@@ -149,4 +145,4 @@ class CorrelationPair:
if len(args) > 0: self._date = args[0]
def date(self):
return self._date
return self._date.date()
+16 -19
View File
@@ -11,11 +11,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import clr
clr.AddReference("System")
clr.AddReference("QuantConnect.Algorithm")
clr.AddReference("QuantConnect.Indicators")
clr.AddReference("QuantConnect.Common")
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Indicators")
AddReference("QuantConnect.Common")
from System import *
from QuantConnect import *
@@ -33,13 +33,10 @@ class DailyAlgorithm(QCAlgorithm):
self.SetEndDate(2014,01,01) #Set End Date
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
spy_security = self.AddSecurity(SecurityType.Equity, "SPY", Resolution.Daily)
ibm_security = self.AddSecurity(SecurityType.Equity, "IBM", Resolution.Hour)
ibm_security.SetLeverage(1.0)
self.ibm = ibm_security.Symbol
self.spy = spy_security.Symbol
self.macd = self.MACD(self.spy, 12, 26, 9, MovingAverageType.Wilders, Resolution.Daily, Field.Close)
self.ema = self.EMA(self.ibm, 15*6, Resolution.Hour, Field.SevenBar)
self.AddEquity("SPY", Resolution.Daily)
self.AddEquity("IBM", Resolution.Hour).SetLeverage(1.0)
self.macd = self.MACD("SPY", 12, 26, 9, MovingAverageType.Wilders, Resolution.Daily, Field.Close)
self.ema = self.EMA("IBM", 15 * 6, Resolution.Hour, Field.SevenBar)
self.lastAction = None
@@ -50,16 +47,16 @@ class DailyAlgorithm(QCAlgorithm):
data: Slice object keyed by symbol containing the stock data
'''
if not self.macd.IsReady: return
if not data.ContainsKey(self.ibm): return
if data[self.ibm] is None:
if not data.ContainsKey("IBM"): return
if data["IBM"] is None:
self.Log("Price Missing Time: %s"%str(self.Time))
return
if self.lastAction is not None and self.lastAction.date() == self.Time.date(): return
self.lastAction = self.Time
holding = self.Portfolio[self.spy]
quantity = self.Portfolio["SPY"].Quantity
if holding.Quantity <= 0 and self.macd.Current.Value > self.macd.Signal.Current.Value and data[self.ibm].Price > self.ema.Current.Value:
self.SetHoldings(self.ibm, 0.25)
elif holding.Quantity >= 0 and self.macd.Current.Value < self.macd.Signal.Current.Value and data[self.ibm].Price < self.ema.Current.Value:
self.SetHoldings(self.ibm, -0.25)
if quantity <= 0 and self.macd.Current.Value > self.macd.Signal.Current.Value and data["IBM"].Price > self.ema.Current.Value:
self.SetHoldings("IBM", 0.25)
elif quantity >= 0 and self.macd.Current.Value < self.macd.Signal.Current.Value and data["IBM"].Price < self.ema.Current.Value:
self.SetHoldings("IBM", -0.25)
+9 -10
View File
@@ -50,9 +50,8 @@ class DataConsolidationAlgorithm(QCAlgorithm):
self.SetStartDate(DateTime(2013, 10, 07, 9, 30, 0)) #Set Start Date
self.SetEndDate(self.StartDate + timedelta(1)) #Set End Date
# Find more symbols here: http://quantconnect.com/data
equity = self.AddEquity("SPY")
self.spy = equity.Symbol
self.AddEquity("SPY")
# define our 30 minute trade bar consolidator. we can
# access the 30 minute bar from the DataConsolidated events
thirtyMinuteConsolidator = TradeBarConsolidator(timedelta(minutes=30))
@@ -63,7 +62,7 @@ class DataConsolidationAlgorithm(QCAlgorithm):
# this call adds our 30 minute consolidator to
# the manager to receive updates from the engine
self.SubscriptionManager.AddConsolidator(self.spy, thirtyMinuteConsolidator)
self.SubscriptionManager.AddConsolidator("SPY", thirtyMinuteConsolidator)
# here we'll define a slightly more complex consolidator. what we're trying to produce is
# a 3 day bar. Now we could just use a single TradeBarConsolidator like above and pass in
@@ -86,7 +85,7 @@ class DataConsolidationAlgorithm(QCAlgorithm):
three_oneDayBar.DataConsolidated += self.ThreeDayBarConsolidatedHandler
# this call adds our 3 day to the manager to receive updates from the engine
self.SubscriptionManager.AddConsolidator(self.spy, three_oneDayBar)
self.SubscriptionManager.AddConsolidator("SPY", three_oneDayBar)
self.__last = None
@@ -97,7 +96,7 @@ class DataConsolidationAlgorithm(QCAlgorithm):
def OnEndOfDay(self):
# close up shop each day and reset our 'last' value so we start tomorrow fresh
self.Liquidate(self.spy)
self.Liquidate("SPY")
self.__last = None
@@ -107,12 +106,12 @@ class DataConsolidationAlgorithm(QCAlgorithm):
will be the instance of the IDataConsolidator that invoked the event, but you'll almost never need that!'''
if self.__last is not None and bar.Close > self.__last.Close:
self.Log("{0} >> SPY >> LONG >> 100 >> {1}".format(bar.Time, self.Portfolio[self.spy].Quantity))
self.Order(self.spy, 100)
self.Log("{0} >> SPY >> LONG >> 100 >> {1}".format(bar.Time, self.Portfolio["SPY"].Quantity))
self.Order("SPY", 100)
elif self.__last is not None and bar.Close < self.__last.Close:
self.Log("{0} >> SPY >> SHORT >> 100 >> {1}".format(bar.Time, self.Portfolio[self.spy].Quantity))
self.Order(self.spy, -100)
self.Log("{0} >> SPY >> SHORT >> 100 >> {1}".format(bar.Time, self.Portfolio["SPY"].Quantity))
self.Order("SPY", -100)
self.__last = bar
+4 -6
View File
@@ -35,11 +35,9 @@ class DelistingEventsAlgorithm(QCAlgorithm):
self.SetEndDate(2007, 05, 25) #Set End Date
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
aaa = self.AddEquity("AAA", Resolution.Daily)
spy = self.AddEquity("SPY", Resolution.Daily)
self.aaa = aaa.Symbol
self.spy = spy.Symbol
self.AddEquity("AAA", Resolution.Daily)
self.AddEquity("SPY", Resolution.Daily)
def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
@@ -48,7 +46,7 @@ class DelistingEventsAlgorithm(QCAlgorithm):
data: Slice object keyed by symbol containing the stock data
'''
if self.Transactions.OrdersCount == 0:
self.SetHoldings(self.aaa, 1)
self.SetHoldings("AAA", 1)
self.Debug("Purchased stock")
for kvp in data.Bars:
+6 -7
View File
@@ -37,8 +37,7 @@ class DividendAlgorithm(QCAlgorithm):
# Find more symbols here: http://quantconnect.com/data
equity = self.AddEquity("MSFT", Resolution.Daily)
equity.SetDataNormalizationMode(DataNormalizationMode.Raw)
self.msft = equity.Symbol
# this will use the Tradier Brokerage open order split behavior
# forward split will modify open order to maintain order value
# reverse split open orders will be cancelled
@@ -47,14 +46,14 @@ class DividendAlgorithm(QCAlgorithm):
def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
bar = data[self.msft]
bar = data["MSFT"]
if self.Transactions.OrdersCount == 0:
self.SetHoldings(self.msft, .5)
self.SetHoldings("MSFT", .5)
# place some orders that won't fill, when the split comes in they'll get modified to reflect the split
quantity = self.CalculateOrderQuantity(self.msft, .25)
quantity = self.CalculateOrderQuantity("MSFT", .25)
self.Debug("Purchased Stock: {0}".format(bar.Price))
self.StopMarketOrder(self.msft, -quantity, bar.Low/2)
self.LimitOrder(self.msft, -quantity, bar.High*2)
self.StopMarketOrder("MSFT", -quantity, bar.Low/2)
self.LimitOrder("MSFT", -quantity, bar.High*2)
for kvp in data.Dividends: # update this to Dividends dictionary
symbol = kvp.Key
@@ -30,18 +30,17 @@ class LimitFillRegressionAlgorithm(QCAlgorithm):
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
self.AddEquity("SPY", Resolution.Second)
self.mid_datetime = self.StartDate + (self.EndDate - self.StartDate)/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):
if data.ContainsKey("SPY"):
if self.IsRoundHour(self.Time):
negative = 1 if self.Time < self.mid_datetime else -1
self.LimitOrder(self.spy, negative*10, data[self.spy].Price)
self.LimitOrder("SPY", negative*10, data["SPY"].Price)
def IsRoundHour(self, dateTime):
+7 -8
View File
@@ -33,14 +33,13 @@ class MACDTrendAlgorithm(QCAlgorithm):
self.SetEndDate(2015, 01, 01) #Set End Date
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
equity = self.AddEquity("SPY", Resolution.Daily)
self.spy = equity.Symbol
self.AddEquity("SPY", Resolution.Daily)
# define our daily macd(12,26) with a 9 day signal
self.__macd = self.MACD(self.spy, 9, 26, 9, MovingAverageType.Exponential, Resolution.Daily)
self.__macd = self.MACD("SPY", 9, 26, 9, MovingAverageType.Exponential, Resolution.Daily)
self.__previous = datetime.min
self.PlotIndicator("MACD", True, self.__macd, self.__macd.Signal)
self.PlotIndicator(str(self.spy), self.__macd.Fast, self.__macd.Slow)
self.PlotIndicator("SPY", self.__macd.Fast, self.__macd.Slow)
def OnData(self, data):
@@ -54,18 +53,18 @@ class MACDTrendAlgorithm(QCAlgorithm):
# define a small tolerance on our checks to avoid bouncing
tolerance = 0.0025;
holdings = self.Portfolio[self.spy].Quantity
holdings = self.Portfolio["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)
self.SetHoldings("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)
self.Liquidate("SPY")
self.__previous = self.Time
@@ -43,12 +43,12 @@ class MarketOnOpenOnCloseAlgorithm(QCAlgorithm):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
if self.Time.date() != self.__last.date(): # each morning submit a market on open order
self.__submittedMarketOnCloseToday = False
self.MarketOnOpenOrder(self.equity.Symbol, 100)
self.MarketOnOpenOrder("SPY", 100)
self.__last = self.Time
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)
self.MarketOnCloseOrder("SPY", -100)
def OnOrderEvent(self, fill):
@@ -36,14 +36,13 @@ class MovingAverageCrossAlgorithm(QCAlgorithm):
self.SetEndDate(2015, 01, 01) #Set End Date
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
equity = self.AddEquity("SPY")
self.spy = equity.Symbol
self.AddEquity("SPY")
# create a 15 day exponential moving average
self.fast = self.EMA(self.spy, 15, Resolution.Daily);
self.fast = self.EMA("SPY", 15, Resolution.Daily);
# create a 30 day exponential moving average
self.slow = self.EMA(self.spy, 30, Resolution.Daily);
self.slow = self.EMA("SPY", 30, Resolution.Daily);
self.previous = None
@@ -66,19 +65,19 @@ class MovingAverageCrossAlgorithm(QCAlgorithm):
# define a small tolerance on our checks to avoid bouncing
tolerance = 0.00015;
holdings = self.Portfolio[self.spy].Quantity
holdings = self.Portfolio["SPY"].Quantity
# we only want to go long if we're currently short or flat
if holdings <= 0:
# if the fast is greater than the slow, we'll go long
if self.fast.Current.Value > self.slow.Current.Value * d.Decimal(1 + tolerance):
self.Log("BUY >> {0}".format(self.Securities[self.spy].Price))
self.SetHoldings(self.spy, 1.0)
self.Log("BUY >> {0}".format(self.Securities["SPY"].Price))
self.SetHoldings("SPY", 1.0)
# we only want to liquidate if we're currently long
# if the fast is less than the slow we'll liquidate our long
if holdings > 0 and self.fast.Current.Value < self.slow.Current.Value:
self.Log("SELL >> {0}".format(self.Securities[self.spy].Price))
self.Liquidate(self.spy)
self.Log("SELL >> {0}".format(self.Securities["SPY"].Price))
self.Liquidate("SPY")
self.previous = self.Time
+6 -7
View File
@@ -33,9 +33,8 @@ class ParameterizedAlgorithm(QCAlgorithm):
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")
self.spy = equity.Symbol
self.AddEquity("SPY")
# Receive parameters from the Job
ema_fast = self.GetParameter("ema-fast")
ema_slow = self.GetParameter("ema-slow")
@@ -44,8 +43,8 @@ class ParameterizedAlgorithm(QCAlgorithm):
fast_period = 100 if ema_fast is None else int(ema_fast)
slow_period = 200 if ema_slow is None else int(ema_slow)
self.fast = self.EMA(self.spy, fast_period)
self.slow = self.EMA(self.spy, slow_period)
self.fast = self.EMA("SPY", fast_period)
self.slow = self.EMA("SPY", slow_period)
def OnData(self, data):
@@ -59,6 +58,6 @@ class ParameterizedAlgorithm(QCAlgorithm):
slow = self.slow.Current.Value
if fast > slow * d.Decimal(1.001):
self.SetHoldings(self.spy, 1)
self.SetHoldings("SPY", 1)
elif fast < slow * d.Decimal(0.999):
self.Liquidate(self.spy)
self.Liquidate("SPY")
+8 -9
View File
@@ -35,19 +35,18 @@ class QuandlImporterAlgorithm(QCAlgorithm):
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.quandlCode = "YAHOO/INDEX_SPY";
self.SetStartDate(2013,1,1) #Set Start Date
self.SetEndDate(datetime.today() - timedelta(1)) #Set End Date
self.SetCash(25000) #Set Strategy Cash
self.AddData[Quandl]("YAHOO/INDEX_SPY", Resolution.Daily)
self.__quandlCode = self.Securities["YAHOO/INDEX_SPY"].Symbol
self.__sma = self.SMA(self.__quandlCode, 14)
print ">>>>>", self.EndDate
self.AddData[Quandl](self.quandlCode, Resolution.Daily)
self.sma = self.SMA(self.quandlCode, 14)
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 self.Portfolio.HoldStock:
self.SetHoldings(self.__quandlCode, 1)
self.Debug("Purchased {0} >> {1}".format(self.__quandlCode, self.Time))
self.SetHoldings(self.quandlCode, 1)
self.Debug("Purchased {0} >> {1}".format(self.quandlCode, self.Time))
self.Plot("SPY", self.__sma.Current.Value)
self.Plot("SPY", self.sma.Current.Value)
+6 -7
View File
@@ -33,9 +33,8 @@ class ScheduledEventsAlgorithm(QCAlgorithm):
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")
self.spy = equity.Symbol
self.AddEquity("SPY")
# events are scheduled using date and time rules
# date rules specify on what dates and event will fire
# time rules specify at what time on thos dates the event will fire
@@ -49,11 +48,11 @@ class ScheduledEventsAlgorithm(QCAlgorithm):
# schedule an event to fire every trading day for a security the
# time rule here tells it to fire 10 minutes after SPY's market open
self.Schedule.On(self.DateRules.EveryDay(self.spy), self.TimeRules.AfterMarketOpen(self.spy, 10), Action(self.EveryDayAfterMarketOpen))
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.AfterMarketOpen("SPY", 10), Action(self.EveryDayAfterMarketOpen))
# schedule an event to fire every trading day for a security the
# time rule here tells it to fire 10 minutes before SPY's market close
self.Schedule.On(self.DateRules.EveryDay(self.spy), self.TimeRules.BeforeMarketClose(self.spy, 10), Action(self.EveryDayAfterMarketClose))
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.BeforeMarketClose("SPY", 10), Action(self.EveryDayAfterMarketClose))
# schedule an event to fire on certain days of the week
self.Schedule.On(self.DateRules.Every(DayOfWeek.Monday, DayOfWeek.Friday), self.TimeRules.At(12, 0), Action(self.EveryMonFriAtNoon))
@@ -65,13 +64,13 @@ class ScheduledEventsAlgorithm(QCAlgorithm):
# schedule an event to fire at the beginning of the month, the symbol is optional
# if specified, it will fire the first trading day for that symbol of the month,
# if not specified it will fire on the first day of the month
self.Schedule.On(self.DateRules.MonthStart(self.spy), self.TimeRules.AfterMarketOpen(self.spy), Action(self.RebalancingCode))
self.Schedule.On(self.DateRules.MonthStart("SPY"), self.TimeRules.AfterMarketOpen("SPY"), Action(self.RebalancingCode))
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 self.Portfolio.Invested:
self.SetHoldings(self.spy, 1)
self.SetHoldings("SPY", 1)
def SpecificTime(self):
@@ -36,12 +36,9 @@ class UniverseSelectionRegressionAlgorithm(QCAlgorithm):
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
# security that exists with no mappings
equity_spy = self.AddEquity("SPY", Resolution.Daily)
self.AddEquity("SPY", Resolution.Daily)
# security that doesn't exist until half way in backtest (comes in as GOOCV)
equity_goog = self.AddSecurity(SecurityType.Equity, "GOOG", Resolution.Daily)
self.spy = equity_spy.Symbol
self.goog = equity_goog.Symbol
self.AddEquity("GOOG", Resolution.Daily)
self.UniverseSettings.Resolution = Resolution.Daily
self.AddUniverse(self.CoarseSelectionFunction)
@@ -61,7 +58,7 @@ class UniverseSelectionRegressionAlgorithm(QCAlgorithm):
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)
self.MarketOrder("SPY", 100)
for kvp in data.Delistings:
self.__delistedSymbols.append(kvp.Key)
@@ -41,61 +41,60 @@ class UpdateOrderRegressionAlgorithm(QCAlgorithm):
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.__Security = self.AddEquity("SPY", Resolution.Daily)
self.__Symbol = self.__Security.Symbol;
self.security = self.AddEquity("SPY", Resolution.Daily)
self.last_month = -1
self.quantity = 100
self.delta_quantity = 10
self.__LastMonth = -1
self.__Quantity = 100
self.__DeltaQuantity = 10
self.__StopPercentage = 0.025
self.__StopPercentageDelta = 0.005
self.__LimitPercentage = 0.025
self.__LimitPercentageDelta = 0.005
self.stop_percentage = 0.025
self.stop_percentage_delta = 0.005
self.limit_percentage = 0.025
self.limit_percentage_delta = 0.005
OrderTypeEnum = [OrderType.Market, OrderType.Limit, OrderType.StopMarket, OrderType.StopLimit, OrderType.MarketOnOpen, OrderType.MarketOnClose]
self.__orderTypesQueue = CircularQueue[OrderType](OrderTypeEnum)
self.__orderTypesQueue.CircleCompleted += self.onCircleCompleted
self.__tickets = []
self.order_types_queue = CircularQueue[OrderType](OrderTypeEnum)
self.order_types_queue.CircleCompleted += self.onCircleCompleted
self.tickets = []
def onCircleCompleted(self, sender, event):
'''Flip our signs when we've gone through all the order types'''
self.__Quantity *= -1
self.quantity *= -1
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):
if not data.ContainsKey("SPY"):
return
if self.Time.month != self.__LastMonth:
if self.Time.month != self.last_month:
# we'll submit the next type of order from the queue
orderType = self.__orderTypesQueue.Dequeue();
orderType = self.order_types_queue.Dequeue();
#Log("");
self.Log("\r\n--------------MONTH: {0}:: {1}\r\n".format(self.Time.strftime("%B"), orderType))
#Log("")
self.__LastMonth = self.Time.month
self.last_month = self.Time.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
isLong = self.quantity > 0
stopPrice = d.Decimal(1 + self.stop_percentage)*data["SPY"].High if isLong else d.Decimal(1 - self.stop_percentage)*data["SPY"].Low
limitPrice = d.Decimal(1 - self.limit_percentage)*stopPrice if isLong else d.Decimal(1 + self.limit_percentage)*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
limitPrice = d.Decimal(1 + self.limit_percentage)*data["SPY"].High if not isLong else d.Decimal(1 - self.limit_percentage)*data["SPY"].Low
request = SubmitOrderRequest(orderType, self.__Symbol.SecurityType, self.__Symbol, self.__Quantity, stopPrice, limitPrice, self.Time, str(orderType))
request = SubmitOrderRequest(orderType, self.security.Symbol.SecurityType, "SPY", self.quantity, stopPrice, limitPrice, self.Time, str(orderType))
ticket = self.Transactions.AddOrder(request)
self.__tickets.append(ticket)
self.tickets.append(ticket)
elif len(self.__tickets) > 0:
ticket = self.__tickets[-1]
elif len(self.tickets) > 0:
ticket = self.tickets[-1]
if self.Time.day > 8 and self.Time.day < 14:
if len(ticket.UpdateRequests) == 0 and ticket.Status is not OrderStatus.Filled:
self.Log("TICKET:: {0}".format(ticket))
updateOrderFields = UpdateOrderFields()
updateOrderFields.Quantity = ticket.Quantity + copysign(self.__DeltaQuantity, self.__Quantity)
updateOrderFields.Quantity = ticket.Quantity + copysign(self.delta_quantity, self.quantity)
updateOrderFields.Tag = "Change quantity: {0}".format(self.Time)
ticket.Update(updateOrderFields)
@@ -103,8 +102,8 @@ class UpdateOrderRegressionAlgorithm(QCAlgorithm):
if len(ticket.UpdateRequests) == 1 and ticket.Status is not OrderStatus.Filled:
self.Log("TICKET:: {0}".format(ticket))
updateOrderFields = UpdateOrderFields()
updateOrderFields.LimitPrice = self.__Security.Price*d.Decimal(1 - copysign(self.__LimitPercentageDelta, ticket.Quantity))
updateOrderFields.StopPrice = self.__Security.Price*d.Decimal(1 + copysign(self.__StopPercentageDelta, ticket.Quantity))
updateOrderFields.LimitPrice = self.security.Price*d.Decimal(1 - copysign(self.limit_percentage_delta, ticket.Quantity))
updateOrderFields.StopPrice = self.security.Price*d.Decimal(1 + copysign(self.stop_percentage_delta, ticket.Quantity))
updateOrderFields.Tag = "Change prices: {0}".format(self.Time)
ticket.Update(updateOrderFields)
else:
@@ -119,4 +118,4 @@ class UpdateOrderRegressionAlgorithm(QCAlgorithm):
self.Log("FILLED:: {0} FILL PRICE:: {1}".format(self.Transactions.GetOrderById(orderEvent.OrderId), orderEvent.FillPrice))
else:
self.Log(orderEvent.ToString())
self.Log("TICKET:: {0}".format(self.__tickets[-1]))
self.Log("TICKET:: {0}".format(self.tickets[-1]))
+16 -17
View File
@@ -34,27 +34,26 @@ class WarmupAlgorithm(QCAlgorithm):
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.__symbol = equity.Symbol
self.AddEquity("SPY", Resolution.Second)
self.__first = True
self.__fastPeriod = 60
self.__slowPeriod = 3600
self.__fast = self.EMA(self.__symbol, self.__fastPeriod)
self.__slow = self.EMA(self.__symbol, self.__slowPeriod)
self.SetWarmup(self.__slowPeriod)
fast_period = 60
slow_period = 3600
self.fast = self.EMA("SPY", fast_period)
self.slow = self.EMA("SPY", slow_period)
self.SetWarmup(slow_period)
self.first = True
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.__first and not self.IsWarmingUp:
self.__first = False
self.Log("Fast: {0}".format(self.__fast.Samples))
self.Log("Slow: {0}".format(self.__slow.Samples))
if self.first and not self.IsWarmingUp:
self.first = False
self.Log("Fast: {0}".format(self.fast.Samples))
self.Log("Slow: {0}".format(self.slow.Samples))
if self.__fast.Current.Value > self.__slow.Current.Value:
self.SetHoldings(self.__symbol, 1)
if self.fast.Current.Value > self.slow.Current.Value:
self.SetHoldings("SPY", 1)
else:
self.SetHoldings(self.__symbol, -1)
self.SetHoldings("SPY", -1)
+14 -15
View File
@@ -32,31 +32,30 @@ retrieve data to warm up indicators before data is received'''
self.SetStartDate(2014,5,2) #Set Start Date
self.SetEndDate(2014,5,2) #Set End Date
self.SetCash(100000) #Set Strategy Cash
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
forex = self.AddForex("EURUSD", Resolution.Second)
self.__symbol = forex.Symbol
self.__fastPeriod = 60
self.__slowPeriod = 3600
self.__fast = self.EMA(self.__symbol, self.__fastPeriod)
self.__slow = self.EMA(self.__symbol, self.__slowPeriod)
fast_period = 60
slow_period = 3600
self.fast = self.EMA("EURUSD", fast_period)
self.slow = self.EMA("EURUSD", slow_period)
# "self.__slowPeriod + 1" because rolling window waits for one to fall off the back to be considered ready
history = map(lambda x: x[self.__symbol], self.History(self.__slowPeriod + 1))
# "slow_period + 1" because rolling window waits for one to fall off the back to be considered ready
history = map(lambda x: x["EURUSD"], self.History(slow_period + 1))
for bar in history:
datapoint = IndicatorDataPoint(bar.EndTime, bar.Close)
self.__fast.Update(datapoint)
self.__slow.Update(datapoint)
self.fast.Update(datapoint)
self.slow.Update(datapoint)
self.Log("FAST IS {0} READY. Samples: {1}".format("" if self.__fast.IsReady else "NOT", self.__fast.Samples))
self.Log("SLOW IS {0} READY. Samples: {1}".format("" if self.__slow.IsReady else "NOT", self.__slow.Samples))
self.Log("FAST {0} READY. Samples: {1}".format("IS" if self.fast.IsReady else "IS NOT", self.fast.Samples))
self.Log("SLOW {0} READY. Samples: {1}".format("IS" if self.slow.IsReady else "IS NOT", self.slow.Samples))
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.__fast.Current.Value > self.__slow.Current.Value:
self.SetHoldings(self.__symbol, 1)
if self.fast.Current.Value > self.slow.Current.Value:
self.SetHoldings("EURUSD", 1)
else:
self.SetHoldings(self.__symbol, -1)
self.SetHoldings("EURUSD", -1)