Skip to content

Commit 24914fb

Browse files
committed
PEP8 Fix: Assigning to a Method
1 parent 52b8326 commit 24914fb

29 files changed

Lines changed: 315 additions & 319 deletions

Algorithm.Python/BasicTemplateOptionEquityStrategyAlgorithm.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def initialize(self):
3030

3131
equity = self.add_equity(self.underlying_ticker)
3232
option = self.add_option(self.underlying_ticker)
33-
self.option_symbol = option.symbol
33+
self._option_symbol = option.symbol
3434

3535
# set our strike/expiry filter for this option chain
3636
option.set_filter(lambda u: (u.strikes(-2, +2)
@@ -39,9 +39,9 @@ def initialize(self):
3939
.expiration(0, 180)))
4040

4141
def on_data(self, slice: Slice):
42-
if self.portfolio.invested or not self.is_market_open(self.option_symbol): return
42+
if self.portfolio.invested or not self.is_market_open(self._option_symbol): return
4343

44-
chain = slice.option_chains.get_value(self.option_symbol)
44+
chain = slice.option_chains.get_value(self._option_symbol)
4545
if chain is None:
4646
return
4747

@@ -57,7 +57,7 @@ def on_data(self, slice: Slice):
5757
middle_strike = call_contracts[1].strike
5858
higher_strike = call_contracts[2].strike
5959

60-
option_strategy = OptionStrategies.call_butterfly(self.option_symbol, higher_strike, middle_strike, lower_strike, expiry)
60+
option_strategy = OptionStrategies.call_butterfly(self._option_symbol, higher_strike, middle_strike, lower_strike, expiry)
6161

6262
self.order(option_strategy, 10)
6363

Algorithm.Python/Benchmarks/IndicatorRibbonBenchmark.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,25 +19,25 @@ class IndicatorRibbonBenchmark(QCAlgorithm):
1919
def initialize(self):
2020
self.set_start_date(2010, 1, 1) #Set Start Date
2121
self.set_end_date(2018, 1, 1) #Set End Date
22-
self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol
22+
self._spy = self.add_equity("SPY", Resolution.MINUTE).symbol
2323
count = 50
2424
offset = 5
2525
period = 15
26-
self.ribbon = []
26+
self._ribbon = []
2727
# define our sma as the base of the ribbon
28-
self.sma = SimpleMovingAverage(period)
28+
self._sma = SimpleMovingAverage(period)
2929

3030
for x in range(count):
3131
# define our offset to the zero sma, these various offsets will create our 'displaced' ribbon
3232
delay = Delay(offset*(x+1))
3333
# define an indicator that takes the output of the sma and pipes it into our delay indicator
34-
delayed_sma = IndicatorExtensions.of(delay, self.sma)
34+
delayed_sma = IndicatorExtensions.of(delay, self._sma)
3535
# register our new 'delayed_sma' for automatic updates on a daily resolution
36-
self.register_indicator(self.spy, delayed_sma, Resolution.DAILY)
37-
self.ribbon.append(delayed_sma)
36+
self.register_indicator(self._spy, delayed_sma, Resolution.DAILY)
37+
self._ribbon.append(delayed_sma)
3838

3939
def on_data(self, data):
4040
# wait for our entire ribbon to be ready
41-
if not all(x.is_ready for x in self.ribbon): return
42-
for x in self.ribbon:
41+
if not all(x.is_ready for x in self._ribbon): return
42+
for x in self._ribbon:
4343
value = x.current.value

Algorithm.Python/BybitCustomDataCryptoRegressionAlgorithm.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# limitations under the License.
1313

1414
from datetime import time
15+
import os
1516
from AlgorithmImports import *
1617

1718
### <summary>
@@ -29,22 +30,22 @@ def initialize(self) -> None:
2930
self.set_brokerage_model(BrokerageName.BYBIT, AccountType.CASH)
3031

3132
symbol = self.add_crypto("BTCUSDT").symbol
32-
self.btc_usdt = self.add_data(CustomCryptoData, symbol, Resolution.MINUTE).symbol
33+
self._btc_usdt = self.add_data(CustomCryptoData, symbol, Resolution.MINUTE).symbol
3334

3435
# create two moving averages
35-
self.fast = self.ema(self.btc_usdt, 30, Resolution.MINUTE)
36-
self.slow = self.ema(self.btc_usdt, 60, Resolution.MINUTE)
36+
self._fast = self.ema(self._btc_usdt, 30, Resolution.MINUTE)
37+
self._slow = self.ema(self._btc_usdt, 60, Resolution.MINUTE)
3738

3839
def on_data(self, data: Slice) -> None:
39-
if not self.slow.is_ready:
40+
if not self._slow.is_ready:
4041
return
4142

42-
if self.fast.current.value > self.slow.current.value:
43+
if self._fast.current.value > self._slow.current.value:
4344
if self.transactions.orders_count == 0:
44-
self.buy(self.btc_usdt, 1)
45+
self.buy(self._btc_usdt, 1)
4546
else:
4647
if self.transactions.orders_count == 1:
47-
self.liquidate(self.btc_usdt)
48+
self.liquidate(self._btc_usdt)
4849

4950
def on_order_event(self, order_event: OrderEvent) -> None:
5051
self.debug(f"{self.time} {order_event}")
@@ -53,7 +54,7 @@ class CustomCryptoData(PythonData):
5354
def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource:
5455
tick_type_string = Extensions.tick_type_to_lower(config.tick_type)
5556
formatted_date = date.strftime("%Y%m%d")
56-
source = os.path.join(Globals.DataFolder, "crypto", "bybit", "minute",
57+
source = os.path.join(Globals.data_folder, "crypto", "bybit", "minute",
5758
config.symbol.value.lower(), f"{formatted_date}_{tick_type_string}.zip")
5859

5960
return SubscriptionDataSource(source, SubscriptionTransportMedium.LOCAL_FILE, FileFormat.CSV)

Algorithm.Python/CallbackCommandRegressionAlgorithm.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,12 @@ class VoidCommand():
2222
parameters: Dict[str, str] = {}
2323
targettime: datetime | None = None
2424

25-
def run(self, algo: QCAlgorithm) -> bool | None:
25+
def run(self, algo: QCAlgorithm) -> bool:
2626
if not self.targettime or self.targettime != algo.time:
27-
return
27+
return False
2828
tag = self.parameters["tag"]
2929
algo.order(self.target[0], self.get_quantity(), tag=tag)
30+
return True
3031

3132
def get_quantity(self):
3233
return self.quantity
@@ -36,7 +37,7 @@ class BoolCommand(Command):
3637
array_test: List[str] = []
3738
result: bool = False
3839

39-
def run(self, algo: QCAlgorithm) -> bool | None:
40+
def run(self, algo: QCAlgorithm) -> bool:
4041
trade_ibm = self.my_custom_method()
4142
if trade_ibm:
4243
algo.debug(f"BoolCommand.run: {str(self)}")

Algorithm.Python/CompleteOrderTagUpdateAlgorithm.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,14 @@ def on_data(self, data: Slice) -> None:
4848
def on_order_event(self, order_event: OrderEvent) -> None:
4949
if order_event.status == OrderStatus.CANCELED:
5050
if not self._limit_order_ticket or order_event.order_id != self._limit_order_ticket.order_id:
51-
raise Exception("The only canceled order should have been the limit order.")
51+
raise AssertionError("The only canceled order should have been the limit order.")
5252

5353
# update canceled order tag
5454
self.update_order_tag(self._limit_order_ticket, self.tag_after_canceled, "Error updating order tag after canceled")
5555
elif order_event.status == OrderStatus.FILLED:
5656
self._market_order_ticket = list(self.transactions.get_order_tickets(lambda x: x.order_type == OrderType.MARKET))[0]
5757
if not self._market_order_ticket or order_event.order_id != self._market_order_ticket.order_id:
58-
raise Exception("The only filled order should have been the market order.")
58+
raise AssertionError("The only filled order should have been the market order.")
5959

6060
# update filled order tag
6161
self.update_order_tag(self._market_order_ticket, self.tag_after_fill, "Error updating order tag after fill")

Algorithm.Python/CustomDataPropertiesRegressionAlgorithm.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# See the License for the specific language governing permissions and
1212
# limitations under the License.
1313

14+
import json
1415
from AlgorithmImports import *
1516

1617
### <summary>
@@ -25,23 +26,23 @@ class CustomDataPropertiesRegressionAlgorithm(QCAlgorithm):
2526

2627
def initialize(self) -> None:
2728
self.set_start_date(2020, 1, 5) # Set Start Date
28-
self.set_end_date(2020, 1, 10) # Set End Date
29-
self.set_cash(100000) # Set Strategy Cash
29+
self.set_end_date(2020, 1, 10) # Set End Date
30+
self.set_cash(100000) # Set Strategy Cash
3031

3132
# Define our custom data properties and exchange hours
32-
self.ticker = 'BTC'
33-
properties = SymbolProperties("Bitcoin", "USD", 1, 0.01, 0.01, self.ticker)
33+
ticker = 'BTC'
34+
properties = SymbolProperties("Bitcoin", "USD", 1, 0.01, 0.01, ticker)
3435
exchange_hours = SecurityExchangeHours.always_open(TimeZones.NEW_YORK)
3536

3637
# Add the custom data to our algorithm with our custom properties and exchange hours
37-
self.bitcoin = self.add_data(Bitcoin, self.ticker, properties, exchange_hours, leverage=1, fill_forward=False)
38+
self._bitcoin = self.add_data(Bitcoin, ticker, properties, exchange_hours, leverage=1, fill_forward=False)
3839

3940
# Verify our symbol properties were changed and loaded into this security
40-
if self.bitcoin.symbol_properties != properties :
41+
if self._bitcoin.symbol_properties != properties :
4142
raise AssertionError("Failed to set and retrieve custom SymbolProperties for BTC")
4243

4344
# Verify our exchange hours were changed and loaded into this security
44-
if self.bitcoin.exchange.hours != exchange_hours :
45+
if self._bitcoin.exchange.hours != exchange_hours :
4546
raise AssertionError("Failed to set and retrieve custom ExchangeHours for BTC")
4647

4748
# For regression purposes on AddData overloads, this call is simply to ensure Lean can accept this
@@ -55,7 +56,7 @@ def on_data(self, data: Slice) -> None:
5556

5657
def on_end_of_algorithm(self) -> None:
5758
#Reset our Symbol property value, for testing purposes.
58-
self.symbol_properties_database.set_entry(Market.USA, self.market_hours_database.get_database_symbol_key(self.bitcoin.symbol), SecurityType.BASE,
59+
self.symbol_properties_database.set_entry(Market.USA, self.market_hours_database.get_database_symbol_key(self._bitcoin.symbol), SecurityType.BASE,
5960
SymbolProperties.get_default("USD"))
6061

6162

@@ -84,7 +85,7 @@ def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_l
8485

8586
# If value is zero, return None
8687
value = live_btc["last"]
87-
if value == 0: return None
88+
if value == 0: return coin
8889

8990
coin.time = datetime.now()
9091
coin.value = value
@@ -99,17 +100,17 @@ def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_l
99100
return coin
100101
except ValueError:
101102
# Do nothing, possible error in json decoding
102-
return None
103+
return coin
103104

104105
# Example Line Format:
105106
#code date high low mid last bid ask volume
106107
#BTCUSD 2024-10-08 63248.0 61940.0 62246.5 62245.0 62246.0 62247.0 5.929230648356
107-
if not (line.strip() and line[7].isdigit()): return None
108+
if not (line.strip() and line[7].isdigit()): return coin
108109

109110
try:
110111
data = line.split(',')
111112
coin.time = datetime.strptime(data[1], "%Y-%m-%d")
112-
coin.end_time = coin.time + timedelta(days=1)
113+
coin.end_time = coin.time + timedelta(1)
113114
coin.value = float(data[5])
114115
coin["High"] = float(data[2])
115116
coin["Low"] = float(data[3])
@@ -122,4 +123,4 @@ def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_l
122123

123124
except ValueError:
124125
# Do nothing, possible error in json decoding
125-
return None
126+
return coin

Algorithm.Python/CustomDataRegressionAlgorithm.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# See the License for the specific language governing permissions and
1212
# limitations under the License.
1313

14+
import json
1415
from AlgorithmImports import *
1516

1617
### <summary>
@@ -75,9 +76,9 @@ def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_l
7576
try:
7677
live_btc = json.loads(line)
7778

78-
# If value is zero, return None
79+
# If value is zero, return coin
7980
value = live_btc["last"]
80-
if value == 0: return None
81+
if value == 0: return coin
8182

8283
coin.time = datetime.now()
8384
coin.value = value
@@ -92,12 +93,12 @@ def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_l
9293
return coin
9394
except ValueError:
9495
# Do nothing, possible error in json decoding
95-
return None
96+
return coin
9697

9798
# Example Line Format:
9899
# code date high low mid last bid ask volume
99100
# BTCUSD 2024-10-08 63248.0 61940.0 62246.5 62245.0 62246.0 62247.0 477.91102114
100-
if not (line.strip() and line[7].isdigit()): return None
101+
if not (line.strip() and line[7].isdigit()): return coin
101102

102103
try:
103104
data = line.split(',')
@@ -115,4 +116,4 @@ def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_l
115116

116117
except ValueError:
117118
# Do nothing, possible error in json decoding
118-
return None
119+
return coin

Algorithm.Python/CustomIndicatorWithExtensionAlgorithm.py

Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -21,54 +21,54 @@ def initialize(self):
2121
self.set_start_date(2013, 10, 9)
2222
self.set_end_date(2013, 10, 9)
2323

24-
self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol
24+
self._spy = self.add_equity("SPY", Resolution.MINUTE).symbol
2525

26-
self.sma_values = []
27-
self.period = 10
26+
self._sma_values = []
27+
self._period = 10
2828

29-
self.sma = self.sma(self.spy, self.period, Resolution.MINUTE)
30-
self.sma.updated += self.on_sma_updated
29+
self._sma = self.sma(self._spy, self._period, Resolution.MINUTE)
30+
self._sma.updated += self.on_sma_updated
3131

32-
self.custom_sma = CustomSimpleMovingAverage("My SMA", self.period)
33-
self.ext = IndicatorExtensions.of(self.custom_sma, self.sma)
34-
self.ext.updated += self.on_indicator_extension_updated
32+
self._custom_sma = CustomSimpleMovingAverage("My SMA", self._period)
33+
self._ext = IndicatorExtensions.of(self._custom_sma, self._sma)
34+
self._ext.updated += self.on_indicator_extension_updated
3535

36-
self.sma_minus_custom = IndicatorExtensions.minus(self.sma, self.custom_sma)
37-
self.sma_minus_custom.updated += self.on_minus_updated
36+
self._sma_minus_custom = IndicatorExtensions.minus(self._sma, self._custom_sma)
37+
self._sma_minus_custom.updated += self.on_minus_updated
3838

39-
self.sma_was_updated = False
40-
self.custom_sma_was_updated = False
41-
self.sma_minus_custom_was_updated = False
39+
self._sma_was_updated = False
40+
self._custom_sma_was_updated = False
41+
self._sma_minus_custom_was_updated = False
4242

4343
def on_sma_updated(self, sender, updated):
44-
self.sma_was_updated = True
44+
self._sma_was_updated = True
4545

46-
if self.sma.is_ready:
47-
self.sma_values.append(self.sma.current.value)
46+
if self._sma.is_ready:
47+
self._sma_values.append(self._sma.current.value)
4848

4949
def on_indicator_extension_updated(self, sender, updated):
50-
self.custom_sma_was_updated = True
50+
self._custom_sma_was_updated = True
5151

52-
sma_last_values = self.sma_values[-self.period:]
52+
sma_last_values = self._sma_values[-self._period:]
5353
expected = sum(sma_last_values) / len(sma_last_values)
5454

55-
if not isclose(expected, self.custom_sma.value):
56-
raise AssertionError(f"Expected the custom SMA to calculate the moving average of the last {self.period} values of the SMA. "
57-
f"Current expected: {expected}. Actual {self.custom_sma.value}.")
55+
if not isclose(expected, self._custom_sma.value):
56+
raise AssertionError(f"Expected the custom SMA to calculate the moving average of the last {self._period} values of the SMA. "
57+
f"Current expected: {expected}. Actual {self._custom_sma.value}.")
5858

59-
self.debug(f"{self.sma.current.value} :: {self.custom_sma.value} :: {updated}")
59+
self.debug(f"{self._sma.current.value} :: {self._custom_sma.value} :: {updated}")
6060

6161
def on_minus_updated(self, sender, updated):
62-
self.sma_minus_custom_was_updated = True
62+
self._sma_minus_custom_was_updated = True
6363

64-
expected = self.sma.current.value - self.custom_sma.value
64+
expected = self._sma.current.value - self._custom_sma.value
6565

66-
if not isclose(expected, self.sma_minus_custom.current.value):
66+
if not isclose(expected, self._sma_minus_custom.current.value):
6767
raise AssertionError(f"Expected the composite minus indicator to calculate the difference between the SMA and custom SMA indicators. "
68-
f"Expected: {expected}. Actual {self.sma_minus_custom.current.value}.")
68+
f"Expected: {expected}. Actual {self._sma_minus_custom.current.value}.")
6969

7070
def on_end_of_algorithm(self):
71-
if not (self.sma_was_updated and self.custom_sma_was_updated and self.sma_minus_custom_was_updated):
71+
if not (self._sma_was_updated and self._custom_sma_was_updated and self._sma_minus_custom_was_updated):
7272
raise AssertionError("Expected all indicators to have been updated.")
7373

7474
# Custom indicator
@@ -85,4 +85,3 @@ def update(self, input: BaseData) -> bool:
8585
self.value = sum(self.queue) / count
8686

8787
return count == self.queue.maxlen
88-

0 commit comments

Comments
 (0)