instruction
stringclasses 1
value | input
stringlengths 81
758
| output
stringlengths 420
23.9k
|
|---|---|---|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This regression algorithm is for testing a custom Python filter for options
that returns a OptionFilterUniverse.
|
```python
from AlgorithmImports import *
class FilterUniverseRegressionAlgorithm(QCAlgorithm):
underlying_ticker = "GOOG"
def initialize(self):
self.set_start_date(2015, 12, 24)
self.set_end_date(2015, 12, 28)
self.set_cash(100000)
equity = self.add_equity(self.underlying_ticker)
option = self.add_option(self.underlying_ticker)
self.option_symbol = option.symbol
# Set our custom universe filter
option.set_filter(self.filter_function)
# use the underlying equity as the benchmark
self.set_benchmark(equity.symbol)
def filter_function(self, universe):
universe = universe.weeklys_only().strikes(-5, +5).calls_only().expiration(0, 1)
return universe
def on_data(self,slice):
if self.portfolio.invested: return
for kvp in slice.option_chains:
if kvp.key != self.option_symbol: continue
chain = kvp.value
contracts = [option for option in sorted(chain, key = lambda x:x.strike, reverse = True)]
if contracts:
self.market_order(contracts[0].symbol, 1)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm to validate SecurityCache.Session functionality.
Verifies that daily session bars (Open, High, Low, Close, Volume) are correctly
|
```python
from AlgorithmImports import *
class SecuritySessionRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.add_security_initializer(self.initialize_session_tracking)
self.initialize_security()
# Check initial session values
session = self.security.session
if session is None:
raise RegressionTestException("Security.Session is none")
if (session.open != 0
or session.high != 0
or session.low != 0
or session.close != 0
or session.volume != 0
or session.open_interest != 0):
raise RegressionTestException("Session should start with all zero values.")
self.security_was_removed = False
self.open = self.close = self.high = self.volume = 0
self.low = float('inf')
self.current_date = self.start_date
self.previous_session_bar = None
self.schedule.on(
self.date_rules.every_day(),
self.time_rules.after_market_close(self.security.symbol, 1),
self.validate_session_bars
)
def initialize_security(self):
self.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 11)
self.security = self.add_equity("SPY", Resolution.HOUR)
def initialize_session_tracking(self, security):
# activate session tracking
security.session.size = 3
def _are_equal(self, value1, value2):
tolerance = 1e-10
return abs(value1 - value2) <= tolerance
def validate_session_bars(self):
session = self.security.session
# At this point the data was consolidated (market close)
# Save previous session bar
self.previous_session_bar = {
'date': self.current_date,
'open': self.open,
'high': self.high,
'low': self.low,
'close': self.close,
'volume': self.volume
}
if self.security_was_removed:
self.previous_session_bar = None
self.security_was_removed = False
return
# Check current session values
if (not self._are_equal(session.open, self.open)
or not self._are_equal(session.high, self.high)
or not self._are_equal(session.low, self.low)
or not self._are_equal(session.close, self.close)
or not self._are_equal(session.volume, self.volume)):
raise RegressionTestException("Mismatch in current session bar (OHLCV)")
def is_within_market_hours(self, current_date_time):
market_open = self.security.exchange.hours.get_next_market_open(current_date_time.date(), False).time()
market_close = self.security.exchange.hours.get_next_market_close(current_date_time.date(), False).time()
current_time = current_date_time.time()
return market_open < current_time <= market_close
def on_data(self, data):
if not self.is_within_market_hours(data.time):
# Skip data outside market hours
return
# Accumulate data within regular market hours
# to later compare against the Session values
self.accumulate_session_data(data)
def accumulate_session_data(self, data):
symbol = self.security.symbol
if self.current_date.date() == data.time.date():
# Same trading day
if self.open == 0:
self.open = data[symbol].open
self.high = max(self.high, data[symbol].high)
self.low = min(self.low, data[symbol].low)
self.close = data[symbol].close
self.volume += data[symbol].volume
else:
# New trading day
if self.previous_session_bar is not None:
session = self.security.session
if (self.previous_session_bar['open'] != session[1].open
or self.previous_session_bar['high'] != session[1].high
or self.previous_session_bar['low'] != session[1].low
or self.previous_session_bar['close'] != session[1].close
or self.previous_session_bar['volume'] != session[1].volume):
raise RegressionTestException("Mismatch in previous session bar (OHLCV)")
# This is the first data point of the new session
self.open = data[symbol].open
self.close = data[symbol].close
self.high = data[symbol].high
self.low = data[symbol].low
self.volume = data[symbol].volume
self.current_date = data.time
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting that tick history request includes both trade and quote data
|
```python
from AlgorithmImports import *
class HistoryTickRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 12)
self.set_end_date(2013, 10, 13)
self._symbol = self.add_equity("SPY", Resolution.TICK).symbol
trades_count = 0
quotes_count = 0
for point in self.history[Tick](self._symbol, timedelta(days=1), Resolution.TICK):
if point.tick_type == TickType.TRADE:
trades_count += 1
elif point.tick_type == TickType.QUOTE:
quotes_count += 1
if trades_count > 0 and quotes_count > 0:
# We already found at least one tick of each type, we can exit the loop
break
if trades_count == 0 or quotes_count == 0:
raise AssertionError("Expected to find at least one tick of each type (quote and trade)")
self.quit()
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm to assert the behavior of <see cref="EmaCrossAlphaModel"/>.
|
```python
from AlgorithmImports import *
from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
from Alphas.EmaCrossAlphaModel import EmaCrossAlphaModel
class EmaCrossAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):
def initialize(self):
super().initialize()
self.set_alpha(EmaCrossAlphaModel())
def on_end_of_algorithm(self):
pass
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Demonstration of how to define a universe using the fundamental data
|
```python
from AlgorithmImports import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel
class FundamentalUniverseSelectionRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2014, 3, 26)
self.set_end_date(2014, 4, 7)
self.universe_settings.resolution = Resolution.DAILY
self.add_equity("SPY")
self.add_equity("AAPL")
self.set_universe_selection(FundamentalUniverseSelectionModelTest())
self.changes = None
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.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.added_securities:
self.set_holdings(security.symbol, 0.02)
self.changes = None
# this event fires whenever we have changes to our universe
def on_securities_changed(self, changes):
self.changes = changes
class FundamentalUniverseSelectionModelTest(FundamentalUniverseSelectionModel):
def select(self, algorithm, fundamental):
# sort descending by daily dollar volume
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
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 sorted_by_pe_ratio[:2] ]
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Demonstration of how to define a universe using the fundamental data
|
```python
from AlgorithmImports import *
class FundamentalUniverseSelectionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2014, 3, 25)
self.set_end_date(2014, 4, 7)
self.universe_settings.resolution = Resolution.DAILY
self.add_equity("SPY")
self.add_equity("AAPL")
self.set_universe_selection(FundamentalUniverseSelectionModel(self.select))
self.changes = None
self.number_of_symbols_fundamental = 10
# return a list of three fixed symbol objects
def selection_function(self, fundamental):
# sort descending by daily dollar volume
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
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 sorted_by_pe_ratio[:self.number_of_symbols_fundamental] ]
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.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.added_securities:
self.set_holdings(security.symbol, 0.02)
self.changes = None
# this event fires whenever we have changes to our universe
def on_securities_changed(self, changes):
self.changes = changes
def select(self, fundamental):
# sort descending by daily dollar volume
sorted_by_dollar_volume = sorted([x for x in fundamental if x.has_fundamental_data and x.price > 1],
key=lambda x: x.dollar_volume, reverse=True)
# sort descending by P/E ratio
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 sorted_by_pe_ratio[:2] ]
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Test algorithm using 'QCAlgorithm.add_risk_management(IRiskManagementModel)'
|
```python
from AlgorithmImports import *
class AddRiskManagementAlgorithm(QCAlgorithm):
'''Basic template framework algorithm uses framework components to define the algorithm.'''
def initialize(self):
''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.universe_settings.resolution = Resolution.MINUTE
self.set_start_date(2013,10,7) #Set Start Date
self.set_end_date(2013,10,11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]
# set algorithm framework models
self.set_universe_selection(ManualUniverseSelectionModel(symbols))
self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
self.set_execution(ImmediateExecutionModel())
# Both setting methods should work
risk_model = CompositeRiskManagementModel(MaximumDrawdownPercentPortfolio(0.02))
risk_model.add_risk_management(MaximumUnrealizedProfitPercentPerSecurity(0.01))
self.set_risk_management(MaximumDrawdownPercentPortfolio(0.02))
self.add_risk_management(MaximumUnrealizedProfitPercentPerSecurity(0.01))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Basic Continuous Futures Template Algorithm with extended market hours
|
```python
from AlgorithmImports import *
class BasicTemplateContinuousFutureWithExtendedMarketAlgorithm(QCAlgorithm):
'''Basic template algorithm simply initializes the date range and cash'''
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013, 7, 1)
self.set_end_date(2014, 1, 1)
self._continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI,
data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO,
data_mapping_mode = DataMappingMode.LAST_TRADING_DAY,
contract_depth_offset = 0,
extended_market_hours = True)
self._fast = self.sma(self._continuous_contract.symbol, 4, Resolution.DAILY)
self._slow = self.sma(self._continuous_contract.symbol, 10, Resolution.DAILY)
self._current_contract = None
def on_data(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''
for changed_event in data.symbol_changed_events.values():
if changed_event.symbol == self._continuous_contract.symbol:
self.log(f"SymbolChanged event: {changed_event}")
if not self.is_market_open(self._continuous_contract.symbol):
return
if not self.portfolio.invested:
if self._fast.current.value > self._slow.current.value:
self._current_contract = self.securities[self._continuous_contract.mapped]
self.buy(self._current_contract.symbol, 1)
elif self._fast.current.value < self._slow.current.value:
self.liquidate()
if self._current_contract is not None and self._current_contract.symbol != self._continuous_contract.mapped:
self.log(f"{Time} - rolling position from {self._current_contract.symbol} to {self._continuous_contract.mapped}")
current_position_size = self._current_contract.holdings.quantity
self.liquidate(self._current_contract.symbol)
self.buy(self._continuous_contract.mapped, current_position_size)
self._current_contract = self.securities[self._continuous_contract.mapped]
def on_order_event(self, order_event):
self.debug("Purchased Stock: {0}".format(order_event.symbol))
def on_securities_changed(self, changes):
self.debug(f"{self.time}-{changes}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Asserts that algorithms can be universe-only, that is, universe selection is performed even if the ETF security is not explicitly added.
Reproduces https://github.com/QuantConnect/Lean/issues/7473
|
```python
from AlgorithmImports import *
class UniverseOnlyRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2020, 12, 1)
self.set_end_date(2020, 12, 12)
self.set_cash(100000)
self.universe_settings.resolution = Resolution.DAILY
# Add universe without a security added
self.add_universe(self.universe.etf("GDVD", self.universe_settings, self.filter_universe))
self.selection_done = False
def filter_universe(self, constituents: List[ETFConstituentData]) -> List[Symbol]:
self.selection_done = True
return [x.symbol for x in constituents]
def on_end_of_algorithm(self):
if not self.selection_done:
raise AssertionError("Universe selection was not performed")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This example demonstrates how to use the OptionUniverseSelectionModel to select options contracts based on specified conditions.
The model is updated daily and selects different options based on the current date.
The algorithm ensures that only valid option contracts are selected for the universe.
|
```python
from AlgorithmImports import *
class AddOptionUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2014, 6, 5)
self.set_end_date(2014, 6, 6)
self.option_count = 0
self.universe_settings.resolution = Resolution.MINUTE
self.set_universe_selection(OptionUniverseSelectionModel(
timedelta(days=1),
self.select_option_chain_symbols
))
def select_option_chain_symbols(self, utc_time):
new_york_time = Extensions.convert_from_utc(utc_time, TimeZones.NEW_YORK)
if new_york_time.date() < datetime(2014, 6, 6).date():
return [ Symbol.create("TWX", SecurityType.OPTION, Market.USA) ]
if new_york_time.date() >= datetime(2014, 6, 6).date():
return [ Symbol.create("AAPL", SecurityType.OPTION, Market.USA) ]
def on_securities_changed(self, changes):
if len(changes.added_securities) > 0:
for security in changes.added_securities:
symbol = security.symbol.underlying if security.symbol.underlying else security.Symbol
if symbol.value != "AAPL" and symbol.value != "TWX":
raise RegressionTestException(f"Unexpected security {security.Symbol}")
if security.symbol.security_type == SecurityType.OPTION:
self.option_count += 1
def on_end_of_algorithm(self):
if len(self.active_securities) == 0:
raise RegressionTestException("No active securities found. Expected at least one active security")
if self.option_count == 0:
raise RegressionTestException("The option count should be greater than 0")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Abstract regression framework algorithm for multiple framework regression tests
|
```python
from AlgorithmImports import *
class BaseFrameworkRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2014, 6, 1)
self.set_end_date(2014, 6, 30)
self.universe_settings.resolution = Resolution.HOUR
self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW
symbols = [Symbol.create(ticker, SecurityType.EQUITY, Market.USA)
for ticker in ["AAPL", "AIG", "BAC", "SPY"]]
# Manually add AAPL and AIG when the algorithm starts
self.set_universe_selection(ManualUniverseSelectionModel(symbols[:2]))
# At midnight, add all securities every day except on the last data
# With this procedure, the Alpha Model will experience multiple universe changes
self.add_universe_selection(ScheduledUniverseSelectionModel(
self.date_rules.every_day(), self.time_rules.midnight,
lambda dt: symbols if dt < self.end_date - timedelta(1) else []))
self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(31), 0.025, None))
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
self.set_execution(ImmediateExecutionModel())
self.set_risk_management(NullRiskManagementModel())
def on_end_of_algorithm(self):
# The base implementation checks for active insights
insights_count = len(self.insights.get_insights(lambda insight: insight.is_active(self.utc_time)))
if insights_count != 0:
raise AssertionError(f"The number of active insights should be 0. Actual: {insights_count}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Shows how to set a custom benchmark for you algorithms
|
```python
from AlgorithmImports import *
class CustomBenchmarkAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013,10,7) #Set Start Date
self.set_end_date(2013,10,11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.add_equity("SPY", Resolution.SECOND)
# Disabling the benchmark / setting to a fixed value
# self.set_benchmark(lambda x: 0)
# Set the benchmark to AAPL US Equity
self.set_benchmark(Symbol.create("AAPL", SecurityType.EQUITY, Market.USA))
def on_data(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
if not self.portfolio.invested:
self.set_holdings("SPY", 1)
self.debug("Purchased Stock")
tuple_result = SymbolCache.try_get_symbol("AAPL", None)
if tuple_result[0]:
raise AssertionError("Benchmark Symbol is not expected to be added to the Symbol cache")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting the behavior of specifying a null position group allowing us to fill orders which would be invalid if not
|
```python
from AlgorithmImports import *
class NullMarginMultipleOrdersRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2015, 12, 24)
self.set_end_date(2015, 12, 24)
self.set_cash(10000)
# override security position group model
self.portfolio.set_positions(SecurityPositionGroupModel.NULL)
# override margin requirements
self.set_security_initializer(lambda security: security.set_buying_power_model(ConstantBuyingPowerModel(1)))
equity = self.add_equity("GOOG", leverage=4, fill_forward=True)
option = self.add_option(equity.symbol, fill_forward=True)
self._option_symbol = option.symbol
option.set_filter(lambda u: u.strikes(-2, +2).expiration(0, 180))
def on_data(self, data: Slice):
if not self.portfolio.invested:
if self.is_market_open(self._option_symbol):
chain = data.option_chains.get(self._option_symbol)
if chain:
call_contracts = [contract for contract in chain if contract.right == OptionRight.CALL]
call_contracts.sort(key=lambda x: (x.expiry, 1/ x.strike), reverse=True)
option_contract = call_contracts[0]
self.market_order(option_contract.symbol.underlying, 1000)
self.market_order(option_contract.symbol, -10)
if self.portfolio.total_margin_used != 1010:
raise ValueError(f"Unexpected margin used {self.portfolio.total_margin_used}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Demonstration of using custom buying power model in backtesting.
QuantConnect allows you to model all orders as deeply and accurately as you need.
|
```python
from AlgorithmImports import *
class CustomBuyingPowerModelAlgorithm(QCAlgorithm):
'''Demonstration of using custom buying power model in backtesting.
QuantConnect allows you to model all orders as deeply and accurately as you need.'''
def initialize(self):
self.set_start_date(2013,10,1) # Set Start Date
self.set_end_date(2013,10,31) # Set End Date
security = self.add_equity("SPY", Resolution.HOUR)
self.spy = security.symbol
# set the buying power model
security.set_buying_power_model(CustomBuyingPowerModel())
def on_data(self, slice):
if self.portfolio.invested:
return
quantity = self.calculate_order_quantity(self.spy, 1)
if quantity % 100 != 0:
raise AssertionError(f'CustomBuyingPowerModel only allow quantity that is multiple of 100 and {quantity} was found')
# We normally get insufficient buying power model, but the
# CustomBuyingPowerModel always says that there is sufficient buying power for the orders
self.market_order(self.spy, quantity * 10)
class CustomBuyingPowerModel(BuyingPowerModel):
def get_maximum_order_quantity_for_target_buying_power(self, parameters):
quantity = super().get_maximum_order_quantity_for_target_buying_power(parameters).quantity
quantity = np.floor(quantity / 100) * 100
return GetMaximumOrderQuantityResult(quantity)
def has_sufficient_buying_power_for_order(self, parameters):
return HasSufficientBuyingPowerForOrderResult(True)
# Let's always return 0 as the maintenance margin so we avoid margin call orders
def get_maintenance_margin(self, parameters):
return MaintenanceMargin(0)
# Override this as well because the base implementation calls GetMaintenanceMargin (overridden)
# because in C# it wouldn't resolve the overridden Python method
def get_reserved_buying_power_for_position(self, parameters):
return parameters.result_in_account_currency(0)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Demonstration algorithm for the Warm Up feature with basic indicators.
|
```python
from AlgorithmImports import *
class WarmupAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013,10,8) #Set Start Date
self.set_end_date(2013,10,11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.add_equity("SPY", Resolution.SECOND)
fast_period = 60
slow_period = 3600
self.fast = self.ema("SPY", fast_period)
self.slow = self.ema("SPY", slow_period)
self.set_warmup(slow_period)
self.first = True
def on_data(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
if self.first and not self.is_warming_up:
self.first = False
self.log("Fast: {0}".format(self.fast.samples))
self.log("Slow: {0}".format(self.slow.samples))
if self.fast.current.value > self.slow.current.value:
self.set_holdings("SPY", 1)
else:
self.set_holdings("SPY", -1)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This regression test tests for the loading of futures options contracts with a contract month of 2020-03 can live
and be loaded from the same ZIP file that the 2020-04 contract month Future Option contract lives in.
|
```python
from AlgorithmImports import *
class FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.expected_symbols = {
self._create_option(datetime(2020, 3, 26), OptionRight.CALL, 1650.0): False,
self._create_option(datetime(2020, 3, 26), OptionRight.PUT, 1540.0): False,
self._create_option(datetime(2020, 2, 25), OptionRight.CALL, 1600.0): False,
self._create_option(datetime(2020, 2, 25), OptionRight.PUT, 1545.0): False
}
# Required for FOPs to use extended hours, until GH #6491 is addressed
self.universe_settings.extended_market_hours = True
self.set_start_date(2020, 1, 4)
self.set_end_date(2020, 1, 6)
gold_futures = self.add_future("GC", Resolution.MINUTE, Market.COMEX, extended_market_hours=True)
gold_futures.SetFilter(0, 365)
self.add_future_option(gold_futures.Symbol)
def on_data(self, data: Slice):
for symbol in data.quote_bars.keys():
# Check that we are in regular hours, we can place a market order (on extended hours, limit orders should be used)
if symbol in self.expected_symbols and self.is_in_regular_hours(symbol):
invested = self.expected_symbols[symbol]
if not invested:
self.market_order(symbol, 1)
self.expected_symbols[symbol] = True
def on_end_of_algorithm(self):
not_encountered = [str(k) for k,v in self.expected_symbols.items() if not v]
if any(not_encountered):
raise AssertionError(f"Expected all Symbols encountered and invested in, but the following were not found: {', '.join(not_encountered)}")
if not self.portfolio.invested:
raise AssertionError("Expected holdings at the end of algorithm, but none were found.")
def is_in_regular_hours(self, symbol):
return self.securities[symbol].exchange.exchange_open
def _create_option(self, expiry: datetime, option_right: OptionRight, strike_price: float) -> Symbol:
return Symbol.create_option(
Symbol.create_future("GC", Market.COMEX, datetime(2020, 4, 28)),
Market.COMEX,
OptionStyle.AMERICAN,
option_right,
strike_price,
expiry
)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This example demonstrates how to use the FutureUniverseSelectionModel to select futures contracts for a given underlying asset.
The model is set to update daily, and the algorithm ensures that the selected contracts meet specific criteria.
This also includes a check to ensure that only future contracts are added to the algorithm's universe.
|
```python
from AlgorithmImports import *
class AddFutureUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 8)
self.set_end_date(2013, 10, 10)
self.set_universe_selection(FutureUniverseSelectionModel(
timedelta(days=1),
lambda time: [ Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME) ]
))
def on_securities_changed(self, changes):
if len(changes.added_securities) > 0:
for security in changes.added_securities:
if security.symbol.security_type != SecurityType.FUTURE:
raise RegressionTestException(f"Expected future security, but found '{security.symbol.security_type}'")
if security.symbol.id.symbol != "ES":
raise RegressionTestException(f"Expected future symbol 'ES', but found '{security.symbol.id.symbol}'")
def on_end_of_algorithm(self):
if len(self.active_securities) == 0:
raise RegressionTestException("No active securities found. Expected at least one active security")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This regression algorithm asserts that futures have data at extended market hours when this is enabled.
|
```python
from AlgorithmImports import *
class FutureContractsExtendedMarketHoursRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 6)
self.set_end_date(2013, 10, 11)
es_future_symbol = Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2013, 12, 20))
self._es = self.add_future_contract(es_future_symbol, Resolution.HOUR, fill_forward=True, extended_market_hours=True)
gc_future_symbol = Symbol.create_future(Futures.Metals.GOLD, Market.COMEX, datetime(2013, 10, 29))
self._gc = self.add_future_contract(gc_future_symbol, Resolution.HOUR, fill_forward=True, extended_market_hours=False)
self._es_ran_on_regular_hours = False
self._es_ran_on_extended_hours = False
self._gc_ran_on_regular_hours = False
self._gc_ran_on_extended_hours = False
def on_data(self, slice):
slice_symbols = set(slice.keys())
slice_symbols.update(slice.bars.keys())
slice_symbols.update(slice.ticks.keys())
slice_symbols.update(slice.quote_bars.keys())
slice_symbols.update([x.canonical for x in slice_symbols])
es_is_in_regular_hours = self._es.exchange.hours.is_open(self.time, False)
es_is_in_extended_hours = not es_is_in_regular_hours and self._es.exchange.hours.is_open(self.time, True)
slice_has_es_data = self._es.symbol in slice_symbols
self._es_ran_on_regular_hours |= es_is_in_regular_hours and slice_has_es_data
self._es_ran_on_extended_hours |= es_is_in_extended_hours and slice_has_es_data
gc_is_in_regular_hours = self._gc.exchange.hours.is_open(self.time, False)
gc_is_in_extended_hours = not gc_is_in_regular_hours and self._gc.exchange.hours.is_open(self.time, True)
slice_has_gc_data = self._gc.symbol in slice_symbols
self._gc_ran_on_regular_hours |= gc_is_in_regular_hours and slice_has_gc_data
self._gc_ran_on_extended_hours |= gc_is_in_extended_hours and slice_has_gc_data
def on_end_of_algorithm(self):
if not self._es_ran_on_regular_hours:
raise AssertionError(f"Algorithm should have run on regular hours for {self._es.symbol} future, which enabled extended market hours")
if not self._es_ran_on_extended_hours:
raise AssertionError(f"Algorithm should have run on extended hours for {self._es.symbol} future, which enabled extended market hours")
if not self._gc_ran_on_regular_hours:
raise AssertionError(f"Algorithm should have run on regular hours for {self._gc.symbol} future, which did not enable extended market hours")
if self._gc_ran_on_extended_hours:
raise AssertionError(f"Algorithm should have not run on extended hours for {self._gc.symbol} future, which did not enable extended market hours")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting 'OnWarmupFinished' is being called
|
```python
from AlgorithmImports import *
class OnWarmupFinishedRegressionAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013,10, 8) #Set Start Date
self.set_end_date(2013,10,11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
self.add_equity("SPY", Resolution.MINUTE)
self.set_warmup(timedelta(days = 1))
self._on_warmup_finished = 0
def on_warmup_finished(self):
self._on_warmup_finished += 1
def on_end_of_algorithm(self):
if self._on_warmup_finished != 1:
raise AssertionError(f"Unexpected OnWarmupFinished call count {self._on_warmup_finished}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Example algorithm to demostrate the event handlers of Brokerage activities
|
```python
from AlgorithmImports import *
class BrokerageActivityEventHandlingAlgorithm(QCAlgorithm):
### <summary>
### 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.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 11)
self.set_cash(100000)
self.add_equity("SPY", Resolution.MINUTE)
### <summary>
### on_data 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 on_data(self, data):
if not self.portfolio.invested:
self.set_holdings("SPY", 1)
### <summary>
### Brokerage message event handler. This method is called for all types of brokerage messages.
### </summary>
def on_brokerage_message(self, message_event):
self.debug(f"Brokerage meesage received - {message_event.to_string()}")
### <summary>
### Brokerage disconnected event handler. This method is called when the brokerage connection is lost.
### </summary>
def on_brokerage_disconnect(self):
self.debug(f"Brokerage disconnected!")
### <summary>
### Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection.
### </summary>
def on_brokerage_reconnect(self):
self.debug(f"Brokerage reconnected!")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This algorithm demonstrates the runtime addition and removal of securities from your algorithm.
With LEAN it is possible to add and remove securities after the initialization.
|
```python
from AlgorithmImports import *
class AddRemoveSecurityRegressionAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013,10,7) #Set Start Date
self.set_end_date(2013,10,11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.add_equity("SPY")
self._last_action = None
def on_data(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
if self._last_action is not None and self._last_action.date() == self.time.date():
return
if not self.portfolio.invested:
self.set_holdings("SPY", .5)
self._last_action = self.time
if self.time.weekday() == 1:
self.add_equity("AIG")
self.add_equity("BAC")
self._last_action = self.time
if self.time.weekday() == 2:
self.set_holdings("AIG", .25)
self.set_holdings("BAC", .25)
self._last_action = self.time
if self.time.weekday() == 3:
self.remove_security("AIG")
self.remove_security("BAC")
self._last_action = self.time
def on_order_event(self, order_event):
if order_event.status == OrderStatus.SUBMITTED:
self.debug("{0}: Submitted: {1}".format(self.time, self.transactions.get_order_by_id(order_event.order_id)))
if order_event.status == OrderStatus.FILLED:
self.debug("{0}: Filled: {1}".format(self.time, self.transactions.get_order_by_id(order_event.order_id)))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Simple indicator demonstration algorithm of MACD
|
```python
from AlgorithmImports import *
class MACDTrendAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2004, 1, 1) #Set Start Date
self.set_end_date(2015, 1, 1) #Set End Date
self.set_cash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.add_equity("SPY", Resolution.DAILY)
# define our daily macd(12,26) with a 9 day signal
self.__macd = self.macd("SPY", 12, 26, 9, MovingAverageType.EXPONENTIAL, Resolution.DAILY)
self.__previous = datetime.min
self.plot_indicator("MACD", True, self.__macd, self.__macd.signal)
self.plot_indicator("SPY", self.__macd.fast, self.__macd.slow)
def on_data(self, data):
'''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
# wait for our macd to fully initialize
if not self.__macd.is_ready: return
# only once per day
if self.__previous.date() == self.time.date(): return
# define a small tolerance on our checks to avoid bouncing
tolerance = 0.0025
holdings = self.portfolio["SPY"].quantity
signal_delta_percent = (self.__macd.current.value - self.__macd.signal.current.value)/self.__macd.fast.current.value
# if our macd is greater than our signal, then let's go long
if holdings <= 0 and signal_delta_percent > tolerance: # 0.01%
# longterm says buy as well
self.set_holdings("SPY", 1.0)
# of our macd is less than our signal, then let's go short
elif holdings >= 0 and signal_delta_percent < -tolerance:
self.liquidate("SPY")
self.__previous = self.time
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Example demonstrating how to access to options history for a given underlying equity security.
|
```python
from AlgorithmImports import *
class BasicTemplateOptionsHistoryAlgorithm(QCAlgorithm):
''' This example demonstrates how to get access to options history for a given underlying equity security.'''
def initialize(self):
# this test opens position in the first day of trading, lives through stock split (7 for 1), and closes adjusted position on the second day
self.set_start_date(2015, 12, 24)
self.set_end_date(2015, 12, 24)
self.set_cash(1000000)
option = self.add_option("GOOG")
# add the initial contract filter
# SetFilter method accepts timedelta objects or integer for days.
# The following statements yield the same filtering criteria
option.set_filter(-2, +2, 0, 180)
# option.set_filter(-2,2, timedelta(0), timedelta(180))
# set the pricing model for Greeks and volatility
# find more pricing models https://www.quantconnect.com/lean/documentation/topic27704.html
option.price_model = OptionPriceModels.crank_nicolson_fd()
# set the warm-up period for the pricing model
self.set_warm_up(TimeSpan.from_days(4))
# set the benchmark to be the initial cash
self.set_benchmark(lambda x: 1000000)
def on_data(self,slice):
if self.is_warming_up: return
if not self.portfolio.invested:
for chain in slice.option_chains:
volatility = self.securities[chain.key.underlying].volatility_model.volatility
for contract in chain.value:
self.log("{0},Bid={1} Ask={2} Last={3} OI={4} sigma={5:.3f} NPV={6:.3f} \
delta={7:.3f} gamma={8:.3f} vega={9:.3f} beta={10:.2f} theta={11:.2f} IV={12:.2f}".format(
contract.symbol.value,
contract.bid_price,
contract.ask_price,
contract.last_price,
contract.open_interest,
volatility,
contract.theoretical_price,
contract.greeks.delta,
contract.greeks.gamma,
contract.greeks.vega,
contract.greeks.rho,
contract.greeks.theta / 365,
contract.implied_volatility))
def on_securities_changed(self, changes):
for change in changes.added_securities:
# only print options price
if change.symbol.value == "GOOG": return
history = self.history(change.symbol, 10, Resolution.MINUTE).sort_index(level='time', ascending=False)[:3]
for index, row in history.iterrows():
self.log("History: " + str(index[3])
+ ": " + index[4].strftime("%m/%d/%Y %I:%M:%S %p")
+ " > " + str(row.close))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm demonstrating the use of custom data sourced from the object store
|
```python
from AlgorithmImports import *
class CustomDataObjectStoreRegressionAlgorithm(QCAlgorithm):
custom_data = "2017-08-18 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-18 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-18 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-18 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-18 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-18 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-18 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-18 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-18 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-18 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-18 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-18 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\n2017-08-18 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\n2017-08-18 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\n2017-08-18 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-18 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-18 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\n2017-08-18 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\n2017-08-18 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\n2017-08-18 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57\n2017-08-19 01:00:00,5771.75,5792.9,5738.6,5760.2,140394424,5894.04\n2017-08-19 02:00:00,5709.35,5729.85,5683.1,5699.1,142041404,5462.45\n2017-08-19 03:00:00,5748.95,5819.4,5739.4,5808.4,124410018,5121.33\n2017-08-19 04:00:00,5820.4,5854.9,5770.25,5850.05,107160887,4560.84\n2017-08-19 05:00:00,5841.9,5863.4,5804.3,5813.6,117541145,4591.91\n2017-08-19 06:00:00,5805.75,5828.4,5777.9,5822.25,115539008,4643.17\n2017-08-19 07:00:00,5754.15,5755,5645.65,5655.9,198400131,7148\n2017-08-19 08:00:00,5639.9,5686.15,5616.85,5667.65,182410583,6697.18\n2017-08-19 09:00:00,5638.05,5640,5566.25,5590.25,193488581,6308.88\n2017-08-19 10:00:00,5606.95,5666.25,5570.25,5609.1,196571543,6792.49\n2017-08-19 11:00:00,5627.95,5635.25,5579.35,5588.7,160095940,5939.3\n2017-08-19 12:00:00,5647.95,5699.35,5630.95,5682.35,239029425,9184.29\n2017-08-19 13:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-19 14:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-19 15:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-19 16:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-19 17:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-19 18:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-19 19:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-19 20:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-19 21:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-19 22:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-19 23:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-21 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-21 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-21 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-21 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-21 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-21 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-21 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-21 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-21 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-21 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\n2017-08-21 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\n2017-08-21 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\n2017-08-21 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-21 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\n2017-08-21 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\n2017-08-21 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\n2017-08-21 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57"
def initialize(self):
self.set_start_date(2017, 8, 18)
self.set_end_date(2017, 8, 21)
self.set_cash(100000)
self.set_benchmark(lambda x: 0)
ExampleCustomData.custom_data_key = self.get_custom_data_key()
self.custom_symbol = self.add_data(ExampleCustomData, "ExampleCustomData", Resolution.HOUR).symbol
# Saving data here for demonstration and regression testing purposes.
# In real scenarios, data has to be saved to the object store before the algorithm starts.
self.save_data_to_object_store()
self.received_data = []
def on_data(self, slice: Slice):
if slice.contains_key(self.custom_symbol):
custom_data = slice.get(ExampleCustomData, self.custom_symbol)
if custom_data.price == 0:
raise AssertionError("Custom data price was not expected to be zero")
self.received_data.append(custom_data)
def on_end_of_algorithm(self):
if not self.received_data:
raise AssertionError("Custom data was not fetched")
custom_security = self.securities[self.custom_symbol]
if custom_security is None or custom_security.price == 0:
raise AssertionError("Expected the custom security to be added to the algorithm securities and to have a price that is not zero")
# Make sure history requests work as expected
history = self.history(ExampleCustomData, self.custom_symbol, self.start_date, self.end_date, Resolution.HOUR)
if history.shape[0] != len(self.received_data):
raise AssertionError("History request returned more or less data than expected")
for i in range(len(self.received_data)):
received_data = self.received_data[i]
if (history.index[i][0] != received_data.symbol or
history.index[i][1] != received_data.time or
history[["value"]].values[i][0] != received_data.value or
history[["open"]].values[i][0] != received_data.open or
history[["high"]].values[i][0] != received_data.high or
history[["low"]].values[i][0] != received_data.low or
history[["close"]].values[i][0] != received_data.close):
raise AssertionError("History request returned different data than expected")
def get_custom_data_key(self):
return "CustomData/ExampleCustomData"
def save_data_to_object_store(self):
self.object_store.save(self.get_custom_data_key(), self.custom_data)
class ExampleCustomData(PythonData):
custom_data_key = ""
def get_source(self, config, date, is_live):
return SubscriptionDataSource(self.custom_data_key, SubscriptionTransportMedium.OBJECT_STORE, FileFormat.CSV)
def reader(self, config, line, date, is_live):
data = line.split(',')
obj_data = ExampleCustomData()
obj_data.symbol = config.symbol
obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S')
obj_data.value = float(data[4])
obj_data["Open"] = float(data[1])
obj_data["High"] = float(data[2])
obj_data["Low"] = float(data[3])
obj_data["Close"] = float(data[4])
return obj_data
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This algorithm showcases two margin related event handlers.
OnMarginCallWarning: Fired when a portfolio's remaining margin dips below 5% of the total portfolio value
OnMarginCall: Fired immediately before margin call orders are execued, this gives the algorithm a change to regain margin on its own through liquidation
|
```python
from AlgorithmImports import *
class MarginCallEventsAlgorithm(QCAlgorithm):
"""
This algorithm showcases two margin related event handlers.
on_margin_call_warning: Fired when a portfolio's remaining margin dips below 5% of the total portfolio value
on_margin_call: Fired immediately before margin call orders are execued, this gives the algorithm a change to regain margin on its own through liquidation
"""
def initialize(self):
self.set_cash(100000)
self.set_start_date(2013,10,1)
self.set_end_date(2013,12,11)
self.add_equity("SPY", Resolution.SECOND)
# cranking up the leverage increases the odds of a margin call
# when the security falls in value
self.securities["SPY"].set_leverage(100)
def on_data(self, data):
if not self.portfolio.invested:
self.set_holdings("SPY",100)
def on_margin_call(self, requests):
# Margin call event handler. This method is called right before the margin call orders are placed in the market.
# <param name="requests">The orders to be executed to bring this algorithm within margin limits</param>
# this code gets called BEFORE the orders are placed, so we can try to liquidate some of our positions
# before we get the margin call orders executed. We could also modify these orders by changing their quantities
for order in requests:
# liquidate an extra 10% each time we get a margin call to give us more padding
new_quantity = int(order.quantity * 1.1)
requests.remove(order)
requests.append(SubmitOrderRequest(order.order_type, order.security_type, order.symbol, new_quantity, order.stop_price, order.limit_price, self.time, "on_margin_call"))
return requests
def on_margin_call_warning(self):
# Margin call warning event handler.
# This method is called when portfolio.margin_remaining is under 5% of your portfolio.total_portfolio_value
# a chance to prevent a margin call from occurring
spy_holdings = self.securities["SPY"].holdings.quantity
shares = int(-spy_holdings * 0.005)
self.error("{0} - on_margin_call_warning(): Liquidating {1} shares of SPY to avoid margin call.".format(self.time, shares))
self.market_order("SPY", shares)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm used to test a fine and coarse selection methods returning Universe.UNCHANGED
|
```python
from AlgorithmImports import *
class UniverseUnchangedRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.universe_settings.resolution = Resolution.DAILY
# Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
# Commented so regression algorithm is more sensitive
#self.settings.minimum_order_margin_portfolio_percentage = 0.005
self.set_start_date(2014,3,25)
self.set_end_date(2014,4,7)
self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(days = 1), 0.025, None))
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
self.add_universe(self.coarse_selection_function, self.fine_selection_function)
self.number_of_symbols_fine = 2
def coarse_selection_function(self, coarse):
# the first and second selection
if self.time.date() <= date(2014, 3, 26):
tickers = [ "AAPL", "AIG", "IBM" ]
return [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers ]
# will skip fine selection
return Universe.UNCHANGED
def fine_selection_function(self, fine):
if self.time.date() == date(2014, 3, 25):
sorted_by_pe_ratio = sorted(fine, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)
return [ x.symbol for x in sorted_by_pe_ratio[:self.number_of_symbols_fine] ]
# the second selection will return unchanged, in the following fine selection will be skipped
return Universe.UNCHANGED
# assert security changes, throw if called more than once
def on_securities_changed(self, changes):
added_symbols = [ x.symbol for x in changes.added_securities ]
if (len(changes.added_securities) != 2
or self.time.date() != date(2014, 3, 25)
or Symbol.create("AAPL", SecurityType.EQUITY, Market.USA) not in added_symbols
or Symbol.create("IBM", SecurityType.EQUITY, Market.USA) not in added_symbols):
raise ValueError("Unexpected security changes")
self.log(f"OnSecuritiesChanged({self.time}):: {changes}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting the behavior of Universe.SELECTED collection
|
```python
from AlgorithmImports import *
class UniverseSelectedRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2014, 3, 25)
self.set_end_date(2014, 3, 27)
self.universe_settings.resolution = Resolution.DAILY
self._universe = self.add_universe(self.selection_function)
self.selection_count = 0
def selection_function(self, fundamentals):
sorted_by_dollar_volume = sorted(fundamentals, key=lambda x: x.dollar_volume, reverse=True)
sorted_by_dollar_volume = sorted_by_dollar_volume[self.selection_count:]
self.selection_count = self.selection_count + 1
# return the symbol objects of the top entries from our sorted collection
return [ x.symbol for x in sorted_by_dollar_volume[:self.selection_count] ]
def on_data(self, data):
if Symbol.create("TSLA", SecurityType.EQUITY, Market.USA) in self._universe.selected:
raise ValueError(f"TSLA shouldn't of been selected")
self.buy(next(iter(self._universe.selected)), 1)
def on_end_of_algorithm(self):
if self.selection_count != 3:
raise ValueError(f"Unexpected selection count {self.selection_count}")
if self._universe.selected.count != 3 or self._universe.selected.count == self._universe.members.count:
raise ValueError(f"Unexpected universe selected count {self._universe.selected.count}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm reproducing data type bugs in the RegisterIndicator API. Related to GH 4205.
|
```python
from AlgorithmImports import *
from CustomDataRegressionAlgorithm import Bitcoin
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.set_start_date(2020, 1, 5)
self.set_end_date(2020, 1, 10)
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._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.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.resolve_consolidator(_symbol, timedelta(minutes=1), QuoteBar)
# We specify a custom selector to be used
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.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
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)
moving_average2 = SimpleMovingAverage(10)
# Using Resolution
self.register_indicator(_symbol, moving_average2, Resolution.MINUTE)
self._indicators.append(moving_average2)
moving_average3 = SimpleMovingAverage(10)
# Using timedelta
self.register_indicator(_symbol, moving_average3, timedelta(minutes=1))
self._indicators.append(moving_average3)
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
symbol_custom = self.add_data(Bitcoin, "BTC", Resolution.MINUTE).symbol
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)
sma_custom_data2 = SimpleMovingAverage(1)
self.register_indicator(symbol_custom, sma_custom_data2, Resolution.MINUTE)
self._indicators.append(sma_custom_data2)
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 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 on_data(self, data):
if not self.portfolio.invested:
self.set_holdings(self._symbol, 0.5)
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.is_ready for indicator in self._indicators):
raise ValueError("All indicators should be 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
def update(self, input):
self.value = input.ask.high
return True
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Tests the delisting of the composite Symbol (ETF symbol) and the removal of
the universe and the symbol from the algorithm.
|
```python
from AlgorithmImports import *
class ETFConstituentUniverseCompositeDelistingRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2020, 12, 1)
self.set_end_date(2021, 1, 31)
self.set_cash(100000)
self.universe_symbol_count = 0
self.universe_selection_done = False
self.universe_added = False
self.universe_removed = False
self.universe_settings.resolution = Resolution.HOUR
self.delisting_date = date(2021, 1, 21)
self.aapl = self.add_equity("AAPL", Resolution.HOUR).symbol
self.gdvd = self.add_equity("GDVD", Resolution.HOUR).symbol
self.add_universe(self.universe.etf(self.gdvd, self.universe_settings, self.filter_etfs))
def filter_etfs(self, constituents):
self.universe_selection_done = True
if self.utc_time.date() > self.delisting_date:
raise AssertionError(f"Performing constituent universe selection on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')} after composite ETF has been delisted")
constituent_symbols = [i.symbol for i in constituents]
self.universe_symbol_count = len(set(constituent_symbols))
return constituent_symbols
def on_data(self, data):
if self.utc_time.date() > self.delisting_date and any([i != self.aapl for i in data.keys()]):
raise AssertionError("Received unexpected slice in OnData(...) after universe was deselected")
if not self.portfolio.invested:
self.set_holdings(self.aapl, 0.5)
def on_securities_changed(self, changes):
if len(changes.added_securities) != 0 and self.utc_time.date() > self.delisting_date:
raise AssertionError("New securities added after ETF constituents were delisted")
# Since we added the etf subscription it will get delisted and send us a removal event
expected_changes_count = self.universe_symbol_count + 1
if self.universe_selection_done:
# "_universe_symbol_count + 1" because selection is done right away,
# so AddedSecurities includes all ETF constituents (including APPL) plus GDVD
self.universe_added = self.universe_added or len(changes.added_securities) == expected_changes_count
# TODO: shouldn't be sending AAPL as a removed security since it was added by another universe
self.universe_removed = self.universe_removed or (
len(changes.removed_securities) == expected_changes_count and
self.utc_time.date() >= self.delisting_date and
self.utc_time.date() < self.end_date.date())
def on_end_of_algorithm(self):
if not self.universe_added:
raise AssertionError("ETF constituent universe was never added to the algorithm")
if not self.universe_removed:
raise AssertionError("ETF constituent universe was not removed from the algorithm after delisting")
if len(self.active_securities) > 2:
raise AssertionError(f"Expected less than 2 securities after algorithm ended, found {len(self.securities)}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering.
This test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture.
All orders are sent from the brokerage, none of them will be placed by the algorithm.
|
```python
from AlgorithmImports import *
class CustomBrokerageSideOrderHandlingRegressionPartialAlgorithm(QCAlgorithm):
'''Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering.
This test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture.
All orders are sent from the brokerage, none of them will be placed by the algorithm.'''
def initialize(self):
self.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 11)
self.set_cash(100000)
self.set_brokerage_message_handler(CustomBrokerageMessageHandler(self))
self._spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
def on_end_of_algorithm(self):
# The security should have been added
if not self.securities.contains_key(self._spy):
raise AssertionError("Expected security to have been added")
if self.transactions.orders_count == 0:
raise AssertionError("Expected orders to be added from brokerage side")
if len(list(self.portfolio.positions.groups)) != 1:
raise AssertionError("Expected only one position")
class CustomBrokerageMessageHandler(DefaultBrokerageMessageHandler):
def __init__(self, algorithm):
super().__init__(algorithm)
self._algorithm = algorithm
def handle_order(self, event_args):
order = event_args.order
if order.tag is None or not order.tag.isdigit():
raise AssertionError("Expected all new brokerage-side orders to have a valid tag")
# We will only process orders with even tags
return int(order.tag) % 2 == 0
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: In this algorithm we show how you can easily use the universe selection feature to fetch symbols
to be traded using the BaseData custom data system in combination with the AddUniverse{T} method.
AddUniverse{T} requires a function that will return the symbols to be traded.
|
```python
from AlgorithmImports import *
import base64
class DropboxUniverseSelectionAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2017, 7, 4)
self.set_end_date(2018, 7, 4)
self._backtest_symbols_per_day = {}
self._current_universe = []
self.universe_settings.resolution = Resolution.DAILY
# Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
# Commented so regression algorithm is more sensitive
#self.settings.minimum_order_margin_portfolio_percentage = 0.005
self.add_universe("my-dropbox-universe", self.selector)
def selector(self, date: datetime) -> list[str]:
# handle live mode file format
if self.live_mode:
# fetch the file from dropbox
str = self.download("https://www.dropbox.com/s/2l73mu97gcehmh7/daily-stock-picker-live.csv?dl=1")
# if we have a file for today, return symbols, else leave universe unchanged
self._current_universe = str.split(',') if len(str) > 0 else self._current_universe
return self._current_universe
# backtest - first cache the entire file
if len(self._backtest_symbols_per_day) == 0:
# No need for headers for authorization with dropbox, these two lines are for example purposes
byte_key = base64.b64encode("UserName:Password".encode('ASCII'))
# The headers must be passed to the Download method as dictionary
headers = { 'Authorization' : f'Basic ({byte_key.decode("ASCII")})' }
str = self.download("https://www.dropbox.com/s/ae1couew5ir3z9y/daily-stock-picker-backtest.csv?dl=1", headers)
for line in str.splitlines():
data = line.split(',')
self._backtest_symbols_per_day[data[0]] = data[1:]
index = date.strftime("%Y%m%d")
self._current_universe = self._backtest_symbols_per_day.get(index, self._current_universe)
return self._current_universe
def on_data(self, slice: Slice) -> None:
if slice.bars.count == 0:
return
if not self._changes:
return
# start fresh
self.liquidate()
percentage = 1 / slice.bars.count
for trade_bar in slice.bars.values():
self.set_holdings(trade_bar.symbol, percentage)
# reset changes
self._changes = None
def on_securities_changed(self, changes: SecurityChanges) -> None:
self._changes = changes
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm showing how to implement a custom universe selection model and asserting it's behavior
|
```python
from AlgorithmImports import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel
class CustomUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2014,3,24)
self.set_end_date(2014,4,7)
self.universe_settings.resolution = Resolution.DAILY
self.set_universe_selection(MyCustomUniverseSelectionModel())
def on_data(self, data):
'''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''
if not self.portfolio.invested:
for kvp in self.active_securities:
self.set_holdings(kvp.key, 0.1)
class MyCustomUniverseSelectionModel(FundamentalUniverseSelectionModel):
def __init__(self, universe_settings = None):
super().__init__(universe_settings)
self._selected = False
def select(self, algorithm, fundamental):
if not self._selected:
self._selected = True
return [ Symbol.create('AAPL', SecurityType.EQUITY, Market.USA) ]
return Universe.UNCHANGED
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting the behavior of the indicator history api
|
```python
from AlgorithmImports import *
class IndicatorHistoryRegressionAlgorithm(QCAlgorithm):
'''Regression algorithm asserting the behavior of the indicator history api'''
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013, 1, 1)
self.set_end_date(2014, 12, 31)
self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol
def on_data(self, slice: Slice):
self.bollinger_bands = BollingerBands("BB", 20, 2.0, MovingAverageType.SIMPLE)
if self.bollinger_bands.window.is_ready:
raise ValueError("Unexpected ready bollinger bands state")
indicatorHistory = self.indicator_history(self.bollinger_bands, self._symbol, 50)
self.debug(f"indicatorHistory: {indicatorHistory}")
self.debug(f"data_frame: {indicatorHistory.data_frame}")
if not self.bollinger_bands.window.is_ready:
raise ValueError("Unexpected not ready bollinger bands state")
# we ask for 50 data points
if indicatorHistory.count != 50:
raise ValueError(f"Unexpected indicators values {indicatorHistory.count}")
for indicatorDataPoints in indicatorHistory:
middle_band = indicatorDataPoints["middle_band"]
self.debug(f"BB @{indicatorDataPoints.current}: middle_band: {middle_band} upper_band: {indicatorDataPoints.upper_band}")
if indicatorDataPoints == 0:
raise ValueError(f"Unexpected indicators point {indicatorDataPoints}")
currentValues = indicatorHistory.current
if len(currentValues) != 50 or len([x for x in currentValues if x.value == 0]) > 0:
raise ValueError(f"Unexpected indicators current values {len(currentValues)}")
upperBandPoints = indicatorHistory["upper_band"]
if len(upperBandPoints) != 50 or len([x for x in upperBandPoints if x.value == 0]) > 0:
raise ValueError(f"Unexpected indicators upperBandPoints values {len(upperBandPoints)}")
# We are done now!
self.quit()
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Demonstration of how to use custom security properties.
In this algorithm we trade a security based on the values of a slow and fast EMAs which are stored in the security itself.
|
```python
from cmath import isclose
from AlgorithmImports import *
class SecurityCustomPropertiesAlgorithm(QCAlgorithm):
'''Demonstration of how to use custom security properties.
In this algorithm we trade a security based on the values of a slow and fast EMAs which are stored in the security itself.'''
def initialize(self):
self.set_start_date(2013,10, 7)
self.set_end_date(2013,10,11)
self.set_cash(100000)
self.spy = self.add_equity("SPY", Resolution.MINUTE)
# Using the dynamic interface to store our indicator as a custom property.
self.spy.slow_ema = self.ema(self.spy.symbol, 30, Resolution.MINUTE)
# Using the generic interface to store our indicator as a custom property.
self.spy.add("fast_ema", self.ema(self.spy.symbol, 60, Resolution.MINUTE))
# Using the indexer to store our indicator as a custom property
self.spy["bb"] = self.bb(self.spy.symbol, 20, 1, MovingAverageType.SIMPLE, Resolution.MINUTE)
# Fee factor to be used by the custom fee model
self.spy.fee_factor = 0.00002
self.spy.set_fee_model(CustomFeeModel())
# This property will be used to store the prices used to calculate the fees in order to assert the correct fee factor is used.
self.spy.orders_fees_prices = {}
def on_data(self, data):
if not self.spy.fast_ema.is_ready:
return
if not self.portfolio.invested:
# Using the property and the generic interface to access our indicator
if self.spy.slow_ema > self.spy.fast_ema:
self.set_holdings(self.spy.symbol, 1)
else:
if self.spy.get[ExponentialMovingAverage]("slow_ema") < self.spy.get[ExponentialMovingAverage]("fast_ema"):
self.liquidate(self.spy.symbol)
# Using the indexer to access our indicator
bb: BollingerBands = self.spy["bb"]
self.plot("bb", bb.upper_band, bb.middle_band, bb.lower_band)
def on_order_event(self, order_event):
if order_event.status == OrderStatus.FILLED:
fee = order_event.order_fee
expected_fee = self.spy.orders_fees_prices[order_event.order_id] * order_event.absolute_fill_quantity * self.spy.fee_factor
if not isclose(fee.value.amount, expected_fee, rel_tol=1e-15):
raise AssertionError(f"Custom fee model failed to set the correct fee. Expected: {expected_fee}. Actual: {fee.value.amount}")
def on_end_of_algorithm(self):
if self.transactions.orders_count == 0:
raise AssertionError("No orders executed")
class CustomFeeModel(FeeModel):
'''This custom fee is implemented for demonstration purposes only.'''
def get_order_fee(self, parameters):
security = parameters.security
# custom fee math using the fee factor stored in security instance
fee_factor = security.fee_factor
if fee_factor is None:
fee_factor = 0.00001
# Store the price used to calculate the fee for this order
security["orders_fees_prices"][parameters.order.id] = security.price
fee = max(1.0, security.price * parameters.order.absolute_quantity * fee_factor)
return OrderFee(CashAmount(fee, "USD"))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting that using separate coarse & fine selection with async universe settings is not allowed
|
```python
from AlgorithmImports import *
class CoarseFineAsyncUniverseRegressionAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 11)
self.universe_settings.asynchronous = True
threw_exception = False
try:
self.add_universe(self.coarse_selection_function, self.fine_selection_function)
except:
# expected
threw_exception = True
pass
if not threw_exception:
raise ValueError("Expected exception to be thrown for AddUniverse")
self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.coarse_selection_function, self.fine_selection_function))
def coarse_selection_function(self, coarse):
return []
def fine_selection_function(self, fine):
return []
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Base regression algorithm exercising different style options with option price models that might
or might not support them. Also, if the option style is supported, greeks are asserted to be accesible and have valid values.
|
```python
from AlgorithmImports import *
class OptionPriceModelForOptionStylesBaseRegressionAlgorithm(QCAlgorithm):
def __init__(self) -> None:
super().__init__()
self._option_style_is_supported = False
self._check_greeks = True
self._tried_greeks_calculation = False
self._option = None
def on_data(self, slice: Slice) -> None:
if self.is_warming_up:
return
for kvp in slice.option_chains:
if not self._option or kvp.key != self._option.symbol:
continue
self.check_greeks([contract for contract in kvp.value])
def on_end_of_day(self, symbol: Symbol) -> None:
self._check_greeks = True
def on_end_of_algorithm(self) -> None:
if not self._tried_greeks_calculation:
raise AssertionError("Expected greeks to be accessed")
def init(self, option: Option, option_style_is_supported: bool) -> None:
self._option = option
self._option_style_is_supported = option_style_is_supported
self._check_greeks = True
self._tried_greeks_calculation = False
def check_greeks(self, contracts: list[OptionContract]) -> None:
if not self._check_greeks or len(contracts) == 0 or not self._option:
return
self._check_greeks = False
self._tried_greeks_calculation = True
for contract in contracts:
greeks = None
try:
greeks = contract.greeks
# Greeks should have not been successfully accessed if the option style is not supported
option_style_str = 'American' if self._option.style == OptionStyle.AMERICAN else 'European'
if not self._option_style_is_supported:
raise AssertionError(f'Expected greeks not to be calculated for {contract.symbol.value}, an {option_style_str} style option, using {type(self._option.price_model).__name__}, which does not support them, but they were')
except ArgumentException:
# ArgumentException is only expected if the option style is not supported
if self._option_style_is_supported:
raise AssertionError(f'Expected greeks to be calculated for {contract.symbol.value}, an {option_style_str} style option, using {type(self._option.price_model).__name__}, which supports them, but they were not')
# Greeks should be valid if they were successfuly accessed for supported option style
# Delta can be {-1, 0, 1} if the price is too wild, rho can be 0 if risk free rate is 0
# Vega can be 0 if the price is very off from theoretical price, Gamma = 0 if Delta belongs to {-1, 1}
if (self._option_style_is_supported
and (not greeks
or ((contract.right == OptionRight.CALL and (greeks.delta < 0.0 or greeks.delta > 1.0 or greeks.rho < 0.0))
or (contract.right == OptionRight.PUT and (greeks.delta < -1.0 or greeks.delta > 0.0 or greeks.rho > 0.0))
or greeks.theta == 0.0 or greeks.vega < 0.0 or greeks.gamma < 0.0))):
raise AssertionError(f'Expected greeks to have valid values. Greeks were: Delta: {greeks.delta}, Rho: {greeks.rho}, Theta: {greeks.theta}, Vega: {greeks.vega}, Gamma: {greeks.gamma}')
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This regression algorithm tests that we only receive the option chain for a single future contract
in the option universe filter.
|
```python
from AlgorithmImports import *
class AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.invested = False
self.on_data_reached = False
self.option_filter_ran = False
self.symbols_received = []
self.expected_symbols_received = []
self.data_received = {}
self.set_start_date(2020, 1, 4)
self.set_end_date(2020, 1, 8)
self.es = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE, Market.CME)
self.es.set_filter(lambda future_filter: future_filter.expiration(0, 365).expiration_cycle([3, 6]))
self.add_future_option(self.es.symbol, self.option_contract_universe_filter_function)
def option_contract_universe_filter_function(self, option_contracts: OptionFilterUniverse) -> OptionFilterUniverse:
self.option_filter_ran = True
expiry_dates = list(set([x.symbol.underlying.id.date for x in option_contracts]))
expiry = None if not any(expiry_dates) else expiry_dates[0]
symbols = [x.symbol.underlying for x in option_contracts]
symbol = None if not any(symbols) else symbols[0]
if expiry is None or symbol is None:
raise AssertionError("Expected a single Option contract in the chain, found 0 contracts")
self.expected_symbols_received.extend([x.symbol for x in option_contracts])
return option_contracts
def on_data(self, data: Slice):
if not data.has_data:
return
self.on_data_reached = True
has_option_quote_bars = False
for qb in data.quote_bars.values():
if qb.symbol.security_type != SecurityType.FUTURE_OPTION:
continue
has_option_quote_bars = True
self.symbols_received.append(qb.symbol)
if qb.symbol not in self.data_received:
self.data_received[qb.symbol] = []
self.data_received[qb.symbol].append(qb)
if self.invested or not has_option_quote_bars:
return
for chain in sorted(data.option_chains.values(), key=lambda chain: chain.symbol.underlying.id.date):
future_invested = False
option_invested = False
for option in chain.contracts.keys():
if future_invested and option_invested:
return
future = option.underlying
if not option_invested and data.contains_key(option):
self.market_order(option, 1)
self.invested = True
option_invested = True
if not future_invested and data.contains_key(future):
self.market_order(future, 1)
self.invested = True
future_invested = True
def on_end_of_algorithm(self):
super().on_end_of_algorithm()
self.symbols_received = list(set(self.symbols_received))
self.expected_symbols_received = list(set(self.expected_symbols_received))
if not self.option_filter_ran:
raise AssertionError("Option chain filter was never ran")
if not self.on_data_reached:
raise AssertionError("OnData() was never called.")
if len(self.symbols_received) != len(self.expected_symbols_received):
raise AssertionError(f"Expected {len(self.expected_symbols_received)} option contracts Symbols, found {len(self.symbols_received)}")
missing_symbols = [expected_symbol for expected_symbol in self.expected_symbols_received if expected_symbol not in self.symbols_received]
if any(missing_symbols):
raise AssertionError(f'Symbols: "{", ".join(missing_symbols)}" were not found in OnData')
for expected_symbol in self.expected_symbols_received:
data = self.data_received[expected_symbol]
for data_point in data:
data_point.end_time = datetime(1970, 1, 1)
non_dupe_data_count = len(set(data))
if non_dupe_data_count < 1000:
raise AssertionError(f"Received too few data points. Expected >=1000, found {non_dupe_data_count} for {expected_symbol}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm to assert the behavior of <see cref="MacdAlphaModel"/>.
|
```python
from AlgorithmImports import *
from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
from Alphas.MacdAlphaModel import MacdAlphaModel
class MacdAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):
def initialize(self):
super().initialize()
self.set_alpha(MacdAlphaModel())
def on_end_of_algorithm(self):
expected = 4
if self.insights.total_count != expected:
raise AssertionError(f"The total number of insights should be {expected}. Actual: {self.insights.total_count}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Tests that orders are denied if they exceed the max shortable quantity.
|
```python
from AlgorithmImports import *
class RegressionTestShortableProvider(LocalDiskShortableProvider):
def __init__(self):
super().__init__("testbrokerage")
class ShortableProviderOrdersRejectedRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.orders_allowed = []
self.orders_denied = []
self.initialized = False
self.invalidated_allowed_order = False
self.invalidated_new_order_with_portfolio_holdings = False
self.set_start_date(2013, 10, 4)
self.set_end_date(2013, 10, 11)
self.set_cash(10000000)
self.spy = self.add_equity("SPY", Resolution.MINUTE)
self.aig = self.add_equity("AIG", Resolution.MINUTE)
self.spy.set_shortable_provider(RegressionTestShortableProvider())
self.aig.set_shortable_provider(RegressionTestShortableProvider())
def on_data(self, data):
if not self.initialized:
self.handle_order(self.limit_order(self.spy.symbol, -1001, 10000)) # Should be canceled, exceeds the max shortable quantity
order_ticket = self.limit_order(self.spy.symbol, -1000, 10000)
self.handle_order(order_ticket) # Allowed, orders at or below 1000 should be accepted
self.handle_order(self.limit_order(self.spy.symbol, -10, 0.01)) # Should be canceled, the total quantity we would be short would exceed the max shortable quantity.
response = order_ticket.update_quantity(-999) # should be allowed, we are reducing the quantity we want to short
if not response.is_success:
raise ValueError("Order update should of succeeded!")
self.initialized = True
return
if not self.invalidated_allowed_order:
if len(self.orders_allowed) != 1:
raise AssertionError(f"Expected 1 successful order, found: {len(self.orders_allowed)}")
if len(self.orders_denied) != 2:
raise AssertionError(f"Expected 2 failed orders, found: {len(self.orders_denied)}")
allowed_order = self.orders_allowed[0]
order_update = UpdateOrderFields()
order_update.limit_price = 0.01
order_update.quantity = -1001
order_update.tag = "Testing updating and exceeding maximum quantity"
response = allowed_order.update(order_update)
if response.error_code != OrderResponseErrorCode.EXCEEDS_SHORTABLE_QUANTITY:
raise AssertionError(f"Expected order to fail due to exceeded shortable quantity, found: {response.error_code}")
cancel_response = allowed_order.cancel()
if cancel_response.is_error:
raise AssertionError("Expected to be able to cancel open order after bad qty update")
self.invalidated_allowed_order = True
self.orders_denied.clear()
self.orders_allowed.clear()
return
if not self.invalidated_new_order_with_portfolio_holdings:
self.handle_order(self.market_order(self.spy.symbol, -1000)) # Should succeed, no holdings and no open orders to stop this
spy_shares = self.portfolio[self.spy.symbol].quantity
if spy_shares != -1000:
raise AssertionError(f"Expected -1000 shares in portfolio, found: {spy_shares}")
self.handle_order(self.limit_order(self.spy.symbol, -1, 0.01)) # Should fail, portfolio holdings are at the max shortable quantity.
if len(self.orders_denied) != 1:
raise AssertionError(f"Expected limit order to fail due to existing holdings, but found {len(self.orders_denied)} failures")
self.orders_allowed.clear()
self.orders_denied.clear()
self.handle_order(self.market_order(self.aig.symbol, -1001))
if len(self.orders_allowed) != 1:
raise AssertionError(f"Expected market order of -1001 BAC to not fail")
self.invalidated_new_order_with_portfolio_holdings = True
def handle_order(self, order_ticket):
if order_ticket.submit_request.status == OrderRequestStatus.ERROR:
self.orders_denied.append(order_ticket)
return
self.orders_allowed.append(order_ticket)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This regression algorithm tests using FutureOptions daily resolution
|
```python
from AlgorithmImports import *
class FutureOptionHourlyRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2020, 1, 7)
self.set_end_date(2020, 1, 8)
resolution = Resolution.HOUR
# Add our underlying future contract
self.es = self.add_future_contract(
Symbol.create_future(
Futures.Indices.SP_500_E_MINI,
Market.CME,
datetime(2020, 3, 20)
),
resolution).symbol
# Attempt to fetch a specific ITM future option contract
es_options = [
self.add_future_option_contract(x, resolution).symbol for x in (self.option_chain_provider.get_option_contract_list(self.es, self.time)) if x.id.strike_price == 3200 and x.id.option_right == OptionRight.CALL
]
self.es_option = es_options[0]
# Validate it is the expected contract
expected_contract = Symbol.create_option(self.es, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3200, datetime(2020, 3, 20))
if self.es_option != expected_contract:
raise AssertionError(f"Contract {self.es_option} was not the expected contract {expected_contract}")
# Schedule a purchase of this contract at noon
self.schedule.on(self.date_rules.today, self.time_rules.noon, self.schedule_callback_buy)
# Schedule liquidation at 2pm when the market is open
self.schedule.on(self.date_rules.today, self.time_rules.at(17,0,0), self.schedule_callback_liquidate)
def schedule_callback_buy(self):
self.ticket = self.market_order(self.es_option, 1)
def on_data(self, slice):
# Assert we are only getting data at 7PM (12AM UTC)
if slice.time.minute != 0:
raise AssertionError(f"Expected data only on hourly intervals; instead was {slice.time}")
def schedule_callback_liquidate(self):
self.liquidate()
def on_end_of_algorithm(self):
if self.portfolio.invested:
raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}")
if self.ticket.status != OrderStatus.FILLED:
raise AssertionError("Future option order failed to fill correctly")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Universe Selection regression algorithm simulates an edge case. In one week, Google listed two new symbols, delisted one of them and changed tickers.
|
```python
from AlgorithmImports import *
class UniverseSelectionRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2014,3,22) #Set Start Date
self.set_end_date(2014,4,7) #Set End Date
self.set_cash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
# security that exists with no mappings
self.add_equity("SPY", Resolution.DAILY)
# security that doesn't exist until half way in backtest (comes in as GOOCV)
self.add_equity("GOOG", Resolution.DAILY)
self.universe_settings.resolution = Resolution.DAILY
self.add_universe(self.coarse_selection_function)
self.delisted_symbols = []
self.changes = None
def coarse_selection_function(self, coarse):
return [ c.symbol for c in coarse if c.symbol.value == "GOOG" or c.symbol.value == "GOOCV" or c.symbol.value == "GOOAV" or c.symbol.value == "GOOGL" ]
def on_data(self, data):
if self.transactions.orders_count == 0:
self.market_order("SPY", 100)
for kvp in data.delistings:
self.delisted_symbols.append(kvp.key)
if self.changes is None:
return
if not all(data.bars.contains_key(x.symbol) for x in self.changes.added_securities):
return
for security in self.changes.added_securities:
self.log("{0}: Added Security: {1}".format(self.time, security.symbol))
self.market_on_open_order(security.symbol, 100)
for security in self.changes.removed_securities:
self.log("{0}: Removed Security: {1}".format(self.time, security.symbol))
if security.symbol not in self.delisted_symbols:
self.log("Not in delisted: {0}:".format(security.symbol))
self.market_on_open_order(security.symbol, -100)
self.changes = None
def on_securities_changed(self, changes):
self.changes = changes
def on_order_event(self, orderEvent):
if orderEvent.status == OrderStatus.SUBMITTED:
self.log("{0}: Submitted: {1}".format(self.time, self.transactions.get_order_by_id(orderEvent.order_id)))
if orderEvent.status == OrderStatus.FILLED:
self.log("{0}: Filled: {1}".format(self.time, self.transactions.get_order_by_id(orderEvent.order_id)))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Demonstration of using the ETFConstituentsUniverseSelectionModel with simple ticker
|
```python
from AlgorithmImports import *
from Selection.ETFConstituentsUniverseSelectionModel import *
from ETFConstituentsFrameworkAlgorithm import ETFConstituentsFrameworkAlgorithm
class ETFConstituentsFrameworkWithDifferentSelectionModelAlgorithm(ETFConstituentsFrameworkAlgorithm):
def initialize(self):
super().initialize()
self.set_universe_selection(ETFConstituentsUniverseSelectionModel("SPY", self.universe_settings, self.etf_constituents_filter))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Example algorithm showing and asserting the usage of the "ShortMarginInterestRateModel"
paired with a "IShortableProvider" instance, for example "InteractiveBrokersShortableProvider"
|
```python
from AlgorithmImports import *
class ShortInterestFeeRegressionAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013,10, 7)
self.set_end_date(2013,10,11)
self._short = self.add_equity("SPY", Resolution.HOUR)
self._long = self.add_equity("AAPL", Resolution.HOUR)
for security in [ self._short, self._long]:
security.set_shortable_provider(LocalDiskShortableProvider("testbrokerage"))
security.margin_interest_rate_model = ShortMarginInterestRateModel()
def on_data(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''
if not self.portfolio.invested:
self.set_holdings("SPY", -0.5)
self.set_holdings("AAPL", 0.5)
def on_end_of_algorithm(self):
if self._short.margin_interest_rate_model.amount >= 0:
raise RegressionTestException("Expected short fee interest rate to be charged")
if self._long.margin_interest_rate_model.amount <= 0:
raise RegressionTestException("Expected short fee interest rate to be earned")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This is an option split regression algorithm
|
```python
from AlgorithmImports import *
class OptionRenameRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_cash(1000000)
self.set_start_date(2013,6,28)
self.set_end_date(2013,7,2)
option = self.add_option("TFCFA")
# set our strike/expiry filter for this option chain
option.set_filter(-1, 1, timedelta(0), timedelta(3650))
# use the underlying equity as the benchmark
self.set_benchmark("TFCFA")
def on_data(self, slice):
''' Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
<param name="slice">The current slice of data keyed by symbol string</param> '''
if not self.portfolio.invested:
for kvp in slice.option_chains:
chain = kvp.value
if self.time.day == 28 and self.time.hour > 9 and self.time.minute > 0:
contracts = [i for i in sorted(chain, key=lambda x:x.expiry)
if i.right == OptionRight.CALL and
i.strike == 33 and
i.expiry.date() == datetime(2013,8,17).date()]
if contracts:
# Buying option
contract = contracts[0]
self.buy(contract.symbol, 1)
# Buy the undelying stock
underlying_symbol = contract.symbol.underlying
self.buy (underlying_symbol, 100)
# check
if float(contract.ask_price) != 1.1:
raise ValueError("Regression test failed: current ask price was not loaded from NWSA backtest file and is not $1.1")
elif self.time.day == 2 and self.time.hour > 14 and self.time.minute > 0:
for kvp in slice.option_chains:
chain = kvp.value
self.liquidate()
contracts = [i for i in sorted(chain, key=lambda x:x.expiry)
if i.right == OptionRight.CALL and
i.strike == 33 and
i.expiry.date() == datetime(2013,8,17).date()]
if contracts:
contract = contracts[0]
self.log("Bid Price" + str(contract.bid_price))
if float(contract.bid_price) != 0.05:
raise ValueError("Regression test failed: current bid price was not loaded from FOXA file and is not $0.05")
def on_order_event(self, order_event):
self.log(str(order_event))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Tests the delisting of the composite Symbol (ETF symbol) and the removal of
the universe and the symbol from the algorithm, without adding a subscription via AddEquity
|
```python
from AlgorithmImports import *
class ETFConstituentUniverseCompositeDelistingRegressionAlgorithmNoAddEquityETF(QCAlgorithm):
def initialize(self):
self.set_start_date(2020, 12, 1)
self.set_end_date(2021, 1, 31)
self.set_cash(100000)
self.universe_symbol_count = 0
self.universe_selection_done = False
self.universe_added = False
self.universe_removed = False
self.universe_settings.resolution = Resolution.HOUR
self.delisting_date = date(2021, 1, 21)
self.aapl = self.add_equity("AAPL", Resolution.HOUR).symbol
self.gdvd = Symbol.create("GDVD", SecurityType.EQUITY, Market.USA)
self.add_universe(self.universe.etf(self.gdvd, self.universe_settings, self.filter_etfs))
def filter_etfs(self, constituents):
self.universe_selection_done = True
if self.utc_time.date() > self.delisting_date:
raise AssertionError(f"Performing constituent universe selection on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')} after composite ETF has been delisted")
constituent_symbols = [i.symbol for i in constituents]
self.universe_symbol_count = len(set(constituent_symbols))
return constituent_symbols
def on_data(self, data):
if self.utc_time.date() > self.delisting_date and any([i != self.aapl for i in data.keys()]):
raise AssertionError("Received unexpected slice in OnData(...) after universe was deselected")
if not self.portfolio.invested:
self.set_holdings(self.aapl, 0.5)
def on_securities_changed(self, changes):
if len(changes.added_securities) != 0 and self.utc_time.date() > self.delisting_date:
raise AssertionError("New securities added after ETF constituents were delisted")
if self.universe_selection_done:
self.universe_added = self.universe_added or len(changes.added_securities) == self.universe_symbol_count
# TODO: shouldn't be sending AAPL as a removed security since it was added by another universe
self.universe_removed = self.universe_removed or (
len(changes.removed_securities) == self.universe_symbol_count and
self.utc_time.date() >= self.delisting_date and
self.utc_time.date() < self.end_date.date())
def on_end_of_algorithm(self):
if not self.universe_added:
raise AssertionError("ETF constituent universe was never added to the algorithm")
if not self.universe_removed:
raise AssertionError("ETF constituent universe was not removed from the algorithm after delisting")
if len(self.active_securities) > 2:
raise AssertionError(f"Expected less than 2 securities after algorithm ended, found {len(self.securities)}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This example demonstrates how to add options for a given underlying equity security.
It also shows how you can prefilter contracts easily based on strikes and expirations.
It also shows how you can inspect the option chain to pick a specific option contract to trade.
|
```python
from AlgorithmImports import *
class BasicTemplateOptionsFilterUniverseAlgorithm(QCAlgorithm):
underlying_ticker = "GOOG"
def initialize(self):
self.set_start_date(2015, 12, 24)
self.set_end_date(2015, 12, 28)
self.set_cash(100000)
equity = self.add_equity(self.underlying_ticker)
option = self.add_option(self.underlying_ticker)
self.option_symbol = option.symbol
# Set our custom universe filter
option.set_filter(self.filter_function)
# use the underlying equity as the benchmark
self.set_benchmark(equity.symbol)
def filter_function(self, universe):
#Expires today, is a call, and is within 10 dollars of the current price
universe = universe.weeklys_only().expiration(0, 1)
return [symbol for symbol in universe
if symbol.id.option_right != OptionRight.PUT
and -10 < universe.underlying.price - symbol.id.strike_price < 10]
def on_data(self, slice):
if self.portfolio.invested: return
for kvp in slice.option_chains:
if kvp.key != self.option_symbol: continue
# Get the first call strike under market price expiring today
chain = kvp.value
contracts = [option for option in sorted(chain, key = lambda x:x.strike, reverse = True)
if option.expiry.date() == self.time.date()
and option.strike < chain.underlying.price]
if contracts:
self.market_order(contracts[0].symbol, 1)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Demonstration of using coarse and fine universe selection together to filter down a smaller universe of stocks.
|
```python
from AlgorithmImports import *
class CoarseFineFundamentalComboAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2014,1,1) #Set Start Date
self.set_end_date(2015,1,1) #Set End Date
self.set_cash(50000) #Set Strategy Cash
# what resolution should the data *added* to the universe be?
self.universe_settings.resolution = Resolution.DAILY
# this add universe method accepts two parameters:
# - coarse selection function: accepts an IEnumerable<CoarseFundamental> and returns an IEnumerable<Symbol>
# - fine selection function: accepts an IEnumerable<FineFundamental> and returns an IEnumerable<Symbol>
self.add_universe(self.coarse_selection_function, self.fine_selection_function)
self.__number_of_symbols = 5
self.__number_of_symbols_fine = 2
self._changes = None
# sort the data by daily dollar volume and take the top 'NumberOfSymbols'
def coarse_selection_function(self, coarse):
# sort descending by daily dollar volume
sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)
# return the symbol objects of the top entries from our sorted collection
return [ x.symbol for x in sorted_by_dollar_volume[:self.__number_of_symbols] ]
# sort the data by P/E ratio and take the top 'NumberOfSymbolsFine'
def fine_selection_function(self, fine):
# sort descending by P/E ratio
sorted_by_pe_ratio = sorted(fine, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)
# take the top entries from our sorted collection
return [ x.symbol for x in sorted_by_pe_ratio[:self.__number_of_symbols_fine] ]
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.removed_securities:
if security.invested:
self.liquidate(security.symbol)
# we want 20% allocation in each security in our universe
for security in self._changes.added_securities:
self.set_holdings(security.symbol, 0.2)
self._changes = None
# this event fires whenever we have changes to our universe
def on_securities_changed(self, changes):
self._changes = changes
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Mean Variance Optimization algorithm
Uses the HistoricalReturnsAlphaModel and the MeanVarianceOptimizationPortfolioConstructionModel
to create an algorithm that rebalances the portfolio according to modern portfolio theory
|
```python
from AlgorithmImports import *
from Portfolio.MeanVarianceOptimizationPortfolioConstructionModel import *
class MeanVarianceOptimizationFrameworkAlgorithm(QCAlgorithm):
'''Mean Variance Optimization algorithm.'''
def initialize(self):
# Set requested data resolution
self.universe_settings.resolution = Resolution.MINUTE
self.settings.rebalance_portfolio_on_insight_changes = False
self.set_start_date(2013,10,7) #Set Start Date
self.set_end_date(2013,10,11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
self._symbols = [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in [ 'AIG', 'BAC', 'IBM', 'SPY' ] ]
# set algorithm framework models
self.set_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selector))
self.set_alpha(HistoricalReturnsAlphaModel(resolution = Resolution.DAILY))
self.set_portfolio_construction(MeanVarianceOptimizationPortfolioConstructionModel())
self.set_execution(ImmediateExecutionModel())
self.set_risk_management(NullRiskManagementModel())
def coarse_selector(self, coarse):
# Drops SPY after the 8th
last = 3 if self.time.day > 8 else len(self._symbols)
return self._symbols[0:last]
def on_order_event(self, order_event):
if order_event.status == OrderStatus.FILLED:
self.log(str(order_event))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Basic template algorithm for the Axos brokerage
|
```python
from AlgorithmImports import *
class BasicTemplateAxosAlgorithm(QCAlgorithm):
'''Basic template algorithm simply initializes the date range and cash'''
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013,10, 7) #Set Start Date
self.set_end_date(2013,10,11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
self.set_brokerage_model(BrokerageName.AXOS)
self.add_equity("SPY", Resolution.MINUTE)
def on_data(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''
if not self.portfolio.invested:
# will set 25% of our buying power with a market order
self.set_holdings("SPY", 0.25)
self.debug("Purchased SPY!")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm for testing parameterized regression algorithms get valid parameters.
|
```python
from AlgorithmImports import *
class GetParameterRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 7)
self.check_parameter(None, self.get_parameter("non-existing"), "GetParameter(\"non-existing\")")
self.check_parameter("100", self.get_parameter("non-existing", "100"), "GetParameter(\"non-existing\", \"100\")")
self.check_parameter(100, self.get_parameter("non-existing", 100), "GetParameter(\"non-existing\", 100)")
self.check_parameter(100.0, self.get_parameter("non-existing", 100.0), "GetParameter(\"non-existing\", 100.0)")
self.check_parameter("10", self.get_parameter("ema-fast"), "GetParameter(\"ema-fast\")")
self.check_parameter(10, self.get_parameter("ema-fast", 100), "GetParameter(\"ema-fast\", 100)")
self.check_parameter(10.0, self.get_parameter("ema-fast", 100.0), "GetParameter(\"ema-fast\", 100.0)")
self.quit()
def check_parameter(self, expected, actual, call):
if expected == None and actual != None:
raise AssertionError(f"{call} should have returned null but returned {actual} ({type(actual)})")
if expected != None and actual == None:
raise AssertionError(f"{call} should have returned {expected} ({type(expected)}) but returned null")
if expected != None and actual != None and type(expected) != type(actual) or expected != actual:
raise AssertionError(f"{call} should have returned {expected} ({type(expected)}) but returned {actual} ({type(actual)})")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm show casing and asserting the behavior of creating a consolidator specifying the start time
|
```python
from AlgorithmImports import *
from collections import deque
class ConsolidatorStartTimeRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 4)
self.set_end_date(2013, 10, 4)
self.add_equity("SPY", Resolution.MINUTE)
consolidator = TradeBarConsolidator(timedelta(hours=1), start_time=timedelta(hours=9, minutes=30))
consolidator.data_consolidated += self.bar_handler
self.subscription_manager.add_consolidator("SPY", consolidator)
self._expectedConsolidationTime = deque()
self._expectedConsolidationTime.append(time(14, 30))
self._expectedConsolidationTime.append(time(13, 30))
self._expectedConsolidationTime.append(time(12, 30))
self._expectedConsolidationTime.append(time(11, 30))
self._expectedConsolidationTime.append(time(10, 30))
self._expectedConsolidationTime.append(time(9, 30))
def bar_handler(self, _, bar):
if self.time != bar.end_time:
raise RegressionTestException(f"Unexpected consolidation time {bar.Time} != {Time}!")
self.debug(f"{self.time} - Consolidation")
expected = self._expectedConsolidationTime.pop()
if bar.time.time() != expected:
raise RegressionTestException(f"Unexpected consolidation time {bar.time.time()} != {expected}!")
if bar.period != timedelta(hours=1):
raise RegressionTestException(f"Unexpected consolidation period {bar.period}!")
def on_end_of_algorithm(self):
if len(self._expectedConsolidationTime) > 0:
raise RegressionTestException("Unexpected consolidation times!")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Framework algorithm that uses the EmaCrossUniverseSelectionModel to
select the universe based on a moving average cross.
|
```python
from AlgorithmImports import *
from Alphas.ConstantAlphaModel import ConstantAlphaModel
from Selection.EmaCrossUniverseSelectionModel import EmaCrossUniverseSelectionModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
class EmaCrossUniverseSelectionFrameworkAlgorithm(QCAlgorithm):
'''Framework algorithm that uses the EmaCrossUniverseSelectionModel to select the universe based on a moving average cross.'''
def initialize(self):
self.set_start_date(2013,1,1)
self.set_end_date(2015,1,1)
self.set_cash(100000)
fast_period = 100
slow_period = 300
count = 10
self.universe_settings.leverage = 2.0
self.universe_settings.resolution = Resolution.DAILY
self.set_universe_selection(EmaCrossUniverseSelectionModel(fast_period, slow_period, count))
self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1), None, None))
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This example demonstrates how to add options for a given underlying equity security.
It also shows how you can prefilter contracts easily based on strikes and expirations.
It also shows how you can inspect the option chain to pick a specific option contract to trade.
|
```python
from AlgorithmImports import *
class BasicTemplateOptionTradesAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2015, 12, 24)
self.set_end_date(2015, 12, 24)
self.set_cash(100000)
option = self.add_option("GOOG")
# add the initial contract filter
# SetFilter method accepts timedelta objects or integer for days.
# The following statements yield the same filtering criteria
option.set_filter(-2, +2, 0, 10)
# option.set_filter(-2, +2, timedelta(0), timedelta(10))
# use the underlying equity as the benchmark
self.set_benchmark("GOOG")
def on_data(self,slice):
if not self.portfolio.invested:
for kvp in slice.option_chains:
chain = kvp.value
# find the second call strike under market price expiring today
contracts = sorted(sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike)),
key = lambda x: x.expiry, reverse=False)
if len(contracts) == 0: continue
if contracts[0] != None:
self.market_order(contracts[0].symbol, 1)
else:
self.liquidate()
for kpv in slice.bars:
self.log("---> OnData: {0}, {1}, {2}".format(self.time, kpv.key.value, str(kpv.value.close)))
def on_order_event(self, order_event):
self.log(str(order_event))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Example algorithm showing that Slice, Securities and Portfolio behave as a Python Dictionary
|
```python
from AlgorithmImports import *
class PythonDictionaryFeatureRegressionAlgorithm(QCAlgorithm):
'''Example algorithm showing that Slice, Securities and Portfolio behave as a Python Dictionary'''
def initialize(self):
self.set_start_date(2013,10, 7) #Set Start Date
self.set_end_date(2013,10,11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
self.spy_symbol = self.add_equity("SPY").symbol
self.ibm_symbol = self.add_equity("IBM").symbol
self.aig_symbol = self.add_equity("AIG").symbol
self.aapl_symbol = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
date_rules = self.date_rules.on(2013, 10, 7)
self.schedule.on(date_rules, self.time_rules.at(13, 0), self.test_securities_dictionary)
self.schedule.on(date_rules, self.time_rules.at(14, 0), self.test_portfolio_dictionary)
self.schedule.on(date_rules, self.time_rules.at(15, 0), self.test_slice_dictionary)
def test_slice_dictionary(self):
slice = self.current_slice
symbols = ', '.join([f'{x}' for x in slice.keys()])
slice_data = ', '.join([f'{x}' for x in slice.values()])
slice_bars = ', '.join([f'{x}' for x in slice.bars.values()])
if "SPY" not in slice:
raise AssertionError('SPY (string) is not in Slice')
if self.spy_symbol not in slice:
raise AssertionError('SPY (Symbol) is not in Slice')
spy = slice.get(self.spy_symbol)
if spy is None:
raise AssertionError('SPY is not in Slice')
for symbol, bar in slice.bars.items():
self.plot(symbol, 'Price', bar.close)
def test_securities_dictionary(self):
symbols = ', '.join([f'{x}' for x in self.securities.keys()])
leverages = ', '.join([str(x.get_last_data()) for x in self.securities.values()])
if "IBM" not in self.securities:
raise AssertionError('IBM (string) is not in Securities')
if self.ibm_symbol not in self.securities:
raise AssertionError('IBM (Symbol) is not in Securities')
ibm = self.securities.get(self.ibm_symbol)
if ibm is None:
raise AssertionError('ibm is None')
aapl = self.securities.get(self.aapl_symbol)
if aapl is not None:
raise AssertionError('aapl is not None')
for symbol, security in self.securities.items():
self.plot(symbol, 'Price', security.price)
def test_portfolio_dictionary(self):
symbols = ', '.join([f'{x}' for x in self.portfolio.keys()])
leverages = ', '.join([f'{x.symbol}: {x.leverage}' for x in self.portfolio.values()])
if "AIG" not in self.securities:
raise AssertionError('AIG (string) is not in Portfolio')
if self.aig_symbol not in self.securities:
raise AssertionError('AIG (Symbol) is not in Portfolio')
aig = self.portfolio.get(self.aig_symbol)
if aig is None:
raise AssertionError('aig is None')
aapl = self.portfolio.get(self.aapl_symbol)
if aapl is not None:
raise AssertionError('aapl is not None')
for symbol, holdings in self.portfolio.items():
msg = f'{symbol}: {holdings.leverage}'
def on_end_of_algorithm(self):
portfolio_copy = self.portfolio.copy()
try:
self.portfolio.clear() # Throws exception
except Exception as e:
self.debug(e)
bar = self.securities.pop("SPY")
length = len(self.securities)
if length != 2:
raise AssertionError(f'After popping SPY, Securities should have 2 elements, {length} found')
securities_copy = self.securities.copy()
self.securities.clear() # Does not throw
def on_data(self, data):
'''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''
if not self.portfolio.invested:
self.set_holdings("SPY", 1/3)
self.set_holdings("IBM", 1/3)
self.set_holdings("AIG", 1/3)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Example structure for structuring an algorithm with indicator and consolidator data for many tickers.
|
```python
from AlgorithmImports import *
class MultipleSymbolConsolidationAlgorithm(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) -> None:
# This is the period of bars we'll be creating
bar_period = TimeSpan.from_minutes(10)
# This is the period of our sma indicators
sma_period = 10
# This is the number of consolidated bars we'll hold in symbol data for reference
rolling_window_size = 10
# Holds all of our data keyed by each symbol
self._data = {}
# Contains all of our equity symbols
equity_symbols = ["AAPL","SPY","IBM"]
# Contains all of our forex symbols
forex_symbols = ["EURUSD", "USDJPY", "EURGBP", "EURCHF", "USDCAD", "USDCHF", "AUDUSD","NZDUSD"]
self.set_start_date(2014, 12, 1)
self.set_end_date(2015, 2, 1)
# initialize our equity data
for symbol in equity_symbols:
equity = self.add_equity(symbol)
self._data[symbol] = SymbolData(equity.symbol, bar_period, rolling_window_size)
# initialize our forex data
for symbol in forex_symbols:
forex = self.add_forex(symbol)
self._data[symbol] = SymbolData(forex.symbol, bar_period, rolling_window_size)
# loop through all our symbols and request data subscriptions and initialize indicator
for symbol, symbol_data in self._data.items():
# define the indicator
symbol_data.sma = SimpleMovingAverage(self.create_indicator_name(symbol, "sma" + str(sma_period), Resolution.MINUTE), sma_period)
# define a consolidator to consolidate data for this symbol on the requested period
if symbol_data._symbol.security_type == SecurityType.EQUITY:
tb_consolidator = TradeBarConsolidator(bar_period)
tb_consolidator.data_consolidated += self.on_trade_bar_consolidated
# we need to add this consolidator so it gets auto updates
self.subscription_manager.add_consolidator(symbol_data._symbol, tb_consolidator)
else:
qb_consolidator = QuoteBarConsolidator(bar_period)
qb_consolidator.data_consolidated += self.on_quote_bar_consolidated
# we need to add this consolidator so it gets auto updates
self.subscription_manager.add_consolidator(symbol_data._symbol, qb_consolidator)
def on_trade_bar_consolidated(self, sender: object, bar: TradeBar) -> None:
self._on_data_consolidated(sender, bar)
def on_quote_bar_consolidated(self, sender: object, bar: QuoteBar) -> None:
self._on_data_consolidated(sender, bar)
def _on_data_consolidated(self, sender: object, bar: TradeBar | QuoteBar) -> None:
self._data[bar.symbol.value].sma.update(bar.time, bar.close)
self._data[bar.symbol.value].bars.add(bar)
# OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
# Argument "data": Slice object, dictionary object with your stock data
def on_data(self, data: Slice) -> None:
# loop through each symbol in our structure
for symbol in self._data.keys():
symbol_data = self._data[symbol]
# this check proves that this symbol was JUST updated prior to this OnData function being called
if symbol_data.is_ready() and symbol_data.was_just_updated(self.time):
if not self.portfolio[symbol].invested:
self.market_order(symbol, 1)
# End of a trading day event handler. This method is called at the end of the algorithm day (or multiple times if trading multiple assets).
# Method is called 10 minutes before closing to allow user to close out position.
def on_end_of_day(self, symbol: Symbol) -> None:
i = 0
for symbol_key in sorted(self._data.keys()):
symbol_data = self._data[symbol_key]
# we have too many symbols to plot them all, so plot every other
i += 1
if symbol_data.is_ready() and i%2 == 0:
self.plot(symbol_key, symbol_key, symbol_data.sma.current.value)
class SymbolData(object):
def __init__(self, symbol: Symbol, bar_period: timedelta, window_size: int) -> None:
self._symbol = symbol
# The period used when population the Bars rolling window
self.bar_period = bar_period
# A rolling window of data, data needs to be pumped into Bars by using Bars.update( trade_bar ) and can be accessed like:
# my_symbol_data.bars[0] - most first recent piece of data
# my_symbol_data.bars[5] - the sixth most recent piece of data (zero based indexing)
self.bars = RollingWindow(window_size)
# The simple moving average indicator for our symbol
self.sma = None
# Returns true if all the data in this instance is ready (indicators, rolling windows, ect...)
def is_ready(self) -> bool:
return self.bars.is_ready and self.sma.is_ready
# Returns true if the most recent trade bar time matches the current time minus the bar's period, this
# indicates that update was just called on this instance
def was_just_updated(self, current: datetime) -> bool:
return self.bars.count > 0 and self.bars[0].time == current - self.bar_period
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm to test we can specify a custom settlement model, and override some of its methods
|
```python
from AlgorithmImports import *
from CustomBrokerageModelRegressionAlgorithm import CustomBrokerageModel
class CustomSettlementModelRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013,10,7)
self.set_end_date(2013,10,11)
self.set_cash(10000)
self.spy = self.add_equity("SPY", Resolution.DAILY)
self.set_settlement_model(self.spy)
def set_settlement_model(self, security):
self.set_brokerage_model(CustomBrokerageModelWithCustomSettlementModel())
def on_data(self, slice):
if self.portfolio.cash_book[Currencies.USD].amount == 10000:
parameters = ApplyFundsSettlementModelParameters(self.portfolio, self.spy, self.time, CashAmount(101, Currencies.USD), None)
self.spy.settlement_model.apply_funds(parameters)
def on_end_of_algorithm(self):
if self.portfolio.cash_book[Currencies.USD].amount != 10101:
raise AssertionError(f"It was expected to have 10101 USD in Portfolio, but was {self.portfolio.cash_book[Currencies.USD].amount}")
parameters = ScanSettlementModelParameters(self.portfolio, self.spy, datetime(2013, 10, 6))
self.spy.settlement_model.scan(parameters)
if self.portfolio.cash_book[Currencies.USD].amount != 10000:
raise AssertionError(f"It was expected to have 10000 USD in Portfolio, but was {self.portfolio.cash_book[Currencies.USD].amount}")
class CustomSettlementModel:
def apply_funds(self, parameters):
self.currency = parameters.cash_amount.currency
self.amount = parameters.cash_amount.amount
parameters.portfolio.cash_book[self.currency].add_amount(self.amount)
def scan(self, parameters):
if parameters.utc_time == datetime(2013, 10, 6):
parameters.portfolio.cash_book[self.currency].add_amount(-self.amount)
def get_unsettled_cash(self):
return None
class CustomBrokerageModelWithCustomSettlementModel(CustomBrokerageModel):
def get_settlement_model(self, security):
return CustomSettlementModel()
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Algorithm demonstrating and ensuring that Bybit crypto brokerage model works as expected
|
```python
from AlgorithmImports import *
class BybitCryptoRegressionAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2022, 12, 13)
self.set_end_date(2022, 12, 13)
# Set account currency (USDT)
self.set_account_currency("USDT")
# Set strategy cash (USD)
self.set_cash(100000)
# Add some coin as initial holdings
# When connected to a real brokerage, the amount specified in SetCash
# will be replaced with the amount in your actual account.
self.set_cash("BTC", 1)
self.set_brokerage_model(BrokerageName.BYBIT, AccountType.CASH)
self.btc_usdt = self.add_crypto("BTCUSDT").symbol
# create two moving averages
self.fast = self.ema(self.btc_usdt, 30, Resolution.MINUTE)
self.slow = self.ema(self.btc_usdt, 60, Resolution.MINUTE)
self.liquidated = False
def on_data(self, data):
if self.portfolio.cash_book["USDT"].conversion_rate == 0 or self.portfolio.cash_book["BTC"].conversion_rate == 0:
self.log(f"USDT conversion rate: {self.portfolio.cash_book['USDT'].conversion_rate}")
self.log(f"BTC conversion rate: {self.portfolio.cash_book['BTC'].conversion_rate}")
raise AssertionError("Conversion rate is 0")
if not self.slow.is_ready:
return
btc_amount = self.portfolio.cash_book["BTC"].amount
if self.fast > self.slow:
if btc_amount == 1 and not self.liquidated:
self.buy(self.btc_usdt, 1)
else:
if btc_amount > 1:
self.liquidate(self.btc_usdt)
self.liquidated = True
elif btc_amount > 0 and self.liquidated and len(self.transactions.get_open_orders()) == 0:
# Place a limit order to sell our initial BTC holdings at 1% above the current price
limit_price = round(self.securities[self.btc_usdt].price * 1.01, 2)
self.limit_order(self.btc_usdt, -btc_amount, limit_price)
def on_order_event(self, order_event):
self.debug("{} {}".format(self.time, order_event.to_string()))
def on_end_of_algorithm(self):
self.log(f"{self.time} - TotalPortfolioValue: {self.portfolio.total_portfolio_value}")
self.log(f"{self.time} - CashBook: {self.portfolio.cash_book}")
btc_amount = self.portfolio.cash_book["BTC"].amount
if btc_amount > 0:
raise AssertionError(f"BTC holdings should be zero at the end of the algorithm, but was {btc_amount}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Example algorithm implementing VolumeShareSlippageModel.
|
```python
from AlgorithmImports import *
from Orders.Slippage.VolumeShareSlippageModel import VolumeShareSlippageModel
class VolumeShareSlippageModelAlgorithm(QCAlgorithm):
_longs = []
_shorts = []
def initialize(self) -> None:
self.set_start_date(2020, 11, 29)
self.set_end_date(2020, 12, 2)
# To set the slippage model to limit to fill only 30% volume of the historical volume, with 5% slippage impact.
self.set_security_initializer(lambda security: security.set_slippage_model(VolumeShareSlippageModel(0.3, 0.05)))
self.universe_settings.resolution = Resolution.DAILY
# Add universe to trade on the most and least weighted stocks among SPY constituents.
self.add_universe(self.universe.etf("SPY", universe_filter_func=self.selection))
def selection(self, constituents: list[ETFConstituentUniverse]) -> list[Symbol]:
sorted_by_weight = sorted(constituents, key=lambda c: c.weight)
# Add the 10 most weighted stocks to the universe to long later.
self._longs = [c.symbol for c in sorted_by_weight[-10:]]
# Add the 10 least weighted stocks to the universe to short later.
self._shorts = [c.symbol for c in sorted_by_weight[:10]]
return self._longs + self._shorts
def on_data(self, slice: Slice) -> None:
# Equally invest into the selected stocks to evenly dissipate capital risk.
# Dollar neutral of long and short stocks to eliminate systematic risk, only capitalize the popularity gap.
targets = [PortfolioTarget(symbol, 0.05) for symbol in self._longs]
targets += [PortfolioTarget(symbol, -0.05) for symbol in self._shorts]
# Liquidate the ones not being the most and least popularity stocks to release fund for higher expected return trades.
self.set_holdings(targets, liquidate_existing_holdings=True)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This regression algorithm tests In The Money (ITM) index option expiry for short calls.
We expect 2 orders from the algorithm, which are:
* Initial entry, sell SPX Call Option (expiring ITM)
* Option assignment
Additionally, we test delistings for index options and assert that our
portfolio holdings reflect the orders the algorithm has submitted.
|
```python
from AlgorithmImports import *
class IndexOptionShortCallITMExpiryRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2021, 1, 4)
self.set_end_date(2021, 1, 31)
self.set_cash(1000000)
self.portfolio.set_margin_call_model(MarginCallModel.NULL);
# avoid getting assigned
self.set_security_initializer(CompositeSecurityInitializer(self.security_initializer, FuncSecurityInitializer(self.custom_security_initializer)))
self.spx = self.add_index("SPX", Resolution.MINUTE).symbol
# Select a index option expiring ITM, and adds it to the algorithm.
self.spx_options = list(self.option_chain(self.spx))
self.spx_options = [i for i in self.spx_options if i.id.strike_price <= 4200 and i.id.option_right == OptionRight.PUT and i.id.date.year == 2021 and i.id.date.month == 1]
self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price, reverse=True))[0]
self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol
self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.PUT, 4200, datetime(2021, 1, 15))
if self.spx_option != self.expected_contract:
raise AssertionError(f"Contract self.expected_contract was not found in the chain")
self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, -1))
def on_data(self, data: Slice):
# Assert delistings, so that we can make sure that we receive the delisting warnings at
# the expected time. These assertions detect bug #4872
for delisting in data.delistings.values():
if delisting.type == DelistingType.WARNING:
if delisting.time != datetime(2021, 1, 15):
raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}")
if delisting.type == DelistingType.DELISTED:
if delisting.time != datetime(2021, 1, 16):
raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}")
def on_order_event(self, order_event: OrderEvent):
if order_event.status != OrderStatus.FILLED:
# There's lots of noise with OnOrderEvent, but we're only interested in fills.
return
if order_event.symbol not in self.securities:
raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
security = self.securities[order_event.symbol]
if security.symbol == self.spx:
self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_contract])
elif security.symbol == self.expected_contract:
self.assert_index_option_contract_order(order_event, security)
else:
raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")
def assert_index_option_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security):
if "Assignment" in order_event.message:
if order_event.fill_price != 4200:
raise AssertionError("Option was not assigned at expected strike price (4200)")
if order_event.direction != OrderDirection.SELL or index.holdings.quantity != 0:
raise AssertionError(f"Expected Qty: 0 index holdings for assigned index option {index.symbol}, found {index.holdings.quantity}")
elif index.holdings.quantity != 0:
raise AssertionError(f"Expected no holdings in index: {index.symbol}")
def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):
if order_event.direction == OrderDirection.SELL and option.holdings.quantity != -1:
raise AssertionError(f"No holdings were created for option contract {option.symbol}")
if order_event.is_assignment and option.holdings.quantity != 0:
raise AssertionError(f"Holdings were found after option contract was assigned: {option.symbol}")
### <summary>
### Ran at the end of the algorithm to ensure the algorithm has no holdings
### </summary>
### <exception cref="Exception">The algorithm has holdings</exception>
def on_end_of_algorithm(self):
if self.portfolio.invested:
raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}")
def custom_security_initializer(self, security):
if Extensions.is_option(security.symbol.security_type):
security.set_option_assignment_model(NullOptionAssignmentModel())
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Hourly regression algorithm trading ADAUSDT binance futures long and short asserting the behavior
|
```python
from AlgorithmImports import *
class BasicTemplateCryptoFutureHourlyAlgorithm(QCAlgorithm):
# <summary>
# 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.set_start_date(2022, 12, 13)
self.set_end_date(2022, 12, 13)
self.set_time_zone(TimeZones.UTC)
try:
self.set_brokerage_model(BrokerageName.BINANCE_COIN_FUTURES, AccountType.CASH)
except:
# expected, we don't allow cash account type
pass
self.set_brokerage_model(BrokerageName.BINANCE_COIN_FUTURES, AccountType.MARGIN)
self.ada_usdt = self.add_crypto_future("ADAUSDT", 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.interest_per_symbol = {self.ada_usdt.symbol: 0}
# Default USD cash, set 1M but it wont be used
self.set_cash(1000000)
# the amount of USDT we need to hold to trade 'ADAUSDT'
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 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 AssertionError(f"Unexpected cached margin interest rate for {interest_rate.key}!")
if self.fast > self.slow:
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 AssertionError(f"Unexpected valid order {self.ticket}, should fail due to margin not sufficient")
self.buy(self.ada_usdt.symbol, 1000)
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.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 AssertionError(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 AssertionError(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 AssertionError(f"Unexpected margin used {self.margin_used}")
# position just opened should be just spread here
self.profit = self.portfolio.total_unrealized_profit
if (5 - abs(self.profit)) < 0:
raise AssertionError(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")
if (self.portfolio.total_profit != 0):
raise AssertionError(f"Unexpected TotalProfit {self.portfolio.total_profit}")
else:
# let's revert our position and double
if self.time.hour > 10 and self.transactions.orders_count == 2:
self.sell(self.ada_usdt.symbol, 3000)
self.ada_usdt_holdings = self.ada_usdt.holdings
# USDT/BUSD futures value is based on it's price
self.holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 2000
if abs(self.ada_usdt_holdings.absolute_holdings_cost - self.holdings_value_usdt) > 1:
raise AssertionError(f"Unexpected holdings cost {self.ada_usdt_holdings.holdings_cost}")
# position just opened should be just spread here
self.profit = self.portfolio.total_unrealized_profit
if (5 - abs(self.profit)) < 0:
raise AssertionError(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")
# we barely did any difference on the previous trade
if (5 - abs(self.portfolio.total_profit)) < 0:
raise AssertionError(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 AssertionError(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))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: EMA cross with SP500 E-mini futures
In this example, we demostrate how to trade futures contracts using
a equity to generate the trading signals
It also shows how you can prefilter contracts easily based on expirations.
It also shows how you can inspect the futures chain to pick a specific contract to trade.
|
```python
from AlgorithmImports import *
class FuturesMomentumAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2016, 1, 1)
self.set_end_date(2016, 8, 18)
self.set_cash(100000)
fast_period = 20
slow_period = 60
self._tolerance = 1 + 0.001
self.is_up_trend = False
self.is_down_trend = False
self.set_warm_up(max(fast_period, slow_period))
# Adds SPY to be used in our EMA indicators
equity = self.add_equity("SPY", Resolution.DAILY)
self._fast = self.ema(equity.symbol, fast_period, Resolution.DAILY)
self._slow = self.ema(equity.symbol, slow_period, Resolution.DAILY)
# Adds the future that will be traded and
# set our expiry filter for this futures chain
future = self.add_future(Futures.Indices.SP_500_E_MINI)
future.set_filter(timedelta(0), timedelta(182))
def on_data(self, slice):
if self._slow.is_ready and self._fast.is_ready:
self.is_up_trend = self._fast.current.value > self._slow.current.value * self._tolerance
self.is_down_trend = self._fast.current.value < self._slow.current.value * self._tolerance
if (not self.portfolio.invested) and self.is_up_trend:
for chain in slice.futures_chains:
# find the front contract expiring no earlier than in 90 days
contracts = list(filter(lambda x: x.expiry > self.time + timedelta(90), chain.value))
# if there is any contract, trade the front contract
if len(contracts) == 0: continue
contract = sorted(contracts, key = lambda x: x.expiry, reverse=True)[0]
self.market_order(contract.symbol , 1)
if self.portfolio.invested and self.is_down_trend:
self.liquidate()
def on_end_of_day(self, symbol):
if self.is_up_trend:
self.plot("Indicator Signal", "EOD",1)
elif self.is_down_trend:
self.plot("Indicator Signal", "EOD",-1)
elif self._slow.is_ready and self._fast.is_ready:
self.plot("Indicator Signal", "EOD",0)
def on_order_event(self, order_event):
self.log(str(order_event))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This regression algorithm is expected to stop executing after Initialization. Related to GH 6168 issue
|
```python
from AlgorithmImports import *
class QuitInInitializationRegressionAlgorithm(QCAlgorithm):
'''Basic template algorithm simply initializes the date range and cash'''
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013,10, 7) #Set Start Date
self.set_end_date(2013,10,11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
self.add_equity("SPY", Resolution.DAILY)
self.quit()
def on_data(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''
raise ValueError("Algorithm should of stopped!")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Tests filtering in coarse selection by shortable quantity
|
```python
from AlgorithmImports import *
class AllShortableSymbolsCoarseSelectionRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self._20140325 = datetime(2014, 3, 25)
self._20140326 = datetime(2014, 3, 26)
self._20140327 = datetime(2014, 3, 27)
self._20140328 = datetime(2014, 3, 28)
self._20140329 = datetime(2014, 3, 29)
self.last_trade_date = date(1,1,1)
self._aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
self._bac = Symbol.create("BAC", SecurityType.EQUITY, Market.USA)
self._gme = Symbol.create("GME", SecurityType.EQUITY, Market.USA)
self._goog = Symbol.create("GOOG", SecurityType.EQUITY, Market.USA)
self._qqq = Symbol.create("QQQ", SecurityType.EQUITY, Market.USA)
self._spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
self.coarse_selected = { self._20140325: False, self._20140326: False, self._20140327:False, self._20140328:False }
self.expected_symbols = { self._20140325: [ self._bac, self._qqq, self._spy ],
self._20140326: [ self._spy ],
self._20140327: [ self._aapl, self._bac, self._gme, self._qqq, self._spy ],
self._20140328: [ self._goog ],
self._20140329: []}
self.set_start_date(2014, 3, 25)
self.set_end_date(2014, 3, 29)
self.set_cash(10000000)
self.shortable_provider = RegressionTestShortableProvider()
self.security = self.add_equity(self._spy)
self.add_universe(self.coarse_selection)
self.universe_settings.resolution = Resolution.DAILY
self.set_brokerage_model(AllShortableSymbolsRegressionAlgorithmBrokerageModel(self.shortable_provider))
def on_data(self, data):
if self.time.date() == self.last_trade_date:
return
for (symbol, security) in {x.key: x.value for x in sorted(self.active_securities, key = lambda kvp:kvp.key)}.items():
if security.invested:
continue
shortable_quantity = security.shortable_provider.shortable_quantity(symbol, self.time)
if not shortable_quantity:
raise AssertionError(f"Expected {symbol} to be shortable on {self.time.strftime('%Y%m%d')}")
"""
Buy at least once into all Symbols. Since daily data will always use
MOO orders, it makes the testing of liquidating buying into Symbols difficult.
"""
self.market_order(symbol, -shortable_quantity)
self.last_trade_date = self.time.date()
def coarse_selection(self, coarse):
shortable_symbols = self.shortable_provider.all_shortable_symbols(self.time)
selected_symbols = list(sorted(filter(lambda x: (x in shortable_symbols.keys()) and (shortable_symbols[x] >= 500), map(lambda x: x.symbol, coarse)), key= lambda x: x.value))
expected_missing = 0
if self.time.date() == self._20140327.date():
gme = Symbol.create("GME", SecurityType.EQUITY, Market.USA)
if gme not in shortable_symbols.keys():
raise AssertionError("Expected unmapped GME in shortable symbols list on 2014-03-27")
if "GME" not in list(map(lambda x: x.symbol.value, coarse)):
raise AssertionError("Expected mapped GME in coarse symbols on 2014-03-27")
expected_missing = 1
missing = list(filter(lambda x: x not in selected_symbols, self.expected_symbols[self.time]))
if len(missing) != expected_missing:
raise AssertionError(f"Expected Symbols selected on {self.time.strftime('%Y%m%d')} to match expected Symbols, but the following Symbols were missing: {', '.join(list(map(lambda x:x.value, missing)))}")
self.coarse_selected[self.time] = True
return selected_symbols
def on_end_of_algorithm(self):
if not all(x for x in self.coarse_selected.values()):
raise AssertionError(f"Expected coarse selection on all dates, but didn't run on: {', '.join(list(map(lambda x: x[0].strftime('%Y%m%d'), filter(lambda x:not x[1], self.coarse_selected.items()))))}")
class AllShortableSymbolsRegressionAlgorithmBrokerageModel(DefaultBrokerageModel):
def __init__(self, shortable_provider):
self.shortable_provider = shortable_provider
super().__init__()
def get_shortable_provider(self, security):
return self.shortable_provider
class RegressionTestShortableProvider(LocalDiskShortableProvider):
def __init__(self):
super().__init__("testbrokerage")
"""
Gets a list of all shortable Symbols, including the quantity shortable as a Dictionary.
"""
def all_shortable_symbols(self, localtime):
shortable_data_directory = os.path.join(Globals.data_folder, "equity", Market.USA, "shortable", self.brokerage)
all_symbols = {}
"""
Check backwards up to one week to see if we can source a previous file.
If not, then we return a list of all Symbols with quantity set to zero.
"""
i = 0
while i <= 7:
shortable_list_file = os.path.join(shortable_data_directory, "dates", f"{(localtime - timedelta(days=i)).strftime('%Y%m%d')}.csv")
for line in Extensions.read_lines(self.data_provider, shortable_list_file):
csv = line.split(',')
ticker = csv[0]
symbol = Symbol(SecurityIdentifier.generate_equity(ticker, Market.USA, mapping_resolve_date = localtime), ticker)
quantity = int(csv[1])
all_symbols[symbol] = quantity
if len(all_symbols) > 0:
return all_symbols
i += 1
# Return our empty dictionary if we did not find a file to extract
return all_symbols
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Demonstration of the parameter system of QuantConnect. Using parameters you can pass the values required into C# algorithms for optimization.
|
```python
from AlgorithmImports import *
class ParameterizedAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013, 10, 7) #Set Start Date
self.set_end_date(2013, 10, 11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.add_equity("SPY")
# Receive parameters from the Job
fast_period = self.get_parameter("ema-fast", 100)
slow_period = self.get_parameter("ema-slow", 200)
self.fast = self.ema("SPY", fast_period)
self.slow = self.ema("SPY", slow_period)
def on_data(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
# wait for our indicators to ready
if not self.fast.is_ready or not self.slow.is_ready:
return
fast = self.fast.current.value
slow = self.slow.current.value
if fast > slow * 1.001:
self.set_holdings("SPY", 1)
elif fast < slow * 0.999:
self.liquidate("SPY")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting the behavior of a ScheduledUniverse
|
```python
from AlgorithmImports import *
class BasicTemplateAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013,10, 7)
self.set_end_date(2013,10, 8)
self._spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
self._selection_time =[ datetime(2013, 10, 7, 1, 0, 0), datetime(2013, 10, 8, 1, 0, 0)]
self.add_universe(ScheduledUniverse(self.date_rules.every_day(), self.time_rules.at(1, 0), self.select_assets))
def select_assets(self, time):
self.debug(f"Universe selection called: {Time}")
expected_time = self._selection_time.pop(0)
if expected_time != self.time:
raise ValueError(f"Unexpected selection time {self.time} expected {expected_time}")
return [ self._spy ]
def on_data(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''
if not self.portfolio.invested:
self.set_holdings(self._spy, 1)
def on_end_of_algorithm(self):
if len(self._selection_time) > 0:
raise ValueError("Unexpected selection times")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This example demonstrates how to get access to futures history for a given root symbol.
It also shows how you can prefilter contracts easily based on expirations, and inspect the futures
chain to pick a specific contract to trade.
|
```python
from AlgorithmImports import *
class BasicTemplateFuturesHistoryAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 8)
self.set_end_date(2013, 10, 9)
self.set_cash(1000000)
extended_market_hours = self.get_extended_market_hours()
# Subscribe and set our expiry filter for the futures chain
# find the front contract expiring no earlier than in 90 days
future_es = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE, extended_market_hours=extended_market_hours)
future_es.set_filter(timedelta(0), timedelta(182))
future_gc = self.add_future(Futures.Metals.GOLD, Resolution.MINUTE, extended_market_hours=extended_market_hours)
future_gc.set_filter(timedelta(0), timedelta(182))
self.set_benchmark(lambda x: 1000000)
self.schedule.on(self.date_rules.every_day(), self.time_rules.every(timedelta(hours=1)), self.make_history_call)
self._success_count = 0
def make_history_call(self):
history = self.history(self.securities.keys(), 10, Resolution.MINUTE)
if len(history) < 10:
raise AssertionError(f'Empty history at {self.time}')
self._success_count += 1
def on_end_of_algorithm(self):
if self._success_count < self.get_expected_history_call_count():
raise AssertionError(f'Scheduled Event did not assert history call as many times as expected: {self._success_count}/49')
def on_data(self,slice):
if self.portfolio.invested: return
for chain in slice.future_chains:
for contract in chain.value:
self.log(f'{contract.symbol.value},' +
f'Bid={contract.bid_price} ' +
f'Ask={contract.ask_price} ' +
f'Last={contract.last_price} ' +
f'OI={contract.open_interest}')
def on_securities_changed(self, changes):
for change in changes.added_securities:
history = self.history(change.symbol, 10, Resolution.MINUTE).sort_index(level='time', ascending=False)[:3]
for index, row in history.iterrows():
self.log(f'History: {index[1]} : {index[2]:%m/%d/%Y %I:%M:%S %p} > {row.close}')
def on_order_event(self, order_event):
# Order fill event handler. On an order fill update the resulting information is passed to this method.
# Order event details containing details of the events
self.log(f'{order_event}')
def get_extended_market_hours(self):
return False
def get_expected_history_call_count(self):
return 42
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm illustrating the usage of the <see cref="QCAlgorithm.FuturesChains(IEnumerable{Symbol}, bool)"/>
method to get multiple futures chains.
|
```python
from AlgorithmImports import *
class FuturesChainsMultipleFullDataRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 7)
es_future = self.add_future(Futures.Indices.SP_500_E_MINI).symbol
gc_future = self.add_future(Futures.Metals.GOLD).symbol
chains = self.futures_chains([es_future, gc_future], flatten=True)
self._es_contract = self.get_contract(chains, es_future)
self._gc_contract = self.get_contract(chains, gc_future)
self.add_future_contract(self._es_contract)
self.add_future_contract(self._gc_contract)
def get_contract(self, chains: FuturesChains, canonical: Symbol) -> Symbol:
df = chains.data_frame
# Index by the requested underlying, by getting all data with canonicals which underlying is the requested underlying symbol:
canonicals = df.index.get_level_values('canonical')
condition = [symbol for symbol in canonicals if symbol == canonical]
contracts = df.loc[condition]
# Get contracts expiring within 6 months, with the latest expiration date, and lowest price
contracts = contracts.loc[(df.expiry <= self.time + timedelta(days=180))]
contracts = contracts.sort_values(['expiry', 'lastprice'], ascending=[False, True])
return contracts.index[0][1]
def on_data(self, data):
# Do some trading with the selected contract for sample purposes
if not self.portfolio.invested:
self.set_holdings(self._es_contract, 0.25)
self.set_holdings(self._gc_contract, 0.25)
else:
self.liquidate()
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Futures framework algorithm that uses open interest to select the active contract.
|
```python
from AlgorithmImports import *
class OpenInterestFuturesRegressionAlgorithm(QCAlgorithm):
expected_expiry_dates = {datetime(2013, 12, 27), datetime(2014,2,26)}
def initialize(self):
self.universe_settings.resolution = Resolution.TICK
self.set_start_date(2013,10,8)
self.set_end_date(2013,10,11)
self.set_cash(10000000)
# set framework models
universe = OpenInterestFutureUniverseSelectionModel(self, lambda date_time: [Symbol.create(Futures.Metals.GOLD, SecurityType.FUTURE, Market.COMEX)], None, len(self.expected_expiry_dates))
self.set_universe_selection(universe)
def on_data(self,data):
if self.transactions.orders_count == 0 and data.has_data:
matched = list(filter(lambda s: not (s.id.date in self.expected_expiry_dates) and not s.is_canonical(), data.keys()))
if len(matched) != 0:
raise AssertionError(f"{len(matched)}/{len(data.keys())} were unexpected expiry date(s): " + ", ".join(list(map(lambda x: x.id.date, matched))))
for symbol in data.keys():
self.market_order(symbol, 1)
elif any(p.value.invested for p in self.portfolio):
self.liquidate()
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This regression algorithm tests Out of The Money (OTM) future option expiry for calls.
We expect 2 orders from the algorithm, which are:
* Initial entry, buy ES Call Option (expiring OTM)
- contract expires worthless, not exercised, so never opened a position in the underlying
* Liquidation of worthless ES call option (expiring OTM)
Additionally, we test delistings for future options and assert that our
portfolio holdings reflect the orders the algorithm has submitted.
|
```python
from AlgorithmImports import *
class FutureOptionCallOTMExpiryRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2020, 1, 5)
self.set_end_date(2020, 6, 30)
self.es19m20 = self.add_future_contract(
Symbol.create_future(
Futures.Indices.SP_500_E_MINI,
Market.CME,
datetime(2020, 6, 19)),
Resolution.MINUTE).symbol
# Select a future option expiring ITM, and adds it to the algorithm.
self.es_option = self.add_future_option_contract(
list(
sorted(
[x for x in self.option_chain(self.es19m20)
if x.id.strike_price >= 3300.0 and x.id.option_right == OptionRight.CALL],
key=lambda x: x.id.strike_price
)
)[0], Resolution.MINUTE).symbol
self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3300.0, datetime(2020, 6, 19))
if self.es_option != self.expected_contract:
raise AssertionError(f"Contract {self.expected_contract} was not found in the chain")
# Place order after regular market opens
self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)
def scheduled_market_order(self):
self.market_order(self.es_option, 1)
def on_data(self, data: Slice):
# Assert delistings, so that we can make sure that we receive the delisting warnings at
# the expected time. These assertions detect bug #4872
for delisting in data.delistings.values():
if delisting.type == DelistingType.WARNING:
if delisting.time != datetime(2020, 6, 19):
raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}")
if delisting.type == DelistingType.DELISTED:
if delisting.time != datetime(2020, 6, 20):
raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}")
def on_order_event(self, order_event: OrderEvent):
if order_event.status != OrderStatus.FILLED:
# There's lots of noise with OnOrderEvent, but we're only interested in fills.
return
if not self.securities.contains_key(order_event.symbol):
raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
security = self.securities[order_event.symbol]
if security.symbol == self.es19m20:
raise AssertionError("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM")
# Expected contract is ES19M20 Call Option expiring OTM @ 3300
if (security.symbol == self.expected_contract):
self.assert_future_option_contract_order(order_event, security)
else:
raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")
self.log(f"{order_event}")
def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):
if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:
raise AssertionError(f"No holdings were created for option contract {option.symbol}")
if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:
raise AssertionError("Holdings were found after a filled option exercise")
if order_event.direction == OrderDirection.SELL and "OTM" not in order_event.message:
raise AssertionError("Contract did not expire OTM")
if "Exercise" in order_event.message:
raise AssertionError("Exercised option, even though it expires OTM")
def on_end_of_algorithm(self):
if self.portfolio.invested:
raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting we can specify a custom Shortable Provider
|
```python
from AlgorithmImports import *
class CustomShortableProviderRegressionAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_cash(10000000)
self.set_start_date(2013,10,4)
self.set_end_date(2013,10,6)
self._spy = self.add_security(SecurityType.EQUITY, "SPY", Resolution.DAILY)
self._spy.set_shortable_provider(CustomShortableProvider())
def on_data(self, data: Slice) -> None:
spy_shortable_quantity = self._spy.shortable_provider.shortable_quantity(self._spy.symbol, self.time)
if spy_shortable_quantity and spy_shortable_quantity > 1000:
self._order_id = self.sell("SPY", int(spy_shortable_quantity)).order_id
def on_end_of_algorithm(self) -> None:
transactions = self.transactions.orders_count
if transactions != 1:
raise AssertionError("Algorithm should have just 1 order, but was " + str(transactions))
order_quantity = self.transactions.get_order_by_id(self._order_id).quantity
if order_quantity != -1001:
raise AssertionError(f"Quantity of order {self._order_id} should be -1001 but was {order_quantity}")
fee_rate = self._spy.shortable_provider.fee_rate(self._spy.symbol, self.time)
if fee_rate != 0.0025:
raise AssertionError(f"Fee rate should be 0.0025, but was {fee_rate}")
rebate_rate = self._spy.shortable_provider.rebate_rate(self._spy.symbol, self.time)
if rebate_rate != 0.0507:
raise AssertionError(f"Rebate rate should be 0.0507, but was {rebate_rate}")
class CustomShortableProvider(NullShortableProvider):
def fee_rate(self, symbol: Symbol, local_time: datetime) -> float:
return 0.0025
def rebate_rate(self, symbol: Symbol, local_time: datetime) -> float:
return 0.0507
def shortable_quantity(self, symbol: Symbol, local_time: datetime) -> int:
if local_time < datetime(2013,10,4,16,0,0):
return 10
return 1001
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm testing history requests for <see cref="OptionUniverse"/> type work as expected
and return the same data as the option chain provider.
|
```python
from AlgorithmImports import *
class OptionUniverseHistoryRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2015, 12, 25)
self.set_end_date(2015, 12, 25)
option = self.add_option("GOOG").symbol
historical_options_data_df = self.history(option, 3, flatten=True)
# Level 0 of the multi-index is the date, we expect 3 dates, 3 option chains
if historical_options_data_df.index.levshape[0] != 3:
raise AssertionError(f"Expected 3 option chains from history request, but got {historical_options_data_df.index.levshape[1]}")
for date in historical_options_data_df.index.levels[0]:
expected_chain = list(self.option_chain_provider.get_option_contract_list(option, date))
expected_chain_count = len(expected_chain)
actual_chain = historical_options_data_df.loc[date]
actual_chain_count = len(actual_chain)
if expected_chain_count != actual_chain_count:
raise AssertionError(f"Expected {expected_chain_count} options in chain on {date}, but got {actual_chain_count}")
for i, symbol in enumerate(actual_chain.index):
expected_symbol = expected_chain[i]
if symbol != expected_symbol:
raise AssertionError(f"Expected symbol {expected_symbol} at index {i} on {date}, but got {symbol}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Basic template framework algorithm uses framework components to define the algorithm.
|
```python
from AlgorithmImports import *
class BasicTemplateFrameworkAlgorithm(QCAlgorithm):
'''Basic template framework algorithm uses framework components to define the algorithm.'''
def initialize(self):
'''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
# Set requested data resolution
self.universe_settings.resolution = Resolution.MINUTE
self.set_start_date(2013,10,7) #Set Start Date
self.set_end_date(2013,10,11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
# Forex, CFD, Equities Resolutions: Tick, Second, Minute, Hour, Daily.
# Futures Resolution: Tick, Second, Minute
# Options Resolution: Minute Only.
symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]
# set algorithm framework models
self.set_universe_selection(ManualUniverseSelectionModel(symbols))
self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))
# We can define how often the EWPCM will rebalance if no new insight is submitted using:
# Resolution Enum:
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.DAILY))
# timedelta
# self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(timedelta(2)))
# A lamdda datetime -> datetime. In this case, we can use the pre-defined func at Expiry helper class
# self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Expiry.END_OF_WEEK))
self.set_execution(ImmediateExecutionModel())
self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))
self.debug("numpy test >>> print numpy.pi: " + str(np.pi))
def on_order_event(self, order_event):
if order_event.status == OrderStatus.FILLED:
self.debug("Purchased Stock: {0}".format(order_event.symbol))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm to test universe additions and removals with open positions
|
```python
from AlgorithmImports import *
class InceptionDateSelectionRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013,10,1)
self.set_end_date(2013,10,31)
self.set_cash(100000)
self.changes = None
self.universe_settings.resolution = Resolution.HOUR
# select IBM once a week, empty universe the other days
self.add_universe_selection(CustomUniverseSelectionModel("my-custom-universe", lambda dt: ["IBM"] if dt.day % 7 == 0 else []))
# Adds SPY 5 days after StartDate and keep it in Universe
self.add_universe_selection(InceptionDateUniverseSelectionModel("spy-inception", {"SPY": self.start_date + timedelta(5)}))
def on_data(self, slice):
if self.changes is None:
return
# we'll simply go long each security we added to the universe
for security in self.changes.added_securities:
self.set_holdings(security.symbol, .5)
self.changes = None
def on_securities_changed(self, changes):
# liquidate removed securities
for security in changes.removed_securities:
self.liquidate(security.symbol, "Removed from Universe")
self.changes = changes
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Demonstration of the Market On Close order for US Equities.
|
```python
from AlgorithmImports import *
class MarketOnOpenOnCloseAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013,10,7) #Set Start Date
self.set_end_date(2013,10,11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.equity = self.add_equity("SPY", Resolution.SECOND, fill_forward = True, extended_market_hours = True)
self.__submitted_market_on_close_today = False
self.__last = datetime.min
def on_data(self, data):
'''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
if self.time.date() != self.__last.date(): # each morning submit a market on open order
self.__submitted_market_on_close_today = False
self.market_on_open_order("SPY", 100)
self.__last = self.time
if not self.__submitted_market_on_close_today and self.equity.exchange.exchange_open: # once the exchange opens submit a market on close order
self.__submitted_market_on_close_today = True
self.market_on_close_order("SPY", -100)
def on_order_event(self, fill):
order = self.transactions.get_order_by_id(fill.order_id)
self.log("{0} - {1}:: {2}".format(self.time, order.type, fill))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm illustrating the usage of the <see cref="QCAlgorithm.OptionChain(Symbol)"/> method
to get an option chain, which contains additional data besides the symbols, including prices, implied volatility and greeks.
It also shows how this data can be used to filter the contracts based on certain criteria.
|
```python
from AlgorithmImports import *
from datetime import timedelta
class OptionChainFullDataRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2015, 12, 24)
self.set_end_date(2015, 12, 24)
self.set_cash(100000)
goog = self.add_equity("GOOG").symbol
option_chain = self.option_chain(goog, flatten=True)
# Demonstration using data frame:
df = option_chain.data_frame
# Get contracts expiring within 10 days, with an implied volatility greater than 0.5 and a delta less than 0.5
contracts = df.loc[(df.expiry <= self.time + timedelta(days=10)) & (df.impliedvolatility > 0.5) & (df.delta < 0.5)]
# Get the contract with the latest expiration date.
# Note: the result of df.loc[] is a series, and its name is a tuple with a single element (contract symbol)
self._option_contract = contracts.loc[contracts.expiry.idxmax()].name
self.add_option_contract(self._option_contract)
def on_data(self, data):
# Do some trading with the selected contract for sample purposes
if not self.portfolio.invested:
self.market_order(self._option_contract, 1)
else:
self.liquidate()
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This regression test is a version of "MarketOnCloseOrderBufferRegressionAlgorithm"
|
```python
from AlgorithmImports import *
class MarketOnCloseOrderBufferExtendedMarketHoursRegressionAlgorithm(QCAlgorithm):
'''This regression test is a version of "MarketOnCloseOrderBufferRegressionAlgorithm"
where we test market-on-close modeling with data from the post market.'''
_valid_order_ticket = None
_invalid_order_ticket = None
_valid_order_ticket_extended_market_hours = None
def initialize(self) -> None:
self.set_start_date(2013,10,7) #Set Start Date
self.set_end_date(2013,10,8) #Set End Date
self.add_equity("SPY", Resolution.MINUTE, extended_market_hours = True)
def moc_at_mid_night():
self._valid_order_ticket_at_midnight = self.market_on_close_order("SPY", 2)
self.schedule.on(self.date_rules.tomorrow, self.time_rules.midnight, moc_at_mid_night)
# Modify our submission buffer time to 10 minutes
MarketOnCloseOrder.submission_time_buffer = timedelta(minutes=10)
def on_data(self, data: Slice) -> None:
# Test our ability to submit MarketOnCloseOrders
# Because we set our buffer to 10 minutes, any order placed
# before 3:50PM should be accepted, any after marked invalid
# Will not throw an order error and execute
if self.time.hour == 15 and self.time.minute == 49 and not self._valid_order_ticket:
self._valid_order_ticket = self.market_on_close_order("SPY", 2)
# Will throw an order error and be marked invalid
if self.time.hour == 15 and self.time.minute == 51 and not self._invalid_order_ticket:
self._invalid_order_ticket = self.market_on_close_order("SPY", 2)
# Will not throw an order error and execute
if self.time.hour == 16 and self.time.minute == 48 and not self._valid_order_ticket_extended_market_hours:
self._valid_order_ticket_extended_market_hours = self.market_on_close_order("SPY", 2)
def on_end_of_algorithm(self) -> None:
# Set it back to default for other regressions
MarketOnCloseOrder.submission_time_buffer = MarketOnCloseOrder.DEFAULT_SUBMISSION_TIME_BUFFER
if self._valid_order_ticket.status != OrderStatus.FILLED:
raise AssertionError("Valid order failed to fill")
if self._invalid_order_ticket.status != OrderStatus.INVALID:
raise AssertionError("Invalid order was not rejected")
if self._valid_order_ticket_extended_market_hours.status != OrderStatus.FILLED:
raise AssertionError("Valid order during extended market hours failed to fill")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm testing history requests for <see cref="FutureUniverse"/> type work as expected
and return the same data as the futures chain provider.
|
```python
from AlgorithmImports import *
class OptionUniverseHistoryRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 11)
self.set_end_date(2013, 10, 11)
future = self.add_future(Futures.Indices.SP_500_E_MINI).symbol
historical_futures_data_df = self.history(FutureUniverse, future, 3, flatten=True)
# Level 0 of the multi-index is the date, we expect 3 dates, 3 future chains
if historical_futures_data_df.index.levshape[0] != 3:
raise RegressionTestException(f"Expected 3 futures chains from history request, "
f"but got {historical_futures_data_df.index.levshape[1]}")
for date in historical_futures_data_df.index.levels[0]:
expected_chain = list(self.future_chain_provider.get_future_contract_list(future, date))
expected_chain_count = len(expected_chain)
actual_chain = historical_futures_data_df.loc[date]
actual_chain_count = len(actual_chain)
if expected_chain_count != actual_chain_count:
raise RegressionTestException(f"Expected {expected_chain_count} futures in chain on {date}, "
f"but got {actual_chain_count}")
for i, symbol in enumerate(actual_chain.index):
expected_symbol = expected_chain[i]
if symbol != expected_symbol:
raise RegressionTestException(f"Expected symbol {expected_symbol} at index "
f" {i} on {date}, but got {symbol}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: def initialize(self) -> None:
|
```python
from AlgorithmImports import *
# <summary>
# Regression algorithm to test the behaviour of ARMA versus AR models at the same order of differencing.
# In particular, an ARIMA(1,1,1) and ARIMA(1,1,0) are instantiated while orders are placed if their difference
# is sufficiently large (which would be due to the inclusion of the MA(1) term).
# </summary>
class AutoRegressiveIntegratedMovingAverageRegressionAlgorithm(QCAlgorithm):
def initialize(self) -> None:
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013, 1, 7)
self.set_end_date(2013, 12, 11)
self.settings.automatic_indicator_warm_up = True
self.add_equity("SPY", Resolution.DAILY)
self._arima = self.arima("SPY", 1, 1, 1, 50)
self._ar = self.arima("SPY", 1, 1, 0, 50)
self._last = None
def on_data(self, data: Slice) -> None:
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''
if self._arima.is_ready:
if abs(self._arima.current.value - self._ar.current.value) > 1:
if self._arima.current.value > self._last:
self.market_order("SPY", 1)
else:
self.market_order("SPY", -1)
self._last = self._arima.current.value
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: In this algorithm we show how you can easily use the universe selection feature to fetch symbols
to be traded using the BaseData custom data system in combination with the AddUniverse{T} method.
AddUniverse{T} requires a function that will return the symbols to be traded.
|
```python
from AlgorithmImports import *
class DropboxBaseDataUniverseSelectionAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.universe_settings.resolution = Resolution.DAILY
# Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
# Commented so regression algorithm is more sensitive
#self.settings.minimum_order_margin_portfolio_percentage = 0.005
self.set_start_date(2017, 7, 6)
self.set_end_date(2018, 7, 4)
universe = self.add_universe(StockDataSource, self.stock_data_source)
historical_selection_data = self.history(universe, 3)
if len(historical_selection_data) != 3:
raise ValueError(f"Unexpected universe data count {len(historical_selection_data)}")
for universe_data in historical_selection_data["symbols"]:
if len(universe_data) != 5:
raise ValueError(f"Unexpected universe data receieved")
self._changes = None
def stock_data_source(self, data: list[DynamicData]) -> list[Symbol]:
list = []
for item in data:
for symbol in item["Symbols"]:
list.append(symbol)
return list
def on_data(self, slice: Slice) -> None:
if slice.bars.count == 0:
return
if not self._changes:
return
# start fresh
self.liquidate()
percentage = 1 / slice.bars.count
for trade_bar in slice.bars.values():
self.set_holdings(trade_bar.symbol, percentage)
# reset changes
self._changes = None
def on_securities_changed(self, changes: SecurityChanges) -> None:
self._changes = changes
class StockDataSource(PythonData):
def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource:
url = "https://www.dropbox.com/s/2l73mu97gcehmh7/daily-stock-picker-live.csv?dl=1" if is_live_mode else \
"https://www.dropbox.com/s/ae1couew5ir3z9y/daily-stock-picker-backtest.csv?dl=1"
return SubscriptionDataSource(url, SubscriptionTransportMedium.REMOTE_FILE)
def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> DynamicData:
if not (line.strip() and line[0].isdigit()):
return None
stocks = StockDataSource()
stocks.symbol = config.symbol
csv = line.split(',')
if is_live_mode:
stocks.time = date
stocks["Symbols"] = csv
else:
stocks.time = datetime.strptime(csv[0], "%Y%m%d")
stocks["Symbols"] = csv[1:]
return stocks
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm checks that adding data via AddData
works as expected
|
```python
from AlgorithmImports import *
from QuantConnect.Data.Custom.IconicTypes import *
class CustomDataIconicTypesAddDataRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 11)
self.set_cash(100000)
twx_equity = self.add_equity("TWX", Resolution.DAILY).symbol
custom_twx_symbol = self.add_data(LinkedData, twx_equity, Resolution.DAILY).symbol
self.googl_equity = self.add_equity("GOOGL", Resolution.DAILY).symbol
custom_googl_symbol = self.add_data(LinkedData, "GOOGL", Resolution.DAILY).symbol
unlinked_data_symbol = self.add_data(UnlinkedData, "GOOGL", Resolution.DAILY).symbol
unlinked_data_symbol_underlying_equity = Symbol.create("MSFT", SecurityType.EQUITY, Market.USA)
unlinked_data_symbol_underlying = self.add_data(UnlinkedData, unlinked_data_symbol_underlying_equity, Resolution.DAILY).symbol
option_symbol = self.add_option("TWX", Resolution.MINUTE).symbol
custom_option_symbol = self.add_data(LinkedData, option_symbol, Resolution.DAILY).symbol
if custom_twx_symbol.underlying != twx_equity:
raise AssertionError(f"Underlying symbol for {custom_twx_symbol} is not equal to TWX equity. Expected {twx_equity} got {custom_twx_symbol.underlying}")
if custom_googl_symbol.underlying != self.googl_equity:
raise AssertionError(f"Underlying symbol for {custom_googl_symbol} is not equal to GOOGL equity. Expected {self.googl_equity} got {custom_googl_symbol.underlying}")
if unlinked_data_symbol.has_underlying:
raise AssertionError(f"Unlinked data type (no underlying) has underlying when it shouldn't. Found {unlinked_data_symbol.underlying}")
if not unlinked_data_symbol_underlying.has_underlying:
raise AssertionError("Unlinked data type (with underlying) has no underlying Symbol even though we added with Symbol")
if unlinked_data_symbol_underlying.underlying != unlinked_data_symbol_underlying_equity:
raise AssertionError(f"Unlinked data type underlying does not equal equity Symbol added. Expected {unlinked_data_symbol_underlying_equity} got {unlinked_data_symbol_underlying.underlying}")
if custom_option_symbol.underlying != option_symbol:
raise AssertionError(f"Option symbol not equal to custom underlying symbol. Expected {option_symbol} got {custom_option_symbol.underlying}")
try:
custom_data_no_cache = self.add_data(LinkedData, "AAPL", Resolution.DAILY)
raise AssertionError("AAPL was found in the SymbolCache, though it should be missing")
except InvalidOperationException as e:
return
def on_data(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''
if not self.portfolio.invested and len(self.transactions.get_open_orders()) == 0:
self.set_holdings(self.googl_equity, 0.5)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Using rolling windows for efficient storage of historical data; which automatically clears after a period of time.
|
```python
from AlgorithmImports import *
class RollingWindowAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013,10,1) #Set Start Date
self.set_end_date(2013,11,1) #Set End Date
self.set_cash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.add_equity("SPY", Resolution.DAILY)
# Creates a Rolling Window indicator to keep the 2 TradeBar
self._window = RollingWindow(2) # For other security types, use QuoteBar
# Creates an indicator and adds to a rolling window when it is updated
self._sma = self.sma("SPY", 5)
self._sma.updated += self._sma_updated
self._sma_win = RollingWindow(5)
def _sma_updated(self, sender, updated):
'''Adds updated values to rolling window'''
self._sma_win.add(updated)
def on_data(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
# Add SPY TradeBar in rollling window
self._window.add(data["SPY"])
# Wait for windows to be ready.
if not (self._window.is_ready and self._sma_win.is_ready): return
curr_bar = self._window[0] # Current bar had index zero.
past_bar = self._window[1] # Past bar has index one.
self.log(f"Price: {past_bar.time} -> {past_bar.close} ... {curr_bar.time} -> {curr_bar.close}")
curr_sma = self._sma_win[0] # Current SMA had index zero.
past_sma = self._sma_win[self._sma_win.count-1] # Oldest SMA has index of window count minus 1.
self.log(f"SMA: {past_sma.time} -> {past_sma.value} ... {curr_sma.time} -> {curr_sma.value}")
if not self.portfolio.invested and curr_sma.value > past_sma.value:
self.set_holdings("SPY", 1)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This example demonstrates how to implement a cross moving average for the futures front contract
|
```python
from AlgorithmImports import *
class EmaCrossFuturesFrontMonthAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 8)
self.set_end_date(2013, 10, 10)
self.set_cash(1000000)
future = self.add_future(Futures.Metals.GOLD)
# Only consider the front month contract
# Update the universe once per day to improve performance
future.set_filter(lambda x: x.front_month().only_apply_filter_at_market_open())
# Symbol of the current contract
self._symbol = None
# Create two exponential moving averages
self.fast = ExponentialMovingAverage(100)
self.slow = ExponentialMovingAverage(300)
self.tolerance = 0.001
self.consolidator = None
# Add a custom chart to track the EMA cross
chart = Chart('EMA Cross')
chart.add_series(Series('Fast', SeriesType.LINE, 0))
chart.add_series(Series('Slow', SeriesType.LINE, 0))
self.add_chart(chart)
def on_data(self,slice):
holding = None if self._symbol is None else self.portfolio.get(self._symbol)
if holding is not None:
# Buy the futures' front contract when the fast EMA is above the slow one
if self.fast.current.value > self.slow.current.value * (1 + self.tolerance):
if not holding.invested:
self.set_holdings(self._symbol, .1)
self.plot_ema()
elif holding.invested:
self.liquidate(self._symbol)
self.plot_ema()
def on_securities_changed(self, changes):
if len(changes.removed_securities) > 0:
# Remove the consolidator for the previous contract
# and reset the indicators
if self._symbol is not None and self.consolidator is not None:
self.subscription_manager.remove_consolidator(self._symbol, self.consolidator)
self.fast.reset()
self.slow.reset()
# We don't need to call Liquidate(_symbol),
# since its positions are liquidated because the contract has expired.
# Only one security will be added: the new front contract
self._symbol = changes.added_securities[0].symbol
# Create a new consolidator and register the indicators to it
self.consolidator = self.resolve_consolidator(self._symbol, Resolution.MINUTE)
self.register_indicator(self._symbol, self.fast, self.consolidator)
self.register_indicator(self._symbol, self.slow, self.consolidator)
# Warm up the indicators
self.warm_up_indicator(self._symbol, self.fast, Resolution.MINUTE)
self.warm_up_indicator(self._symbol, self.slow, Resolution.MINUTE)
self.plot_ema()
def plot_ema(self):
self.plot('EMA Cross', 'Fast', self.fast.current.value)
self.plot('EMA Cross', 'Slow', self.slow.current.value)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: The demonstration algorithm shows some of the most common order methods when working with CFD assets.
|
```python
from AlgorithmImports import *
class BasicTemplateCfdAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_account_currency('EUR')
self.set_start_date(2019, 2, 20)
self.set_end_date(2019, 2, 21)
self.set_cash('EUR', 100000)
self._symbol = self.add_cfd('DE30EUR').symbol
# Historical Data
history = self.history(self._symbol, 60, Resolution.DAILY)
self.log(f"Received {len(history)} bars from CFD historical data call.")
def on_data(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
slice: Slice object keyed by symbol containing the stock data
'''
# Access Data
if data.quote_bars.contains_key(self._symbol):
quote_bar = data.quote_bars[self._symbol]
self.log(f"{quote_bar.end_time} :: {quote_bar.close}")
if not self.portfolio.invested:
self.set_holdings(self._symbol, 1)
def on_order_event(self, order_event):
self.debug("{} {}".format(self.time, order_event.to_string()))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This algorithm tests and demonstrates EUREX futures subscription and trading:
- It tests contracts rollover by adding a continuous future and asserting that mapping happens at some point.
- It tests basic trading by buying a contract and holding it until expiration.
- It tests delisting and asserts the holdings are liquidated after that.
|
```python
from AlgorithmImports import *
class BasicTemplateEurexFuturesAlgorithm(QCAlgorithm):
def __init__(self):
super().__init__()
self._continuous_contract = None
self._mapped_symbol = None
self._contract_to_trade = None
self._mappings_count = 0
self._bought_quantity = 0
self._liquidated_quantity = 0
self._delisted = False
def initialize(self):
self.set_start_date(2024, 5, 30)
self.set_end_date(2024, 6, 23)
self.set_account_currency(Currencies.EUR);
self.set_cash(1000000)
self._continuous_contract = self.add_future(
Futures.Indices.EURO_STOXX_50,
Resolution.MINUTE,
data_normalization_mode=DataNormalizationMode.BACKWARDS_RATIO,
data_mapping_mode=DataMappingMode.FIRST_DAY_MONTH,
contract_depth_offset=0,
)
self._continuous_contract.set_filter(timedelta(days=0), timedelta(days=180))
self._mapped_symbol = self._continuous_contract.mapped
benchmark = self.add_index("SX5E")
self.set_benchmark(benchmark.symbol)
func_seeder = FuncSecuritySeeder(self.get_last_known_prices)
self.set_security_initializer(lambda security: func_seeder.seed_security(security))
def on_data(self, slice):
for changed_event in slice.symbol_changed_events.values():
self._mappings_count += 1
if self._mappings_count > 1:
raise AssertionError(f"{self.time} - Unexpected number of symbol changed events (mappings): {self._mappings_count}. Expected only 1.")
self.debug(f"{self.time} - SymbolChanged event: {changed_event}")
if changed_event.old_symbol != str(self._mapped_symbol.id):
raise AssertionError(f"{self.time} - Unexpected symbol changed event old symbol: {changed_event}")
if changed_event.new_symbol != str(self._continuous_contract.mapped.id):
raise AssertionError(f"{self.time} - Unexpected symbol changed event new symbol: {changed_event}")
# Let's trade the previous mapped contract, so we can hold it until expiration for testing
# (will be sooner than the new mapped contract)
self._contract_to_trade = self._mapped_symbol
self._mapped_symbol = self._continuous_contract.mapped
# Let's trade after the mapping is done
if self._contract_to_trade is not None and self._bought_quantity == 0 and self.securities[self._contract_to_trade].exchange.exchange_open:
self.buy(self._contract_to_trade, 1)
if self._contract_to_trade is not None and slice.delistings.contains_key(self._contract_to_trade):
delisting = slice.delistings[self._contract_to_trade]
if delisting.type == DelistingType.DELISTED:
self._delisted = True
if self.portfolio.invested:
raise AssertionError(f"{self.time} - Portfolio should not be invested after the traded contract is delisted.")
def on_order_event(self, order_event):
if order_event.symbol != self._contract_to_trade:
raise AssertionError(f"{self.time} - Unexpected order event symbol: {order_event.symbol}. Expected {self._contract_to_trade}")
if order_event.direction == OrderDirection.BUY:
if order_event.status == OrderStatus.FILLED:
if self._bought_quantity != 0 and self._liquidated_quantity != 0:
raise AssertionError(f"{self.time} - Unexpected buy order event status: {order_event.status}")
self._bought_quantity = order_event.quantity
elif order_event.direction == OrderDirection.SELL:
if order_event.status == OrderStatus.FILLED:
if self._bought_quantity <= 0 and self._liquidated_quantity != 0:
raise AssertionError(f"{self.time} - Unexpected sell order event status: {order_event.status}")
self._liquidated_quantity = order_event.quantity
if self._liquidated_quantity != -self._bought_quantity:
raise AssertionError(f"{self.time} - Unexpected liquidated quantity: {self._liquidated_quantity}. Expected: {-self._bought_quantity}")
def on_securities_changed(self, changes):
for added_security in changes.added_securities:
if added_security.symbol.security_type == SecurityType.FUTURE and added_security.symbol.is_canonical():
self._mapped_symbol = self._continuous_contract.mapped
def on_end_of_algorithm(self):
if self._mappings_count == 0:
raise AssertionError(f"Unexpected number of symbol changed events (mappings): {self._mappings_count}. Expected 1.")
if not self._delisted:
raise AssertionError("Contract was not delisted")
# Make sure we traded and that the position was liquidated on delisting
if self._bought_quantity <= 0 or self._liquidated_quantity >= 0:
raise AssertionError(f"Unexpected sold quantity: {self._bought_quantity} and liquidated quantity: {self._liquidated_quantity}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Strategy example algorithm using CAPE - a bubble indicator dataset saved in dropbox. CAPE is based on a macroeconomic indicator(CAPE Ratio),
we are looking for entry/exit points for momentum stocks CAPE data: January 1990 - December 2014
Goals:
Capitalize in overvalued markets by generating returns with momentum and selling before the crash
Capitalize in undervalued markets by purchasing stocks at bottom of trough
|
```python
# 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 *
class BubbleAlgorithm(QCAlgorithm):
def initialize(self):
self.set_cash(100000)
self.set_start_date(1998,1,1)
self.set_end_date(2014,6,1)
self._symbols = []
self._macd_dic, self._rsi_dic = {},{}
self._new_low, self._curr_cape = None, None
self._counter, self._counter2 = 0, 0
self._c, self._c_copy = np.empty([4]), np.empty([4])
self._symbols.append("SPY")
# add CAPE data
self.add_data(Cape, "CAPE")
# # Present Social Media Stocks:
# self._symbols.append("FB"), self._symbols.append("LNKD"),self._symbols.append("GRPN"), self._symbols.append("TWTR")
# self.set_start_date(2011, 1, 1)
# self.set_end_date(2014, 12, 1)
# # 2008 Financials
# self._symbols.append("C"), self._symbols.append("AIG"), self._symbols.append("BAC"), self._symbols.append("HBOS")
# self.set_start_date(2003, 1, 1)
# self.set_end_date(2011, 1, 1)
# # 2000 Dot.com
# self._symbols.append("IPET"), self._symbols.append("WBVN"), self._symbols.append("GCTY")
# self.set_start_date(1998, 1, 1)
# self.set_end_date(2000, 1, 1)
for stock in self._symbols:
self.add_security(SecurityType.EQUITY, stock, Resolution.MINUTE)
self._macd = self.macd(stock, 12, 26, 9, MovingAverageType.EXPONENTIAL, Resolution.DAILY)
self._macd_dic[stock] = self._macd
self._rsi = self.rsi(stock, 14, MovingAverageType.EXPONENTIAL, Resolution.DAILY)
self._rsi_dic[stock] = self._rsi
# Trying to find if current Cape is the lowest Cape in three months to indicate selling period
def on_data(self, data):
if self._curr_cape and self._new_low is not None:
try:
# Bubble territory
if self._curr_cape > 20 and self._new_low == False:
for stock in self._symbols:
# Order stock based on MACD
# During market hours, stock is trading, and sufficient cash
if self.securities[stock].holdings.quantity == 0 and self._rsi_dic[stock].current.value < 70 \
and self.securities[stock].price != 0 \
and self.portfolio.cash > self.securities[stock].price * 100 \
and self.time.hour == 9 and self.time.minute == 31:
self.buy_stock(stock)
# Utilize RSI for overbought territories and liquidate that stock
if self._rsi_dic[stock].current.value > 70 and self.securities[stock].holdings.quantity > 0 \
and self.time.hour == 9 and self.time.minute == 31:
self.sell_stock(stock)
# Undervalued territory
elif self._new_low:
for stock in self._symbols:
# Sell stock based on MACD
if self.securities[stock].holdings.quantity > 0 and self._rsi_dic[stock].current.value > 30 \
and self.time.hour == 9 and self.time.minute == 31:
self.sell_stock(stock)
# Utilize RSI and MACD to understand oversold territories
elif self.securities[stock].holdings.quantity == 0 and self._rsi_dic[stock].current.value < 30 \
and self.securities[stock].price != 0 and self.portfolio.cash > self.securities[stock].price * 100 \
and self.time.hour == 9 and self.time.minute == 31:
self.buy_stock(stock)
# Cape Ratio is missing from original data
# Most recent cape data is most likely to be missing
elif self._curr_cape == 0:
self.debug("Exiting due to no CAPE!")
self.quit("CAPE ratio not supplied in data, exiting.")
except:
# Do nothing
return None
if not data.contains_key("CAPE"): return
self._new_low = False
# Adds first four Cape Ratios to array c
self._curr_cape = data["CAPE"].cape
if self._counter < 4:
self._c[self._counter] = self._curr_cape
self._counter +=1
# Replaces oldest Cape with current Cape
# Checks to see if current Cape is lowest in the previous quarter
# Indicating a sell off
else:
self._c_copy = self._c
self._c_copy = np.sort(self._c_copy)
if self._c_copy[0] > self._curr_cape:
self._new_low = True
self._c[self._counter2] = self._curr_cape
self._counter2 += 1
if self._counter2 == 4: self._counter2 = 0
self.debug("Current Cape: " + str(self._curr_cape) + " on " + str(self.time))
if self._new_low:
self.debug("New Low has been hit on " + str(self.time))
# Buy this symbol
def buy_stock(self,symbol):
s = self.securities[symbol].holdings
if self._macd_dic[symbol].current.value>0:
self.set_holdings(symbol, 1)
self.debug("Purchasing: " + str(symbol) + " MACD: " + str(self._macd_dic[symbol]) + " RSI: " + str(self._rsi_dic[symbol])
+ " Price: " + str(round(self.securities[symbol].price, 2)) + " Quantity: " + str(s.quantity))
# Sell this symbol
def sell_stock(self,symbol):
s = self.securities[symbol].holdings
if s.quantity > 0 and self._macd_dic[symbol].current.value < 0:
self.liquidate(symbol)
self.debug("Selling: " + str(symbol) + " at sell MACD: " + str(self._macd_dic[symbol]) + " RSI: " + str(self._rsi_dic[symbol])
+ " Price: " + str(round(self.securities[symbol].price, 2)) + " Profit from sale: " + str(s.last_trade_profit))
# CAPE Ratio for SP500 PE Ratio for avg inflation adjusted earnings for previous ten years Custom Data from DropBox
# Original Data from: http://www.econ.yale.edu/~shiller/data.htm
class Cape(PythonData):
# Return the URL string source of the file. This will be converted to a stream
# <param name="config">Configuration object</param>
# <param name="date">Date of this source file</param>
# <param name="is_live_mode">true if we're in live mode, false for backtesting mode</param>
# <returns>String URL of source file.</returns>
def get_source(self, config, date, is_live_mode):
# Remember to add the "?dl=1" for dropbox links
return SubscriptionDataSource("https://www.dropbox.com/s/ggt6blmib54q36e/CAPE.csv?dl=1", SubscriptionTransportMedium.REMOTE_FILE)
''' Reader Method : using set of arguments we specify read out type. Enumerate until
the end of the data stream or file. E.g. Read CSV file line by line and convert into data types. '''
# <returns>BaseData type set by Subscription Method.</returns>
# <param name="config">Config.</param>
# <param name="line">Line.</param>
# <param name="date">Date.</param>
# <param name="is_live_mode">true if we're in live mode, false for backtesting mode</param>
def reader(self, config, line, date, is_live_mode):
if not (line.strip() and line[0].isdigit()): return None
# New Nifty object
index = Cape()
index.symbol = config.symbol
try:
# Example File Format:
# Date | Price | Div | Earning | CPI | FractionalDate | Interest Rate | RealPrice | RealDiv | RealEarnings | CAPE
# 2014.06 1947.09 37.38 103.12 238.343 2014.37 2.6 1923.95 36.94 101.89 25.55
data = line.split(',')
# Dates must be in the format YYYY-MM-DD. If your data source does not have this format, you must use
# DateTime.parse_exact() and explicit declare the format your data source has.
index.time = datetime.strptime(data[0], "%Y-%m")
index["Cape"] = float(data[10])
index.value = data[10]
except ValueError:
# Do nothing
return None
return index
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This example demonstrates how to add futures for a given underlying asset.
It also shows how you can prefilter contracts easily based on expirations, and how you
can inspect the futures chain to pick a specific contract to trade.
|
```python
from AlgorithmImports import *
class BasicTemplateFuturesAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 8)
self.set_end_date(2013, 10, 10)
self.set_cash(1000000)
self.contract_symbol = None
# Subscribe and set our expiry filter for the futures chain
futureSP500 = self.add_future(Futures.Indices.SP_500_E_MINI)
future_gold = self.add_future(Futures.Metals.GOLD)
# set our expiry filter for this futures chain
# SetFilter method accepts timedelta objects or integer for days.
# The following statements yield the same filtering criteria
futureSP500.set_filter(timedelta(0), timedelta(182))
future_gold.set_filter(0, 182)
benchmark = self.add_equity("SPY")
self.set_benchmark(benchmark.symbol)
seeder = FuncSecuritySeeder(self.get_last_known_prices)
self.set_security_initializer(lambda security: seeder.seed_security(security))
def on_data(self,slice):
if not self.portfolio.invested:
for chain in slice.future_chains:
# Get contracts expiring no earlier than in 90 days
contracts = list(filter(lambda x: x.expiry > self.time + timedelta(90), chain.value))
# if there is any contract, trade the front contract
if len(contracts) == 0: continue
front = sorted(contracts, key = lambda x: x.expiry, reverse=True)[0]
self.contract_symbol = front.symbol
self.market_order(front.symbol , 1)
else:
self.liquidate()
def on_end_of_algorithm(self):
# Get the margin requirements
buying_power_model = self.securities[self.contract_symbol].buying_power_model
name = type(buying_power_model).__name__
if name != 'FutureMarginModel':
raise AssertionError(f"Invalid buying power model. Found: {name}. Expected: FutureMarginModel")
initial_overnight = buying_power_model.initial_overnight_margin_requirement
maintenance_overnight = buying_power_model.maintenance_overnight_margin_requirement
initial_intraday = buying_power_model.initial_intraday_margin_requirement
maintenance_intraday = buying_power_model.maintenance_intraday_margin_requirement
def on_securities_changed(self, changes):
for added_security in changes.added_securities:
if added_security.symbol.security_type == SecurityType.FUTURE and not added_security.symbol.is_canonical() and not added_security.has_data:
raise AssertionError(f"Future contracts did not work up as expected: {added_security.symbol}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Example algorithm using and asserting the behavior of auxiliary data handlers
|
```python
from AlgorithmImports import *
class AuxiliaryDataHandlersRegressionAlgorithm(QCAlgorithm):
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2007, 5, 16)
self.set_end_date(2015, 1, 1)
self.universe_settings.resolution = Resolution.DAILY
# will get delisted
self.add_equity("AAA.1")
# get's remapped
self.add_equity("SPWR")
# has a split & dividends
self.add_equity("AAPL")
def on_delistings(self, delistings: Delistings):
self._on_delistings_called = True
def on_symbol_changed_events(self, symbolsChanged: SymbolChangedEvents):
self._on_symbol_changed_events = True
def on_splits(self, splits: Splits):
self._on_splits = True
def on_dividends(self, dividends: Dividends):
self._on_dividends = True
def on_end_of_algorithm(self):
if not self._on_delistings_called:
raise ValueError("OnDelistings was not called!")
if not self._on_symbol_changed_events:
raise ValueError("OnSymbolChangedEvents was not called!")
if not self._on_splits:
raise ValueError("OnSplits was not called!")
if not self._on_dividends:
raise ValueError("OnDividends was not called!")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting slice.get() works for both the alpha and the algorithm
|
```python
from AlgorithmImports import *
trade_flag = False
class SliceGetByTypeRegressionAlgorithm(QCAlgorithm):
def initialize(self) -> None:
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013,10, 7)
self.set_end_date(2013,10,11)
self.add_equity("SPY", Resolution.MINUTE)
self.set_alpha(TestAlphaModel())
def on_data(self, data: Slice) -> None:
if "SPY" in data:
tb = data.get(TradeBar)["SPY"]
global trade_flag
if not self.portfolio.invested and trade_flag:
self.set_holdings("SPY", 1)
class TestAlphaModel(AlphaModel):
def update(self, algorithm: QCAlgorithm, data: Slice) -> list[Insight]:
insights = []
if "SPY" in data:
tb = data.get(TradeBar)["SPY"]
global trade_flag
trade_flag = True
return insights
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm illustrating how to request history data for continuous contracts with different depth offsets.
|
```python
from AlgorithmImports import *
class HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 6)
self.set_end_date(2014, 1, 1)
self._continuous_contract_symbol = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.DAILY).symbol
def on_end_of_algorithm(self):
contract_depth_offsets = range(3)
history_results = [
self.history([self._continuous_contract_symbol], self.start_date, self.end_date, Resolution.DAILY, contract_depth_offset=contract_depth_offset)
.droplevel(0, axis=0)
.loc[self._continuous_contract_symbol]
.close
for contract_depth_offset in contract_depth_offsets
]
if any(x.size == 0 or x.size != history_results[0].size for x in history_results):
raise AssertionError("History results are empty or bar counts did not match")
# Check that prices at each time are different for different contract depth offsets
for j in range(history_results[0].size):
close_prices = set(history_results[i][j] for i in range(len(history_results)))
if len(close_prices) != len(contract_depth_offsets):
raise AssertionError("History results close prices should have been different for each data mapping mode at each time")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm testing portfolio construction model control over rebalancing,
specifying a date rules, see GH 4075.
|
```python
from AlgorithmImports import *
class PortfolioRebalanceOnDateRulesRegressionAlgorithm(QCAlgorithm):
def initialize(self):
''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.universe_settings.resolution = Resolution.DAILY
# Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
# Commented so regression algorithm is more sensitive
#self.settings.minimum_order_margin_portfolio_percentage = 0.005
# let's use 0 minimum order margin percentage so we can assert trades are only submitted immediately after rebalance on Wednesday
# if not, due to TPV variations happening every day we might no cross the minimum on wednesday but yes another day of the week
self.settings.minimum_order_margin_portfolio_percentage = 0
self.set_start_date(2015,1,1)
self.set_end_date(2017,1,1)
self.settings.rebalance_portfolio_on_insight_changes = False
self.settings.rebalance_portfolio_on_security_changes = False
self.set_universe_selection(CustomUniverseSelectionModel("CustomUniverseSelectionModel", lambda time: [ "AAPL", "IBM", "FB", "SPY" ]))
self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, TimeSpan.from_minutes(20), 0.025, None))
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(self.date_rules.every(DayOfWeek.WEDNESDAY)))
self.set_execution(ImmediateExecutionModel())
def on_order_event(self, order_event):
if order_event.status == OrderStatus.SUBMITTED:
self.debug(str(order_event))
if self.utc_time.weekday() != 2:
raise ValueError(str(self.utc_time) + " " + str(order_event.symbol) + " " + str(self.utc_time.weekday()))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Demonstration of how to initialize and use the Classic RenkoConsolidator
|
```python
from AlgorithmImports import *
class ClassicRenkoConsolidatorAlgorithm(QCAlgorithm):
'''Demonstration of how to initialize and use the RenkoConsolidator'''
def initialize(self) -> None:
self.set_start_date(2012, 1, 1)
self.set_end_date(2013, 1, 1)
self.add_equity("SPY", Resolution.DAILY)
# this is the simple constructor that will perform the
# renko logic to the Value property of the data it receives.
# break SPY into $2.5 renko bricks and send that data to our 'OnRenkoBar' method
renko_close = ClassicRenkoConsolidator(2.5)
renko_close.data_consolidated += self.handle_renko_close
self.subscription_manager.add_consolidator("SPY", renko_close)
# this is the full constructor that can accept a value selector and a volume selector
# this allows us to perform the renko logic on values other than Close, even computed values!
# break SPY into (2*o + h + l + 3*c)/7
renko7bar = ClassicRenkoConsolidator(2.5, lambda x: (2 * x.open + x.high + x.low + 3 * x.close) / 7, lambda x: x.volume)
renko7bar.data_consolidated += self.handle_renko7_bar
self.subscription_manager.add_consolidator("SPY", renko7bar)
# We're doing our analysis in the on_renko_bar method, but the framework verifies that this method exists, so we define it.
def on_data(self, data: Slice) -> None:
pass
def handle_renko_close(self, sender: object, data: RenkoBar) -> None:
'''This function is called by our renko_close consolidator defined in Initialize()
Args:
data: The new renko bar produced by the consolidator'''
if not self.portfolio.invested:
self.set_holdings(data.symbol, 1)
self.log(f"CLOSE - {data.time} - {data.open} {data.close}")
def handle_renko7_bar(self, sender: object, data: RenkoBar) -> None:
'''This function is called by our renko7bar consolidator defined in Initialize()
Args:
data: The new renko bar produced by the consolidator'''
if self.portfolio.invested:
self.liquidate(data.symbol)
self.log(f"7BAR - {data.time} - {data.open} {data.close}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This algorithm demonstrate how to use Option Strategies (e.g. OptionStrategies.STRADDLE) helper classes to batch send orders for common strategies.
It also shows how you can prefilter contracts easily based on strikes and expirations, and how you can inspect the
option chain to pick a specific option contract to trade.
|
```python
from AlgorithmImports import *
class BasicTemplateOptionStrategyAlgorithm(QCAlgorithm):
def initialize(self):
# Set the cash we'd like to use for our backtest
self.set_cash(1000000)
# Start and end dates for the backtest.
self.set_start_date(2015,12,24)
self.set_end_date(2015,12,24)
# Add assets you'd like to see
option = self.add_option("GOOG")
self.option_symbol = option.symbol
# set our strike/expiry filter for this option chain
# SetFilter method accepts timedelta objects or integer for days.
# The following statements yield the same filtering criteria
option.set_filter(-2, +2, 0, 180)
# option.set_filter(-2,2, timedelta(0), timedelta(180))
# use the underlying equity as the benchmark
self.set_benchmark("GOOG")
def on_data(self,slice):
if not self.portfolio.invested:
for kvp in slice.option_chains:
chain = kvp.value
contracts = sorted(sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike)),
key = lambda x: x.expiry, reverse=False)
if len(contracts) == 0: continue
atm_straddle = contracts[0]
if atm_straddle != None:
self.sell(OptionStrategies.straddle(self.option_symbol, atm_straddle.strike, atm_straddle.expiry), 2)
else:
self.liquidate()
def on_order_event(self, order_event):
self.log(str(order_event))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm to test we can liquidate our portfolio holdings using order properties
|
```python
from AlgorithmImports import *
class CanLiquidateWithOrderPropertiesRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2014, 6, 5)
self.set_end_date(2014, 6, 6)
self.set_cash(100000)
self.open_exchange = datetime(2014, 6, 6, 10, 0, 0)
self.close_exchange = datetime(2014, 6, 6, 16, 0, 0)
self.add_equity("AAPL", resolution = Resolution.MINUTE)
def on_data(self, slice):
if self.time > self.open_exchange and self.time < self.close_exchange:
if not self.portfolio.invested:
self.market_order("AAPL", 10)
else:
order_properties = OrderProperties()
order_properties.time_in_force = TimeInForce.DAY
tickets = self.liquidate(asynchronous = True, order_properties = order_properties)
for ticket in tickets:
if ticket.submit_request.order_properties.time_in_force != TimeInForce.DAY:
raise AssertionError(f"The TimeInForce for all orders should be daily, but it was {ticket.submit_request.order_properties.time_in_force}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression test to demonstrate importing and trading on custom data.
|
```python
import json
from AlgorithmImports import *
class CustomDataRegressionAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2020,1,5) # Set Start Date
self.set_end_date(2020,1,10) # Set End Date
self.set_cash(100000) # Set Strategy Cash
resolution = Resolution.SECOND if self.live_mode else Resolution.DAILY
self.add_data(Bitcoin, "BTC", resolution)
seeder = FuncSecuritySeeder(self.get_last_known_prices)
self.set_security_initializer(lambda x: seeder.seed_security(x))
self._warmed_up_checked = False
def on_data(self, data: Slice) -> None:
if not self.portfolio.invested:
if data['BTC'].close != 0 :
self.order('BTC', self.portfolio.margin_remaining/abs(data['BTC'].close + 1))
def on_securities_changed(self, changes: SecurityChanges) -> None:
changes.filter_custom_securities = False
for added_security in changes.added_securities:
if added_security.symbol.value == "BTC":
self._warmed_up_checked = True
if not added_security.has_data:
raise ValueError(f"Security {added_security.symbol} was not warmed up!")
def on_end_of_algorithm(self) -> None:
if not self._warmed_up_checked:
raise ValueError("Security was not warmed up!")
class Bitcoin(PythonData):
'''Custom Data Type: Bitcoin data from Quandl - https://data.nasdaq.com/databases/BCHAIN'''
def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource:
if is_live_mode:
return SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.REST)
#return "http://my-ftp-server.com/futures-data-" + date.to_string("Ymd") + ".zip"
# OR simply return a fixed small data file. Large files will slow down your backtest
subscription = SubscriptionDataSource("https://www.quantconnect.com/api/v2/proxy/nasdaq/api/v3/datatables/QDL/BITFINEX.csv?code=BTCUSD&api_key=WyAazVXnq7ATy_fefTqm")
subscription.sort = True
return subscription
def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> DynamicData:
coin = Bitcoin()
coin.symbol = config.symbol
if is_live_mode:
# Example Line Format:
# {"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"}
try:
live_btc = json.loads(line)
# If value is zero, return coin
value = live_btc["last"]
if value == 0:
return coin
coin.time = datetime.now()
coin.value = value
coin["Open"] = float(live_btc["open"])
coin["High"] = float(live_btc["high"])
coin["Low"] = float(live_btc["low"])
coin["Close"] = float(live_btc["last"])
coin["Ask"] = float(live_btc["ask"])
coin["Bid"] = float(live_btc["bid"])
coin["VolumeBTC"] = float(live_btc["volume"])
coin["WeightedPrice"] = float(live_btc["vwap"])
return coin
except ValueError:
# Do nothing, possible error in json decoding
return coin
# Example Line Format:
# code date high low mid last bid ask volume
# BTCUSD 2024-10-08 63248.0 61940.0 62246.5 62245.0 62246.0 62247.0 477.91102114
if not (line.strip() and line[7].isdigit()): return coin
try:
data = line.split(',')
coin.time = datetime.strptime(data[1], "%Y-%m-%d")
coin.end_time = coin.time + timedelta(days=1)
coin.value = float(data[5])
coin["High"] = float(data[2])
coin["Low"] = float(data[3])
coin["Mid"] = float(data[4])
coin["Close"] = float(data[5])
coin["Bid"] = float(data[6])
coin["Ask"] = float(data[7])
coin["VolumeBTC"] = float(data[8])
return coin
except ValueError:
# Do nothing, possible error in json decoding
return coin
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm to demonstrate the use of SetBenchmark() with custom data
|
```python
from AlgorithmImports import *
class CustomDataBenchmarkRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2017, 8, 18) # Set Start Date
self.set_end_date(2017, 8, 21) # Set End Date
self.set_cash(100000) # Set Strategy Cash
self.add_equity("SPY", Resolution.HOUR)
# Load benchmark data
self.custom_symbol = self.add_data(ExampleCustomData, "ExampleCustomData", Resolution.HOUR).symbol
self.set_benchmark(self.custom_symbol)
def on_data(self, data):
if not self.portfolio.invested:
self.set_holdings("SPY", 1)
def on_end_of_algorithm(self):
security_benchmark = self.benchmark
if security_benchmark.security.price == 0:
raise AssertionError("Security benchmark price was not expected to be zero")
class ExampleCustomData(PythonData):
def get_source(self, config, date, is_live):
source = "https://www.dl.dropboxusercontent.com/s/d83xvd7mm9fzpk0/path_to_my_csv_data.csv?dl=0"
return SubscriptionDataSource(source, SubscriptionTransportMedium.REMOTE_FILE)
def reader(self, config, line, date, is_live):
data = line.split(',')
obj_data = ExampleCustomData()
obj_data.symbol = config.symbol
obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S') + timedelta(hours=20)
obj_data.value = float(data[4])
obj_data["Open"] = float(data[1])
obj_data["High"] = float(data[2])
obj_data["Low"] = float(data[3])
obj_data["Close"] = float(data[4])
return obj_data
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: This regression algorithm is expected to stop executing after Initialization. Related to GH 6168 issue
|
```python
from AlgorithmImports import *
class QuitAfterInitializationRegressionAlgorithm(QCAlgorithm):
'''Basic template algorithm simply initializes the date range and cash'''
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013,10, 7) #Set Start Date
self.set_end_date(2013,10,11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
self.add_equity("SPY", Resolution.DAILY)
self._stopped = False
def on_data(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''
if self._stopped:
raise ValueError("Algorithm should of stopped!")
self._stopped = True
self.quit()
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Minute resolution regression algorithm trading Coin and USDT binance futures long and short asserting the behavior
|
```python
from AlgorithmImports import *
class BasicTemplateCryptoFutureAlgorithm(QCAlgorithm):
# <summary>
# 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.set_start_date(2022, 12, 13)
self.set_end_date(2022, 12, 13)
self.set_time_zone(TimeZones.UTC)
try:
self.set_brokerage_model(BrokerageName.BINANCE_FUTURES, AccountType.CASH)
except:
# expected, we don't allow cash account type
pass
self.set_brokerage_model(BrokerageName.BINANCE_FUTURES, AccountType.MARGIN)
self.btc_usd = self.add_crypto_future("BTCUSD")
self.ada_usdt = self.add_crypto_future("ADAUSDT")
self.fast = self.ema(self.btc_usd.symbol, 30, Resolution.MINUTE)
self.slow = self.ema(self.btc_usd.symbol, 60, Resolution.MINUTE)
self.interest_per_symbol = {self.btc_usd.symbol: 0, self.ada_usdt.symbol: 0}
self.set_cash(1000000)
# the amount of BTC we need to hold to trade 'BTCUSD'
self.btc_usd.base_currency.set_amount(0.005)
# the amount of USDT we need to hold to trade 'ADAUSDT'
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 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 AssertionError(f"Unexpected cached margin interest rate for {interest_rate.key}!")
if self.fast > self.slow:
if self.portfolio.invested == False and self.transactions.orders_count == 0:
self.ticket = self.buy(self.btc_usd.symbol, 50)
if self.ticket.status != OrderStatus.INVALID:
raise AssertionError(f"Unexpected valid order {self.ticket}, should fail due to margin not sufficient")
self.buy(self.btc_usd.symbol, 1)
self.margin_used = self.portfolio.total_margin_used
self.btc_usd_holdings = self.btc_usd.holdings
# Coin futures value is 100 USD
self.holdings_value_btc_usd = 100
if abs(self.btc_usd_holdings.total_sale_volume - self.holdings_value_btc_usd) > 1:
raise AssertionError(f"Unexpected TotalSaleVolume {self.btc_usd_holdings.total_sale_volume}")
if abs(self.btc_usd_holdings.absolute_holdings_cost - self.holdings_value_btc_usd) > 1:
raise AssertionError(f"Unexpected holdings cost {self.btc_usd_holdings.holdings_cost}")
# margin used is based on the maintenance rate
if (abs(self.btc_usd_holdings.absolute_holdings_cost * 0.05 - self.margin_used) > 1) or (BuyingPowerModelExtensions.get_maintenance_margin(self.btc_usd.buying_power_model, self.btc_usd) != self.margin_used):
raise AssertionError(f"Unexpected margin used {self.margin_used}")
self.buy(self.ada_usdt.symbol, 1000)
self.margin_used = self.portfolio.total_margin_used - self.margin_used
self.ada_usdt_holdings = self.ada_usdt.holdings
# USDT/BUSD futures value is based on it's price
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 AssertionError(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 AssertionError(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 AssertionError(f"Unexpected margin used {self.margin_used}")
# position just opened should be just spread here
self.profit = self.portfolio.total_unrealized_profit
if (5 - abs(self.profit)) < 0:
raise AssertionError(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")
if (self.portfolio.total_profit != 0):
raise AssertionError(f"Unexpected TotalProfit {self.portfolio.total_profit}")
else:
if self.time.hour > 10 and self.transactions.orders_count == 3:
self.sell(self.btc_usd.symbol, 3)
self.btc_usd_holdings = self.btc_usd.holdings
if abs(self.btc_usd_holdings.absolute_holdings_cost - 100 * 2) > 1:
raise AssertionError(f"Unexpected holdings cost {self.btc_usd_holdings.holdings_cost}")
self.sell(self.ada_usdt.symbol, 3000)
ada_usdt_holdings = self.ada_usdt.holdings
# USDT/BUSD futures value is based on it's price
holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 2000
if abs(ada_usdt_holdings.absolute_holdings_cost - holdings_value_usdt) > 1:
raise AssertionError(f"Unexpected holdings cost {ada_usdt_holdings.holdings_cost}")
# position just opened should be just spread here
profit = self.portfolio.total_unrealized_profit
if (5 - abs(profit)) < 0:
raise AssertionError(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")
# we barely did any difference on the previous trade
if (5 - abs(self.portfolio.total_profit)) < 0:
raise AssertionError(f"Unexpected TotalProfit {self.portfolio.total_profit}")
def on_end_of_algorithm(self):
if self.interest_per_symbol[self.ada_usdt.symbol] != 1:
raise AssertionError(f"Unexpected interest rate count {self.interest_per_symbol[self.ada_usdt.symbol]}")
if self.interest_per_symbol[self.btc_usd.symbol] != 3:
raise AssertionError(f"Unexpected interest rate count {self.interest_per_symbol[self.btc_usd.symbol]}")
def on_order_event(self, order_event):
self.debug("{0} {1}".format(self.time, order_event))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Regression algorithm for the SpreadExecutionModel.
This algorithm shows how the execution model works to
submit orders only when the price is on desirably tight spread.
|
```python
from AlgorithmImports import *
from Alphas.RsiAlphaModel import RsiAlphaModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
from Execution.SpreadExecutionModel import SpreadExecutionModel
class SpreadExecutionModelRegressionAlgorithm(QCAlgorithm):
'''Regression algorithm for the SpreadExecutionModel.
This algorithm shows how the execution model works to
submit orders only when the price is on desirably tight spread.'''
def initialize(self):
self.set_start_date(2013,10,7)
self.set_end_date(2013,10,11)
self.set_universe_selection(ManualUniverseSelectionModel([
Symbol.create('AIG', SecurityType.EQUITY, Market.USA),
Symbol.create('BAC', SecurityType.EQUITY, Market.USA),
Symbol.create('IBM', SecurityType.EQUITY, Market.USA),
Symbol.create('SPY', SecurityType.EQUITY, Market.USA)
]))
# using hourly rsi to generate more insights
self.set_alpha(RsiAlphaModel(14, Resolution.HOUR))
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
self.set_execution(SpreadExecutionModel())
self.insights_generated += self.on_insights_generated
def on_insights_generated(self, algorithm, data):
self.log(f"{self.time}: {', '.join(str(x) for x in data.insights)}")
def on_order_event(self, order_event):
self.log(f"{self.time}: {order_event}")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Demonstrates how to create a custom indicator and register it for automatic updated
|
```python
from AlgorithmImports import *
from collections import deque
class CustomIndicatorAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2013,10,7)
self.set_end_date(2013,10,11)
self.add_equity("SPY", Resolution.SECOND)
# Create a QuantConnect indicator and a python custom indicator for comparison
self._sma = self.sma("SPY", 60, Resolution.MINUTE)
self._custom = CustomSimpleMovingAverage('custom', 60)
# The python custom class must inherit from PythonIndicator to enable Updated event handler
self._custom.updated += self.custom_updated
self._custom_window = RollingWindow(5)
self.register_indicator("SPY", self._custom, Resolution.MINUTE)
self.plot_indicator('CSMA', self._custom)
def custom_updated(self, sender: object, updated: IndicatorDataPoint) -> None:
self._custom_window.add(updated)
def on_data(self, data: Slice) -> None:
if not self.portfolio.invested:
self.set_holdings("SPY", 1)
if self.time.second == 0:
self.log(f" sma -> IsReady: {self._sma.is_ready}. Value: {self._sma.current.value}")
self.log(f"custom -> IsReady: {self._custom.is_ready}. Value: {self._custom.value}")
# Regression test: test fails with an early quit
diff = abs(self._custom.value - self._sma.current.value)
if diff > 1e-10:
self.quit(f"Quit: indicators difference is {diff}")
def on_end_of_algorithm(self) -> None:
for item in self._custom_window:
self.log(f'{item}')
# Python implementation of SimpleMovingAverage.
# Represents the traditional simple moving average indicator (SMA).
class CustomSimpleMovingAverage(PythonIndicator):
def __init__(self, name: str, period: int) -> None:
super().__init__()
self.name = name
self.value = 0
self._queue = deque(maxlen=period)
# Update method is mandatory
def update(self, input: IndicatorDataPoint) -> bool:
self._queue.appendleft(input.value)
count = len(self._queue)
self.value = np.sum(self._queue) / count
return count == self._queue.maxlen
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN Algorithm that can be described like this
: Show cases how to use the CompositeAlphaModel to define.
|
```python
from AlgorithmImports import *
from Alphas.RsiAlphaModel import RsiAlphaModel
from Alphas.EmaCrossAlphaModel import EmaCrossAlphaModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
class CompositeAlphaModelFrameworkAlgorithm(QCAlgorithm):
'''Show cases how to use the CompositeAlphaModel to define.'''
def initialize(self):
self.set_start_date(2013,10,7) #Set Start Date
self.set_end_date(2013,10,11) #Set End Date
self.set_cash(100000) #Set Strategy Cash
# even though we're using a framework algorithm, we can still add our securities
# using the AddEquity/Forex/Crypto/ect methods and then pass them into a manual
# universe selection model using securities.keys()
self.add_equity("SPY")
self.add_equity("IBM")
self.add_equity("BAC")
self.add_equity("AIG")
# define a manual universe of all the securities we manually registered
self.set_universe_selection(ManualUniverseSelectionModel())
# define alpha model as a composite of the rsi and ema cross models
self.set_alpha(CompositeAlphaModel(RsiAlphaModel(), EmaCrossAlphaModel()))
# default models for the rest
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
self.set_execution(ImmediateExecutionModel())
self.set_risk_management(NullRiskManagementModel())
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.