Skip to content

Commit e591d23

Browse files
Fix some python regression algorithms
1 parent eb7fe09 commit e591d23

15 files changed

+37
-37
lines changed

Algorithm.Python/BasicTemplateIndexDailyAlgorithm.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -45,23 +45,23 @@ def initialize(self) -> None:
4545
self.settings.daily_precise_end_time = True
4646

4747
def on_data(self, data: Slice):
48-
if not self.Portfolio.Invested:
48+
if not self.portfolio.invested:
4949
# SPX Index is not tradable, but we can trade an option
50-
self.MarketOrder(self.spx_option, 1)
50+
self.market_order(self.spx_option, 1)
5151
else:
52-
self.Liquidate()
52+
self.liquidate()
5353

5454
# Count how many slices we receive with SPX data in it to assert later
55-
if data.ContainsKey(self.spx):
55+
if data.contains_key(self.spx):
5656
self.BarCounter = self.BarCounter + 1
5757

5858
def OnEndOfAlgorithm(self):
5959
if self.BarCounter != self.ExpectedBarCount:
6060
raise ValueError(f"Bar Count {self.BarCounter} is not expected count of {self.ExpectedBarCount}")
6161

6262
for symbol in [ self.spx_option, self.spx ]:
63-
history = self.History(symbol, 10)
63+
history = self.history(symbol, 10)
6464
if len(history) != 10:
65-
raise ValueError(f"Unexpected history count: {history.Count}")
65+
raise ValueError(f"Unexpected history count: {len(history)}")
6666
if any(x for x in history.index.get_level_values('time') if x.time() != time(15, 15, 0)):
6767
raise ValueError(f"Unexpected history data time")

Algorithm.Python/CanLiquidateWithOrderPropertiesRegressionAlgorithm.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -35,5 +35,5 @@ def on_data(self, slice):
3535
order_properties.time_in_force = TimeInForce.DAY
3636
tickets = self.liquidate(asynchronous = True, order_properties = order_properties)
3737
for ticket in tickets:
38-
if ticket.SubmitRequest.OrderProperties.TimeInForce != TimeInForce.DAY:
39-
raise AssertionError(f"The TimeInForce for all orders should be daily, but it was {ticket.SubmitRequest.OrderProperties.TimeInForce}")
38+
if ticket.submit_request.order_properties.time_in_force != TimeInForce.DAY:
39+
raise AssertionError(f"The TimeInForce for all orders should be daily, but it was {ticket.submit_request.order_properties.time_in_force}")

Algorithm.Python/ConstituentsUniverseRegressionAlgorithm.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,10 @@ def on_end_of_algorithm(self):
7575

7676
def OnSecuritiesChanged(self, changes):
7777
for added in changes.added_securities:
78-
self.log(f"{self.Time} AddedSecurities " + str(added))
78+
self.log(f"{self.time} AddedSecurities " + str(added))
7979

8080
for removed in changes.removed_securities:
81-
self.log(f"{self.Time} RemovedSecurities " + str(removed) + str(self._step))
81+
self.log(f"{self.time} RemovedSecurities " + str(removed) + str(self._step))
8282
# we are currently notifying the removal of AAPl twice,
8383
# when deselected and when finally removed (since it stayed pending)
8484
if removed.symbol == self._appl and self._step != 1 and self._step != 2 or removed.symbol == self._qqq and self._step != 1:

Algorithm.Python/DataConsolidationAlgorithm.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ class DataConsolidationAlgorithm(QCAlgorithm):
3333
def initialize(self):
3434
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
3535

36-
self.set_start_date(DateTime(2013, 10, 7, 9, 30, 0)) #Set Start Date
37-
self.set_end_date(self.start_date + timedelta(60)) #Set End Date
36+
self.set_start_date(2013, 10, 7) #Set Start Date
37+
self.set_end_date(2013, 12, 7) #Set End Date
3838
# Find more symbols here: http://quantconnect.com/data
3939
self.add_equity("SPY")
4040
self.add_forex("EURUSD", Resolution.HOUR)

Algorithm.Python/DescendingCustomDataObjectStoreRegressionAlgorithm.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def on_end_of_algorithm(self):
7979
for i in range(len(history) - 1):
8080
# [1] - time
8181
if history.index[i][1] > history.index[i + 1][1]:
82-
raise RegressionTestException(
82+
raise AssertionError(
8383
f"Order failure: {history.index[i][1]} > {history.index[i + 1][1]} at index {i}.")
8484

8585
def get_custom_data_key(self):

Algorithm.Python/FundamentalUniverseSelectionAlgorithm.py

+1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ def initialize(self):
3434
self.set_universe_selection(FundamentalUniverseSelectionModel(self.select))
3535

3636
self.changes = None
37+
self.number_of_symbols_fundamental = 10
3738

3839
# return a list of three fixed symbol objects
3940
def selection_function(self, fundamental):

Algorithm.Python/FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,10 @@ def on_data(self, data: Slice):
5151
def on_end_of_algorithm(self):
5252
not_encountered = [str(k) for k,v in self.expected_symbols.items() if not v]
5353
if any(not_encountered):
54-
raise AggregateException(f"Expected all Symbols encountered and invested in, but the following were not found: {', '.join(not_encountered)}")
54+
raise AssertionError(f"Expected all Symbols encountered and invested in, but the following were not found: {', '.join(not_encountered)}")
5555

5656
if not self.portfolio.invested:
57-
raise AggregateException("Expected holdings at the end of algorithm, but none were found.")
57+
raise AssertionError("Expected holdings at the end of algorithm, but none were found.")
5858

5959
def is_in_regular_hours(self, symbol):
6060
return self.securities[symbol].exchange.exchange_open

Algorithm.Python/ImmediateExecutionModelWorksWithBinanceFeeModel.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,10 @@ class ImmediateExecutionModelWorksWithBinanceFeeModel(QCAlgorithm):
2626

2727
def Initialize(self):
2828
# *** initial configurations and backtest ***
29-
self.SetStartDate(2022, 12, 13) # Set Start Date
30-
self.SetEndDate(2022, 12, 14) # Set End Date
31-
self.SetAccountCurrency("BUSD") # Set Account Currency
32-
self.SetCash("BUSD", 100000, 1) # Set Strategy Cash
29+
self.set_start_date(2022, 12, 13) # Set Start Date
30+
self.set_end_date(2022, 12, 14) # Set End Date
31+
self.set_account_currency("BUSD") # Set Account Currency
32+
self.set_cash("BUSD", 100000, 1) # Set Strategy Cash
3333

3434
self.universe_settings.resolution = Resolution.MINUTE
3535

@@ -43,7 +43,7 @@ def Initialize(self):
4343
self.set_execution(ImmediateExecutionModel())
4444

4545

46-
self.SetBrokerageModel(BrokerageName.Binance, AccountType.Margin)
46+
self.set_brokerage_model(BrokerageName.BINANCE, AccountType.MARGIN)
4747

4848
def on_order_event(self, order_event: OrderEvent) -> None:
4949
if order_event.status == OrderStatus.FILLED:

Algorithm.Python/LiveFeaturesAlgorithm.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
# limitations under the License.
1313

1414
from AlgorithmImports import *
15-
from System.Globalization import *
1615

1716
### <summary>
1817
### Live Trading Functionality Demonstration algorithm including SMS, Email and Web hook notifications.
@@ -47,7 +46,7 @@ def initialize(self):
4746

4847

4948
### New Bitcoin Data Event
50-
def on_data(Bitcoin, data):
49+
def on_data(self, Bitcoin, data):
5150
if self.live_mode:
5251
self.set_runtime_statistic('BTC', str(data.close))
5352

@@ -94,7 +93,7 @@ def get_source(self, config, date, is_live_mode):
9493
if is_live_mode:
9594
return SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.REST)
9695

97-
return SubscriptionDataSource("https://www.quandl.com/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc", SubscriptionTransportMedium.REMOTE_FILE)
96+
return SubscriptionDataSource("https://www.quandl.com/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc", SubscriptionTransportMedium.REMOTE_FILE)
9897

9998

10099
def reader(self, config, line, date, is_live_mode):

Algorithm.Python/MacdAlphaModelFrameworkRegressionAlgorithm.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,4 @@ def initialize(self):
2727
def on_end_of_algorithm(self):
2828
expected = 4
2929
if self.insights.total_count != expected:
30-
raise Exception(f"The total number of insights should be {expected}. Actual: {self.insights.total_count}")
30+
raise AssertionError(f"The total number of insights should be {expected}. Actual: {self.insights.total_count}")

Algorithm.Python/OptionUniverseFilterGreeksRegressionAlgorithm.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ def main_filter(self, universe: OptionFilterUniverse) -> OptionFilterUniverse:
5353
filtered_contracts = len(list(filtered_universe))
5454

5555
if filtered_contracts == total_contracts:
56-
raise RegressionTestException(f"Expected filtered universe to have less contracts than original universe. "
57-
f"Filtered contracts count ({filtered_contracts}) is equal to total contracts count ({total_contracts})")
56+
raise AssertionError(f"Expected filtered universe to have less contracts than original universe. "
57+
f"Filtered contracts count ({filtered_contracts}) is equal to total contracts count ({total_contracts})")
5858

5959
return filtered_universe
6060

@@ -88,4 +88,4 @@ def on_data(self, slice: Slice) -> None:
8888

8989
def on_end_of_algorithm(self) -> None:
9090
if not self.option_chain_received:
91-
raise RegressionTestException("Option chain was not received.")
91+
raise AssertionError("Option chain was not received.")

Algorithm.Python/OptionUniverseHistoryRegressionAlgorithm.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def initialize(self):
2929

3030
# Level 0 of the multi-index is the date, we expect 3 dates, 3 option chains
3131
if historical_options_data_df.index.levshape[0] != 3:
32-
raise RegressionTestException(f"Expected 3 option chains from history request, but got {historical_options_data_df.index.levshape[1]}")
32+
raise AssertionError(f"Expected 3 option chains from history request, but got {historical_options_data_df.index.levshape[1]}")
3333

3434
for date in historical_options_data_df.index.levels[0]:
3535
expected_chain = list(self.option_chain_provider.get_option_contract_list(option, date))
@@ -39,9 +39,9 @@ def initialize(self):
3939
actual_chain_count = len(actual_chain)
4040

4141
if expected_chain_count != actual_chain_count:
42-
raise RegressionTestException(f"Expected {expected_chain_count} options in chain on {date}, but got {actual_chain_count}")
42+
raise AssertionError(f"Expected {expected_chain_count} options in chain on {date}, but got {actual_chain_count}")
4343

4444
for i, symbol in enumerate(actual_chain.index):
4545
expected_symbol = expected_chain[i]
4646
if symbol != expected_symbol:
47-
raise RegressionTestException(f"Expected symbol {expected_symbol} at index {i} on {date}, but got {symbol}")
47+
raise AssertionError(f"Expected symbol {expected_symbol} at index {i} on {date}, but got {symbol}")

Algorithm.Python/PersistentCustomDataUniverseRegressionAlgorithm.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -35,23 +35,23 @@ def universe_selector(self, data):
3535
def retrieve_historical_data(self):
3636
history = list(self.history[StockDataSource](self._universe_symbol, datetime(2018, 1, 1), datetime(2018, 6, 1), Resolution.DAILY))
3737
if (len(history) == 0):
38-
raise RegressionTestException(f"No historical data received for symbol {self._universe_symbol}.")
38+
raise AssertionError(f"No historical data received for symbol {self._universe_symbol}.")
3939

4040
# Ensure all values are of type StockDataSource
4141
for item in history:
4242
if not isinstance(item, StockDataSource):
43-
raise RegressionTestException(f"Unexpected data type in history. Expected StockDataSource but received {type(item).__name__}.")
43+
raise AssertionError(f"Unexpected data type in history. Expected StockDataSource but received {type(item).__name__}.")
4444

4545
def OnData(self, slice: Slice):
4646
if self._universe_symbol not in slice:
47-
raise RegressionTestException(f"No data received for the universe symbol: {self._universe_symbol}.")
47+
raise AssertionError(f"No data received for the universe symbol: {self._universe_symbol}.")
4848
if (not self._data_received):
4949
self.retrieve_historical_data()
5050
self._data_received = True
5151

5252
def OnEndOfAlgorithm(self) -> None:
5353
if not self._data_received:
54-
raise RegressionTestException("No data was received after the universe selection.")
54+
raise AssertionError("No data was received after the universe selection.")
5555

5656
class StockDataSource(PythonData):
5757

Algorithm.Python/RawDataRegressionAlgorithm.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,6 @@ def on_data(self, data):
6161
day_factor = self._factor_file.get_price_scale_factor(googl_data.time)
6262
probable_raw_price = googl_data.close / day_factor # Undo adjustment
6363

64-
raise Exception("Close price was incorrect; it appears to be the adjusted value"
64+
raise AssertionError("Close price was incorrect; it appears to be the adjusted value"
6565
if expected_raw_price == probable_raw_price else
6666
"Close price was incorrect; Data may have changed.")

Algorithm.Python/WarmupAlgorithm.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ def initialize(self):
3434
fast_period = 60
3535
slow_period = 3600
3636

37-
self.fast = self.EMA("SPY", fast_period)
38-
self.slow = self.EMA("SPY", slow_period)
37+
self.fast = self.ema("SPY", fast_period)
38+
self.slow = self.ema("SPY", slow_period)
3939

4040
self.set_warmup(slow_period)
4141
self.first = True

0 commit comments

Comments
 (0)