class MyUniverseSelection(QCAlgorithm):
def Initialize(self):
# Set Start Date
self.SetStartDate(2017, 1, 1)
# Set Strategy Cash
self.SetCash(100000)
# Make dictionary for universe selection
self.stateData = { }
# Add the universe
self.AddUniverse(self.CoarseSelectionFilter)
# Schdule for everyday on market open
self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.At(9, 33), self.EveryDayAfterMarketOpen)
# Schedule for everyday before market close
self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.At(15, 57), self.EveryDayBeforeMarketClose)
# Function for coarse selection (to define our universe)
def CoarseSelectionFilter(self, coarse):
self.coarse = coarse
# We are going to use a dictionary to refer the object that will keep the moving averages
# Adds the stocks that fit the volume criteria to the dictionary
for c in coarse:
if c.Symbol not in self.stateData:
self.stateData[c.Symbol] = SelectionData(c.Symbol, 10)
# Update the stateData to make sure it has the most recent stock data
avg = self.stateData[c.Symbol]
avg.update(c.EndTime, c.AdjustedPrice, c.DollarVolume)
# Makes sure price is between 1 and 100
filtered = [x for x in self.stateData.values() if x.price >= 1 and x.price <= 100]
return filtered
# Everyday after market open
def EveryDayAfterMarketOpen(self):
# If current slice contains "SPY" data place a market order
for c in self.securities:
if c.Open[0] < c.Close[1]:
self.MarketOrder(c, .01)
# Everyday before market close
def EveryDayBeforeMarketClose(self):
# Liquidate all holdings
self.Liquidate()
# Chnages self.securitues as the universe changes
def OnSecuritiesChanged(self, algorithm, changes):
# add new securities
for added in changes.AddedSecurities:
self.securities.append(added)
# remove securities
for removed in changes.RemovedSecurities:
if removed in self.securities:
self.securities.remove(removed)
class SelectionData(object):
def __init__(self, symbol, period):
self.symbol = symbol
self.price = 0
self.volume = 0
self.sma = SimpleMovingAverage(period)
self.is_above_vol = False
def update(self, time, price, volume):
self.volume = volume
self.price = price
if self.sma.Update(time, volume):
self.is_above_vol = sma > 3500000