pep8 conversion of python algos #1-25 (#7926)
* pep8 conversion of python algos * address peer-review * PEP8 updates/fixes * More fixes --------- Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
This commit is contained in:
@@ -22,34 +22,34 @@ from AlgorithmImports import *
|
||||
### <meta name="tag" content="regression test" />
|
||||
class FundamentalRegressionAlgorithm(QCAlgorithm):
|
||||
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2014, 3, 26)
|
||||
self.SetEndDate(2014, 4, 7)
|
||||
def initialize(self):
|
||||
self.set_start_date(2014, 3, 26)
|
||||
self.set_end_date(2014, 4, 7)
|
||||
|
||||
self.UniverseSettings.Resolution = Resolution.Daily
|
||||
self.universe_settings.resolution = Resolution.DAILY
|
||||
|
||||
self._universe = self.AddUniverse(self.SelectionFunction)
|
||||
self._universe = self.add_universe(self.selection_function)
|
||||
|
||||
# before we add any symbol
|
||||
self.AssertFundamentalUniverseData()
|
||||
self.assert_fundamental_universe_data()
|
||||
|
||||
self.AddEquity("SPY")
|
||||
self.AddEquity("AAPL")
|
||||
self.add_equity("SPY")
|
||||
self.add_equity("AAPL")
|
||||
|
||||
# Request fundamental data for symbols at current algorithm time
|
||||
ibm = Symbol.Create("IBM", SecurityType.Equity, Market.USA)
|
||||
ibmFundamental = self.Fundamentals(ibm)
|
||||
if self.Time != self.StartDate or self.Time != ibmFundamental.EndTime:
|
||||
raise ValueError(f"Unexpected Fundamental time {ibmFundamental.EndTime}")
|
||||
if ibmFundamental.Price == 0:
|
||||
ibm = Symbol.create("IBM", SecurityType.EQUITY, Market.USA)
|
||||
ibm_fundamental = self.fundamentals(ibm)
|
||||
if self.time != self.start_date or self.time != ibm_fundamental.end_time:
|
||||
raise ValueError(f"Unexpected Fundamental time {ibm_fundamental.end_time}")
|
||||
if ibm_fundamental.price == 0:
|
||||
raise ValueError(f"Unexpected Fundamental IBM price!")
|
||||
nb = Symbol.Create("NB", SecurityType.Equity, Market.USA)
|
||||
fundamentals = self.Fundamentals([ nb, ibm ])
|
||||
nb = Symbol.create("NB", SecurityType.EQUITY, Market.USA)
|
||||
fundamentals = self.fundamentals([ nb, ibm ])
|
||||
if len(fundamentals) != 2:
|
||||
raise ValueError(f"Unexpected Fundamental count {len(fundamentals)}! Expected 2")
|
||||
|
||||
# Request historical fundamental data for symbols
|
||||
history = self.History(Fundamental, TimeSpan(2, 0, 0, 0))
|
||||
history = self.history(Fundamental, TimeSpan(2, 0, 0, 0))
|
||||
if len(history) != 4:
|
||||
raise ValueError(f"Unexpected Fundamental history count {len(history)}! Expected 4")
|
||||
|
||||
@@ -57,75 +57,75 @@ class FundamentalRegressionAlgorithm(QCAlgorithm):
|
||||
data = history.loc[ticker]
|
||||
if data["value"][0] == 0:
|
||||
raise ValueError(f"Unexpected {data} fundamental data")
|
||||
if Object.ReferenceEquals(data.earningreports.iloc[0], data.earningreports.iloc[1]):
|
||||
if Object.reference_equals(data.earningreports.iloc[0], data.earningreports.iloc[1]):
|
||||
raise ValueError(f"Unexpected fundamental data instance duplication")
|
||||
if data.earningreports.iloc[0]._timeProvider.GetUtcNow() == data.earningreports.iloc[1]._timeProvider.GetUtcNow():
|
||||
if data.earningreports.iloc[0]._time_provider.get_utc_now() == data.earningreports.iloc[1]._time_provider.get_utc_now():
|
||||
raise ValueError(f"Unexpected fundamental data instance duplication")
|
||||
|
||||
self.AssertFundamentalUniverseData()
|
||||
self.assert_fundamental_universe_data()
|
||||
|
||||
self.changes = None
|
||||
self.numberOfSymbolsFundamental = 2
|
||||
self.number_of_symbols_fundamental = 2
|
||||
|
||||
def AssertFundamentalUniverseData(self):
|
||||
def assert_fundamental_universe_data(self):
|
||||
# Case A
|
||||
universeDataPerTime = self.History(self._universe.DataType, [self._universe.Symbol], TimeSpan(2, 0, 0, 0))
|
||||
if len(universeDataPerTime) != 2:
|
||||
raise ValueError(f"Unexpected Fundamentals history count {len(universeDataPerTime)}! Expected 2")
|
||||
universe_data_per_time = self.history(self._universe.data_type, [self._universe.symbol], TimeSpan(2, 0, 0, 0))
|
||||
if len(universe_data_per_time) != 2:
|
||||
raise ValueError(f"Unexpected Fundamentals history count {len(universe_data_per_time)}! Expected 2")
|
||||
|
||||
for universeDataCollection in universeDataPerTime:
|
||||
self.AssertFundamentalEnumerator(universeDataCollection, "A")
|
||||
for universe_data_collection in universe_data_per_time:
|
||||
self.assert_fundamental_enumerator(universe_data_collection, "A")
|
||||
|
||||
# Case B (sugar on A)
|
||||
universeDataPerTime = self.History(self._universe, TimeSpan(2, 0, 0, 0))
|
||||
if len(universeDataPerTime) != 2:
|
||||
raise ValueError(f"Unexpected Fundamentals history count {len(universeDataPerTime)}! Expected 2")
|
||||
universe_data_per_time = self.history(self._universe, TimeSpan(2, 0, 0, 0))
|
||||
if len(universe_data_per_time) != 2:
|
||||
raise ValueError(f"Unexpected Fundamentals history count {len(universe_data_per_time)}! Expected 2")
|
||||
|
||||
for universeDataCollection in universeDataPerTime:
|
||||
self.AssertFundamentalEnumerator(universeDataCollection, "B")
|
||||
for universe_data_collection in universe_data_per_time:
|
||||
self.assert_fundamental_enumerator(universe_data_collection, "B")
|
||||
|
||||
# Case C: Passing through the unvierse type and symbol
|
||||
enumerableOfDataDictionary = self.History[self._universe.DataType]([self._universe.Symbol], 100)
|
||||
for selectionCollectionForADay in enumerableOfDataDictionary:
|
||||
self.AssertFundamentalEnumerator(selectionCollectionForADay[self._universe.Symbol], "C")
|
||||
enumerable_of_data_dictionary = self.history[self._universe.data_type]([self._universe.symbol], 100)
|
||||
for selection_collection_for_a_day in enumerable_of_data_dictionary:
|
||||
self.assert_fundamental_enumerator(selection_collection_for_a_day[self._universe.symbol], "C")
|
||||
|
||||
def AssertFundamentalEnumerator(self, enumerable, caseName):
|
||||
dataPointCount = 0
|
||||
def assert_fundamental_enumerator(self, enumerable, case_name):
|
||||
data_point_count = 0
|
||||
for fundamental in enumerable:
|
||||
dataPointCount += 1
|
||||
data_point_count += 1
|
||||
if type(fundamental) is not Fundamental:
|
||||
raise ValueError(f"Unexpected Fundamentals data type {type(fundamental)} case {caseName}! {str(fundamental)}")
|
||||
if dataPointCount < 7000:
|
||||
raise ValueError(f"Unexpected historical Fundamentals data count {dataPointCount} case {caseName}! Expected > 7000")
|
||||
raise ValueError(f"Unexpected Fundamentals data type {type(fundamental)} case {case_name}! {str(fundamental)}")
|
||||
if data_point_count < 7000:
|
||||
raise ValueError(f"Unexpected historical Fundamentals data count {data_point_count} case {case_name}! Expected > 7000")
|
||||
|
||||
# return a list of three fixed symbol objects
|
||||
def SelectionFunction(self, fundamental):
|
||||
def selection_function(self, fundamental):
|
||||
# sort descending by daily dollar volume
|
||||
sortedByDollarVolume = sorted([x for x in fundamental if x.Price > 1],
|
||||
key=lambda x: x.DollarVolume, reverse=True)
|
||||
sorted_by_dollar_volume = sorted([x for x in fundamental if x.price > 1],
|
||||
key=lambda x: x.dollar_volume, reverse=True)
|
||||
|
||||
# sort descending by P/E ratio
|
||||
sortedByPeRatio = sorted(sortedByDollarVolume, key=lambda x: x.ValuationRatios.PERatio, reverse=True)
|
||||
sorted_by_pe_ratio = sorted(sorted_by_dollar_volume, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)
|
||||
|
||||
# take the top entries from our sorted collection
|
||||
return [ x.Symbol for x in sortedByPeRatio[:self.numberOfSymbolsFundamental] ]
|
||||
return [ x.symbol for x in sorted_by_pe_ratio[:self.number_of_symbols_fundamental] ]
|
||||
|
||||
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:
|
||||
self.SetHoldings(security.Symbol, 0.02)
|
||||
for security in self.changes.added_securities:
|
||||
self.set_holdings(security.symbol, 0.02)
|
||||
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user