Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 26 additions & 26 deletions Algorithm.Python/CoarseFineFundamentalRegressionAlgorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,57 +22,57 @@
### <meta name="tag" content="regression test" />
class CoarseFineFundamentalRegressionAlgorithm(QCAlgorithm):

def Initialize(self):
self.SetStartDate(2014,3,24) #Set Start Date
self.SetEndDate(2014,4,7) #Set End Date
self.SetCash(50000) #Set Strategy Cash
def initialize(self):
self.set_start_date(2014,3,24) #Set Start Date
self.set_end_date(2014,4,7) #Set End Date
self.set_cash(50000) #Set Strategy Cash

self.UniverseSettings.Resolution = Resolution.Daily
self.universe_settings.resolution = Resolution.DAILY

# this add universe method accepts two parameters:
# - coarse selection function: accepts an IEnumerable<CoarseFundamental> and returns an IEnumerable<Symbol>
# - fine selection function: accepts an IEnumerable<FineFundamental> and returns an IEnumerable<Symbol>
self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
# - coarse selection function: accepts an List[CoarseFundamental] and returns an List[Symbol]
# - fine selection function: accepts an List[FineFundamental] and returns an List[Symbol]
self.add_universe(self.coarse_selection_function, self.fine_selection_function)

self.changes = None
self.numberOfSymbolsFine = 2
self.number_of_symbols_fine = 2

# return a list of three fixed symbol objects
def CoarseSelectionFunction(self, coarse):
def coarse_selection_function(self, coarse):
tickers = [ "GOOG", "BAC", "SPY" ]

if self.Time.date() < date(2014, 4, 1):
if self.time.date() < date(2014, 4, 1):
tickers = [ "AAPL", "AIG", "IBM" ]

return [ Symbol.Create(x, SecurityType.Equity, Market.USA) for x in tickers ]
return [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers ]


# sort the data by market capitalization and take the top 'NumberOfSymbolsFine'
def FineSelectionFunction(self, fine):
# sort the data by market capitalization and take the top 'number_of_symbols_fine'
def fine_selection_function(self, fine):
# sort descending by market capitalization
sortedByMarketCap = sorted(fine, key=lambda x: x.MarketCap, reverse=True)
sorted_by_market_cap = sorted(fine, key=lambda x: x.market_cap, reverse=True)

# take the top entries from our sorted collection
return [ x.Symbol for x in sortedByMarketCap[:self.numberOfSymbolsFine] ]
return [ x.symbol for x in sorted_by_market_cap[:self.number_of_symbols_fine] ]

def OnData(self, data):
def on_data(self, data):
# if we have no changes, do nothing
if self.changes is None: return

# liquidate removed securities
for security in self.changes.RemovedSecurities:
if security.Invested:
self.Liquidate(security.Symbol)
self.Debug("Liquidated Stock: " + str(security.Symbol.Value))
for security in self.changes.removed_securities:
if security.invested:
self.liquidate(security.symbol)
self.debug("Liquidated Stock: " + str(security.symbol.value))

# we want 50% allocation in each security in our universe
for security in self.changes.AddedSecurities:
if (security.Fundamentals.EarningRatios.EquityPerShareGrowth.OneYear > 0.25):
self.SetHoldings(security.Symbol, 0.5)
self.Debug("Purchased Stock: " + str(security.Symbol.Value))
for security in self.changes.added_securities:
if (security.fundamentals.earning_ratios.equity_per_share_growth.one_year > 0.25):
self.set_holdings(security.symbol, 0.5)
self.debug("Purchased Stock: " + str(security.symbol.value))

self.changes = None

# this event fires whenever we have changes to our universe
def OnSecuritiesChanged(self, changes):
def on_securities_changed(self, changes):
self.changes = changes
Original file line number Diff line number Diff line change
Expand Up @@ -19,71 +19,71 @@
### </summary>
class CoarseFineOptionUniverseChainRegressionAlgorithm(QCAlgorithm):

def Initialize(self):
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(2014,6,4) #Set Start Date
self.SetEndDate(2014,6,6) #Set End Date
self.set_start_date(2014,6,4) #Set Start Date
self.set_end_date(2014,6,6) #Set End Date

self.UniverseSettings.Resolution = Resolution.Minute
self._twx = Symbol.Create("TWX", SecurityType.Equity, Market.USA)
self._aapl = Symbol.Create("AAPL", SecurityType.Equity, Market.USA)
self._lastEquityAdded = None
self.universe_settings.resolution = Resolution.MINUTE
self._twx = Symbol.create("TWX", SecurityType.EQUITY, Market.USA)
self._aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
self._last_equity_added = None
self._changes = None
self._optionCount = 0
self._option_count = 0

universe = self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
universe = self.add_universe(self.coarse_selection_function, self.fine_selection_function)

self.AddUniverseOptions(universe, self.OptionFilterFunction)
self.add_universe_options(universe, self.option_filter_function)

def OptionFilterFunction(self, universe):
universe.IncludeWeeklys().FrontMonth()
def option_filter_function(self, universe):
universe.include_weeklys().front_month()

contracts = list()
for symbol in universe:
if len(contracts) == 5:
break
contracts.append(symbol)
return universe.Contracts(contracts)
return universe.contracts(contracts)

def CoarseSelectionFunction(self, coarse):
if self.Time <= datetime(2014,6,5):
def coarse_selection_function(self, coarse):
if self.time <= datetime(2014,6,5):
return [ self._twx ]
return [ self._aapl ]

def FineSelectionFunction(self, fine):
if self.Time <= datetime(2014,6,5):
def fine_selection_function(self, fine):
if self.time <= datetime(2014,6,5):
return [ self._twx ]
return [ self._aapl ]

def OnData(self, data):
if self._changes == None or any(security.Price == 0 for security in self._changes.AddedSecurities):
def on_data(self, data):
if self._changes == None or any(security.price == 0 for security in self._changes.added_securities):
return

# liquidate removed securities
for security in self._changes.RemovedSecurities:
if security.Invested:
self.Liquidate(security.Symbol)
for security in self._changes.removed_securities:
if security.invested:
self.liquidate(security.symbol)

for security in self._changes.AddedSecurities:
if not security.Symbol.HasUnderlying:
self._lastEquityAdded = security.Symbol
for security in self._changes.added_securities:
if not security.symbol.has_underlying:
self._last_equity_added = security.symbol
else:
# options added should all match prev added security
if security.Symbol.Underlying != self._lastEquityAdded:
raise ValueError(f"Unexpected symbol added {security.Symbol}")
self._optionCount += 1
if security.symbol.underlying != self._last_equity_added:
raise ValueError(f"Unexpected symbol added {security.symbol}")
self._option_count += 1

self.SetHoldings(security.Symbol, 0.05)
self.set_holdings(security.symbol, 0.05)
self._changes = None

# this event fires whenever we have changes to our universe
def OnSecuritiesChanged(self, changes):
def on_securities_changed(self, changes):
if self._changes == None:
self._changes = changes
return
self._changes = self._changes.op_Addition(self._changes, changes)
self._changes = self._changes + changes

def OnEndOfAlgorithm(self):
if self._optionCount == 0:
def on_end_of_algorithm(self):
if self._option_count == 0:
raise ValueError("Option universe chain did not add any option!")
44 changes: 22 additions & 22 deletions Algorithm.Python/CoarseFundamentalTop3Algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,56 +22,56 @@
### <meta name="tag" content="fine universes" />
class CoarseFundamentalTop3Algorithm(QCAlgorithm):

def Initialize(self):
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(2014,3,24) #Set Start Date
self.SetEndDate(2014,4,7) #Set End Date
self.SetCash(50000) #Set Strategy Cash
self.set_start_date(2014,3,24) #Set Start Date
self.set_end_date(2014,4,7) #Set End Date
self.set_cash(50000) #Set Strategy Cash

# what resolution should the data *added* to the universe be?
self.UniverseSettings.Resolution = Resolution.Daily
self.universe_settings.resolution = Resolution.DAILY

# this add universe method accepts a single parameter that is a function that
# accepts an IEnumerable<CoarseFundamental> and returns IEnumerable<Symbol>
self.AddUniverse(self.CoarseSelectionFunction)
self.add_universe(self.coarse_selection_function)

self.__numberOfSymbols = 3
self.__number_of_symbols = 3
self._changes = None


# sort the data by daily dollar volume and take the top 'NumberOfSymbols'
def CoarseSelectionFunction(self, coarse):
# sort the data by daily dollar volume and take the top '__number_of_symbols'
def coarse_selection_function(self, coarse):
# sort descending by daily dollar volume
sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True)
sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)

# return the symbol objects of the top entries from our sorted collection
return [ x.Symbol for x in sortedByDollarVolume[:self.__numberOfSymbols] ]
return [ x.symbol for x in sorted_by_dollar_volume[:self.__number_of_symbols] ]


def OnData(self, data):
def on_data(self, data):

self.Log(f"OnData({self.UtcTime}): Keys: {', '.join([key.Value for key in data.Keys])}")
self.log(f"OnData({self.utc_time}): Keys: {', '.join([key.value for key in data.keys()])}")

# if we have no changes, do nothing
if self._changes is None: return

# liquidate removed securities
for security in self._changes.RemovedSecurities:
if security.Invested:
self.Liquidate(security.Symbol)
for security in self._changes.removed_securities:
if security.invested:
self.liquidate(security.symbol)

# we want 1/N allocation in each security in our universe
for security in self._changes.AddedSecurities:
self.SetHoldings(security.Symbol, 1 / self.__numberOfSymbols)
for security in self._changes.added_securities:
self.set_holdings(security.symbol, 1 / self.__number_of_symbols)

self._changes = None


# this event fires whenever we have changes to our universe
def OnSecuritiesChanged(self, changes):
def on_securities_changed(self, changes):
self._changes = changes
self.Log(f"OnSecuritiesChanged({self.UtcTime}):: {changes}")
self.log(f"OnSecuritiesChanged({self.utc_time}):: {changes}")

def OnOrderEvent(self, fill):
self.Log(f"OnOrderEvent({self.UtcTime}):: {fill}")
def on_order_event(self, fill):
self.log(f"OnOrderEvent({self.utc_time}):: {fill}")
Original file line number Diff line number Diff line change
Expand Up @@ -22,66 +22,71 @@
### <meta name="tag" content="securities and portfolio" />
class Collective2PortfolioSignalExportDemonstrationAlgorithm(QCAlgorithm):

def Initialize(self):
def initialize(self):
''' Initialize the date and add all equity symbols present in list _symbols '''

self.SetStartDate(2013, 10, 7) #Set Start Date
self.SetEndDate(2013, 10, 11) #Set End Date
self.SetCash(100000) #Set Strategy Cash
self.set_start_date(2013, 10, 7) #Set Start Date
self.set_end_date(2013, 10, 11) #Set End Date
self.set_cash(100000) #Set Strategy Cash

# Symbols accepted by Collective2. Collective2 accepts stock, future, forex and US stock option symbols
self.AddEquity("GOOG")
self.symbols = [Symbol.Create("SPY", SecurityType.Equity, Market.USA, None, None), Symbol.Create("EURUSD", SecurityType.Forex, Market.Oanda, None, None), Symbol.CreateFuture("ES", Market.CME, datetime(2023, 12, 15), None), Symbol.CreateOption("GOOG", Market.USA, OptionStyle.American, OptionRight.Call, 130, datetime(2023, 9, 1))]
for item in self.symbols:
self.AddSecurity(item)
self.add_equity("GOOG")
self._symbols = [
Symbol.create("SPY", SecurityType.EQUITY, Market.USA, None, None),
Symbol.create("EURUSD", SecurityType.FOREX, Market.OANDA, None, None),
Symbol.create_future("ES", Market.CME, datetime(2023, 12, 15), None),
Symbol.create_option("GOOG", Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 130, datetime(2023, 9, 1))
]
for item in self._symbols:
self.add_security(item)

self.fast = self.EMA("SPY", 10)
self.slow = self.EMA("SPY", 100)
self.fast = self.ema("SPY", 10)
self.slow = self.ema("SPY", 100)

# Initialize these flags, to check when the ema indicators crosses between themselves
self.emaFastIsNotSet = True;
self.emaFastWasAbove = False;
self.ema_fast_is_not_set = True;
self.ema_fast_was_above = False;

# Collective2 APIv4 KEY: This value is provided by Collective2 in their webpage in your account section (See https://collective2.com/account-info)
# See API documentation at https://trade.collective2.com/c2-api
self.collective2Apikey = "YOUR APIV4 KEY"
self.collective2_apikey = "YOUR APIV4 KEY"

# Collective2 System ID: This value is found beside the system's name (strategy's name) on the main system page
self.collective2SystemId = 0
self.collective2_system_id = 0

self.signal_export.add_signal_export_providers(Collective2SignalExport(self.collective2_apikey, self.collective2_system_id))

self.SignalExport.AddSignalExportProviders(Collective2SignalExport(self.collective2Apikey, self.collective2SystemId))

self.first_call = True

self.SetWarmUp(100)

def OnData(self, data):
self.set_warm_up(100)

def on_data(self, data):
''' Reduce the quantity of holdings for one security and increase the holdings to the another
one when the EMA's indicators crosses between themselves, then send a signal to Collective2 API '''
if self.IsWarmingUp: return
if self.is_warming_up: return

# Place an order as soon as possible to send a signal.
if self.first_call:
self.SetHoldings("SPY", 0.1)
self.SignalExport.SetTargetPortfolioFromPortfolio()
self.set_holdings("SPY", 0.1)
self.signal_export.set_target_portfolio_from_portfolio()
self.first_call = False

fast = self.fast.Current.Value
slow = self.slow.Current.Value
fast = self.fast.current.value
slow = self.slow.current.value

# Set the value of flag _emaFastWasAbove, to know when the ema indicators crosses between themselves
if self.emaFastIsNotSet == True:
# Set the value of flag _ema_fast_was_above, to know when the ema indicators crosses between themselves
if self.ema_fast_is_not_set == True:
if fast > slow *1.001:
self.emaFastWasAbove = True
self.ema_fast_was_above = True
else:
self.emaFastWasAbove = False
self.emaFastIsNotSet = False;
self.ema_fast_was_above = False
self.ema_fast_is_not_set = False;

# Check whether ema fast and ema slow crosses. If they do, set holdings to SPY
# or reduce its holdings, and send signals to Collective2 API from your Portfolio
if fast > slow * 1.001 and (not self.emaFastWasAbove):
self.SetHoldings("SPY", 0.1)
self.SignalExport.SetTargetPortfolioFromPortfolio()
elif fast < slow * 0.999 and (self.emaFastWasAbove):
self.SetHoldings("SPY", 0.01)
self.SignalExport.SetTargetPortfolioFromPortfolio()
if fast > slow * 1.001 and (not self.ema_fast_was_above):
self.set_holdings("SPY", 0.1)
self.signal_export.set_target_portfolio_from_portfolio()
elif fast < slow * 0.999 and (self.ema_fast_was_above):
self.set_holdings("SPY", 0.01)
self.signal_export.set_target_portfolio_from_portfolio()
Loading