PEP8 algorithms conversion (#7962)

* PEP8 algorithms conversion

* PEP8 unit tests algorithms conversion

* Minor fixes
This commit is contained in:
Jhonathan Abreu
2024-04-22 12:59:50 -04:00
committed by GitHub
parent 8fa824b19e
commit 6bfe45dbcf
14 changed files with 208 additions and 269 deletions
@@ -21,106 +21,106 @@ class BasicTemplateCryptoFutureHourlyAlgorithm(QCAlgorithm):
# Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
# </summary>
def Initialize(self):
self.SetStartDate(2022, 12, 13)
self.SetEndDate(2022, 12, 13)
def initialize(self):
self.set_start_date(2022, 12, 13)
self.set_end_date(2022, 12, 13)
self.SetTimeZone(TimeZones.Utc)
self.set_time_zone(TimeZones.UTC)
try:
self.SetBrokerageModel(BrokerageName.BinanceCoinFutures, AccountType.Cash)
self.set_brokerage_model(BrokerageName.BINANCE_COIN_FUTURES, AccountType.CASH)
except:
# expected, we don't allow cash account type
pass
self.SetBrokerageModel(BrokerageName.BinanceCoinFutures, AccountType.Margin)
self.set_brokerage_model(BrokerageName.BINANCE_COIN_FUTURES, AccountType.MARGIN)
self.adaUsdt = self.AddCryptoFuture("ADAUSDT", Resolution.Hour)
self.ada_usdt = self.add_crypto_future("ADAUSDT", Resolution.HOUR)
self.fast = self.EMA(self.adaUsdt.Symbol, 3, Resolution.Hour)
self.slow = self.EMA(self.adaUsdt.Symbol, 6, Resolution.Hour)
self.fast = self.ema(self.ada_usdt.symbol, 3, Resolution.HOUR)
self.slow = self.ema(self.ada_usdt.symbol, 6, Resolution.HOUR)
self.interestPerSymbol = {self.adaUsdt.Symbol: 0}
self.interest_per_symbol = {self.ada_usdt.symbol: 0}
# Default USD cash, set 1M but it wont be used
self.SetCash(1000000)
self.set_cash(1000000)
# the amount of USDT we need to hold to trade 'ADAUSDT'
self.adaUsdt.QuoteCurrency.SetAmount(200)
self.ada_usdt.quote_currency.set_amount(200)
# <summary>
# OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
# </summary>
# <param name="data">Slice object keyed by symbol containing the stock data</param>
def OnData(self, slice):
interestRates = slice.Get(MarginInterestRate);
for interestRate in interestRates:
self.interestPerSymbol[interestRate.Key] += 1
self.cachedInterestRate = self.Securities[interestRate.Key].Cache.GetData[MarginInterestRate]()
if self.cachedInterestRate != interestRate.Value:
raise Exception(f"Unexpected cached margin interest rate for {interestRate.Key}!")
def on_data(self, slice):
interest_rates = slice.get(MarginInterestRate);
for interest_rate in interest_rates:
self.interest_per_symbol[interest_rate.key] += 1
self.cached_interest_rate = self.securities[interest_rate.key].cache.get_data[MarginInterestRate]()
if self.cached_interest_rate != interest_rate.value:
raise Exception(f"Unexpected cached margin interest rate for {interest_rate.key}!")
if self.fast > self.slow:
if self.Portfolio.Invested == False and self.Transactions.OrdersCount == 0:
self.ticket = self.Buy(self.adaUsdt.Symbol, 100000)
if self.ticket.Status != OrderStatus.Invalid:
if self.portfolio.invested == False and self.transactions.orders_count == 0:
self.ticket = self.buy(self.ada_usdt.symbol, 100000)
if self.ticket.status != OrderStatus.INVALID:
raise Exception(f"Unexpected valid order {self.ticket}, should fail due to margin not sufficient")
self.Buy(self.adaUsdt.Symbol, 1000)
self.marginUsed = self.Portfolio.TotalMarginUsed
self.buy(self.ada_usdt.symbol, 1000)
self.adaUsdtHoldings = self.adaUsdt.Holdings
self.margin_used = self.portfolio.total_margin_used
self.ada_usdt_holdings = self.ada_usdt.holdings
# USDT/BUSD futures value is based on it's price
self.holdingsValueUsdt = self.adaUsdt.Price * self.adaUsdt.SymbolProperties.ContractMultiplier * 1000
self.holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 1000
if abs(self.ada_usdt_holdings.total_sale_volume - self.holdings_value_usdt) > 1:
raise Exception(f"Unexpected TotalSaleVolume {self.ada_usdt_holdings.total_sale_volume}")
if abs(self.ada_usdt_holdings.absolute_holdings_cost - self.holdings_value_usdt) > 1:
raise Exception(f"Unexpected holdings cost {self.ada_usdt_holdings.holdings_cost}")
if (abs(self.ada_usdt_holdings.absolute_holdings_cost * 0.05 - self.margin_used) > 1) or (BuyingPowerModelExtensions.get_maintenance_margin(self.ada_usdt.buying_power_model, self.ada_usdt) != self.margin_used):
raise Exception(f"Unexpected margin used {self.margin_used}")
if abs(self.adaUsdtHoldings.TotalSaleVolume - self.holdingsValueUsdt) > 1:
raise Exception(f"Unexpected TotalSaleVolume {self.adaUsdtHoldings.TotalSaleVolume}")
if abs(self.adaUsdtHoldings.AbsoluteHoldingsCost - self.holdingsValueUsdt) > 1:
raise Exception(f"Unexpected holdings cost {self.adaUsdtHoldings.HoldingsCost}")
if (abs(self.adaUsdtHoldings.AbsoluteHoldingsCost * 0.05 - self.marginUsed) > 1) or (BuyingPowerModelExtensions.GetMaintenanceMargin(self.adaUsdt.BuyingPowerModel, self.adaUsdt) != self.marginUsed):
raise Exception(f"Unexpected margin used {self.marginUsed}")
# position just opened should be just spread here
self.profit = self.Portfolio.TotalUnrealizedProfit
if (5 - abs(self.profit)) < 0:
raise Exception(f"Unexpected TotalUnrealizedProfit {self.Portfolio.TotalUnrealizedProfit}")
self.profit = self.portfolio.total_unrealized_profit
if (5 - abs(self.profit)) < 0:
raise Exception(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")
if (self.portfolio.total_profit != 0):
raise Exception(f"Unexpected TotalProfit {self.portfolio.total_profit}")
if (self.Portfolio.TotalProfit != 0):
raise Exception(f"Unexpected TotalProfit {self.Portfolio.TotalProfit}")
else:
# let's revert our position and double
if self.Time.hour > 10 and self.Transactions.OrdersCount == 2:
self.Sell(self.adaUsdt.Symbol, 3000)
if self.time.hour > 10 and self.transactions.orders_count == 2:
self.sell(self.ada_usdt.symbol, 3000)
self.adaUsdtHoldings = self.adaUsdt.Holdings
self.ada_usdt_holdings = self.ada_usdt.holdings
# USDT/BUSD futures value is based on it's price
self.holdingsValueUsdt = self.adaUsdt.Price * self.adaUsdt.SymbolProperties.ContractMultiplier * 2000
self.holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 2000
if abs(self.adaUsdtHoldings.AbsoluteHoldingsCost - self.holdingsValueUsdt) > 1:
raise Exception(f"Unexpected holdings cost {self.adaUsdtHoldings.HoldingsCost}")
if abs(self.ada_usdt_holdings.absolute_holdings_cost - self.holdings_value_usdt) > 1:
raise Exception(f"Unexpected holdings cost {self.ada_usdt_holdings.holdings_cost}")
# position just opened should be just spread here
self.profit = self.Portfolio.TotalUnrealizedProfit
self.profit = self.portfolio.total_unrealized_profit
if (5 - abs(self.profit)) < 0:
raise Exception(f"Unexpected TotalUnrealizedProfit {self.Portfolio.TotalUnrealizedProfit}")
# we barely did any difference on the previous trade
if (5 - abs(self.Portfolio.TotalProfit)) < 0:
raise Exception(f"Unexpected TotalProfit {self.Portfolio.TotalProfit}")
if self.Time.hour >= 22 and self.Transactions.OrdersCount == 3:
self.Liquidate()
def OnEndOfAlgorithm(self):
if self.interestPerSymbol[self.adaUsdt.Symbol] != 1:
raise Exception(f"Unexpected interest rate count {self.interestPerSymbol[self.adaUsdt.Symbol]}")
raise Exception(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")
def OnOrderEvent(self, orderEvent):
self.Debug("{0} {1}".format(self.Time, orderEvent))
# we barely did any difference on the previous trade
if (5 - abs(self.portfolio.total_profit)) < 0:
raise Exception(f"Unexpected TotalProfit {self.portfolio.total_profit}")
if self.time.hour >= 22 and self.transactions.orders_count == 3:
self.liquidate()
def on_end_of_algorithm(self):
if self.interest_per_symbol[self.ada_usdt.symbol] != 1:
raise Exception(f"Unexpected interest rate count {self.interest_per_symbol[self.ada_usdt.symbol]}")
def on_order_event(self, order_event):
self.debug("{0} {1}".format(self.time, order_event))
@@ -240,7 +240,6 @@
<None Include="StandardDeviationExecutionModelRegressionAlgorithm.py" />
<None Include="TimeInForceAlgorithm.py" />
<None Include="TrailingStopRiskFrameworkRegressionAlgorithm.py" />
<None Include="UncorrelatedUniverseSelectionFrameworkAlgorithm.py" />
<None Include="UniverseSelectionRegressionAlgorithm.py" />
<None Include="UpdateOrderRegressionAlgorithm.py" />
<None Include="UserDefinedUniverseAlgorithm.py" />
@@ -19,98 +19,98 @@ from CustomDataRegressionAlgorithm import Bitcoin
### </summary>
class RegisterIndicatorRegressionAlgorithm(QCAlgorithm):
# Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
def Initialize(self):
self.SetStartDate(2013, 10, 7)
self.SetEndDate(2013, 10, 9)
def initialize(self):
self.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 9)
SP500 = Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME)
self._symbol = _symbol = self.FutureChainProvider.GetFutureContractList(SP500, (self.StartDate + timedelta(days=1)))[0]
self.AddFutureContract(_symbol)
SP500 = Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME)
self._symbol = _symbol = self.future_chain_provider.get_future_contract_list(SP500, (self.start_date + timedelta(days=1)))[0]
self.add_future_contract(_symbol)
# this collection will hold all indicators and at the end of the algorithm we will assert that all of them are ready
self._indicators = []
# this collection will be used to determine if the Selectors were called, we will assert so at the end of algorithm
self._selectorCalled = [ False, False, False, False, False, False ]
self._selector_called = [ False, False, False, False, False, False ]
# First we will test that we can register our custom indicator using a QuoteBar consolidator
indicator = CustomIndicator()
consolidator = self.ResolveConsolidator(_symbol, Resolution.Minute, QuoteBar)
self.RegisterIndicator(_symbol, indicator, consolidator)
consolidator = self.resolve_consolidator(_symbol, Resolution.MINUTE, QuoteBar)
self.register_indicator(_symbol, indicator, consolidator)
self._indicators.append(indicator)
indicator2 = CustomIndicator()
# We use the TimeDelta overload to fetch the consolidator
consolidator = self.ResolveConsolidator(_symbol, timedelta(minutes=1), QuoteBar)
consolidator = self.resolve_consolidator(_symbol, timedelta(minutes=1), QuoteBar)
# We specify a custom selector to be used
self.RegisterIndicator(_symbol, indicator2, consolidator, lambda bar: self.SetSelectorCalled(0) and bar)
self.register_indicator(_symbol, indicator2, consolidator, lambda bar: self.set_selector_called(0) and bar)
self._indicators.append(indicator2)
# We use a IndicatorBase<IndicatorDataPoint> with QuoteBar data and a custom selector
indicator3 = SimpleMovingAverage(10)
consolidator = self.ResolveConsolidator(_symbol, timedelta(minutes=1), QuoteBar)
self.RegisterIndicator(_symbol, indicator3, consolidator, lambda bar: self.SetSelectorCalled(1) and (bar.Ask.High - bar.Bid.Low))
consolidator = self.resolve_consolidator(_symbol, timedelta(minutes=1), QuoteBar)
self.register_indicator(_symbol, indicator3, consolidator, lambda bar: self.set_selector_called(1) and (bar.ask.high - bar.bid.low))
self._indicators.append(indicator3)
# We test default consolidator resolution works correctly
movingAverage = SimpleMovingAverage(10)
# Using Resolution, specifying custom selector and explicitly using TradeBar.Volume
self.RegisterIndicator(_symbol, movingAverage, Resolution.Minute, lambda bar: self.SetSelectorCalled(2) and bar.Volume)
self._indicators.append(movingAverage)
moving_average = SimpleMovingAverage(10)
# Using Resolution, specifying custom selector and explicitly using TradeBar.volume
self.register_indicator(_symbol, moving_average, Resolution.MINUTE, lambda bar: self.set_selector_called(2) and bar.volume)
self._indicators.append(moving_average)
movingAverage2 = SimpleMovingAverage(10)
moving_average2 = SimpleMovingAverage(10)
# Using Resolution
self.RegisterIndicator(_symbol, movingAverage2, Resolution.Minute)
self._indicators.append(movingAverage2)
self.register_indicator(_symbol, moving_average2, Resolution.MINUTE)
self._indicators.append(moving_average2)
movingAverage3 = SimpleMovingAverage(10)
moving_average3 = SimpleMovingAverage(10)
# Using timedelta
self.RegisterIndicator(_symbol, movingAverage3, timedelta(minutes=1))
self._indicators.append(movingAverage3)
self.register_indicator(_symbol, moving_average3, timedelta(minutes=1))
self._indicators.append(moving_average3)
movingAverage4 = SimpleMovingAverage(10)
# Using timeDelta, specifying custom selector and explicitly using TradeBar.Volume
self.RegisterIndicator(_symbol, movingAverage4, timedelta(minutes=1), lambda bar: self.SetSelectorCalled(3) and bar.Volume)
self._indicators.append(movingAverage4)
moving_average4 = SimpleMovingAverage(10)
# Using time_delta, specifying custom selector and explicitly using TradeBar.volume
self.register_indicator(_symbol, moving_average4, timedelta(minutes=1), lambda bar: self.set_selector_called(3) and bar.volume)
self._indicators.append(moving_average4)
# Test custom data is able to register correctly and indicators updated
symbolCustom = self.AddData(Bitcoin, "BTC", Resolution.Minute).Symbol
symbol_custom = self.add_data(Bitcoin, "BTC", Resolution.MINUTE).symbol
smaCustomData = SimpleMovingAverage(1)
self.RegisterIndicator(symbolCustom, smaCustomData, timedelta(minutes=1), lambda bar: self.SetSelectorCalled(4) and bar.Volume)
self._indicators.append(smaCustomData)
sma_custom_data = SimpleMovingAverage(1)
self.register_indicator(symbol_custom, sma_custom_data, timedelta(minutes=1), lambda bar: self.set_selector_called(4) and bar.volume)
self._indicators.append(sma_custom_data)
smaCustomData2 = SimpleMovingAverage(1)
self.RegisterIndicator(symbolCustom, smaCustomData2, Resolution.Minute)
self._indicators.append(smaCustomData2)
sma_custom_data2 = SimpleMovingAverage(1)
self.register_indicator(symbol_custom, sma_custom_data2, Resolution.MINUTE)
self._indicators.append(sma_custom_data2)
smaCustomData3 = SimpleMovingAverage(1)
consolidator = self.ResolveConsolidator(symbolCustom, timedelta(minutes=1))
self.RegisterIndicator(symbolCustom, smaCustomData3, consolidator, lambda bar: self.SetSelectorCalled(5) and bar.Volume)
self._indicators.append(smaCustomData3)
sma_custom_data3 = SimpleMovingAverage(1)
consolidator = self.resolve_consolidator(symbol_custom, timedelta(minutes=1))
self.register_indicator(symbol_custom, sma_custom_data3, consolidator, lambda bar: self.set_selector_called(5) and bar.volume)
self._indicators.append(sma_custom_data3)
def SetSelectorCalled(self, position):
self._selectorCalled[position] = True
def set_selector_called(self, position):
self._selector_called[position] = True
return True
# OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
def OnData(self, data):
if not self.Portfolio.Invested:
self.SetHoldings(self._symbol, 0.5)
def on_data(self, data):
if not self.portfolio.invested:
self.set_holdings(self._symbol, 0.5)
def OnEndOfAlgorithm(self):
if any(not wasCalled for wasCalled in self._selectorCalled):
def on_end_of_algorithm(self):
if any(not was_called for was_called in self._selector_called):
raise ValueError("All selectors should of been called")
if any(not indicator.IsReady for indicator in self._indicators):
if any(not indicator.is_ready for indicator in self._indicators):
raise ValueError("All indicators should be ready")
self.Log(f'Total of {len(self._indicators)} are ready')
self.log(f'Total of {len(self._indicators)} are ready')
class CustomIndicator(PythonIndicator):
def __init__(self):
super().__init__()
self.Name = "Jose"
self.Value = 0
self.name = "Jose"
self.value = 0
def Update(self, input):
self.Value = input.Ask.High
def update(self, input):
self.value = input.ask.high
return True
@@ -1,60 +0,0 @@
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from AlgorithmImports import *
from Selection.UncorrelatedUniverseSelectionModel import UncorrelatedUniverseSelectionModel
class UncorrelatedUniverseSelectionFrameworkAlgorithm(QCAlgorithm):
def Initialize(self):
self.UniverseSettings.Resolution = Resolution.Daily
self.SetStartDate(2018,1,1) # Set Start Date
self.SetCash(1000000) # Set Strategy Cash
benchmark = Symbol.Create("SPY", SecurityType.Equity, Market.USA)
self.SetUniverseSelection(UncorrelatedUniverseSelectionModel(benchmark))
self.SetAlpha(UncorrelatedUniverseSelectionAlphaModel())
self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())
self.SetExecution(ImmediateExecutionModel())
class UncorrelatedUniverseSelectionAlphaModel(AlphaModel):
'''Uses ranking of intraday percentage difference between open price and close price to create magnitude and direction prediction for insights'''
def __init__(self, numberOfStocks = 10, predictionInterval = timedelta(1)):
self.predictionInterval = predictionInterval
self.numberOfStocks = numberOfStocks
def Update(self, algorithm, data):
symbolsRet = dict()
for kvp in algorithm.ActiveSecurities:
security = kvp.Value
if security.HasData:
open = security.Open
if open != 0:
symbolsRet[security.Symbol] = security.Close / open - 1
# Rank on the absolute value of price change
symbolsRet = dict(sorted(symbolsRet.items(), key=lambda kvp: abs(kvp[1]),reverse=True)[:self.numberOfStocks])
insights = []
for symbol, price_change in symbolsRet.items():
# Emit "up" insight if the price change is positive and "down" otherwise
direction = InsightDirection.Up if price_change > 0 else InsightDirection.Down
insights.append(Insight.Price(symbol, self.predictionInterval, direction, abs(price_change), None))
return insights