Skip to content

Commit 784e497

Browse files
pep8 conversion on python algorithms #2 (#7933)
* pep8 conversion * more * Minor fix * Fix related regression algorithm --------- Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
1 parent c2bea3c commit 784e497

25 files changed

Lines changed: 469 additions & 469 deletions

‎Algorithm.Python/BasicTemplateDailyAlgorithm.py‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,22 +21,22 @@
2121
class BasicTemplateDailyAlgorithm(QCAlgorithm):
2222
'''Basic template algorithm simply initializes the date range and cash'''
2323

24-
def Initialize(self):
25-
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
24+
def initialize(self):
25+
'''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
2626

27-
self.SetStartDate(2013,10,8) #Set Start Date
28-
self.SetEndDate(2013,10,17) #Set End Date
29-
self.SetCash(100000) #Set Strategy Cash
27+
self.set_start_date(2013,10,8) #Set Start Date
28+
self.set_end_date(2013,10,17) #Set End Date
29+
self.set_cash(100000) #Set Strategy Cash
3030
# Find more symbols here: http://quantconnect.com/data
31-
self.AddEquity("SPY", Resolution.Daily)
31+
self.add_equity("SPY", Resolution.DAILY)
3232

3333

34-
def OnData(self, data):
35-
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
34+
def on_data(self, data):
35+
'''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
3636
3737
Arguments:
3838
data: Slice object keyed by symbol containing the stock data
3939
'''
40-
if not self.Portfolio.Invested:
41-
self.SetHoldings("SPY", 1)
42-
self.Debug("Purchased Stock")
40+
if not self.portfolio.invested:
41+
self.set_holdings("SPY", 1)
42+
self.debug("Purchased Stock")

‎Algorithm.Python/BasicTemplateFillForwardAlgorithm.py‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,20 +16,20 @@
1616
class BasicTemplateFillForwardAlgorithm(QCAlgorithm):
1717
'''Basic template algorithm simply initializes the date range and cash'''
1818

19-
def Initialize(self):
20-
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
19+
def initialize(self):
20+
'''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
2121

22-
self.SetStartDate(2013,10,7) #Set Start Date
23-
self.SetEndDate(2013,11,30) #Set End Date
24-
self.SetCash(100000) #Set Strategy Cash
22+
self.set_start_date(2013,10,7) #Set Start Date
23+
self.set_end_date(2013,11,30) #Set End Date
24+
self.set_cash(100000) #Set Strategy Cash
2525
# Find more symbols here: http://quantconnect.com/data
26-
self.AddSecurity(SecurityType.Equity, "ASUR", Resolution.Second)
26+
self.add_security(SecurityType.EQUITY, "ASUR", Resolution.SECOND)
2727

28-
def OnData(self, data):
29-
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
28+
def on_data(self, data):
29+
'''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
3030
3131
Arguments:
3232
data: Slice object keyed by symbol containing the stock data
3333
'''
34-
if not self.Portfolio.Invested:
35-
self.SetHoldings("ASUR", 1)
34+
if not self.portfolio.invested:
35+
self.set_holdings("ASUR", 1)

‎Algorithm.Python/BasicTemplateForexAlgorithm.py‎

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -23,31 +23,31 @@
2323
### <meta name="tag" content="forex" />
2424
class BasicTemplateForexAlgorithm(QCAlgorithm):
2525

26-
def Initialize(self):
26+
def initialize(self):
2727
# Set the cash we'd like to use for our backtest
28-
self.SetCash(100000)
28+
self.set_cash(100000)
2929

3030
# Start and end dates for the backtest.
31-
self.SetStartDate(2013, 10, 7)
32-
self.SetEndDate(2013, 10, 11)
31+
self.set_start_date(2013, 10, 7)
32+
self.set_end_date(2013, 10, 11)
3333

3434
# Add FOREX contract you want to trade
3535
# find available contracts here https://www.quantconnect.com/data#forex/oanda/cfd
36-
self.AddForex("EURUSD", Resolution.Minute)
37-
self.AddForex("GBPUSD", Resolution.Minute)
38-
self.AddForex("EURGBP", Resolution.Minute)
36+
self.add_forex("EURUSD", Resolution.MINUTE)
37+
self.add_forex("GBPUSD", Resolution.MINUTE)
38+
self.add_forex("EURGBP", Resolution.MINUTE)
3939

40-
self.History(5, Resolution.Daily)
41-
self.History(5, Resolution.Hour)
42-
self.History(5, Resolution.Minute)
40+
self.history(5, Resolution.DAILY)
41+
self.history(5, Resolution.HOUR)
42+
self.history(5, Resolution.MINUTE)
4343

44-
history = self.History(TimeSpan.FromSeconds(5), Resolution.Second)
44+
history = self.history(TimeSpan.from_seconds(5), Resolution.SECOND)
4545

46-
for data in sorted(history, key=lambda x: x.Time):
47-
for key in data.Keys:
48-
self.Log(str(key.Value) + ": " + str(data.Time) + " > " + str(data[key].Value))
46+
for data in sorted(history, key=lambda x: x.time):
47+
for key in data.keys():
48+
self.log(str(key.value) + ": " + str(data.time) + " > " + str(data[key].value))
4949

50-
def OnData(self, data):
50+
def on_data(self, data):
5151
# Print to console to verify that data is coming in
52-
for key in data.Keys:
53-
self.Log(str(key.Value) + ": " + str(data.Time) + " > " + str(data[key].Value))
52+
for key in data.keys():
53+
self.log(str(key.value) + ": " + str(data.time) + " > " + str(data[key].value))

‎Algorithm.Python/BasicTemplateFrameworkAlgorithm.py‎

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,39 +22,39 @@
2222
class BasicTemplateFrameworkAlgorithm(QCAlgorithm):
2323
'''Basic template framework algorithm uses framework components to define the algorithm.'''
2424

25-
def Initialize(self):
26-
''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
25+
def initialize(self):
26+
'''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
2727

2828
# Set requested data resolution
29-
self.UniverseSettings.Resolution = Resolution.Minute
29+
self.universe_settings.resolution = Resolution.MINUTE
3030

31-
self.SetStartDate(2013,10,7) #Set Start Date
32-
self.SetEndDate(2013,10,11) #Set End Date
33-
self.SetCash(100000) #Set Strategy Cash
31+
self.set_start_date(2013,10,7) #Set Start Date
32+
self.set_end_date(2013,10,11) #Set End Date
33+
self.set_cash(100000) #Set Strategy Cash
3434

3535
# Find more symbols here: http://quantconnect.com/data
3636
# Forex, CFD, Equities Resolutions: Tick, Second, Minute, Hour, Daily.
3737
# Futures Resolution: Tick, Second, Minute
3838
# Options Resolution: Minute Only.
39-
symbols = [ Symbol.Create("SPY", SecurityType.Equity, Market.USA) ]
39+
symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]
4040

4141
# set algorithm framework models
42-
self.SetUniverseSelection(ManualUniverseSelectionModel(symbols))
43-
self.SetAlpha(ConstantAlphaModel(InsightType.Price, InsightDirection.Up, timedelta(minutes = 20), 0.025, None))
42+
self.set_universe_selection(ManualUniverseSelectionModel(symbols))
43+
self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))
4444

4545
# We can define how often the EWPCM will rebalance if no new insight is submitted using:
4646
# Resolution Enum:
47-
self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel(Resolution.Daily))
47+
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.DAILY))
4848
# timedelta
49-
# self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel(timedelta(2)))
49+
# self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(timedelta(2)))
5050
# A lamdda datetime -> datetime. In this case, we can use the pre-defined func at Expiry helper class
51-
# self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel(Expiry.EndOfWeek))
51+
# self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Expiry.END_OF_WEEK))
5252

53-
self.SetExecution(ImmediateExecutionModel())
54-
self.SetRiskManagement(MaximumDrawdownPercentPerSecurity(0.01))
53+
self.set_execution(ImmediateExecutionModel())
54+
self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))
5555

56-
self.Debug("numpy test >>> print numpy.pi: " + str(np.pi))
56+
self.debug("numpy test >>> print numpy.pi: " + str(np.pi))
5757

58-
def OnOrderEvent(self, orderEvent):
59-
if orderEvent.Status == OrderStatus.Filled:
60-
self.Debug("Purchased Stock: {0}".format(orderEvent.Symbol))
58+
def on_order_event(self, order_event):
59+
if order_event.status == OrderStatus.FILLED:
60+
self.debug("Purchased Stock: {0}".format(order_event.symbol))

‎Algorithm.Python/BasicTemplateFutureOptionAlgorithm.py‎

Lines changed: 32 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -22,50 +22,50 @@
2222

2323
class BasicTemplateFutureOptionAlgorithm(QCAlgorithm):
2424

25-
def Initialize(self):
26-
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
27-
self.SetStartDate(2022, 1, 1)
28-
self.SetEndDate(2022, 2, 1)
29-
self.SetCash(100000)
25+
def initialize(self):
26+
'''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
27+
self.set_start_date(2022, 1, 1)
28+
self.set_end_date(2022, 2, 1)
29+
self.set_cash(100000)
3030

31-
gold_futures = self.AddFuture(Futures.Metals.Gold, Resolution.Minute)
32-
gold_futures.SetFilter(0, 180)
33-
self.symbol = gold_futures.Symbol
34-
self.AddFutureOption(self.symbol, lambda universe: universe.Strikes(-5, +5)
35-
.CallsOnly()
36-
.BackMonth()
37-
.OnlyApplyFilterAtMarketOpen())
31+
gold_futures = self.add_future(Futures.Metals.GOLD, Resolution.MINUTE)
32+
gold_futures.set_filter(0, 180)
33+
self._symbol = gold_futures.symbol
34+
self.add_future_option(self._symbol, lambda universe: universe.strikes(-5, +5)
35+
.calls_only()
36+
.back_month()
37+
.only_apply_filter_at_market_open())
3838

3939
# Historical Data
40-
history = self.History(self.symbol, 60, Resolution.Daily)
41-
self.Log(f"Received {len(history)} bars from {self.symbol} FutureOption historical data call.")
40+
history = self.history(self._symbol, 60, Resolution.DAILY)
41+
self.log(f"Received {len(history)} bars from {self._symbol} FutureOption historical data call.")
4242

43-
def OnData(self, data):
44-
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
43+
def on_data(self, data):
44+
'''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
4545
Arguments:
4646
slice: Slice object keyed by symbol containing the stock data
4747
'''
4848
# Access Data
49-
for kvp in data.OptionChains:
50-
underlying_future_contract = kvp.Key.Underlying
51-
chain = kvp.Value
49+
for kvp in data.option_chains:
50+
underlying_future_contract = kvp.key.underlying
51+
chain = kvp.value
5252

5353
if not chain: continue
5454

5555
for contract in chain:
56-
self.Log(f"""Canonical Symbol: {kvp.Key};
56+
self.log(f"""Canonical Symbol: {kvp.key};
5757
Contract: {contract};
58-
Right: {contract.Right};
59-
Expiry: {contract.Expiry};
60-
Bid price: {contract.BidPrice};
61-
Ask price: {contract.AskPrice};
62-
Implied Volatility: {contract.ImpliedVolatility}""")
58+
Right: {contract.right};
59+
Expiry: {contract.expiry};
60+
Bid price: {contract.bid_price};
61+
Ask price: {contract.ask_price};
62+
Implied Volatility: {contract.implied_volatility}""")
6363

64-
if not self.Portfolio.Invested:
65-
atm_strike = sorted(chain, key = lambda x: abs(chain.Underlying.Price - x.Strike))[0].Strike
66-
selected_contract = sorted([contract for contract in chain if contract.Strike == atm_strike], \
67-
key = lambda x: x.Expiry, reverse=True)[0]
68-
self.MarketOrder(selected_contract.Symbol, 1)
64+
if not self.portfolio.invested:
65+
atm_strike = sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike))[0].strike
66+
selected_contract = sorted([contract for contract in chain if contract.strike == atm_strike], \
67+
key = lambda x: x.expiry, reverse=True)[0]
68+
self.market_order(selected_contract.symbol, 1)
6969

70-
def OnOrderEvent(self, orderEvent):
71-
self.Debug("{} {}".format(self.Time, orderEvent.ToString()))
70+
def on_order_event(self, order_event):
71+
self.debug("{} {}".format(self.time, order_event.to_string()))

0 commit comments

Comments
 (0)