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
: Regression algorithm for the VolumeWeightedAveragePriceExecutionModel.
This algorithm shows how the execution model works to split up orders and
submit them only when the price is on the favorable side of the intraday VWAP.
|
```python
from AlgorithmImports import *
from Alphas.RsiAlphaModel import RsiAlphaModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
from Execution.VolumeWeightedAveragePriceExecutionModel import VolumeWeightedAveragePriceExecutionModel
class VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm(QCAlgorithm):
'''Regression algorithm for the VolumeWeightedAveragePriceExecutionModel.
This algorithm shows how the execution model works to split up orders and
submit them only when the price is on the favorable side of the intraday VWAP.'''
def initialize(self):
self.universe_settings.resolution = Resolution.MINUTE
self.set_start_date(2013,10,7)
self.set_end_date(2013,10,11)
self.set_cash(1000000)
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(VolumeWeightedAveragePriceExecutionModel())
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, orderEvent):
self.log(f"{self.time}: {orderEvent}")
```
|
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 CoarseFundamentalTop3Algorithm(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,3,24) #Set Start Date
self.set_end_date(2014,4,7) #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 a single parameter that is a function that
# accepts an IEnumerable<CoarseFundamental> and returns IEnumerable<Symbol>
self.add_universe(self.coarse_selection_function)
self.__number_of_symbols = 3
self._changes = None
# sort the data by daily dollar volume and take the top '__number_of_symbols'
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] ]
def on_data(self, data):
self.log(f"OnData({self.utc_time}): Keys: {', '.join([key.value for key in data.keys()])}")
# 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 1/N allocation in each security in our universe
for security in self._changes.added_securities:
self.set_holdings(security.symbol, 1 / self.__number_of_symbols)
self._changes = None
# this event fires whenever we have changes to our universe
def on_securities_changed(self, changes):
self._changes = changes
self.log(f"OnSecuritiesChanged({self.utc_time}):: {changes}")
def on_order_event(self, fill):
self.log(f"OnOrderEvent({self.utc_time}):: {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
: Basic template framework algorithm uses framework components to define the algorithm.
Shows EqualWeightingPortfolioConstructionModel.long_only() application
|
```python
from AlgorithmImports import *
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
from Execution.ImmediateExecutionModel import ImmediateExecutionModel
from Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel
class LongOnlyAlphaStreamAlgorithm(QCAlgorithm):
def initialize(self):
# 1. Required:
self.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 11)
# 2. Required: Alpha Streams Models:
self.set_brokerage_model(BrokerageName.ALPHA_STREAMS)
# 3. Required: Significant AUM Capacity
self.set_cash(1000000)
# Only SPY will be traded
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.DAILY, PortfolioBias.LONG))
self.set_execution(ImmediateExecutionModel())
# 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
# Set algorithm framework models
self.set_universe_selection(ManualUniverseSelectionModel(
[Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in ["SPY", "IBM"]]))
def on_data(self, slice):
if self.portfolio.invested: return
self.emit_insights(
[
Insight.price("SPY", timedelta(1), InsightDirection.UP),
Insight.price("IBM", timedelta(1), InsightDirection.DOWN)
])
def on_order_event(self, order_event):
if order_event.status == OrderStatus.FILLED:
if self.securities[order_event.symbol].holdings.is_short:
raise ValueError("Invalid position, should not be short")
self.debug(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
: Algorithm demonstrating FOREX asset types and requesting history on them in bulk. As FOREX uses
QuoteBars you should request slices
|
```python
from AlgorithmImports import *
class BasicTemplateForexAlgorithm(QCAlgorithm):
def initialize(self):
# Set the cash we'd like to use for our backtest
self.set_cash(100000)
# Start and end dates for the backtest.
self.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 11)
# Add FOREX contract you want to trade
# find available contracts here https://www.quantconnect.com/data#forex/oanda/cfd
self.add_forex("EURUSD", Resolution.MINUTE)
self.add_forex("GBPUSD", Resolution.MINUTE)
self.add_forex("EURGBP", Resolution.MINUTE)
self.history(5, Resolution.DAILY)
self.history(5, Resolution.HOUR)
self.history(5, Resolution.MINUTE)
history = self.history(TimeSpan.from_seconds(5), Resolution.SECOND)
for data in sorted(history, key=lambda x: x.time):
for key in data.keys():
self.log(str(key.value) + ": " + str(data.time) + " > " + str(data[key].value))
def on_data(self, data):
# Print to console to verify that data is coming in
for key in data.keys():
self.log(str(key.value) + ": " + str(data.time) + " > " + str(data[key].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
: Basic template algorithm that implements a fill model with combo orders
<meta name="tag" content="trading and orders" />
|
```python
from AlgorithmImports import *
class ComboOrdersFillModelAlgorithm(QCAlgorithm):
'''Basic template algorithm that implements a fill model with combo orders'''
def initialize(self) -> None:
self.set_start_date(2019, 1, 1)
self.set_end_date(2019, 1, 20)
self.spy = self.add_equity("SPY", Resolution.HOUR)
self.ibm = self.add_equity("IBM", Resolution.HOUR)
# Set the fill model
self.spy.set_fill_model(CustomPartialFillModel())
self.ibm.set_fill_model(CustomPartialFillModel())
self._order_types = {}
def on_data(self, data: Slice) -> None:
if not self.portfolio.invested:
legs = [Leg.create(self.spy.symbol, 1), Leg.create(self.ibm.symbol, -1)]
self.combo_market_order(legs, 100)
self.combo_limit_order(legs, 100, round(self.spy.bid_price))
legs = [Leg.create(self.spy.symbol, 1, round(self.spy.bid_price) + 1), Leg.create(self.ibm.symbol, -1, round(self.ibm.bid_price) + 1)]
self.combo_leg_limit_order(legs, 100)
def on_order_event(self, order_event: OrderEvent) -> None:
if order_event.status == OrderStatus.FILLED:
order_type = self.transactions.get_order_by_id(order_event.order_id).type
if order_type == OrderType.COMBO_MARKET and order_event.absolute_fill_quantity != 50:
raise AssertionError(f"The absolute quantity filled for all combo market orders should be 50, but for order {order_event.order_id} was {order_event.absolute_fill_quantity}")
elif order_type == OrderType.COMBO_LIMIT and order_event.absolute_fill_quantity != 20:
raise AssertionError(f"The absolute quantity filled for all combo limit orders should be 20, but for order {order_event.order_id} was {order_event.absolute_fill_quantity}")
elif order_type == OrderType.COMBO_LEG_LIMIT and order_event.absolute_fill_quantity != 10:
raise AssertionError(f"The absolute quantity filled for all combo leg limit orders should be 10, but for order {order_event.order_id} was {order_event.absolute_fill_quantity}")
self._order_types[order_type] = 1
def on_end_of_algorithm(self) -> None:
if len(self._order_types) != 3:
raise AssertionError(f"Just 3 different types of order were submitted in this algorithm, but the amount of order types was {len(self._order_types)}")
if OrderType.COMBO_MARKET not in self._order_types.keys():
raise AssertionError(f"One Combo Market Order should have been submitted but it was not")
if OrderType.COMBO_LIMIT not in self._order_types.keys():
raise AssertionError(f"One Combo Limit Order should have been submitted but it was not")
if OrderType.COMBO_LEG_LIMIT not in self._order_types.keys():
raise AssertionError(f"One Combo Leg Limit Order should have been submitted but it was not")
class CustomPartialFillModel(FillModel):
'''Implements a custom fill model that inherit from FillModel. Overrides combo_market_fill, combo_limit_fill and combo_leg_limit_fill
methods to test FillModelPythonWrapper works as expected'''
def __init__(self) -> None:
self.absolute_remaining_by_order_id = {}
def fill_orders_partially(self, parameters: FillModelParameters, fills: list[OrderEvent], quantity: int) -> list[OrderEvent]:
partial_fills = []
if len(fills) == 0:
return partial_fills
for kvp, fill in zip(sorted(parameters.securities_for_orders, key=lambda x: x.key.id), fills):
order = kvp.key
absolute_remaining = self.absolute_remaining_by_order_id.get(order.id, order.absolute_quantity)
# Set the fill amount
fill.fill_quantity = np.sign(order.quantity) * quantity
if (min(abs(fill.fill_quantity), absolute_remaining) == absolute_remaining):
fill.fill_quantity = np.sign(order.quantity) * absolute_remaining
fill.status = OrderStatus.FILLED
self.absolute_remaining_by_order_id.pop(order.id, None)
else:
fill.status = OrderStatus.PARTIALLY_FILLED
self.absolute_remaining_by_order_id[order.id] = absolute_remaining - abs(fill.fill_quantity)
price = fill.fill_price
# self.algorithm.debug(f"{self.algorithm.time} - Partial Fill - Remaining {self.absolute_remaining_by_order_id[order.id]} Price - {price}")
partial_fills.append(fill)
return partial_fills
def combo_market_fill(self, order: Order, parameters: FillModelParameters) -> list[OrderEvent]:
fills = super().combo_market_fill(order, parameters)
partial_fills = self.fill_orders_partially(parameters, fills, 50)
return partial_fills
def combo_limit_fill(self, order: Order, parameters: FillModelParameters) -> list[OrderEvent]:
fills = super().combo_limit_fill(order, parameters)
partial_fills = self.fill_orders_partially(parameters, fills, 20)
return partial_fills
def combo_leg_limit_fill(self, order: Order, parameters: FillModelParameters) -> list[OrderEvent]:
fills = super().combo_leg_limit_fill(order, parameters)
partial_fills = self.fill_orders_partially(parameters, fills, 10)
return partial_fills
```
|
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 BasicTemplateFuturesWithExtendedMarketAlgorithm(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
self.future_sp500 = self.add_future(Futures.Indices.SP_500_E_MINI, extended_market_hours = True)
self.future_gold = self.add_future(Futures.Metals.GOLD, extended_market_hours = True)
# 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
self.future_sp500.set_filter(timedelta(0), timedelta(182))
self.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
: Demonstration of using custom fee, slippage, fill, and buying power models for modelling transactions in backtesting.
QuantConnect allows you to model all orders as deeply and accurately as you need.
|
```python
from AlgorithmImports import *
import random
class CustomModelsAlgorithm(QCAlgorithm):
'''Demonstration of using custom fee, slippage, fill, and buying power models for modelling transactions 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
self.security = self.add_equity("SPY", Resolution.HOUR)
self.spy = self.security.symbol
# set our models
self.security.set_fee_model(CustomFeeModel(self))
self.security.set_fill_model(CustomFillModel(self))
self.security.set_slippage_model(CustomSlippageModel(self))
self.security.set_buying_power_model(CustomBuyingPowerModel(self))
def on_data(self, data):
open_orders = self.transactions.get_open_orders(self.spy)
if len(open_orders) != 0: return
if self.time.day > 10 and self.security.holdings.quantity <= 0:
quantity = self.calculate_order_quantity(self.spy, .5)
self.log(f"MarketOrder: {quantity}")
self.market_order(self.spy, quantity, True) # async needed for partial fill market orders
elif self.time.day > 20 and self.security.holdings.quantity >= 0:
quantity = self.calculate_order_quantity(self.spy, -.5)
self.log(f"MarketOrder: {quantity}")
self.market_order(self.spy, quantity, True) # async needed for partial fill market orders
# If we want to use methods from other models, you need to inherit from one of them
class CustomFillModel(ImmediateFillModel):
def __init__(self, algorithm):
super().__init__()
self.algorithm = algorithm
self.absolute_remaining_by_order_id = {}
self.random = Random(387510346)
def market_fill(self, asset, order):
absolute_remaining = order.absolute_quantity
if order.id in self.absolute_remaining_by_order_id.keys():
absolute_remaining = self.absolute_remaining_by_order_id[order.id]
fill = super().market_fill(asset, order)
absolute_fill_quantity = int(min(absolute_remaining, self.random.next(0, 2*int(order.absolute_quantity))))
fill.fill_quantity = np.sign(order.quantity) * absolute_fill_quantity
if absolute_remaining == absolute_fill_quantity:
fill.status = OrderStatus.FILLED
if self.absolute_remaining_by_order_id.get(order.id):
self.absolute_remaining_by_order_id.pop(order.id)
else:
absolute_remaining = absolute_remaining - absolute_fill_quantity
self.absolute_remaining_by_order_id[order.id] = absolute_remaining
fill.status = OrderStatus.PARTIALLY_FILLED
self.algorithm.log(f"CustomFillModel: {fill}")
return fill
class CustomFeeModel(FeeModel):
def __init__(self, algorithm):
super().__init__()
self.algorithm = algorithm
def get_order_fee(self, parameters):
# custom fee math
fee = max(1, parameters.security.price
* parameters.order.absolute_quantity
* 0.00001)
self.algorithm.log(f"CustomFeeModel: {fee}")
return OrderFee(CashAmount(fee, "USD"))
class CustomSlippageModel:
def __init__(self, algorithm):
self.algorithm = algorithm
def get_slippage_approximation(self, asset, order):
# custom slippage math
slippage = asset.price * 0.0001 * np.log10(2*float(order.absolute_quantity))
self.algorithm.log(f"CustomSlippageModel: {slippage}")
return slippage
class CustomBuyingPowerModel(BuyingPowerModel):
def __init__(self, algorithm):
super().__init__()
self.algorithm = algorithm
def has_sufficient_buying_power_for_order(self, parameters):
# custom behavior: this model will assume that there is always enough buying power
has_sufficient_buying_power_for_order_result = HasSufficientBuyingPowerForOrderResult(True)
self.algorithm.log(f"CustomBuyingPowerModel: {has_sufficient_buying_power_for_order_result.is_sufficient}")
return has_sufficient_buying_power_for_order_result
# The simple fill model shows how to implement a simpler version of
# the most popular order fills: Market, Stop Market and Limit
class SimpleCustomFillModel(FillModel):
def __init__(self):
super().__init__()
def _create_order_event(self, asset, order):
utc_time = Extensions.convert_to_utc(asset.local_time, asset.exchange.time_zone)
return OrderEvent(order, utc_time, OrderFee.ZERO)
def _set_order_event_to_filled(self, fill, fill_price, fill_quantity):
fill.status = OrderStatus.FILLED
fill.fill_quantity = fill_quantity
fill.fill_price = fill_price
return fill
def _get_trade_bar(self, asset, order_direction):
trade_bar = asset.cache.get_data(TradeBar)
if trade_bar: return trade_bar
# Tick-resolution data doesn't have TradeBar, use the asset price
price = asset.price
return TradeBar(asset.local_time, asset.symbol, price, price, price, price, 0)
def market_fill(self, asset, order):
fill = self._create_order_event(asset, order)
if order.status == OrderStatus.CANCELED: return fill
return self._set_order_event_to_filled(fill,
asset.cache.ask_price \
if order.direction == OrderDirection.BUY else asset.cache.bid_price,
order.quantity)
def stop_market_fill(self, asset, order):
fill = self._create_order_event(asset, order)
if order.status == OrderStatus.CANCELED: return fill
stop_price = order.stop_price
trade_bar = self._get_trade_bar(asset, order.direction)
if order.direction == OrderDirection.SELL and trade_bar.low < stop_price:
return self._set_order_event_to_filled(fill, stop_price, order.quantity)
if order.direction == OrderDirection.BUY and trade_bar.high > stop_price:
return self._set_order_event_to_filled(fill, stop_price, order.quantity)
return fill
def limit_fill(self, asset, order):
fill = self._create_order_event(asset, order)
if order.status == OrderStatus.CANCELED: return fill
limit_price = order.limit_price
trade_bar = self._get_trade_bar(asset, order.direction)
if order.direction == OrderDirection.SELL and trade_bar.high > limit_price:
return self._set_order_event_to_filled(fill, limit_price, order.quantity)
if order.direction == OrderDirection.BUY and trade_bar.low < limit_price:
return self._set_order_event_to_filled(fill, limit_price, order.quantity)
return 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
: Algorithm asserting that security dynamic properties keep Python references to the Python class they are instances of,
specifically when this class is a subclass of a C# class.
|
```python
from AlgorithmImports import *
from collections import deque
import numpy as np
class SecurityDynamicPropertyPythonClassAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 7)
self._spy = self.add_equity("SPY", Resolution.MINUTE)
custom_sma = CustomSimpleMovingAverage('custom', 60)
self._spy.custom_sma = custom_sma
custom_sma.security = self._spy
self.register_indicator(self._spy.symbol, self._spy.custom_sma, Resolution.MINUTE)
def on_warmup_finished(self) -> None:
if type(self._spy.custom_sma) != CustomSimpleMovingAverage:
raise AssertionError("spy.custom_sma is not an instance of CustomSimpleMovingAverage")
if not self._spy.custom_sma.security:
raise AssertionError("spy.custom_sma.security is None")
else:
self.debug(f"spy.custom_sma.security.symbol: {self._spy.custom_sma.security.symbol}")
def on_data(self, slice: Slice) -> None:
if self._spy.custom_sma.is_ready:
self.debug(f"CustomSMA: {self._spy.custom_sma.current.value}")
class CustomSimpleMovingAverage(PythonIndicator):
def __init__(self, name: str, period: int) -> None:
super().__init__()
self.name = name
self.value = 0
self._queue = deque(maxlen=period)
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
: _valid_order_ticket = None
|
```python
from AlgorithmImports import *
class MarketOnCloseOrderBufferRegressionAlgorithm(QCAlgorithm):
_valid_order_ticket = None
_invalid_order_ticket = 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)
def moc_at_post_market():
self._valid_order_ticket_extended_market_hours = self.market_on_close_order("SPY", 2)
self.schedule.on(self.date_rules.today, self.time_rules.at(17,0), moc_at_post_market)
# 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)
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 for testing that period-based history requests are not allowed with tick resolution
|
```python
from AlgorithmImports import *
class PeriodBasedHistoryRequestNotAllowedWithTickResolutionRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 8)
self.set_end_date(2013, 10, 9)
spy = self.add_equity("SPY", Resolution.TICK).symbol
# Tick resolution is not allowed for period-based history requests
self.assert_that_history_throws_for_tick_resolution(lambda: self.history[Tick](spy, 1),
"Tick history call with implicit tick resolution")
self.assert_that_history_throws_for_tick_resolution(lambda: self.history[Tick](spy, 1, Resolution.TICK),
"Tick history call with explicit tick resolution")
self.assert_that_history_throws_for_tick_resolution(lambda: self.history[Tick]([spy], 1),
"Tick history call with symbol array with implicit tick resolution")
self.assert_that_history_throws_for_tick_resolution(lambda: self.history[Tick]([spy], 1, Resolution.TICK),
"Tick history call with symbol array with explicit tick resolution")
history = self.history[Tick](spy, TimeSpan.from_hours(12))
# Check whether history has data without enumerating the whole list
if not any(x for x in history):
raise AssertionError("On history call with implicit tick resolution: history returned no results")
history = self.history[Tick](spy, TimeSpan.from_hours(12), Resolution.TICK)
if not any(x for x in history):
raise AssertionError("On history call with explicit tick resolution: history returned no results")
# We already tested what we wanted to test, we can quit now
self.quit()
def assert_that_history_throws_for_tick_resolution(self, history_call, history_call_description):
try:
history_call()
raise AssertionError(f"{history_call_description}: expected an exception to be thrown")
except InvalidOperationException:
# expected
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
: Test algorithm using 'AccumulativeInsightPortfolioConstructionModel.py' and 'ConstantAlphaModel'
generating a constant 'Insight'
|
```python
from AlgorithmImports import *
class AccumulativeInsightPortfolioRegressionAlgorithm(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.'''
# 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
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, 0.25))
self.set_portfolio_construction(AccumulativeInsightPortfolioConstructionModel())
self.set_execution(ImmediateExecutionModel())
def on_end_of_algorithm(self):
# holdings value should be 0.03 - to avoid price fluctuation issue we compare with 0.06 and 0.01
if (self.portfolio.total_holdings_value > self.portfolio.total_portfolio_value * 0.06
or self.portfolio.total_holdings_value < self.portfolio.total_portfolio_value * 0.01):
raise ValueError("Unexpected Total Holdings Value: " + str(self.portfolio.total_holdings_value))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN AlphaModel that can be described like this
: Regression algorithm to test ImmediateExecutionModel places orders with the
correct quantity (taking into account the fee's) so that the fill quantity
is the expected one.
|
```python
# region imports
from AlgorithmImports import *
from Execution.ImmediateExecutionModel import ImmediateExecutionModel
from QuantConnect.Orders import OrderEvent
# endregion
class ImmediateExecutionModelWorksWithBinanceFeeModel(QCAlgorithm):
def Initialize(self):
# *** initial configurations and backtest ***
self.set_start_date(2022, 12, 13) # Set Start Date
self.set_end_date(2022, 12, 14) # Set End Date
self.set_account_currency("BUSD") # Set Account Currency
self.set_cash("BUSD", 100000, 1) # Set Strategy Cash
self.universe_settings.resolution = Resolution.MINUTE
symbols = [ Symbol.create("BTCBUSD", SecurityType.CRYPTO, Market.BINANCE) ]
# 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(Resolution.MINUTE))
self.set_execution(ImmediateExecutionModel())
self.set_brokerage_model(BrokerageName.BINANCE, AccountType.MARGIN)
def on_order_event(self, order_event: OrderEvent) -> None:
if order_event.status == OrderStatus.FILLED:
if abs(order_event.quantity - 5.8) > 0.01:
raise AssertionError(f"The expected quantity was 5.8 but the quantity from the order was {order_event.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
: This algorithm sends a list of portfolio targets to vBsase API
|
```python
from AlgorithmImports import *
class VBaseSignalExportDemonstrationAlgorithm(QCAlgorithm):
def initialize(self):
''' Initialize the date'''
self.set_start_date(2013,10, 7)
self.set_end_date(2013,10,11)
self.set_cash(100000) # Set Strategy Cash
self.vbase_apikey = "YOUR VBASE API KEY"
self.vbase_collection_name = "YOUR VBASE COLLECTION NAME"
self._symbols = [
Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
]
for symbol in self._symbols:
self.add_equity(symbol)
self._sentSignal = False
self.signal_export.add_signal_export_provider(VBaseSignalExport(self.vbase_apikey, self.vbase_collection_name))
def on_data(self, data):
if self._sentSignal:
return
self._sentSignal = True
self.targets = []
for symbol in self._symbols:
self.targets.append(PortfolioTarget(symbol, 0.25))
self.signal_export.set_target_portfolio(self.targets)
```
|
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 IndiaDataRegressionAlgorithm(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.set_account_currency("INR")
self.set_start_date(2004, 5, 20)
self.set_end_date(2016, 7, 26)
self._mapping_symbol = self.add_equity("3MINDIA", Resolution.DAILY, Market.INDIA).symbol
self._split_and_dividend_symbol = self.add_equity("CCCL", Resolution.DAILY, Market.INDIA).symbol
self._received_warning_event = False
self._received_occurred_event = False
self._initial_mapping = False
self._execution_mapping = False
self.debug("numpy test >>> print numpy.pi: " + str(np.pi))
def on_dividends(self, dividends: Dividends):
if dividends.contains_key(self._split_and_dividend_symbol):
dividend = dividends[self._split_and_dividend_symbol]
if ((self.time.year == 2010 and self.time.month == 6 and self.time.day == 15) and
(dividend.price != 0.5 or dividend.reference_price != 88.8 or dividend.distribution != 0.5)):
raise AssertionError("Did not receive expected dividend values")
def on_splits(self, splits: Splits):
if splits.contains_key(self._split_and_dividend_symbol):
split = splits[self._split_and_dividend_symbol]
if split.type == SplitType.WARNING:
self._received_warning_event = True
elif split.type == SplitType.SPLIT_OCCURRED:
self._received_occurred_event = True
if split.price != 421.0 or split.reference_price != 421.0 or split.split_factor != 0.2:
raise AssertionError("Did not receive expected price values")
def on_symbol_changed_events(self, symbols_changed: SymbolChangedEvents):
if symbols_changed.contains_key(self._mapping_symbol):
mapping_event = [x.value for x in symbols_changed if x.key.security_type == 1][0]
if self.time.year == 1999 and self.time.month == 1 and self.time.day == 1:
self._initial_mapping = True
elif self.time.year == 2004 and self.time.month == 6 and self.time.day == 15:
if mapping_event.new_symbol == "3MINDIA" and mapping_event.old_symbol == "BIRLA3M":
self._execution_mapping = True
def on_end_of_algorithm(self):
if self._initial_mapping:
raise AssertionError("The ticker generated the initial rename event")
if not self._execution_mapping:
raise AssertionError("The ticker did not rename throughout the course of its life even though it should have")
if not self._received_occurred_event:
raise AssertionError("Did not receive expected split event")
if not self._received_warning_event:
raise AssertionError("Did not receive expected split warning 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 tests various overloads of the Consolidate method
using RenkoBar, VolumeRenkoBar, and RangeBar types,
as well as common bars like TradeBar and QuoteBar with a maxCount parameter.
It ensures each overload behaves as expected and that the appropriate consolidator instances are correctly created and triggered.
|
```python
from AlgorithmImports import *
class ConsolidateWithSizeAttributeRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 7)
self.set_cash(100000)
self.add_equity("SPY", Resolution.MINUTE)
self.sma_indicators = [
SimpleMovingAverage("RenkoBarSMA", 10),
SimpleMovingAverage("VolumeRenkoBarSMA", 10),
SimpleMovingAverage("RangeBarSMA", 10),
SimpleMovingAverage("TradeBarSMA", 10),
SimpleMovingAverage("QuoteBarSMA", 10),
SimpleMovingAverage("BaseDataSMA", 10)
]
self.consolidators = [
self.consolidate(RenkoBar, "SPY", 0.1, None, lambda bar: self.update_with_renko_bar(bar, 0)),
self.consolidate(VolumeRenkoBar, "SPY", 10000, None, lambda bar: self.update_with_volume_renko_bar(bar, 1)),
self.consolidate(RangeBar, "SPY", 12, None, lambda bar: self.update_with_range_bar(bar, 2)),
# Trade and Quote consolidators with max count
self.consolidate(TradeBar, "SPY", 10, None, lambda bar: self.update_with_trade_bar(bar, 3)),
self.consolidate(QuoteBar, "SPY", 10, None, lambda bar: self.update_with_quote_bar(bar, 4)),
self.consolidate(BaseData, "SPY", 10, None, lambda bar: self.update_with_base_data(bar, 5))
]
def update_with_base_data(self, base_data, position):
self.sma_indicators[position].update(base_data.end_time, base_data.value)
if type(base_data) != TradeBar:
raise AssertionError(f"The type of the bar should be Trade, but was {type(base_data)}")
def update_with_trade_bar(self, trade_bar, position):
self.sma_indicators[position].update(trade_bar.end_time, trade_bar.high)
if type(trade_bar) != TradeBar:
raise AssertionError(f"The type of the bar should be Trade, but was {type(trade_bar)}")
def update_with_quote_bar(self, quote_bar, position):
self.sma_indicators[position].update(quote_bar.end_time, quote_bar.high)
if type(quote_bar) != QuoteBar:
raise AssertionError(f"The type of the bar should be Quote, but was {type(quote_bar)}")
def update_with_renko_bar(self, renko_bar, position):
self.sma_indicators[position].update(renko_bar.end_time, renko_bar.high)
if type(renko_bar) != RenkoBar:
raise AssertionError(f"The type of the bar should be Renko, but was {type(renko_bar)}")
def update_with_volume_renko_bar(self, volume_renko_bar, position):
self.sma_indicators[position].update(volume_renko_bar.end_time, volume_renko_bar.high)
if type(volume_renko_bar) != VolumeRenkoBar:
raise AssertionError(f"The type of the bar should be VolumeRenko, but was {type(volume_renko_bar)}")
def update_with_range_bar(self, range_bar, position):
self.sma_indicators[position].update(range_bar.end_time, range_bar.high)
if type(range_bar) != RangeBar:
raise AssertionError(f"The type of the bar should be Range, but was {type(range_bar)}")
def on_end_of_algorithm(self):
# Verifies that each SMA was updated and is ready, confirming the Consolidate overloads functioned correctly.
for sma in self.sma_indicators:
if (sma.samples == 0):
raise AssertionError(f'The indicator {sma.name} did not receive any updates. This indicates the associated consolidator was not triggered.')
if (not sma.is_ready):
raise AssertionError(f'The indicator {sma.name} is not ready. It received only {sma.samples} samples, but requires at least {sma.period} to be ready.')
expected_consolidator_types = [
RenkoConsolidator,
VolumeRenkoConsolidator,
RangeConsolidator,
TradeBarConsolidator,
QuoteBarConsolidator,
BaseDataConsolidator
]
for i in range(len(self.consolidators)):
consolidator = self.consolidators[i]
if type(consolidator) != expected_consolidator_types[i]:
raise AssertionError(f"Expected consolidator type {expected_consolidator_types[i]} but received {type(consolidator)}")
```
|
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) index option expiry for calls.
We expect 2 orders from the algorithm, which are:
* Initial entry, buy SPX Call Option (expiring OTM)
- contract expires worthless, not exercised, so never opened a position in the underlying
* Liquidation of worthless SPX call option (expiring OTM)
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 IndexOptionCallOTMExpiryRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2021, 1, 4)
self.set_end_date(2021, 1, 31)
self.spx = self.add_index("SPX", Resolution.MINUTE).symbol
# Select a index option call expiring OTM, 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 >= 4250 and i.id.option_right == OptionRight.CALL 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))[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.CALL,
4250,
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:
raise AssertionError("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM")
if 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_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 not "OTM" 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")
### <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())}")
```
|
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 WeeklyUniverseSelectionRegressionAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_cash(100000)
self.set_start_date(2013,10,1)
self.set_end_date(2013,10,31)
self.universe_settings.resolution = Resolution.HOUR
# select IBM once a week, empty universe the other days
self.add_universe("my-custom-universe", lambda dt: ["IBM"] if dt.day % 7 == 0 else [])
def on_data(self, slice: Slice) -> None:
if not self._changes:
return
# liquidate removed securities
for security in self._changes.removed_securities:
if security.invested:
self.log("{} Liquidate {}".format(self.time, security.symbol))
self.liquidate(security.symbol)
# we'll simply go long each security we added to the universe
for security in self._changes.added_securities:
if not security.invested:
self.log("{} Buy {}".format(self.time, security.symbol))
self.set_holdings(security.symbol, 1)
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
: Basic template futures framework algorithm uses framework components
to define an algorithm that trades futures.
|
```python
from AlgorithmImports import *
from Alphas.ConstantAlphaModel import ConstantAlphaModel
from Selection.FutureUniverseSelectionModel import FutureUniverseSelectionModel
class BasicTemplateFuturesFrameworkAlgorithm(QCAlgorithm):
def initialize(self):
self.universe_settings.resolution = Resolution.MINUTE
self.universe_settings.extended_market_hours = self.get_extended_market_hours()
self.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 11)
self.set_cash(100000)
# set framework models
self.set_universe_selection(FrontMonthFutureUniverseSelectionModel(self.select_future_chain_symbols))
self.set_alpha(ConstantFutureContractAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))
self.set_portfolio_construction(SingleSharePortfolioConstructionModel())
self.set_execution(ImmediateExecutionModel())
self.set_risk_management(NullRiskManagementModel())
def select_future_chain_symbols(self, utc_time):
new_york_time = Extensions.convert_from_utc(utc_time, TimeZones.NEW_YORK)
if new_york_time.date() < date(2013, 10, 9):
return [ Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME) ]
else:
return [ Symbol.create(Futures.Metals.GOLD, SecurityType.FUTURE, Market.COMEX) ]
def get_extended_market_hours(self):
return False
class FrontMonthFutureUniverseSelectionModel(FutureUniverseSelectionModel):
'''Creates futures chain universes that select the front month contract and runs a user
defined future_chain_symbol_selector every day to enable choosing different futures chains'''
def __init__(self, select_future_chain_symbols):
super().__init__(timedelta(1), select_future_chain_symbols)
def filter(self, filter):
'''Defines the futures chain universe filter'''
return (filter.front_month()
.only_apply_filter_at_market_open())
class ConstantFutureContractAlphaModel(ConstantAlphaModel):
'''Implementation of a constant alpha model that only emits insights for future symbols'''
def __init__(self, _type, direction, period):
super().__init__(_type, direction, period)
def should_emit_insight(self, utc_time, symbol):
# only emit alpha for future symbols and not underlying equity symbols
if symbol.security_type != SecurityType.FUTURE:
return False
return super().should_emit_insight(utc_time, symbol)
class SingleSharePortfolioConstructionModel(PortfolioConstructionModel):
'''Portfolio construction model that sets target quantities to 1 for up insights and -1 for down insights'''
def create_targets(self, algorithm, insights):
targets = []
for insight in insights:
targets.append(PortfolioTarget(insight.symbol, insight.direction))
return targets
```
|
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 margin interest rate model in backtesting.
|
```python
from AlgorithmImports import *
class CustomMarginInterestRateModelAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013, 10, 1)
self.set_end_date(2013, 10, 31)
security = self.add_equity("SPY", Resolution.HOUR)
self._spy = security.symbol
# set the margin interest rate model
self._margin_interest_rate_model = CustomMarginInterestRateModel()
security.set_margin_interest_rate_model(self._margin_interest_rate_model)
self._cash_after_order = 0
def on_data(self, data: Slice):
if not self.portfolio.invested:
self.set_holdings(self._spy, 1)
def on_order_event(self, order_event: OrderEvent):
if order_event.status == OrderStatus.FILLED:
self._cash_after_order = self.portfolio.cash
def on_end_of_algorithm(self):
if self._margin_interest_rate_model.call_count == 0:
raise AssertionError("CustomMarginInterestRateModel was not called")
expected_cash = self._cash_after_order * pow(1 + self._margin_interest_rate_model.interest_rate, self._margin_interest_rate_model.call_count)
if abs(self.portfolio.cash - expected_cash) > 1e-10:
raise AssertionError(f"Expected cash {expected_cash} but got {self.portfolio.cash}")
class CustomMarginInterestRateModel:
def __init__(self):
self.interest_rate = 0.01
self.call_count = 0
def apply_margin_interest_rate(self, parameters: MarginInterestRateParameters):
security = parameters.security
position_value = security.holdings.get_quantity_value(security.holdings.quantity)
if position_value.amount > 0:
position_value.cash.add_amount(self.interest_rate * position_value.cash.amount)
self.call_count += 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 that asserts Stochastic indicator, registered with a different resolution consolidator,
is warmed up properly by calling QCAlgorithm.WarmUpIndicator
|
```python
from datetime import timedelta
from AlgorithmImports import *
class StochasticIndicatorWarmsUpProperlyRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2020, 1, 1) # monday = holiday..
self.set_end_date(2020, 2, 1)
self.set_cash(100000)
self.data_points_received = False
self.spy = self.add_equity("SPY", Resolution.HOUR).symbol
self.daily_consolidator = TradeBarConsolidator(timedelta(days=1))
self._rsi = RelativeStrengthIndex(14, MovingAverageType.WILDERS)
self._sto = Stochastic("FIRST", 10, 3, 3)
self.register_indicator(self.spy, self._rsi, self.daily_consolidator)
self.register_indicator(self.spy, self._sto, self.daily_consolidator)
# warm_up indicator
self.warm_up_indicator(self.spy, self._rsi, timedelta(days=1))
self.warm_up_indicator(self.spy, self._sto, timedelta(days=1))
self._rsi_history = RelativeStrengthIndex(14, MovingAverageType.WILDERS)
self._sto_history = Stochastic("SECOND", 10, 3, 3)
self.register_indicator(self.spy, self._rsi_history, self.daily_consolidator)
self.register_indicator(self.spy, self._sto_history, self.daily_consolidator)
# history warm up
history = self.history[TradeBar](self.spy, max(self._rsi_history.warm_up_period, self._sto_history.warm_up_period), Resolution.DAILY)
for bar in history:
self._rsi_history.update(bar.end_time, bar.close)
if self._rsi_history.samples == 1:
continue
self._sto_history.update(bar)
indicators = [self._rsi, self._sto, self._rsi_history, self._sto_history]
for indicator in indicators:
if not indicator.is_ready:
raise AssertionError(f"{indicator.name} should be ready, but it is not. Number of samples: {indicator.samples}")
def on_data(self, data: Slice):
if self.is_warming_up:
return
if data.contains_key(self.spy):
self.data_points_received = True
if self._rsi.current.value != self._rsi_history.current.value:
raise AssertionError(f"Values of indicators differ: {self._rsi.name}: {self._rsi.current.value} | {self._rsi_history.name}: {self._rsi_history.current.value}")
if self._sto.stoch_k.current.value != self._sto_history.stoch_k.current.value:
raise AssertionError(f"Stoch K values of indicators differ: {self._sto.name}.StochK: {self._sto.stoch_k.current.value} | {self._sto_history.name}.StochK: {self._sto_history.stoch_k.current.value}")
if self._sto.stoch_d.current.value != self._sto_history.stoch_d.current.value:
raise AssertionError(f"Stoch D values of indicators differ: {self._sto.name}.StochD: {self._sto.stoch_d.current.value} | {self._sto_history.name}.StochD: {self._sto_history.stoch_d.current.value}")
def on_end_of_algorithm(self):
if not self.data_points_received:
raise AssertionError("No data points received")
```
|
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 that implements a fill model with partial fills
<meta name="tag" content="trading and orders" />
|
```python
from AlgorithmImports import *
class CustomPartialFillModelAlgorithm(QCAlgorithm):
'''Basic template algorithm that implements a fill model with partial fills'''
def initialize(self):
self.set_start_date(2019, 1, 1)
self.set_end_date(2019, 3, 1)
equity = self.add_equity("SPY", Resolution.HOUR)
self.spy = equity.symbol
self.holdings = equity.holdings
# Set the fill model
equity.set_fill_model(CustomPartialFillModel(self))
def on_data(self, data):
open_orders = self.transactions.get_open_orders(self.spy)
if len(open_orders) != 0: return
if self.time.day > 10 and self.holdings.quantity <= 0:
self.market_order(self.spy, 105, True)
elif self.time.day > 20 and self.holdings.quantity >= 0:
self.market_order(self.spy, -100, True)
class CustomPartialFillModel(FillModel):
'''Implements a custom fill model that inherit from FillModel. Override the MarketFill method to simulate partially fill orders'''
def __init__(self, algorithm):
self.algorithm = algorithm
self.absolute_remaining_by_order_id = {}
def market_fill(self, asset, order):
absolute_remaining = self.absolute_remaining_by_order_id.get(order.id, order. AbsoluteQuantity)
# Create the object
fill = super().market_fill(asset, order)
# Set the fill amount
fill.fill_quantity = np.sign(order.quantity) * 10
if (min(abs(fill.fill_quantity), absolute_remaining) == absolute_remaining):
fill.fill_quantity = np.sign(order.quantity) * absolute_remaining
fill.status = OrderStatus.FILLED
self.absolute_remaining_by_order_id.pop(order.id, None)
else:
fill.status = OrderStatus.PARTIALLY_FILLED
self.absolute_remaining_by_order_id[order.id] = absolute_remaining - abs(fill.fill_quantity)
price = fill.fill_price
# self.algorithm.debug(f"{self.algorithm.time} - Partial Fill - Remaining {self.absolute_remaining_by_order_id[order.id]} Price - {price}")
return 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
: This regression algorithm tests Out of The Money (OTM) future option expiry for short puts.
We expect 2 orders from the algorithm, which are:
* Initial entry, sell ES Put Option (expiring OTM)
- Profit the option premium, since the option was not assigned.
* Liquidation of ES put OTM contract on the last trade date
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 FutureOptionShortPutOTMExpiryRegressionAlgorithm(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 <= 3000.0 and x.id.option_right == OptionRight.PUT],
key=lambda x: x.id.strike_price,
reverse=True
)
)[0], Resolution.MINUTE).symbol
self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3000.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")
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(f"Expected no order events for underlying Symbol {security.symbol}")
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_contract: Security):
if order_event.direction == OrderDirection.SELL and option_contract.holdings.quantity != -1:
raise AssertionError(f"No holdings were created for option contract {option_contract.symbol}")
if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0:
raise AssertionError("Expected no options holdings after closing position")
if order_event.is_assignment:
raise AssertionError(f"Assignment was not expected for {order_event.symbol}")
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
: # Keep new created instance of stop_market_order
|
```python
from AlgorithmImports import *
# <summary>
# This example demonstrates how to create future 'stop_market_order' in extended Market Hours time
# </summary>
class FutureStopMarketOrderOnExtendedHoursRegressionAlgorithm(QCAlgorithm):
# Keep new created instance of stop_market_order
_stop_market_ticket = None
# Initialize the Algorithm and Prepare Required Data
def initialize(self) -> None:
self.set_start_date(2013, 10, 6)
self.set_end_date(2013, 10, 12)
# Add mini SP500 future with extended Market hours flag
self._sp_500_e_mini = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE, extended_market_hours=True)
# Init new schedule event with params: every_day, 19:00:00 PM, what should to do
self.schedule.on(self.date_rules.every_day(),self.time_rules.at(19, 0),self.make_market_and_stop_market_order)
# This method is opened 2 new orders by scheduler
def make_market_and_stop_market_order(self) -> None:
# Don't place orders at the end of the last date, the market-on-stop order won't have time to fill
if self.time.date() == self.end_date.date() - timedelta(1) or not self._sp_500_e_mini.mapped:
return
self.market_order(self._sp_500_e_mini.mapped, 1)
self._stop_market_ticket = self.stop_market_order(self._sp_500_e_mini.mapped, -1, self._sp_500_e_mini.price * 1.1)
# New Data Event handler receiving all subscription data in a single event
def on_data(self, slice: Slice) -> None:
if (self._stop_market_ticket == None or self._stop_market_ticket.status != OrderStatus.SUBMITTED):
return None
self.stop_price = self._stop_market_ticket.get(OrderField.STOP_PRICE)
self.bar = self.securities[self._stop_market_ticket.symbol].cache.get_data()
# An order fill update the resulting information is passed to this method.
def on_order_event(self, order_event: OrderEvent) -> None:
if self.transactions.get_order_by_id(order_event.order_id).type is not OrderType.STOP_MARKET:
return None
if order_event.status == OrderStatus.FILLED:
# Get Exchange Hours for specific security
exchange_hours = self.market_hours_database.get_exchange_hours(self._sp_500_e_mini.subscription_data_config)
# Validate, Exchange is opened explicitly
if (not exchange_hours.is_open(order_event.utc_time, self._sp_500_e_mini.is_extended_market_hours)):
raise AssertionError("The Exchange hours was closed, verify 'extended_market_hours' flag in Initialize() when added new security(ies)")
def on_end_of_algorithm(self) -> None:
self.stop_market_orders = self.transactions.get_orders(lambda o: o.type is OrderType.STOP_MARKET)
for o in self.stop_market_orders:
if o.status != OrderStatus.FILLED:
raise AssertionError("The Algorithms was not handled any StopMarketOrders")
```
|
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 for history and warm up using the data available in open source.
|
```python
from AlgorithmImports import *
class IndicatorWarmupAlgorithm(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(1000000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.add_equity("SPY")
self.add_equity("IBM")
self.add_equity("BAC")
self.add_equity("GOOG", Resolution.DAILY)
self.add_equity("GOOGL", Resolution.DAILY)
self.__sd = { }
for security in self.securities:
self.__sd[security.key] = self.SymbolData(security.key, self)
# we want to warm up our algorithm
self.set_warmup(self.SymbolData.REQUIRED_BARS_WARMUP)
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
'''
# we are only using warmup for indicator spooling, so wait for us to be warm then continue
if self.is_warming_up: return
for sd in self.__sd.values():
last_price_time = sd.close.current.time
if self.round_down(last_price_time, sd.security.subscription_data_config.increment):
sd.update()
def on_order_event(self, fill):
sd = self.__sd.get(fill.symbol, None)
if sd is not None:
sd.on_order_event(fill)
def round_down(self, time, increment):
if increment.days != 0:
return time.hour == 0 and time.minute == 0 and time.second == 0
else:
return time.second == 0
class SymbolData:
REQUIRED_BARS_WARMUP = 40
PERCENT_TOLERANCE = 0.001
PERCENT_GLOBAL_STOP_LOSS = 0.01
LOT_SIZE = 10
def __init__(self, symbol, algorithm):
self.symbol = symbol
self.__algorithm = algorithm # if we're receiving daily
self.__current_stop_loss = None
self.security = algorithm.securities[symbol]
self.close = algorithm.identity(symbol)
self._adx = algorithm.adx(symbol, 14)
self._ema = algorithm.ema(symbol, 14)
self._macd = algorithm.macd(symbol, 12, 26, 9)
self.is_ready = self.close.is_ready and self._adx.is_ready and self._ema.is_ready and self._macd.is_ready
self.is_uptrend = False
self.is_downtrend = False
def update(self):
self.is_ready = self.close.is_ready and self._adx.is_ready and self._ema.is_ready and self._macd.is_ready
tolerance = 1 - self.PERCENT_TOLERANCE
self.is_uptrend = self._macd.signal.current.value > self._macd.current.value * tolerance and\
self._ema.current.value > self.close.current.value * tolerance
self.is_downtrend = self._macd.signal.current.value < self._macd.current.value * tolerance and\
self._ema.current.value < self.close.current.value * tolerance
self.try_enter()
self.try_exit()
def try_enter(self):
# can't enter if we're already in
if self.security.invested: return False
qty = 0
limit = 0.0
if self.is_uptrend:
# 100 order lots
qty = self.LOT_SIZE
limit = self.security.low
elif self.is_downtrend:
qty = -self.LOT_SIZE
limit = self.security.high
if qty != 0:
ticket = self.__algorithm.limit_order(self.symbol, qty, limit, tag="TryEnter at: {0}".format(limit))
def try_exit(self):
# can't exit if we haven't entered
if not self.security.invested: return
limit = 0
qty = self.security.holdings.quantity
exit_tolerance = 1 + 2 * self.PERCENT_TOLERANCE
if self.security.holdings.is_long and self.close.current.value * exit_tolerance < self._ema.current.value:
limit = self.security.high
elif self.security.holdings.is_short and self.close.current.value > self._ema.current.value * exit_tolerance:
limit = self.security.low
if limit != 0:
ticket = self.__algorithm.limit_order(self.symbol, -qty, limit, tag="TryExit at: {0}".format(limit))
def on_order_event(self, fill):
if fill.status != OrderStatus.FILLED: return
qty = self.security.holdings.quantity
# if we just finished entering, place a stop loss as well
if self.security.invested:
stop = fill.fill_price*(1 - self.PERCENT_GLOBAL_STOP_LOSS) if self.security.holdings.is_long \
else fill.fill_price*(1 + self.PERCENT_GLOBAL_STOP_LOSS)
self.__current_stop_loss = self.__algorithm.stop_market_order(self.symbol, -qty, stop, tag="StopLoss at: {0}".format(stop))
# check for an exit, cancel the stop loss
elif (self.__current_stop_loss is not None and self.__current_stop_loss.status is not OrderStatus.FILLED):
# cancel our current stop loss
self.__current_stop_loss.cancel("Exited position")
self.__current_stop_loss = None
```
|
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 demonstrate how to use the coarse fundamental data to define a universe as the top dollar volume and set the algorithm to use raw prices
|
```python
from AlgorithmImports import *
class RawPricesCoarseUniverseAlgorithm(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.'''
# what resolution should the data *added* to the universe be?
self.universe_settings.resolution = Resolution.DAILY
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
# Set the security initializer with the characteristics defined in CustomSecurityInitializer
self.set_security_initializer(self.custom_security_initializer)
# this add universe method accepts a single parameter that is a function that
# accepts an IEnumerable<CoarseFundamental> and returns IEnumerable<Symbol>
self.add_universe(self.coarse_selection_function)
self.__number_of_symbols = 5
def custom_security_initializer(self, security):
'''Initialize the security with raw prices and zero fees
Args:
security: Security which characteristics we want to change'''
security.set_data_normalization_mode(DataNormalizationMode.RAW)
security.set_fee_model(ConstantFeeModel(0))
# 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] ]
# this event fires whenever we have changes to our universe
def on_securities_changed(self, changes):
# liquidate removed securities
for security in changes.removed_securities:
if security.invested:
self.liquidate(security.symbol)
# we want 20% allocation in each security in our universe
for security in changes.added_securities:
self.set_holdings(security.symbol, 0.2)
def on_order_event(self, order_event):
if order_event.status == OrderStatus.FILLED:
self.log(f"OnOrderEvent({self.utc_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 to assert the behavior of <see cref="MaximumDrawdownPercentPortfolio"/>.
|
```python
from AlgorithmImports import *
from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
from Risk.CompositeRiskManagementModel import CompositeRiskManagementModel
from Risk.MaximumDrawdownPercentPortfolio import MaximumDrawdownPercentPortfolio
class MaximumDrawdownPercentPortfolioFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):
def initialize(self):
super().initialize()
self.set_universe_selection(ManualUniverseSelectionModel(Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)))
# define risk management model as a composite of several risk management models
self.set_risk_management(CompositeRiskManagementModel(
MaximumDrawdownPercentPortfolio(0.01), # Avoid loss of initial capital
MaximumDrawdownPercentPortfolio(0.015, True) # Avoid profit losses
))
```
|
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 ScheduledUniverseSelectionModel scheduling functions.
|
```python
from AlgorithmImports import *
class ScheduledUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):
'''Regression algorithm for testing ScheduledUniverseSelectionModel scheduling functions.'''
def initialize(self):
self.universe_settings.resolution = Resolution.HOUR
# 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, 1, 1)
self.set_end_date(2017, 2, 1)
# selection will run on mon/tues/thurs at 00:00/06:00/12:00/18:00
self.set_universe_selection(ScheduledUniverseSelectionModel(
self.date_rules.every(DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.THURSDAY),
self.time_rules.every(timedelta(hours = 12)),
self.select_symbols
))
self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
# some days of the week have different behavior the first time -- less securities to remove
self.seen_days = []
def select_symbols(self, dateTime):
symbols = []
weekday = dateTime.weekday()
if weekday == 0 or weekday == 1:
symbols.append(Symbol.create('SPY', SecurityType.EQUITY, Market.USA))
elif weekday == 2:
# given the date/time rules specified in Initialize, this symbol will never be selected (not invoked on wednesdays)
symbols.append(Symbol.create('AAPL', SecurityType.EQUITY, Market.USA))
else:
symbols.append(Symbol.create('IBM', SecurityType.EQUITY, Market.USA))
if weekday == 1 or weekday == 3:
symbols.append(Symbol.create('EURUSD', SecurityType.FOREX, Market.OANDA))
elif weekday == 4:
# given the date/time rules specified in Initialize, this symbol will never be selected (every 6 hours never lands on hour==1)
symbols.append(Symbol.create('EURGBP', SecurityType.FOREX, Market.OANDA))
else:
symbols.append(Symbol.create('NZDUSD', SecurityType.FOREX, Market.OANDA))
return symbols
def on_securities_changed(self, changes):
self.log("{}: {}".format(self.time, changes))
weekday = self.time.weekday()
if weekday == 0:
self.expect_additions(changes, 'SPY', 'NZDUSD')
if weekday not in self.seen_days:
self.seen_days.append(weekday)
self.expect_removals(changes, None)
else:
self.expect_removals(changes, 'EURUSD', 'IBM')
if weekday == 1:
self.expect_additions(changes, 'EURUSD')
if weekday not in self.seen_days:
self.seen_days.append(weekday)
self.expect_removals(changes, 'NZDUSD')
else:
self.expect_removals(changes, 'NZDUSD')
if weekday == 2 or weekday == 4:
# selection function not invoked on wednesdays (2) or friday (4)
self.expect_additions(changes, None)
self.expect_removals(changes, None)
if weekday == 3:
self.expect_additions(changes, "IBM")
self.expect_removals(changes, "SPY")
def on_order_event(self, orderEvent):
self.log("{}: {}".format(self.time, orderEvent))
def expect_additions(self, changes, *tickers):
if tickers is None and changes.added_securities.count > 0:
raise AssertionError("{}: Expected no additions: {}".format(self.time, self.time.weekday()))
for ticker in tickers:
if ticker is not None and ticker not in [s.symbol.value for s in changes.added_securities]:
raise AssertionError("{}: Expected {} to be added: {}".format(self.time, ticker, self.time.weekday()))
def expect_removals(self, changes, *tickers):
if tickers is None and changes.removed_securities.count > 0:
raise AssertionError("{}: Expected no removals: {}".format(self.time, self.time.weekday()))
for ticker in tickers:
if ticker is not None and ticker not in [s.symbol.value for s in changes.removed_securities]:
raise AssertionError("{}: Expected {} to be removed: {}".format(self.time, ticker, self.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 requesting daily resolution data for US Equities.
This is a simple regression test algorithm using a skeleton algorithm and requesting daily data.
|
```python
from AlgorithmImports import *
class BasicTemplateDailyAlgorithm(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,8) #Set Start Date
self.set_end_date(2013,10,17) #Set End Date
self.set_cash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.add_equity("SPY", Resolution.DAILY)
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)
self.debug("Purchased Stock")
```
|
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 Option Chain Provider -- a much faster mechanism for manually specifying the option contracts you'd like to recieve
data for and manually subscribing to them.
|
```python
from AlgorithmImports import *
class OptionChainProviderAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2015, 12, 24)
self.set_end_date(2015, 12, 24)
self.set_cash(100000)
# add the underlying asset
self.equity = self.add_equity("GOOG", Resolution.MINUTE)
self.equity.set_data_normalization_mode(DataNormalizationMode.RAW)
# initialize the option contract with empty string
self.contract = str()
self.contracts_added = set()
def on_data(self, data):
if not self.portfolio[self.equity.symbol].invested:
self.market_order(self.equity.symbol, 100)
if not (self.securities.contains_key(self.contract) and self.portfolio[self.contract].invested):
self.contract = self.options_filter(data)
if self.securities.contains_key(self.contract) and not self.portfolio[self.contract].invested:
self.market_order(self.contract, -1)
def options_filter(self, data):
''' OptionChainProvider gets a list of option contracts for an underlying symbol at requested date.
Then you can manually filter the contract list returned by GetOptionContractList.
The manual filtering will be limited to the information included in the Symbol
(strike, expiration, type, style) and/or prices from a History call '''
contracts = self.option_chain_provider.get_option_contract_list(self.equity.symbol, data.time)
self.underlying_price = self.securities[self.equity.symbol].price
# filter the out-of-money call options from the contract list which expire in 10 to 30 days from now on
otm_calls = [i for i in contracts if i.id.option_right == OptionRight.CALL and
i.id.strike_price - self.underlying_price > 0 and
10 < (i.id.date - data.time).days < 30]
if len(otm_calls) > 0:
contract = sorted(sorted(otm_calls, key = lambda x: x.id.date),
key = lambda x: x.id.strike_price - self.underlying_price)[0]
if contract not in self.contracts_added:
self.contracts_added.add(contract)
# use AddOptionContract() to subscribe the data for specified contract
self.add_option_contract(contract, Resolution.MINUTE)
return contract
else:
return str()
```
|
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 option exercise and assignment functionality
We open two positions and go with them into expiration. We expect to see our long position exercised and short position assigned.
|
```python
from AlgorithmImports import *
class OptionExerciseAssignRegressionAlgorithm(QCAlgorithm):
underlying_ticker = "GOOG"
def initialize(self):
self.set_cash(100000)
self.set_start_date(2015,12,24)
self.set_end_date(2015,12,28)
self.equity = self.add_equity(self.underlying_ticker)
self.option = self.add_option(self.underlying_ticker)
# set our strike/expiry filter for this option chain
self.option.set_filter(self.universe_func)
self.set_benchmark(self.equity.symbol)
self._assigned_option = False
def on_data(self, slice):
if self.portfolio.invested: return
for kvp in slice.option_chains:
chain = kvp.value
# find the call options expiring today
contracts = filter(lambda x:
x.expiry.date() == self.time.date() and
x.strike < chain.underlying.price and
x.right == OptionRight.CALL, chain)
# sorted the contracts by their strikes, find the second strike under market price
sorted_contracts = sorted(contracts, key = lambda x: x.strike, reverse = True)[:2]
if sorted_contracts:
self.market_order(sorted_contracts[0].symbol, 1)
self.market_order(sorted_contracts[1].symbol, -1)
# set our strike/expiry filter for this option chain
def universe_func(self, universe):
return universe.include_weeklys().strikes(-2, 2).expiration(timedelta(0), timedelta(10))
def on_order_event(self, order_event):
self.log(str(order_event))
def on_assignment_order_event(self, assignment_event):
self.log(str(assignment_event))
self._assigned_option = 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
: Algorithm asserting the correct values for the deployment target and algorithm mode.
|
```python
from AlgorithmImports import *
class AlgorithmModeAndDeploymentTargetAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2013,10, 7)
self.set_end_date(2013,10,11)
self.set_cash(100000)
#translate commented code from c# to python
self.debug(f"Algorithm Mode: {self.algorithm_mode}. Is Live Mode: {self.live_mode}. Deployment Target: {self.deployment_target}.")
if self.algorithm_mode != AlgorithmMode.BACKTESTING:
raise AssertionError(f"Algorithm mode is not backtesting. Actual: {self.algorithm_mode}")
if self.live_mode:
raise AssertionError("Algorithm should not be live")
if self.deployment_target != DeploymentTarget.LOCAL_PLATFORM:
raise AssertionError(f"Algorithm deployment target is not local. Actual{self.deployment_target}")
# For a live deployment these checks should pass:
# if self.algorithm_mode != AlgorithmMode.LIVE: raise AssertionError("Algorithm mode is not live")
# if not self.live_mode: raise AssertionError("Algorithm should be live")
# For a cloud deployment these checks should pass:
# if self.deployment_target != DeploymentTarget.CLOUD_PLATFORM: raise AssertionError("Algorithm deployment target is not cloud")
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
: Basic template options framework algorithm uses framework components
to define an algorithm that trades options.
|
```python
from AlgorithmImports import *
from Alphas.ConstantAlphaModel import ConstantAlphaModel
from Selection.OptionUniverseSelectionModel import OptionUniverseSelectionModel
from Execution.ImmediateExecutionModel import ImmediateExecutionModel
from Risk.NullRiskManagementModel import NullRiskManagementModel
class BasicTemplateOptionsFrameworkAlgorithm(QCAlgorithm):
def initialize(self):
self.universe_settings.resolution = Resolution.MINUTE
self.set_start_date(2014, 6, 5)
self.set_end_date(2014, 6, 9)
self.set_cash(100000)
# set framework models
self.set_universe_selection(EarliestExpiringWeeklyAtTheMoneyPutOptionUniverseSelectionModel(self.select_option_chain_symbols))
self.set_alpha(ConstantOptionContractAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(hours = 0.5)))
self.set_portfolio_construction(SingleSharePortfolioConstructionModel())
self.set_execution(ImmediateExecutionModel())
self.set_risk_management(NullRiskManagementModel())
def select_option_chain_symbols(self, utc_time):
new_york_time = Extensions.convert_from_utc(utc_time, TimeZones.NEW_YORK)
ticker = "TWX" if new_york_time.date() < date(2014, 6, 6) else "AAPL"
return [ Symbol.create(ticker, SecurityType.OPTION, Market.USA, f"?{ticker}") ]
class EarliestExpiringWeeklyAtTheMoneyPutOptionUniverseSelectionModel(OptionUniverseSelectionModel):
'''Creates option chain universes that select only the earliest expiry ATM weekly put contract
and runs a user defined option_chain_symbol_selector every day to enable choosing different option chains'''
def __init__(self, select_option_chain_symbols):
super().__init__(timedelta(1), select_option_chain_symbols)
def filter(self, filter):
'''Defines the option chain universe filter'''
return (filter.strikes(+1, +1)
# Expiration method accepts timedelta objects or integer for days.
# The following statements yield the same filtering criteria
.expiration(0, 7)
# .expiration(timedelta(0), timedelta(7))
.weeklys_only()
.puts_only()
.only_apply_filter_at_market_open())
class ConstantOptionContractAlphaModel(ConstantAlphaModel):
'''Implementation of a constant alpha model that only emits insights for option symbols'''
def __init__(self, type, direction, period):
super().__init__(type, direction, period)
def should_emit_insight(self, utc_time, symbol):
# only emit alpha for option symbols and not underlying equity symbols
if symbol.security_type != SecurityType.OPTION:
return False
return super().should_emit_insight(utc_time, symbol)
class SingleSharePortfolioConstructionModel(PortfolioConstructionModel):
'''Portfolio construction model that sets target quantities to 1 for up insights and -1 for down insights'''
def create_targets(self, algorithm, insights):
targets = []
for insight in insights:
targets.append(PortfolioTarget(insight.symbol, insight.direction))
return targets
```
|
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
: Live Trading Functionality Demonstration algorithm including SMS, Email and Web hook notifications.
|
```python
from AlgorithmImports import *
class LiveTradingFeaturesAlgorithm(QCAlgorithm):
### Initialize the Algorithm and Prepare Required Data
def initialize(self):
self.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 11)
self.set_cash(25000)
##Equity Data for US Markets
self.add_security(SecurityType.EQUITY, 'IBM', Resolution.SECOND)
##FOREX Data for Weekends: 24/6
self.add_security(SecurityType.FOREX, 'EURUSD', Resolution.MINUTE)
##Custom/Bitcoin Live Data: 24/7
self.add_data(Bitcoin, 'BTC', Resolution.SECOND, TimeZones.UTC)
##if the algorithm is connected to the brokerage
self.is_connected = True
### Raises the data event
def on_data(self, data):
if (not self.portfolio['IBM'].hold_stock) and data.contains_key('IBM'):
quantity = int(np.floor(self.portfolio.margin_remaining / data['IBM'].close))
self.market_order('IBM',quantity)
self.debug('Purchased IBM on ' + str(self.time.strftime("%m/%d/%Y")))
self.notify.email("myemail@gmail.com", "Test", "Test Body", "test attachment")
if "BTC" in data:
btcData = data['BTC']
if self.live_mode:
self.set_runtime_statistic('BTC', str(btcData.close))
if not self.portfolio.hold_stock:
self.market_order('BTC', 100)
##Send a notification email/SMS/web request on events:
self.notify.email("myemail@gmail.com", "Test", "Test Body", "test attachment")
self.notify.sms("+11233456789", str(btcData.time) + ">> Test message from live BTC server.")
self.notify.web("http://api.quantconnect.com", str(btcData.time) + ">> Test data packet posted from live BTC server.")
self.notify.ftp("ftp.quantconnect.com", "username", "password", "path/to/file.txt",
str(btcData.time) + ">> Test file from live BTC server.")
self.notify.sftp("ftp.quantconnect.com", "username", "password", "path/to/file.txt",
str(btcData.time) + ">> Test file from live BTC server.")
self.notify.sftp("ftp.quantconnect.com", "username", "privatekey", "optionalprivatekeypassphrase", "path/to/file.txt",
str(btcData.time) + ">> Test file from live BTC server.")
# Brokerage message event handler. This method is called for all types of brokerage messages.
def on_brokerage_message(self, message_event):
self.debug(f"Brokerage meesage received - {message_event.to_string()}")
# Brokerage disconnected event handler. This method is called when the brokerage connection is lost.
def on_brokerage_disconnect(self):
self.is_connected = False
self.debug(f"Brokerage disconnected!")
# Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection.
def on_brokerage_reconnect(self):
self.is_connected = True
self.debug(f"Brokerage reconnected!")
class Bitcoin(PythonData):
def get_source(self, config, date, is_live_mode):
if is_live_mode:
return SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.REST)
return SubscriptionDataSource("https://www.quandl.com/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc", SubscriptionTransportMedium.REMOTE_FILE)
def reader(self, config, line, date, is_live_mode):
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 None
value = live_btc["last"]
if value == 0: return None
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 None
# Example Line Format:
# Date Open High Low Close Volume (BTC) Volume (Currency) Weighted Price
# 2011-09-13 5.8 6.0 5.65 5.97 58.37138238, 346.0973893944 5.929230648356
if not (line.strip() and line[0].isdigit()): return None
try:
data = line.split(',')
coin.time = datetime.strptime(data[0], "%Y-%m-%d")
coin.value = float(data[4])
coin["Open"] = float(data[1])
coin["High"] = float(data[2])
coin["Low"] = float(data[3])
coin["Close"] = float(data[4])
coin["VolumeBTC"] = float(data[5])
coin["VolumeUSD"] = float(data[6])
coin["WeightedPrice"] = float(data[7])
return coin
except ValueError:
# Do nothing, possible error in json decoding
return None
```
|
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 a custom filter function when creating an ETF constituents universe for SPY
|
```python
from AlgorithmImports import *
class ETFConstituentUniverseFilterFunctionRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2020, 12, 1)
self.set_end_date(2021, 1, 31)
self.set_cash(100000)
self.filtered = False
self.securities_changed = False
self.received_data = False
self.etf_constituent_data = {}
self.etf_rebalanced = False
self.rebalance_count = 0
self.rebalance_asset_count = 0
self.universe_settings.resolution = Resolution.HOUR
self.spy = self.add_equity("SPY", Resolution.HOUR).symbol
self.aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
self.add_universe(self.universe.etf(self.spy, self.universe_settings, self.filter_etfs))
def filter_etfs(self, constituents):
constituents_data = list(constituents)
constituents_symbols = [i.symbol for i in constituents_data]
self.etf_constituent_data = {i.symbol: i for i in constituents_data}
if len(constituents_data) == 0:
raise AssertionError(f"Constituents collection is empty on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')}")
if self.aapl not in constituents_symbols:
raise AssertionError("AAPL is not int he constituents data provided to the algorithm")
aapl_data = [i for i in constituents_data if i.symbol == self.aapl][0]
if aapl_data.weight == 0.0:
raise AssertionError("AAPL weight is expected to be a non-zero value")
self.filtered = True
self.etf_rebalanced = True
return constituents_symbols
def on_data(self, data):
if not self.filtered and len(data.bars) != 0 and self.aapl in data.bars:
raise AssertionError("AAPL TradeBar data added to algorithm before constituent universe selection took place")
if len(data.bars) == 1 and self.spy in data.bars:
return
if len(data.bars) != 0 and self.aapl not in data.bars:
raise AssertionError(f"Expected AAPL TradeBar data on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')}")
self.received_data = True
if not self.etf_rebalanced:
return
for bar in data.bars.values():
constituent_data = self.etf_constituent_data.get(bar.symbol)
if constituent_data is not None and constituent_data.weight is not None and constituent_data.weight >= 0.0001:
# If the weight of the constituent is less than 1%, then it will be set to 1%
# If the weight of the constituent exceeds more than 5%, then it will be capped to 5%
# Otherwise, if the weight falls in between, then we use that value.
bounded_weight = max(0.01, min(constituent_data.weight, 0.05))
self.set_holdings(bar.symbol, bounded_weight)
if self.etf_rebalanced:
self.rebalance_count += 1
self.etf_rebalanced = False
self.rebalance_asset_count += 1
def on_securities_changed(self, changes):
if self.filtered and not self.securities_changed and len(changes.added_securities) < 500:
raise AssertionError(f"Added SPY S&P 500 ETF to algorithm, but less than 500 equities were loaded (added {len(changes.added_securities)} securities)")
self.securities_changed = True
def on_end_of_algorithm(self):
if self.rebalance_count != 2:
raise AssertionError(f"Expected 2 rebalance, instead rebalanced: {self.rebalance_count}")
if self.rebalance_asset_count != 8:
raise AssertionError(f"Invested in {self.rebalance_asset_count} assets (expected 8)")
if not self.filtered:
raise AssertionError("Universe selection was never triggered")
if not self.securities_changed:
raise AssertionError("Security changes never propagated to the algorithm")
if not self.received_data:
raise AssertionError("Data was never loaded for the S&P 500 constituent AAPL")
```
|
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
: Provides an example where WarmUpIndicator method is used to warm up indicators
|
```python
from AlgorithmImports import *
class SmaCrossUniverseSelectionAlgorithm(QCAlgorithm):
'''Provides an example where WarmUpIndicator method is used to warm up indicators
after their security is added and before (Universe Selection scenario)'''
_count = 10
_tolerance = 0.01
_target_percent = 1 / _count
_averages = dict()
def initialize(self) -> None:
self.universe_settings.leverage = 2
self.universe_settings.resolution = Resolution.DAILY
self.set_start_date(2018, 1, 1)
self.set_end_date(2019, 1, 1)
self.set_cash(1000000)
self.settings.automatic_indicator_warm_up = True
ibm = self.add_equity("IBM", Resolution.HOUR).symbol
ibm_sma = self.sma(ibm, 40)
self.log(f"{ibm_sma.name}: {ibm_sma.current.time} - {ibm_sma}. IsReady? {ibm_sma.is_ready}")
spy = self.add_equity("SPY", Resolution.HOUR).symbol
spy_sma = self.sma(spy, 10) # Data point indicator
spy_atr = self.atr(spy, 10,) # Bar indicator
spy_vwap = self.vwap(spy, 10) # TradeBar indicator
self.log(f"SPY - Is ready? SMA: {spy_sma.is_ready}, ATR: {spy_atr.is_ready}, VWAP: {spy_vwap.is_ready}")
eur = self.add_forex("EURUSD", Resolution.HOUR).symbol
eur_sma = self.sma(eur, 20, Resolution.DAILY)
eur_atr = self.atr(eur, 20, MovingAverageType.SIMPLE, Resolution.DAILY)
self.log(f"EURUSD - Is ready? SMA: {eur_sma.is_ready}, ATR: {eur_atr.is_ready}")
self.add_universe(self.coarse_sma_selector)
# Since the indicators are ready, we will receive error messages
# reporting that the algorithm manager is trying to add old information
self.set_warm_up(10)
def coarse_sma_selector(self, coarse: list[Fundamental]) -> list[Symbol]:
score = dict()
for cf in coarse:
if not cf.has_fundamental_data:
continue
symbol = cf.symbol
price = cf.adjusted_price
# grab the SMA instance for this symbol
avg = self._averages.setdefault(symbol, SimpleMovingAverage(100))
self.warm_up_indicator(symbol, avg, Resolution.DAILY)
# Update returns true when the indicators are ready, so don't accept until they are
if avg.update(cf.end_time, price):
value = avg.current.value
# only pick symbols who have their price over their 100 day sma
if value > price * self._tolerance:
score[symbol] = (value - price) / ((value + price) / 2)
# prefer symbols with a larger delta by percentage between the two _averages
sorted_score = sorted(score.items(), key=lambda kvp: kvp[1], reverse=True)
return [x[0] for x in sorted_score[:self._count]]
def on_securities_changed(self, changes: SecurityChanges) -> None:
for security in changes.removed_securities:
if security.invested:
self.liquidate(security.symbol)
for security in changes.added_securities:
self.set_holdings(security.symbol, self._target_percent)
```
|
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 security data filter
|
```python
from AlgorithmImports import *
class CustomSecurityDataFilterRegressionAlgorithm(QCAlgorithm):
def initialize(self):
self.set_cash(2500000)
self.set_start_date(2013,10,7)
self.set_end_date(2013,10,7)
security = self.add_security(SecurityType.EQUITY, "SPY")
security.set_data_filter(CustomDataFilter())
self.data_points = 0
def on_data(self, data):
self.data_points += 1
self.set_holdings("SPY", 0.2)
if self.data_points > 5:
raise AssertionError("There should not be more than 5 data points, but there were " + str(self.data_points))
class CustomDataFilter(SecurityDataFilter):
def filter(self, vehicle: Security, data: BaseData) -> bool:
"""
Skip data after 9:35am
"""
if data.time >= datetime(2013,10,7,9,35,0):
return False
else:
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
: This demonstration imports indian NSE index "NIFTY" as a tradable security in addition to the USDINR currency pair. We move into the
NSE market when the economy is performing well.
|
```python
from AlgorithmImports import *
class CustomDataNIFTYAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2008, 1, 8)
self.set_end_date(2014, 7, 25)
self.set_cash(100000)
# Define the symbol and "type" of our generic data:
rupee = self.add_data(DollarRupee, "USDINR", Resolution.DAILY).symbol
nifty = self.add_data(Nifty, "NIFTY", Resolution.DAILY).symbol
self.settings.automatic_indicator_warm_up = True
rupee_sma = self.sma(rupee, 20)
nifty_sma = self.sma(rupee, 20)
self.log(f"SMA - Is ready? USDINR: {rupee_sma.is_ready} NIFTY: {nifty_sma.is_ready}")
self.minimum_correlation_history = 50
self.today = CorrelationPair()
self.prices = []
def on_data(self, data):
if data.contains_key("USDINR"):
self.today = CorrelationPair(self.time)
self.today.currency_price = data["USDINR"].close
if not data.contains_key("NIFTY"): return
self.today.nifty_price = data["NIFTY"].close
if self.today.date() == data["NIFTY"].time.date():
self.prices.append(self.today)
if len(self.prices) > self.minimum_correlation_history:
self.prices.pop(0)
# Strategy
if self.time.weekday() != 2: return
cur_qnty = self.portfolio["NIFTY"].quantity
quantity = int(self.portfolio.margin_remaining * 0.9 / data["NIFTY"].close)
hi_nifty = max(price.nifty_price for price in self.prices)
lo_nifty = min(price.nifty_price for price in self.prices)
if data["NIFTY"].open >= hi_nifty:
code = self.order("NIFTY", quantity - cur_qnty)
self.debug("LONG {0} Time: {1} Quantity: {2} Portfolio: {3} Nifty: {4} Buying Power: {5}".format(code, self.time, quantity, self.portfolio["NIFTY"].quantity, data["NIFTY"].close, self.portfolio.total_portfolio_value))
elif data["NIFTY"].open <= lo_nifty:
code = self.order("NIFTY", -quantity - cur_qnty)
self.debug("SHORT {0} Time: {1} Quantity: {2} Portfolio: {3} Nifty: {4} Buying Power: {5}".format(code, self.time, quantity, self.portfolio["NIFTY"].quantity, data["NIFTY"].close, self.portfolio.total_portfolio_value))
class Nifty(PythonData):
'''NIFTY Custom Data Class'''
def get_source(self, config, date, is_live_mode):
return SubscriptionDataSource("https://www.dropbox.com/s/rsmg44jr6wexn2h/CNXNIFTY.csv?dl=1", SubscriptionTransportMedium.REMOTE_FILE)
def reader(self, config, line, date, is_live_mode):
if not (line.strip() and line[0].isdigit()): return None
# New Nifty object
index = Nifty()
index.symbol = config.symbol
try:
# Example File Format:
# Date, Open High Low Close Volume Turnover
# 2011-09-13 7792.9 7799.9 7722.65 7748.7 116534670 6107.78
data = line.split(',')
index.time = datetime.strptime(data[0], "%Y-%m-%d")
index.end_time = index.time + timedelta(days=1)
index.value = data[4]
index["Open"] = float(data[1])
index["High"] = float(data[2])
index["Low"] = float(data[3])
index["Close"] = float(data[4])
except ValueError:
# Do nothing
return None
return index
class DollarRupee(PythonData):
'''Dollar Rupe is a custom data type we create for this algorithm'''
def get_source(self, config, date, is_live_mode):
return SubscriptionDataSource("https://www.dropbox.com/s/m6ecmkg9aijwzy2/USDINR.csv?dl=1", SubscriptionTransportMedium.REMOTE_FILE)
def reader(self, config, line, date, is_live_mode):
if not (line.strip() and line[0].isdigit()): return None
# New USDINR object
currency = DollarRupee()
currency.symbol = config.symbol
try:
data = line.split(',')
currency.time = datetime.strptime(data[0], "%Y-%m-%d")
currency.end_time = currency.time + timedelta(days=1)
currency.value = data[1]
currency["Close"] = float(data[1])
except ValueError:
# Do nothing
return None
return currency
class CorrelationPair:
'''Correlation Pair is a helper class to combine two data points which we'll use to perform the correlation.'''
def __init__(self, *args):
self.nifty_price = 0 # Nifty price for this correlation pair
self.currency_price = 0 # Currency price for this correlation pair
self._date = datetime.min # Date of the correlation pair
if len(args) > 0: self._date = args[0]
def date(self):
return self._date.date()
```
|
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 ad asserting security to symbol implicit conversion
|
```python
from AlgorithmImports import *
class SecurityToSymbolRegressionAlgorithm(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)
asset = self.add_equity("SPY", Resolution.MINUTE)
self.schedule.on(self.date_rules.every_day(asset), self.time_rules.after_market_open(asset, 1), lambda: None if self.portfolio.invested else self.set_holdings(asset, 1))
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN AlphaModel that can be described like this
: Alpha Streams: Benchmark Alpha: Pick stocks according to Joel Greenblatt's Magic Formula
|
```python
from AlgorithmImports import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel
from math import ceil
from itertools import chain
class GreenblattMagicFormulaAlpha(QCAlgorithm):
''' Alpha Streams: Benchmark Alpha: Pick stocks according to Joel Greenblatt's Magic Formula
This alpha picks stocks according to Joel Greenblatt's Magic Formula.
First, each stock is ranked depending on the relative value of the ratio EV/EBITDA. For example, a stock
that has the lowest EV/EBITDA ratio in the security universe receives a score of one while a stock that has
the tenth lowest EV/EBITDA score would be assigned 10 points.
Then, each stock is ranked and given a score for the second valuation ratio, Return on Capital (ROC).
Similarly, a stock that has the highest ROC value in the universe gets one score point.
The stocks that receive the lowest combined score are chosen for insights.
Source: Greenblatt, J. (2010) The Little Book That Beats the Market
This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
sourced so the community and client funds can see an example of an alpha.'''
def initialize(self):
self.set_start_date(2018, 1, 1)
self.set_cash(100000)
#Set zero transaction fees
self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
# select stocks using MagicFormulaUniverseSelectionModel
self.set_universe_selection(GreenBlattMagicFormulaUniverseSelectionModel())
# Use MagicFormulaAlphaModel to establish insights
self.set_alpha(RateOfChangeAlphaModel())
# Equally weigh securities in portfolio, based on insights
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
## Set Immediate Execution Model
self.set_execution(ImmediateExecutionModel())
## Set Null Risk Management Model
self.set_risk_management(NullRiskManagementModel())
class RateOfChangeAlphaModel(AlphaModel):
'''Uses Rate of Change (ROC) to create magnitude prediction for insights.'''
def __init__(self, *args, **kwargs):
self.lookback = kwargs.get('lookback', 1)
self.resolution = kwargs.get('resolution', Resolution.DAILY)
self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), self.lookback)
self._symbol_data_by_symbol = {}
def update(self, algorithm, data):
insights = []
for symbol, symbol_data in self._symbol_data_by_symbol.items():
if symbol_data.can_emit:
insights.append(Insight.price(symbol, self.prediction_interval, InsightDirection.UP, symbol_data.returns, None))
return insights
def on_securities_changed(self, algorithm, changes):
# clean up data for removed securities
for removed in changes.removed_securities:
symbol_data = self._symbol_data_by_symbol.pop(removed.symbol, None)
if symbol_data is not None:
symbol_data.remove_consolidators(algorithm)
# initialize data for added securities
symbols = [ x.symbol for x in changes.added_securities
if x.symbol not in self._symbol_data_by_symbol]
history = algorithm.history(symbols, self.lookback, self.resolution)
if history.empty: return
for symbol in symbols:
symbol_data = SymbolData(algorithm, symbol, self.lookback, self.resolution)
self._symbol_data_by_symbol[symbol] = symbol_data
symbol_data.warm_up_indicators(history.loc[symbol])
class SymbolData:
'''Contains data specific to a symbol required by this model'''
def __init__(self, algorithm, symbol, lookback, resolution):
self.previous = 0
self._symbol = symbol
self.roc = RateOfChange(f'{symbol}.roc({lookback})', lookback)
self.consolidator = algorithm.resolve_consolidator(symbol, resolution)
algorithm.register_indicator(symbol, self.roc, self.consolidator)
def remove_consolidators(self, algorithm):
algorithm.subscription_manager.remove_consolidator(self._symbol, self.consolidator)
def warm_up_indicators(self, history):
for tuple in history.itertuples():
self.roc.update(tuple.Index, tuple.close)
@property
def returns(self):
return self.roc.current.value
@property
def can_emit(self):
if self.previous == self.roc.samples:
return False
self.previous = self.roc.samples
return self.roc.is_ready
def __str__(self, **kwargs):
return f'{self.roc.name}: {(1 + self.returns)**252 - 1:.2%}'
class GreenBlattMagicFormulaUniverseSelectionModel(FundamentalUniverseSelectionModel):
'''Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm.
From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Value to EBITDA (EV/EBITDA) and Return on Assets (ROA).
'''
def __init__(self,
filter_fine_data = True,
universe_settings = None):
'''Initializes a new default instance of the MagicFormulaUniverseSelectionModel'''
super().__init__(filter_fine_data, universe_settings)
# Number of stocks in Coarse Universe
self.number_of_symbols_coarse = 500
# Number of sorted stocks in the fine selection subset using the valuation ratio, EV to EBITDA (EV/EBITDA)
self.number_of_symbols_fine = 20
# Final number of stocks in security list, after sorted by the valuation ratio, Return on Assets (ROA)
self.number_of_symbols_in_portfolio = 10
self.last_month = -1
self.dollar_volume_by_symbol = {}
def select_coarse(self, algorithm, coarse):
'''Performs coarse selection for constituents.
The stocks must have fundamental data'''
month = algorithm.time.month
if month == self.last_month:
return Universe.UNCHANGED
self.last_month = month
# sort the stocks by dollar volume and take the top 1000
top = sorted([x for x in coarse if x.has_fundamental_data],
key=lambda x: x.dollar_volume, reverse=True)[:self.number_of_symbols_coarse]
self.dollar_volume_by_symbol = { i.symbol: i.dollar_volume for i in top }
return list(self.dollar_volume_by_symbol.keys())
def select_fine(self, algorithm, fine):
'''QC500: Performs fine selection for the coarse selection constituents
The company's headquarter must in the U.S.
The stock must be traded on either the NYSE or NASDAQ
At least half a year since its initial public offering
The stock's market cap must be greater than 500 million
Magic Formula: Rank stocks by Enterprise Value to EBITDA (EV/EBITDA)
Rank subset of previously ranked stocks (EV/EBITDA), using the valuation ratio Return on Assets (ROA)'''
# QC500:
## The company's headquarter must in the U.S.
## The stock must be traded on either the NYSE or NASDAQ
## At least half a year since its initial public offering
## The stock's market cap must be greater than 500 million
filtered_fine = [x for x in fine if x.company_reference.country_id == "USA"
and (x.company_reference.primary_exchange_id == "NYS" or x.company_reference.primary_exchange_id == "NAS")
and (algorithm.time - x.security_reference.ipo_date).days > 180
and x.earning_reports.basic_average_shares.three_months * x.earning_reports.basic_eps.twelve_months * x.valuation_ratios.pe_ratio > 5e8]
count = len(filtered_fine)
if count == 0: return []
my_dict = dict()
percent = self.number_of_symbols_fine / count
# select stocks with top dollar volume in every single sector
for key in ["N", "M", "U", "T", "B", "I"]:
value = [x for x in filtered_fine if x.company_reference.industry_template_code == key]
value = sorted(value, key=lambda x: self.dollar_volume_by_symbol[x.symbol], reverse = True)
my_dict[key] = value[:ceil(len(value) * percent)]
# stocks in QC500 universe
top_fine = chain.from_iterable(my_dict.values())
# Magic Formula:
## Rank stocks by Enterprise Value to EBITDA (EV/EBITDA)
## Rank subset of previously ranked stocks (EV/EBITDA), using the valuation ratio Return on Assets (ROA)
# sort stocks in the security universe of QC500 based on Enterprise Value to EBITDA valuation ratio
sorted_by_ev_to_ebitda = sorted(top_fine, key=lambda x: x.valuation_ratios.ev_to_ebitda , reverse=True)
# sort subset of stocks that have been sorted by Enterprise Value to EBITDA, based on the valuation ratio Return on Assets (ROA)
sorted_by_roa = sorted(sorted_by_ev_to_ebitda[:self.number_of_symbols_fine], key=lambda x: x.valuation_ratios.forward_roa, reverse=False)
# retrieve list of securites in portfolio
return [f.symbol for f in sorted_by_roa[:self.number_of_symbols_in_portfolio]]
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN AlphaModel that can be described like this
: The motivating idea for this Alpha Model is that a large price gap (here we use true outliers --
|
```python
from AlgorithmImports import *
class PriceGapMeanReversionAlpha(QCAlgorithm):
'''The motivating idea for this Alpha Model is that a large price gap (here we use true outliers --
price gaps that whose absolutely values are greater than 3 * Volatility) is due to rebound
back to an appropriate price or at least retreat from its brief extreme. Using a Coarse Universe selection
function, the algorithm selects the top x-companies by Dollar Volume (x can be any number you choose)
to trade with, and then uses the Standard Deviation of the 100 most-recent closing prices to determine
which price movements are outliers that warrant emitting insights.
This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
sourced so the community and client funds can see an example of an alpha.'''
def initialize(self):
self.set_start_date(2018, 1, 1) #Set Start Date
self.set_cash(100000) #Set Strategy Cash
## Initialize variables to be used in controlling frequency of universe selection
self.week = -1
## Manual Universe Selection
self.universe_settings.resolution = Resolution.MINUTE
self.set_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selection_function))
## Set trading fees to $0
self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
## Set custom Alpha Model
self.set_alpha(PriceGapMeanReversionAlphaModel())
## Set equal-weighting Portfolio Construction Model
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
## Set Execution Model
self.set_execution(ImmediateExecutionModel())
## Set Risk Management Model
self.set_risk_management(NullRiskManagementModel())
def coarse_selection_function(self, coarse):
## If it isn't a new week, return the same symbols
current_week = self.time.isocalendar()[1]
if current_week == self.week:
return Universe.UNCHANGED
self.week = current_week
## If its a new week, then re-filter stocks by Dollar Volume
sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)
return [ x.symbol for x in sorted_by_dollar_volume[:25] ]
class PriceGapMeanReversionAlphaModel(AlphaModel):
def __init__(self, *args, **kwargs):
''' Initialize variables and dictionary for Symbol Data to support algorithm's function '''
self.lookback = 100
self.resolution = kwargs['resolution'] if 'resolution' in kwargs else Resolution.MINUTE
self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), 5) ## Arbitrary
self._symbol_data_by_symbol = {}
def update(self, algorithm, data):
insights = []
## Loop through all Symbol Data objects
for symbol, symbol_data in self._symbol_data_by_symbol.items():
## Evaluate whether or not the price jump is expected to rebound
if not symbol_data.is_trend(data):
continue
## Emit insights accordingly to the price jump sign
direction = InsightDirection.DOWN if symbol_data.price_jump > 0 else InsightDirection.UP
insights.append(Insight.price(symbol, self.prediction_interval, direction, symbol_data.price_jump, None))
return insights
def on_securities_changed(self, algorithm, changes):
# Clean up data for removed securities
for removed in changes.removed_securities:
symbol_data = self._symbol_data_by_symbol.pop(removed.symbol, None)
if symbol_data is not None:
symbol_data.remove_consolidators(algorithm)
symbols = [x.symbol for x in changes.added_securities
if x.symbol not in self._symbol_data_by_symbol]
history = algorithm.history(symbols, self.lookback, self.resolution)
if history.empty: return
## Create and initialize SymbolData objects
for symbol in symbols:
symbol_data = SymbolData(algorithm, symbol, self.lookback, self.resolution)
symbol_data.warm_up_indicators(history.loc[symbol])
self._symbol_data_by_symbol[symbol] = symbol_data
class SymbolData:
def __init__(self, algorithm, symbol, lookback, resolution):
self._symbol = symbol
self.close = 0
self.last_price = 0
self.price_jump = 0
self.consolidator = algorithm.resolve_consolidator(symbol, resolution)
self.volatility = StandardDeviation(f'{symbol}.std({lookback})', lookback)
algorithm.register_indicator(symbol, self.volatility, self.consolidator)
def remove_consolidators(self, algorithm):
algorithm.subscription_manager.remove_consolidator(self._symbol, self.consolidator)
def warm_up_indicators(self, history):
self.close = history.iloc[-1].close
for tuple in history.itertuples():
self.volatility.update(tuple.Index, tuple.close)
def is_trend(self, data):
## Check for any data events that would return a NoneBar in the Alpha Model Update() method
if not data.bars.contains_key(self._symbol):
return False
self.last_price = self.close
self.close = data.bars[self._symbol].close
self.price_jump = (self.close / self.last_price) - 1
return abs(100*self.price_jump) > 3*self.volatility.current.value
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN AlphaModel that can be described like this
: Alpha Benchmark Strategy capitalizing on ETF rebalancing causing momentum during trending markets.
|
```python
from AlgorithmImports import *
class RebalancingLeveragedETFAlpha(QCAlgorithm):
''' Alpha Streams: Benchmark Alpha: Leveraged ETF Rebalancing
Strategy by Prof. Shum, reposted by Ernie Chan.
Source: http://epchan.blogspot.com/2012/10/a-leveraged-etfs-strategy.html'''
def initialize(self):
self.set_start_date(2017, 6, 1)
self.set_end_date(2018, 8, 1)
self.set_cash(100000)
underlying = ["SPY","QLD","DIA","IJR","MDY","IWM","QQQ","IYE","EEM","IYW","EFA","GAZB","SLV","IEF","IYM","IYF","IYH","IYR","IYC","IBB","FEZ","USO","TLT"]
ultra_long = ["SSO","UGL","DDM","SAA","MZZ","UWM","QLD","DIG","EET","ROM","EFO","BOIL","AGQ","UST","UYM","UYG","RXL","URE","UCC","BIB","ULE","UCO","UBT"]
ultra_short = ["SDS","GLL","DXD","SDD","MVV","TWM","QID","DUG","EEV","REW","EFU","KOLD","ZSL","PST","SMN","SKF","RXD","SRS","SCC","BIS","EPV","SCO","TBT"]
groups = []
for i in range(len(underlying)):
group = ETFGroup(self.add_equity(underlying[i], Resolution.MINUTE).symbol,
self.add_equity(ultra_long[i], Resolution.MINUTE).symbol,
self.add_equity(ultra_short[i], Resolution.MINUTE).symbol)
groups.append(group)
# Manually curated universe
self.set_universe_selection(ManualUniverseSelectionModel())
# Select the demonstration alpha model
self.set_alpha(RebalancingLeveragedETFAlphaModel(groups))
# Equally weigh securities in portfolio, based on insights
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
# Set Immediate Execution Model
self.set_execution(ImmediateExecutionModel())
# Set Null Risk Management Model
self.set_risk_management(NullRiskManagementModel())
class RebalancingLeveragedETFAlphaModel(AlphaModel):
'''
If the underlying ETF has experienced a return >= 1% since the previous day's close up to the current time at 14:15,
then buy it's ultra ETF right away, and exit at the close. If the return is <= -1%, sell it's ultra-short ETF.
'''
def __init__(self, ETFgroups):
self.etfgroups = ETFgroups
self.date = datetime.min.date
self.name = "RebalancingLeveragedETFAlphaModel"
def update(self, algorithm, data):
'''Scan to see if the returns are greater than 1% at 2.15pm to emit an insight.'''
insights = []
magnitude = 0.0005
# Paper suggests leveraged ETF's rebalance from 2.15pm - to close
# giving an insight period of 105 minutes.
period = timedelta(minutes=105)
# Get yesterday's close price at the market open
if algorithm.time.date() != self.date:
self.date = algorithm.time.date()
# Save yesterday's price and reset the signal
for group in self.etfgroups:
history = algorithm.history([group.underlying], 1, Resolution.DAILY)
group.yesterday_close = None if history.empty else history.loc[str(group.underlying)]['close'][0]
# Check if the returns are > 1% at 14.15
if algorithm.time.hour == 14 and algorithm.time.minute == 15:
for group in self.etfgroups:
if group.yesterday_close == 0 or group.yesterday_close is None: continue
returns = round((algorithm.portfolio[group.underlying].price - group.yesterday_close) / group.yesterday_close, 10)
if returns > 0.01:
insights.append(Insight.price(group.ultra_long, period, InsightDirection.UP, magnitude))
elif returns < -0.01:
insights.append(Insight.price(group.ultra_short, period, InsightDirection.DOWN, magnitude))
return insights
class ETFGroup:
'''
Group the underlying ETF and it's ultra ETFs
Args:
underlying: The underlying index ETF
ultra_long: The long-leveraged version of underlying ETF
ultra_short: The short-leveraged version of the underlying ETF
'''
def __init__(self,underlying, ultra_long, ultra_short):
self.underlying = underlying
self.ultra_long = ultra_long
self.ultra_short = ultra_short
self.yesterday_close = 0
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN AlphaModel that can be described like this
: Contingent Claim Analysis is put forth by Robert Merton, recepient of the Noble Prize in Economics in 1997 for his work in contributing to
|
```python
from AlgorithmImports import *
import scipy.stats as sp
from Risk.NullRiskManagementModel import NullRiskManagementModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
from Execution.ImmediateExecutionModel import ImmediateExecutionModel
class ContingentClaimsAnalysisDefaultPredictionAlpha(QCAlgorithm):
''' Contingent Claim Analysis is put forth by Robert Merton, recepient of the Noble Prize in Economics in 1997 for his work in contributing to
Black-Scholes option pricing theory, which says that the equity market value of stockholders’ equity is given by the Black-Scholes solution
for a European call option. This equation takes into account Debt, which in CCA is the equivalent to a strike price in the BS solution. The probability
of default on corporate debt can be calculated as the N(-d2) term, where d2 is a function of the interest rate on debt(µ), face value of the debt (B), value of the firm's assets (V),
standard deviation of the change in a firm's asset value (σ), the dividend and interest payouts due (D), and the time to maturity of the firm's debt(τ). N(*) is the cumulative
distribution function of a standard normal distribution, and calculating N(-d2) gives us the probability of the firm's assets being worth less
than the debt of the company at the time that the debt reaches maturity -- that is, the firm doesn't have enough in assets to pay off its debt and defaults.
We use a Fine/Coarse Universe Selection model to select small cap stocks, who we postulate are more likely to default
on debt in general than blue-chip companies, and extract Fundamental data to plug into the CCA formula.
This Alpha emits insights based on whether or not a company is likely to default given its probability of default vs a default probability threshold that we set arbitrarily.
Prob. default (on principal B at maturity T) = Prob(VT < B) = 1 - N(d2) = N(-d2) where -d2(µ) = -{ln(V/B) + [(µ - D) - ½σ2]τ}/ σ √τ.
N(d) = (univariate) cumulative standard normal distribution function (from -inf to d)
B = face value (principal) of the debt
D = dividend + interest payout
V = value of firm’s assets
σ (sigma) = standard deviation of firm value changes (returns in V)
τ (tau) = time to debt’s maturity
µ (mu) = interest rate
This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
sourced so the community and client funds can see an example of an alpha.'''
def initialize(self):
## Set requested data resolution and variables to help with Universe Selection control
self.universe_settings.resolution = Resolution.DAILY
self.month = -1
## Declare single variable to be passed in multiple places -- prevents issue with conflicting start dates declared in different places
self.set_start_date(2018,1,1)
self.set_cash(100000)
## SPDR Small Cap ETF is a better benchmark than the default SP500
self.set_benchmark('IJR')
## Set Universe Selection Model
self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.coarse_selection_function, self.fine_selection_function))
self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
## Set CCA Alpha Model
self.set_alpha(ContingentClaimsAnalysisAlphaModel())
## Set Portfolio Construction Model
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
## Set Execution Model
self.set_execution(ImmediateExecutionModel())
## Set Risk Management Model
self.set_risk_management(NullRiskManagementModel())
def coarse_selection_function(self, coarse):
## Boolean controls so that our symbol universe is only updated once per month
if self.time.month == self.month:
return Universe.UNCHANGED
self.month = self.time.month
## Sort by dollar volume, lowest to highest
sorted_by_dollar_volume = sorted([x for x in coarse if x.has_fundamental_data],
key=lambda x: x.dollar_volume, reverse=True)
## Return smallest 750 -- idea is that smaller companies are most likely to go bankrupt than blue-chip companies
## Filter for assets with fundamental data
return [x.symbol for x in sorted_by_dollar_volume[:750]]
def fine_selection_function(self, fine):
def is_valid(x):
statement = x.financial_statements
sheet = statement.balance_sheet
total_assets = sheet.total_assets
ratios = x.operation_ratios
return total_assets.one_month > 0 and \
total_assets.three_months > 0 and \
total_assets.six_months > 0 and \
total_assets.twelve_months > 0 and \
sheet.current_liabilities.twelve_months > 0 and \
sheet.interest_payable.twelve_months > 0 and \
ratios.total_assets_growth.one_year > 0 and \
statement.income_statement.gross_dividend_payment.twelve_months > 0 and \
ratios.roa.one_year > 0
return [x.symbol for x in sorted(fine, key=lambda x: is_valid(x))]
class ContingentClaimsAnalysisAlphaModel(AlphaModel):
def __init__(self, *args, **kwargs):
self.probability_of_default_by_symbol = {}
self.default_threshold = kwargs['default_threshold'] if 'default_threshold' in kwargs else 0.25
def update(self, algorithm, data):
'''Updates this alpha model with the latest data from the algorithm.
This is called each time the algorithm receives data for subscribed securities
Args:
algorithm: The algorithm instance
data: The new data available
Returns:
The new insights generated'''
## Build a list to hold our insights
insights = []
for symbol, pod in self.probability_of_default_by_symbol.items():
## If Prob. of Default is greater than our set threshold, then emit an insight indicating that this asset is trending downward
if pod >= self.default_threshold and pod != 1.0:
insights.append(Insight.price(symbol, timedelta(30), InsightDirection.DOWN, pod, None))
return insights
def on_securities_changed(self, algorithm, changes):
for removed in changes.removed_securities:
self.probability_of_default_by_symbol.pop(removed.symbol, None)
# initialize data for added securities
symbols = [ x.symbol for x in changes.added_securities ]
for symbol in symbols:
if symbol not in self.probability_of_default_by_symbol:
## CCA valuation
pod = self.get_probability_of_default(algorithm, symbol)
if pod is not None:
self.probability_of_default_by_symbol[symbol] = pod
def get_probability_of_default(self, algorithm, symbol):
'''This model applies options pricing theory, Black-Scholes specifically,
to fundamental data to give the probability of a default'''
security = algorithm.securities[symbol]
if security.fundamentals is None or security.fundamentals.financial_statements is None or security.fundamentals.operation_ratios is None:
return None
statement = security.fundamentals.financial_statements
sheet = statement.balance_sheet
total_assets = sheet.total_assets
tau = 360 ## Days
mu = security.fundamentals.operation_ratios.roa.one_year
V = total_assets.twelve_months
B = sheet.current_liabilities.twelve_months
D = statement.income_statement.gross_dividend_payment.twelve_months + sheet.interest_payable.twelve_months
series = pd.Series(
[
total_assets.one_month,
total_assets.three_months,
total_assets.six_months,
V
])
sigma = series.iloc[series.nonzero()[0]]
sigma = np.std(sigma.pct_change()[1:len(sigma)])
d2 = ((np.log(V) - np.log(B)) + ((mu - D) - 0.5*sigma**2.0)*tau)/ (sigma*np.sqrt(tau))
return sp.norm.cdf(-d2)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN AlphaModel that can be described like this
: Alpha Streams: Benchmark Alpha: Identify "pumped" penny stocks and predict that the price of a "pumped" penny stock reverts to mean
|
```python
from AlgorithmImports import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel
class SykesShortMicroCapAlpha(QCAlgorithm):
''' Alpha Streams: Benchmark Alpha: Identify "pumped" penny stocks and predict that the price of a "pumped" penny stock reverts to mean
This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
sourced so the community and client funds can see an example of an alpha.'''
def initialize(self):
self.set_start_date(2018, 1, 1)
self.set_cash(100000)
# Set zero transaction fees
self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
# select stocks using PennyStockUniverseSelectionModel
self.universe_settings.resolution = Resolution.DAILY
self.universe_settings.schedule.on(self.date_rules.month_start())
self.set_universe_selection(PennyStockUniverseSelectionModel())
# Use SykesShortMicroCapAlphaModel to establish insights
self.set_alpha(SykesShortMicroCapAlphaModel())
# Equally weigh securities in portfolio, based on insights
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
# Set Immediate Execution Model
self.set_execution(ImmediateExecutionModel())
# Set Null Risk Management Model
self.set_risk_management(NullRiskManagementModel())
class SykesShortMicroCapAlphaModel(AlphaModel):
'''Uses ranking of intraday percentage difference between open price and close price to create magnitude and direction prediction for insights'''
def __init__(self, *args, **kwargs):
lookback = kwargs['lookback'] if 'lookback' in kwargs else 1
resolution = kwargs['resolution'] if 'resolution' in kwargs else Resolution.DAILY
self.prediction_interval = Time.multiply(Extensions.to_time_span(resolution), lookback)
self.number_of_stocks = kwargs['number_of_stocks'] if 'number_of_stocks' in kwargs else 10
def update(self, algorithm, data):
insights = []
symbols_ret = dict()
for security in algorithm.active_securities.values:
if security.has_data:
open_ = security.open
if open_ != 0:
# Intraday price change for penny stocks
symbols_ret[security.symbol] = security.close / open_ - 1
# Rank penny stocks on one day price change and retrieve list of ten "pumped" penny stocks
pumped_stocks = dict(sorted(symbols_ret.items(),
key = lambda kv: (-round(kv[1], 6), kv[0]))[:self.number_of_stocks])
# Emit "down" insight for "pumped" penny stocks
for symbol, value in pumped_stocks.items():
insights.append(Insight.price(symbol, self.prediction_interval, InsightDirection.DOWN, abs(value), None))
return insights
class PennyStockUniverseSelectionModel(FundamentalUniverseSelectionModel):
'''Defines a universe of penny stocks, as a universe selection model for the framework algorithm:
The stocks must have fundamental data
The stock must have positive previous-day close price
The stock must have volume between $1000000 and $10000 on the previous trading day
The stock must cost less than $5'''
def __init__(self):
super().__init__()
# Number of stocks in Coarse Universe
self.number_of_symbols_coarse = 500
def select(self, algorithm, fundamental):
# sort the stocks by dollar volume and take the top 500
top = sorted([x for x in fundamental if x.has_fundamental_data
and 5 > x.price > 0
and 1000000 > x.volume > 10000],
key=lambda x: x.dollar_volume, reverse=True)[:self.number_of_symbols_coarse]
return [x.symbol for x in top]
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN ExecutionModel that can be described like this
: Execution model that submits orders while the current market prices is at least the configured number of standard
|
```python
from AlgorithmImports import *
class StandardDeviationExecutionModel(ExecutionModel):
'''Execution model that submits orders while the current market prices is at least the configured number of standard
deviations away from the mean in the favorable direction (below/above for buy/sell respectively)'''
def __init__(self,
period = 60,
deviations = 2,
resolution = Resolution.MINUTE,
asynchronous=True):
'''Initializes a new instance of the StandardDeviationExecutionModel class
Args:
period: Period of the standard deviation indicator
deviations: The number of deviations away from the mean before submitting an order
resolution: The resolution of the STD and SMA indicators
asynchronous: If True, orders will be submitted asynchronously.'''
super().__init__(asynchronous)
self.period = period
self.deviations = deviations
self.resolution = resolution
self.targets_collection = PortfolioTargetCollection()
self._symbol_data = {}
# Gets or sets the maximum order value in units of the account currency.
# This defaults to $20,000. For example, if purchasing a stock with a price
# of $100, then the maximum order size would be 200 shares.
self.maximum_order_value = 20000
def execute(self, algorithm, targets):
'''Executes market orders if the standard deviation of price is more
than the configured number of deviations in the favorable direction.
Args:
algorithm: The algorithm instance
targets: The portfolio targets'''
self.targets_collection.add_range(targets)
# for performance we check count value, OrderByMarginImpact and ClearFulfilled are expensive to call
if not self.targets_collection.is_empty:
for target in self.targets_collection.order_by_margin_impact(algorithm):
symbol = target.symbol
# calculate remaining quantity to be ordered
unordered_quantity = OrderSizing.get_unordered_quantity(algorithm, target)
# fetch our symbol data containing our STD/SMA indicators
data = self._symbol_data.get(symbol, None)
if data is None: return
# check order entry conditions
if data.std.is_ready and self.price_is_favorable(data, unordered_quantity):
# Adjust order size to respect the maximum total order value
order_size = OrderSizing.get_order_size_for_maximum_value(data.security, self.maximum_order_value, unordered_quantity)
if order_size != 0:
algorithm.market_order(symbol, order_size, self.asynchronous, target.tag)
self.targets_collection.clear_fulfilled(algorithm)
def on_securities_changed(self, algorithm, changes):
'''Event fired each time the we add/remove securities from the data feed
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
for added in changes.added_securities:
if added.symbol not in self._symbol_data:
self._symbol_data[added.symbol] = SymbolData(algorithm, added, self.period, self.resolution)
for removed in changes.removed_securities:
# clean up data from removed securities
symbol = removed.symbol
if symbol in self._symbol_data:
if self.is_safe_to_remove(algorithm, symbol):
data = self._symbol_data.pop(symbol)
algorithm.subscription_manager.remove_consolidator(symbol, data.consolidator)
def price_is_favorable(self, data, unordered_quantity):
'''Determines if the current price is more than the configured
number of standard deviations away from the mean in the favorable direction.'''
sma = data.sma.current.value
deviations = self.deviations * data.std.current.value
if unordered_quantity > 0:
return data.security.bid_price < sma - deviations
else:
return data.security.ask_price > sma + deviations
def is_safe_to_remove(self, algorithm, symbol):
'''Determines if it's safe to remove the associated symbol data'''
# confirm the security isn't currently a member of any universe
return not any([kvp.value.contains_member(symbol) for kvp in algorithm.universe_manager])
class SymbolData:
def __init__(self, algorithm, security, period, resolution):
symbol = security.symbol
self.security = security
self.consolidator = algorithm.resolve_consolidator(symbol, resolution)
sma_name = algorithm.create_indicator_name(symbol, f"SMA{period}", resolution)
self.sma = SimpleMovingAverage(sma_name, period)
algorithm.register_indicator(symbol, self.sma, self.consolidator)
std_name = algorithm.create_indicator_name(symbol, f"STD{period}", resolution)
self.std = StandardDeviation(std_name, period)
algorithm.register_indicator(symbol, self.std, self.consolidator)
# warmup our indicators by pushing history through the indicators
bars = algorithm.history[self.consolidator.input_type](symbol, period, resolution)
for bar in bars:
self.sma.update(bar.end_time, bar.close)
self.std.update(bar.end_time, bar.close)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN ExecutionModel that can be described like this
: Execution model that submits orders while the current market price is more favorable that the current volume weighted average price.
|
```python
from AlgorithmImports import *
class VolumeWeightedAveragePriceExecutionModel(ExecutionModel):
'''Execution model that submits orders while the current market price is more favorable that the current volume weighted average price.'''
def __init__(self, asynchronous=True):
'''Initializes a new instance of the VolumeWeightedAveragePriceExecutionModel class'''
super().__init__(asynchronous)
self.targets_collection = PortfolioTargetCollection()
self.symbol_data = {}
# Gets or sets the maximum order quantity as a percentage of the current bar's volume.
# This defaults to 0.01m = 1%. For example, if the current bar's volume is 100,
# then the maximum order size would equal 1 share.
self.maximum_order_quantity_percent_volume = 0.01
def execute(self, algorithm, targets):
'''Executes market orders if the standard deviation of price is more
than the configured number of deviations in the favorable direction.
Args:
algorithm: The algorithm instance
targets: The portfolio targets'''
# update the complete set of portfolio targets with the new targets
self.targets_collection.add_range(targets)
# for performance we check count value, OrderByMarginImpact and ClearFulfilled are expensive to call
if not self.targets_collection.is_empty:
for target in self.targets_collection.order_by_margin_impact(algorithm):
symbol = target.symbol
# calculate remaining quantity to be ordered
unordered_quantity = OrderSizing.get_unordered_quantity(algorithm, target)
# fetch our symbol data containing our VWAP indicator
data = self.symbol_data.get(symbol, None)
if data is None: return
# check order entry conditions
if self.price_is_favorable(data, unordered_quantity):
# adjust order size to respect maximum order size based on a percentage of current volume
order_size = OrderSizing.get_order_size_for_percent_volume(data.security, self.maximum_order_quantity_percent_volume, unordered_quantity)
if order_size != 0:
algorithm.market_order(symbol, order_size, self.asynchronous, target.tag)
self.targets_collection.clear_fulfilled(algorithm)
def on_securities_changed(self, algorithm, changes):
'''Event fired each time the we add/remove securities from the data feed
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
for removed in changes.removed_securities:
# clean up removed security data
if removed.symbol in self.symbol_data:
if self.is_safe_to_remove(algorithm, removed.symbol):
data = self.symbol_data.pop(removed.symbol)
algorithm.subscription_manager.remove_consolidator(removed.symbol, data.consolidator)
for added in changes.added_securities:
if added.symbol not in self.symbol_data:
self.symbol_data[added.symbol] = SymbolData(algorithm, added)
def price_is_favorable(self, data, unordered_quantity):
'''Determines if the current price is more than the configured
number of standard deviations away from the mean in the favorable direction.'''
if unordered_quantity > 0:
if data.security.bid_price < data.vwap:
return True
else:
if data.security.ask_price > data.vwap:
return True
return False
def is_safe_to_remove(self, algorithm, symbol):
'''Determines if it's safe to remove the associated symbol data'''
# confirm the security isn't currently a member of any universe
return not any([kvp.value.contains_member(symbol) for kvp in algorithm.universe_manager])
class SymbolData:
def __init__(self, algorithm, security):
self.security = security
self.consolidator = algorithm.resolve_consolidator(security.symbol, security.resolution)
name = algorithm.create_indicator_name(security.symbol, "VWAP", security.resolution)
self._vwap = IntradayVwap(name)
algorithm.register_indicator(security.symbol, self._vwap, self.consolidator)
@property
def vwap(self):
return self._vwap.value
class IntradayVwap:
'''Defines the canonical intraday VWAP indicator'''
def __init__(self, name):
self.name = name
self.value = 0.0
self.last_date = datetime.min
self.sum_of_volume = 0.0
self.sum_of_price_times_volume = 0.0
@property
def is_ready(self):
return self.sum_of_volume > 0.0
def update(self, input):
'''Computes the new VWAP'''
success, volume, average_price = self.get_volume_and_average_price(input)
if not success:
return self.is_ready
# reset vwap on daily boundaries
if self.last_date != input.end_time.date():
self.sum_of_volume = 0.0
self.sum_of_price_times_volume = 0.0
self.last_date = input.end_time.date()
# running totals for Σ PiVi / Σ Vi
self.sum_of_volume += volume
self.sum_of_price_times_volume += average_price * volume
if self.sum_of_volume == 0.0:
# if we have no trade volume then use the current price as VWAP
self.value = input.value
return self.is_ready
self.value = self.sum_of_price_times_volume / self.sum_of_volume
return self.is_ready
def get_volume_and_average_price(self, input):
'''Determines the volume and price to be used for the current input in the VWAP computation'''
if type(input) is Tick:
if input.tick_type == TickType.TRADE:
return True, float(input.quantity), float(input.last_price)
if type(input) is TradeBar:
if not input.is_fill_forward:
average_price = float(input.high + input.low + input.close) / 3
return True, float(input.volume), average_price
return False, 0.0, 0.0
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN ExecutionModel that can be described like this
: Execution model that submits orders while the current spread is tight.
|
```python
from AlgorithmImports import *
class SpreadExecutionModel(ExecutionModel):
'''Execution model that submits orders while the current spread is tight.
Note this execution model will not work using Resolution.DAILY since Exchange.exchange_open will be false, suggested resolution is Minute
'''
def __init__(self, accepting_spread_percent=0.005, asynchronous=True):
'''Initializes a new instance of the SpreadExecutionModel class'''
super().__init__(asynchronous)
self.targets_collection = PortfolioTargetCollection()
# Gets or sets the maximum spread compare to current price in percentage.
self.accepting_spread_percent = Math.abs(accepting_spread_percent)
def execute(self, algorithm, targets):
'''Executes market orders if the spread percentage to price is in desirable range.
Args:
algorithm: The algorithm instance
targets: The portfolio targets'''
# update the complete set of portfolio targets with the new targets
self.targets_collection.add_range(targets)
# for performance we check count value, OrderByMarginImpact and ClearFulfilled are expensive to call
if not self.targets_collection.is_empty:
for target in self.targets_collection.order_by_margin_impact(algorithm):
symbol = target.symbol
# calculate remaining quantity to be ordered
unordered_quantity = OrderSizing.get_unordered_quantity(algorithm, target)
# check order entry conditions
if unordered_quantity != 0:
# get security information
security = algorithm.securities[symbol]
if self.spread_is_favorable(security):
algorithm.market_order(symbol, unordered_quantity, self.asynchronous, target.tag)
self.targets_collection.clear_fulfilled(algorithm)
def spread_is_favorable(self, security):
'''Determines if the spread is in desirable range.'''
# Price has to be larger than zero to avoid zero division error, or negative price causing the spread percentage < 0 by error
# Has to be in opening hours of exchange to avoid extreme spread in OTC period
return security.exchange.exchange_open \
and security.price > 0 and security.ask_price > 0 and security.bid_price > 0 \
and (security.ask_price - security.bid_price) / security.price <= self.accepting_spread_percent
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN AlphaModel that can be described like this
: This alpha model is designed to accept every possible pair combination
|
```python
from AlgorithmImports import *
from enum import Enum
class BasePairsTradingAlphaModel(AlphaModel):
'''This alpha model is designed to accept every possible pair combination
from securities selected by the universe selection model
This model generates alternating long ratio/short ratio insights emitted as a group'''
def __init__(self, lookback = 1,
resolution = Resolution.DAILY,
threshold = 1):
''' Initializes a new instance of the PairsTradingAlphaModel class
Args:
lookback: Lookback period of the analysis
resolution: Analysis resolution
threshold: The percent [0, 100] deviation of the ratio from the mean before emitting an insight'''
self.lookback = lookback
self.resolution = resolution
self.threshold = threshold
self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), self.lookback)
self.pairs = dict()
self.securities = set()
self.name = f'{self.__class__.__name__}({self.lookback},{resolution},{Extensions.normalize_to_str(threshold)})'
def update(self, algorithm, data):
''' Updates this alpha model with the latest data from the algorithm.
This is called each time the algorithm receives data for subscribed securities
Args:
algorithm: The algorithm instance
data: The new data available
Returns:
The new insights generated'''
insights = []
for key, pair in self.pairs.items():
insights.extend(pair.get_insight_group())
return insights
def on_securities_changed(self, algorithm, changes):
'''Event fired each time the we add/remove securities from the data feed.
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
for security in changes.added_securities:
self.securities.add(security)
for security in changes.removed_securities:
if security in self.securities:
self.securities.remove(security)
self.update_pairs(algorithm)
for security in changes.removed_securities:
keys = [k for k in self.pairs.keys() if security.symbol in k]
for key in keys:
self.pairs.pop(key).dispose()
def update_pairs(self, algorithm):
symbols = sorted([x.symbol for x in self.securities])
for i in range(0, len(symbols)):
asset_i = symbols[i]
for j in range(1 + i, len(symbols)):
asset_j = symbols[j]
pair_symbol = (asset_i, asset_j)
invert = (asset_j, asset_i)
if pair_symbol in self.pairs or invert in self.pairs:
continue
if not self.has_passed_test(algorithm, asset_i, asset_j):
continue
pair = self.Pair(algorithm, asset_i, asset_j, self.prediction_interval, self.threshold)
self.pairs[pair_symbol] = pair
def has_passed_test(self, algorithm, asset1, asset2):
'''Check whether the assets pass a pairs trading test
Args:
algorithm: The algorithm instance that experienced the change in securities
asset1: The first asset's symbol in the pair
asset2: The second asset's symbol in the pair
Returns:
True if the statistical test for the pair is successful'''
return True
class Pair:
class State(Enum):
SHORT_RATIO = -1
FLAT_RATIO = 0
LONG_RATIO = 1
def __init__(self, algorithm, asset1, asset2, prediction_interval, threshold):
'''Create a new pair
Args:
algorithm: The algorithm instance that experienced the change in securities
asset1: The first asset's symbol in the pair
asset2: The second asset's symbol in the pair
prediction_interval: Period over which this insight is expected to come to fruition
threshold: The percent [0, 100] deviation of the ratio from the mean before emitting an insight'''
self.state = self.State.FLAT_RATIO
self.algorithm = algorithm
self.asset1 = asset1
self.asset2 = asset2
# Created the Identity indicator for a given Symbol and
# the consolidator it is registered to. The consolidator reference
# will be used to remove it from SubscriptionManager
def create_identity_indicator(symbol: Symbol):
resolution = min([x.resolution for x in algorithm.subscription_manager.subscription_data_config_service.get_subscription_data_configs(symbol)])
name = algorithm.create_indicator_name(symbol, "close", resolution)
identity = Identity(name)
consolidator = algorithm.resolve_consolidator(symbol, resolution)
algorithm.register_indicator(symbol, identity, consolidator)
return identity, consolidator
self.asset1_price, self.identity_consolidator1 = create_identity_indicator(asset1);
self.asset2_price, self.identity_consolidator2 = create_identity_indicator(asset2);
self.ratio = IndicatorExtensions.over(self.asset1_price, self.asset2_price)
self.mean = IndicatorExtensions.of(ExponentialMovingAverage(500), self.ratio)
upper = ConstantIndicator[IndicatorDataPoint]("ct", 1 + threshold / 100)
self.upper_threshold = IndicatorExtensions.times(self.mean, upper)
lower = ConstantIndicator[IndicatorDataPoint]("ct", 1 - threshold / 100)
self.lower_threshold = IndicatorExtensions.times(self.mean, lower)
self.prediction_interval = prediction_interval
def dispose(self):
'''
On disposal, remove the consolidators from the subscription manager
'''
self.algorithm.subscription_manager.remove_consolidator(self.asset1, self.identity_consolidator1)
self.algorithm.subscription_manager.remove_consolidator(self.asset2, self.identity_consolidator2)
def get_insight_group(self):
'''Gets the insights group for the pair
Returns:
Insights grouped by an unique group id'''
if not self.mean.is_ready:
return []
# don't re-emit the same direction
if self.state is not self.State.LONG_RATIO and self.ratio > self.upper_threshold:
self.state = self.State.LONG_RATIO
# asset1/asset2 is more than 2 std away from mean, short asset1, long asset2
short_asset_1 = Insight.price(self.asset1, self.prediction_interval, InsightDirection.DOWN)
long_asset_2 = Insight.price(self.asset2, self.prediction_interval, InsightDirection.UP)
# creates a group id and set the GroupId property on each insight object
return Insight.group(short_asset_1, long_asset_2)
# don't re-emit the same direction
if self.state is not self.State.SHORT_RATIO and self.ratio < self.lower_threshold:
self.state = self.State.SHORT_RATIO
# asset1/asset2 is less than 2 std away from mean, long asset1, short asset2
long_asset_1 = Insight.price(self.asset1, self.prediction_interval, InsightDirection.UP)
short_asset_2 = Insight.price(self.asset2, self.prediction_interval, InsightDirection.DOWN)
# creates a group id and set the GroupId property on each insight object
return Insight.group(long_asset_1, short_asset_2)
return []
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN AlphaModel that can be described like this
: Defines a custom alpha model that uses MACD crossovers. The MACD signal line
|
```python
from AlgorithmImports import *
class MacdAlphaModel(AlphaModel):
'''Defines a custom alpha model that uses MACD crossovers. The MACD signal line
is used to generate up/down insights if it's stronger than the bounce threshold.
If the MACD signal is within the bounce threshold then a flat price insight is returned.'''
def __init__(self,
fastPeriod = 12,
slowPeriod = 26,
signalPeriod = 9,
movingAverageType = MovingAverageType.Exponential,
resolution = Resolution.Daily):
''' Initializes a new instance of the MacdAlphaModel class
Args:
fastPeriod: The MACD fast period
slowPeriod: The MACD slow period</param>
signalPeriod: The smoothing period for the MACD signal
movingAverageType: The type of moving average to use in the MACD'''
self.fastPeriod = fastPeriod
self.slowPeriod = slowPeriod
self.signalPeriod = signalPeriod
self.movingAverageType = movingAverageType
self.resolution = resolution
self.insightPeriod = Time.Multiply(Extensions.ToTimeSpan(resolution), fastPeriod)
self.bounceThresholdPercent = 0.01
self.insightCollection = InsightCollection()
self.symbolData = {}
self.Name = '{}({},{},{},{},{})'.format(self.__class__.__name__, fastPeriod, slowPeriod, signalPeriod, movingAverageType, resolution)
def Update(self, algorithm, data):
''' Determines an insight for each security based on it's current MACD signal
Args:
algorithm: The algorithm instance
data: The new data available
Returns:
The new insights generated'''
insights = []
for key, sd in self.symbolData.items():
if sd.Security.Price == 0:
continue
direction = InsightDirection.Flat
normalized_signal = sd.MACD.Signal.Current.Value / sd.Security.Price
if normalized_signal > self.bounceThresholdPercent:
direction = InsightDirection.Up
elif normalized_signal < -self.bounceThresholdPercent:
direction = InsightDirection.Down
# ignore signal for same direction as previous signal
if direction == sd.PreviousDirection:
continue
sd.PreviousDirection = direction
if direction == InsightDirection.Flat:
self.CancelInsights(algorithm, sd.Security.Symbol)
continue
insight = Insight.Price(sd.Security.Symbol, self.insightPeriod, direction)
insights.append(insight)
self.insightCollection.Add(insight)
return insights
def OnSecuritiesChanged(self, algorithm, changes):
'''Event fired each time the we add/remove securities from the data feed.
This initializes the MACD for each added security and cleans up the indicator for each removed security.
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
for added in changes.AddedSecurities:
self.symbolData[added.Symbol] = SymbolData(algorithm, added, self.fastPeriod, self.slowPeriod, self.signalPeriod, self.movingAverageType, self.resolution)
for removed in changes.RemovedSecurities:
symbol = removed.Symbol
data = self.symbolData.pop(symbol, None)
if data is not None:
# clean up our consolidator
algorithm.SubscriptionManager.RemoveConsolidator(symbol, data.Consolidator)
# remove from insight collection manager
self.CancelInsights(algorithm, symbol)
def CancelInsights(self, algorithm, symbol):
if not self.insightCollection.ContainsKey(symbol):
return
insights = self.insightCollection[symbol]
algorithm.Insights.Cancel(insights)
self.insightCollection.Clear([ symbol ]);
class SymbolData:
def __init__(self, algorithm, security, fastPeriod, slowPeriod, signalPeriod, movingAverageType, resolution):
self.Security = security
self.MACD = MovingAverageConvergenceDivergence(fastPeriod, slowPeriod, signalPeriod, movingAverageType)
self.Consolidator = algorithm.ResolveConsolidator(security.Symbol, resolution)
algorithm.RegisterIndicator(security.Symbol, self.MACD, self.Consolidator)
algorithm.WarmUpIndicator(security.Symbol, self.MACD, resolution)
self.PreviousDirection = None
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN AlphaModel that can be described like this
: Uses Wilder's RSI to create insights.
|
```python
from AlgorithmImports import *
from QuantConnect.Logging import *
from enum import Enum
class RsiAlphaModel(AlphaModel):
'''Uses Wilder's RSI to create insights.
Using default settings, a cross over below 30 or above 70 will trigger a new insight.'''
def __init__(self,
period = 14,
resolution = Resolution.DAILY):
'''Initializes a new instance of the RsiAlphaModel class
Args:
period: The RSI indicator period'''
self.period = period
self.resolution = resolution
self.insight_period = Time.multiply(Extensions.to_time_span(resolution), period)
self.symbol_data_by_symbol ={}
self.name = '{}({},{})'.format(self.__class__.__name__, period, resolution)
def update(self, algorithm, data):
'''Updates this alpha model with the latest data from the algorithm.
This is called each time the algorithm receives data for subscribed securities
Args:
algorithm: The algorithm instance
data: The new data available
Returns:
The new insights generated'''
insights = []
for symbol, symbol_data in self.symbol_data_by_symbol.items():
rsi = symbol_data.rsi
previous_state = symbol_data.state
state = self.get_state(rsi, previous_state)
if state != previous_state and rsi.is_ready:
if state == State.TRIPPED_LOW:
insights.append(Insight.price(symbol, self.insight_period, InsightDirection.UP))
if state == State.TRIPPED_HIGH:
insights.append(Insight.price(symbol, self.insight_period, InsightDirection.DOWN))
symbol_data.state = state
return insights
def on_securities_changed(self, algorithm, changes):
'''Cleans out old security data and initializes the RSI for any newly added securities.
Event fired each time the we add/remove securities from the data feed
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
# clean up data for removed securities
for security in changes.removed_securities:
symbol_data = self.symbol_data_by_symbol.pop(security.symbol, None)
if symbol_data:
symbol_data.dispose()
# initialize data for added securities
added_symbols = []
for security in changes.added_securities:
symbol = security.symbol
if symbol not in self.symbol_data_by_symbol:
symbol_data = SymbolData(algorithm, symbol, self.period, self.resolution)
self.symbol_data_by_symbol[symbol] = symbol_data
added_symbols.append(symbol)
if added_symbols:
history = algorithm.history[TradeBar](added_symbols, self.period, self.resolution)
for trade_bars in history:
for bar in trade_bars.values():
self.symbol_data_by_symbol[bar.symbol].update(bar)
def get_state(self, rsi, previous):
''' Determines the new state. This is basically cross-over detection logic that
includes considerations for bouncing using the configured bounce tolerance.'''
if rsi.current.value > 70:
return State.TRIPPED_HIGH
if rsi.current.value < 30:
return State.TRIPPED_LOW
if previous == State.TRIPPED_LOW:
if rsi.current.value > 35:
return State.MIDDLE
if previous == State.TRIPPED_HIGH:
if rsi.current.value < 65:
return State.MIDDLE
return previous
class SymbolData:
'''Contains data specific to a symbol required by this model'''
def __init__(self, algorithm, symbol, period, resolution):
self.algorithm = algorithm
self.symbol = symbol
self.state = State.MIDDLE
self.rsi = RelativeStrengthIndex(period, MovingAverageType.WILDERS)
self.consolidator = algorithm.resolve_consolidator(symbol, resolution)
algorithm.register_indicator(symbol, self.rsi, self.consolidator)
def update(self, bar):
self.consolidator.update(bar)
def dispose(self):
self.algorithm.subscription_manager.remove_consolidator(self.symbol, self.consolidator)
class State(Enum):
'''Defines the state. This is used to prevent signal spamming and aid in bounce detection.'''
TRIPPED_LOW = 0
MIDDLE = 1
TRIPPED_HIGH = 2
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN AlphaModel that can be described like this
: This alpha model is designed to rank every pair combination by its pearson correlation
|
```python
from AlgorithmImports import *
from Alphas.BasePairsTradingAlphaModel import BasePairsTradingAlphaModel
from scipy.stats import pearsonr
class PearsonCorrelationPairsTradingAlphaModel(BasePairsTradingAlphaModel):
''' This alpha model is designed to rank every pair combination by its pearson correlation
and trade the pair with the hightest correlation
This model generates alternating long ratio/short ratio insights emitted as a group'''
def __init__(self, lookback = 15,
resolution = Resolution.MINUTE,
threshold = 1,
minimum_correlation = .5):
'''Initializes a new instance of the PearsonCorrelationPairsTradingAlphaModel class
Args:
lookback: lookback period of the analysis
resolution: analysis resolution
threshold: The percent [0, 100] deviation of the ratio from the mean before emitting an insight
minimum_correlation: The minimum correlation to consider a tradable pair'''
super().__init__(lookback, resolution, threshold)
self.lookback = lookback
self.resolution = resolution
self.minimum_correlation = minimum_correlation
self.best_pair = ()
def on_securities_changed(self, algorithm, changes):
'''Event fired each time the we add/remove securities from the data feed.
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
for security in changes.added_securities:
self.securities.add(security)
for security in changes.removed_securities:
if security in self.securities:
self.securities.remove(security)
symbols = sorted([ x.symbol for x in self.securities ])
history = algorithm.history(symbols, self.lookback, self.resolution)
if not history.empty:
history = history.close.unstack(level=0)
df = self.get_price_dataframe(history)
stop = len(df.columns)
corr = dict()
for i in range(0, stop):
for j in range(i+1, stop):
if (j, i) not in corr:
corr[(i, j)] = pearsonr(df.iloc[:,i], df.iloc[:,j])[0]
corr = sorted(corr.items(), key = lambda kv: kv[1])
if corr[-1][1] >= self.minimum_correlation:
self.best_pair = (symbols[corr[-1][0][0]], symbols[corr[-1][0][1]])
super().on_securities_changed(algorithm, changes)
def has_passed_test(self, algorithm, asset1, asset2):
'''Check whether the assets pass a pairs trading test
Args:
algorithm: The algorithm instance that experienced the change in securities
asset1: The first asset's symbol in the pair
asset2: The second asset's symbol in the pair
Returns:
True if the statistical test for the pair is successful'''
return self.best_pair is not None and self.best_pair[0] == asset1 and self.best_pair[1] == asset2
def get_price_dataframe(self, df):
timezones = { x.symbol.value: x.exchange.time_zone for x in self.securities }
# Use log prices
df = np.log(df)
is_single_timeZone = len(set(timezones.values())) == 1
if not is_single_timeZone:
series_dict = dict()
for column in df:
# Change the dataframe index from data time to UTC time
to_utc = lambda x: Extensions.convert_to_utc(x, timezones[column])
if self.resolution == Resolution.DAILY:
to_utc = lambda x: Extensions.convert_to_utc(x, timezones[column]).date()
data = df[[column]]
data.index = data.index.map(to_utc)
series_dict[column] = data[column]
df = pd.DataFrame(series_dict).dropna()
return (df - df.shift(1)).dropna()
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN AlphaModel that can be described like this
: Uses Historical returns to create insights.
|
```python
from AlgorithmImports import *
class HistoricalReturnsAlphaModel(AlphaModel):
'''Uses Historical returns to create insights.'''
def __init__(self, *args, **kwargs):
'''Initializes a new default instance of the HistoricalReturnsAlphaModel class.
Args:
lookback(int): Historical return lookback period
resolution: The resolution of historical data'''
self.lookback = kwargs['lookback'] if 'lookback' in kwargs else 1
self.resolution = kwargs['resolution'] if 'resolution' in kwargs else Resolution.DAILY
self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), self.lookback)
self._symbol_data_by_symbol = {}
self.insight_collection = InsightCollection()
def update(self, algorithm, data):
'''Updates this alpha model with the latest data from the algorithm.
This is called each time the algorithm receives data for subscribed securities
Args:
algorithm: The algorithm instance
data: The new data available
Returns:
The new insights generated'''
insights = []
for symbol, symbol_data in self._symbol_data_by_symbol.items():
if symbol_data.can_emit:
direction = InsightDirection.FLAT
magnitude = symbol_data.return_
if magnitude > 0: direction = InsightDirection.UP
if magnitude < 0: direction = InsightDirection.DOWN
if direction == InsightDirection.FLAT:
self.cancel_insights(algorithm, symbol)
continue
insights.append(Insight.price(symbol, self.prediction_interval, direction, magnitude, None))
self.insight_collection.add_range(insights)
return insights
def on_securities_changed(self, algorithm, changes):
'''Event fired each time the we add/remove securities from the data feed
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
# clean up data for removed securities
for removed in changes.removed_securities:
symbol_data = self._symbol_data_by_symbol.pop(removed.symbol, None)
if symbol_data is not None:
symbol_data.remove_consolidators(algorithm)
self.cancel_insights(algorithm, removed.symbol)
# initialize data for added securities
symbols = [ x.symbol for x in changes.added_securities ]
history = algorithm.history(symbols, self.lookback, self.resolution)
if history.empty: return
tickers = history.index.levels[0]
for ticker in tickers:
symbol = SymbolCache.get_symbol(ticker)
if symbol not in self._symbol_data_by_symbol:
symbol_data = SymbolData(symbol, self.lookback)
self._symbol_data_by_symbol[symbol] = symbol_data
symbol_data.register_indicators(algorithm, self.resolution)
symbol_data.warm_up_indicators(history.loc[ticker])
def cancel_insights(self, algorithm, symbol):
if not self.insight_collection.contains_key(symbol):
return
insights = self.insight_collection[symbol]
algorithm.insights.cancel(insights)
self.insight_collection.clear([ symbol ]);
class SymbolData:
'''Contains data specific to a symbol required by this model'''
def __init__(self, symbol, lookback):
self.symbol = symbol
self.roc = RateOfChange('{}.roc({})'.format(symbol, lookback), lookback)
self.consolidator = None
self.previous = 0
def register_indicators(self, algorithm, resolution):
self.consolidator = algorithm.resolve_consolidator(self.symbol, resolution)
algorithm.register_indicator(self.symbol, self.roc, self.consolidator)
def remove_consolidators(self, algorithm):
if self.consolidator is not None:
algorithm.subscription_manager.remove_consolidator(self.symbol, self.consolidator)
def warm_up_indicators(self, history):
for tuple in history.itertuples():
self.roc.update(tuple.Index, tuple.close)
@property
def return_(self):
return float(self.roc.current.value)
@property
def can_emit(self):
if self.previous == self.roc.samples:
return False
self.previous = self.roc.samples
return self.roc.is_ready
def __str__(self, **kwargs):
return '{}: {:.2%}'.format(self.roc.name, (1 + self.return_)**252 - 1)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN AlphaModel that can be described like this
: Alpha model that uses an EMA cross to create insights
|
```python
from AlgorithmImports import *
class EmaCrossAlphaModel(AlphaModel):
'''Alpha model that uses an EMA cross to create insights'''
def __init__(self,
fast_period = 12,
slow_period = 26,
resolution = Resolution.DAILY):
'''Initializes a new instance of the EmaCrossAlphaModel class
Args:
fast_period: The fast EMA period
slow_period: The slow EMA period'''
self.fast_period = fast_period
self.slow_period = slow_period
self.resolution = resolution
self.prediction_interval = Time.multiply(Extensions.to_time_span(resolution), fast_period)
self.symbol_data_by_symbol = {}
self.name = '{}({},{},{})'.format(self.__class__.__name__, fast_period, slow_period, resolution)
def update(self, algorithm, data):
'''Updates this alpha model with the latest data from the algorithm.
This is called each time the algorithm receives data for subscribed securities
Args:
algorithm: The algorithm instance
data: The new data available
Returns:
The new insights generated'''
insights = []
for symbol, symbol_data in self.symbol_data_by_symbol.items():
if symbol_data.fast.is_ready and symbol_data.slow.is_ready:
if symbol_data.fast_is_over_slow:
if symbol_data.slow > symbol_data.fast:
insights.append(Insight.price(symbol_data.symbol, self.prediction_interval, InsightDirection.DOWN))
elif symbol_data.slow_is_over_fast:
if symbol_data.fast > symbol_data.slow:
insights.append(Insight.price(symbol_data.symbol, self.prediction_interval, InsightDirection.UP))
symbol_data.fast_is_over_slow = symbol_data.fast > symbol_data.slow
return insights
def on_securities_changed(self, algorithm, changes):
'''Event fired each time the we add/remove securities from the data feed
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
for added in changes.added_securities:
symbol_data = self.symbol_data_by_symbol.get(added.symbol)
if symbol_data is None:
symbol_data = SymbolData(added, self.fast_period, self.slow_period, algorithm, self.resolution)
self.symbol_data_by_symbol[added.symbol] = symbol_data
else:
# a security that was already initialized was re-added, reset the indicators
symbol_data.fast.reset()
symbol_data.slow.reset()
for removed in changes.removed_securities:
data = self.symbol_data_by_symbol.pop(removed.symbol, None)
if data is not None:
# clean up our consolidators
data.remove_consolidators()
class SymbolData:
'''Contains data specific to a symbol required by this model'''
def __init__(self, security, fast_period, slow_period, algorithm, resolution):
self.security = security
self.symbol = security.symbol
self.algorithm = algorithm
self.fast_consolidator = algorithm.resolve_consolidator(security.symbol, resolution)
self.slow_consolidator = algorithm.resolve_consolidator(security.symbol, resolution)
algorithm.subscription_manager.add_consolidator(security.symbol, self.fast_consolidator)
algorithm.subscription_manager.add_consolidator(security.symbol, self.slow_consolidator)
# create fast/slow EMAs
self.fast = ExponentialMovingAverage(security.symbol, fast_period, ExponentialMovingAverage.smoothing_factor_default(fast_period))
self.slow = ExponentialMovingAverage(security.symbol, slow_period, ExponentialMovingAverage.smoothing_factor_default(slow_period))
algorithm.register_indicator(security.symbol, self.fast, self.fast_consolidator);
algorithm.register_indicator(security.symbol, self.slow, self.slow_consolidator);
algorithm.warm_up_indicator(security.symbol, self.fast, resolution);
algorithm.warm_up_indicator(security.symbol, self.slow, resolution);
# True if the fast is above the slow, otherwise false.
# This is used to prevent emitting the same signal repeatedly
self.fast_is_over_slow = False
def remove_consolidators(self):
self.algorithm.subscription_manager.remove_consolidator(self.security.symbol, self.fast_consolidator)
self.algorithm.subscription_manager.remove_consolidator(self.security.symbol, self.slow_consolidator)
@property
def slow_is_over_fast(self):
return not self.fast_is_over_slow
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN AlphaModel that can be described like this
: Provides an implementation of IAlphaModel that always returns the same insight for each security
|
```python
from AlgorithmImports import *
class ConstantAlphaModel(AlphaModel):
''' Provides an implementation of IAlphaModel that always returns the same insight for each security'''
def __init__(self, type, direction, period, magnitude = None, confidence = None, weight = None):
'''Initializes a new instance of the ConstantAlphaModel class
Args:
type: The type of insight
direction: The direction of the insight
period: The period over which the insight with come to fruition
magnitude: The predicted change in magnitude as a +- percentage
confidence: The confidence in the insight
weight: The portfolio weight of the insights'''
self.type = type
self.direction = direction
self.period = period
self.magnitude = magnitude
self.confidence = confidence
self.weight = weight
self.securities = []
self.insights_time_by_symbol = {}
self.Name = '{}({},{},{}'.format(self.__class__.__name__, type, direction, strfdelta(period))
if magnitude is not None:
self.Name += ',{}'.format(magnitude)
if confidence is not None:
self.Name += ',{}'.format(confidence)
self.Name += ')'
def update(self, algorithm, data):
''' Creates a constant insight for each security as specified via the constructor
Args:
algorithm: The algorithm instance
data: The new data available
Returns:
The new insights generated'''
insights = []
for security in self.securities:
# security price could be zero until we get the first data point. e.g. this could happen
# when adding both forex and equities, we will first get a forex data point
if security.price != 0 and self.should_emit_insight(algorithm.utc_time, security.symbol):
insights.append(Insight(security.symbol, self.period, self.type, self.direction, self.magnitude, self.confidence, weight = self.weight))
return insights
def on_securities_changed(self, algorithm, changes):
''' Event fired each time the we add/remove securities from the data feed
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
for added in changes.added_securities:
self.securities.append(added)
# this will allow the insight to be re-sent when the security re-joins the universe
for removed in changes.removed_securities:
if removed in self.securities:
self.securities.remove(removed)
if removed.symbol in self.insights_time_by_symbol:
self.insights_time_by_symbol.pop(removed.symbol)
def should_emit_insight(self, utc_time, symbol):
if symbol.is_canonical():
# canonical futures & options are none tradable
return False
generated_time_utc = self.insights_time_by_symbol.get(symbol)
if generated_time_utc is not None:
# we previously emitted a insight for this symbol, check it's period to see
# if we should emit another insight
if utc_time - generated_time_utc < self.period:
return False
# we either haven't emitted a insight for this symbol or the previous
# insight's period has expired, so emit a new insight now for this symbol
self.insights_time_by_symbol[symbol] = utc_time
return True
def strfdelta(tdelta):
d = tdelta.days
h, rem = divmod(tdelta.seconds, 3600)
m, s = divmod(rem, 60)
return "{}.{:02d}:{:02d}:{:02d}".format(d,h,m,s)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN RiskManagementModel that can be described like this
: Provides an implementation of IRiskManagementModel that limits the unrealized profit per holding to the specified percentage
|
```python
from AlgorithmImports import *
class MaximumUnrealizedProfitPercentPerSecurity(RiskManagementModel):
'''Provides an implementation of IRiskManagementModel that limits the unrealized profit per holding to the specified percentage'''
def __init__(self, maximum_unrealized_profit_percent = 0.05):
'''Initializes a new instance of the MaximumUnrealizedProfitPercentPerSecurity class
Args:
maximum_unrealized_profit_percent: The maximum percentage unrealized profit allowed for any single security holding, defaults to 5% drawdown per security'''
self.maximum_unrealized_profit_percent = abs(maximum_unrealized_profit_percent)
def manage_risk(self, algorithm, targets):
'''Manages the algorithm's risk at each time step
Args:
algorithm: The algorithm instance
targets: The current portfolio targets to be assessed for risk'''
targets = []
for kvp in algorithm.securities:
security = kvp.value
if not security.invested:
continue
pnl = security.holdings.unrealized_profit_percent
if pnl > self.maximum_unrealized_profit_percent:
symbol = security.symbol
# Cancel insights
algorithm.insights.cancel([ symbol ]);
# liquidate
targets.append(PortfolioTarget(symbol, 0))
return targets
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN RiskManagementModel that can be described like this
: Provides an implementation of IRiskManagementModel that limits the drawdown per holding to the specified percentage
|
```python
from AlgorithmImports import *
class MaximumDrawdownPercentPerSecurity(RiskManagementModel):
'''Provides an implementation of IRiskManagementModel that limits the drawdown per holding to the specified percentage'''
def __init__(self, maximum_drawdown_percent = 0.05):
'''Initializes a new instance of the MaximumDrawdownPercentPerSecurity class
Args:
maximum_drawdown_percent: The maximum percentage drawdown allowed for any single security holding'''
self.maximum_drawdown_percent = -abs(maximum_drawdown_percent)
def manage_risk(self, algorithm, targets):
'''Manages the algorithm's risk at each time step
Args:
algorithm: The algorithm instance
targets: The current portfolio targets to be assessed for risk'''
targets = []
for kvp in algorithm.securities:
security = kvp.value
if not security.invested:
continue
pnl = security.holdings.unrealized_profit_percent
if pnl < self.maximum_drawdown_percent:
symbol = security.symbol
# Cancel insights
algorithm.insights.cancel([symbol])
# liquidate
targets.append(PortfolioTarget(symbol, 0))
return targets
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN RiskManagementModel that can be described like this
: Provides an implementation of IRiskManagementModel that that limits the sector exposure to the specified percentage
|
```python
from AlgorithmImports import *
from itertools import groupby
class MaximumSectorExposureRiskManagementModel(RiskManagementModel):
'''Provides an implementation of IRiskManagementModel that that limits the sector exposure to the specified percentage'''
def __init__(self, maximum_sector_exposure = 0.20):
'''Initializes a new instance of the MaximumSectorExposureRiskManagementModel class
Args:
maximum_drawdown_percent: The maximum exposure for any sector, defaults to 20% sector exposure.'''
if maximum_sector_exposure <= 0:
raise ValueError('MaximumSectorExposureRiskManagementModel: the maximum sector exposure cannot be a non-positive value.')
self.maximum_sector_exposure = maximum_sector_exposure
self.targets_collection = PortfolioTargetCollection()
def manage_risk(self, algorithm, targets):
'''Manages the algorithm's risk at each time step
Args:
algorithm: The algorithm instance'''
maximum_sector_exposure_value = float(algorithm.portfolio.total_portfolio_value) * self.maximum_sector_exposure
self.targets_collection.add_range(targets)
risk_targets = list()
# Group the securities by their sector
filtered = list(filter(lambda x: x.value.fundamentals is not None and x.value.fundamentals.has_fundamental_data, algorithm.universe_manager.active_securities))
filtered.sort(key = lambda x: x.value.fundamentals.company_reference.industry_template_code)
group_by_sector = groupby(filtered, lambda x: x.value.fundamentals.company_reference.industry_template_code)
for code, securities in group_by_sector:
# Compute the sector absolute holdings value
# If the construction model has created a target, we consider that
# value to calculate the security absolute holding value
quantities = {}
sector_absolute_holdings_value = 0
for security in securities:
symbol = security.value.symbol
quantities[symbol] = security.value.holdings.quantity
absolute_holdings_value = security.value.holdings.absolute_holdings_value
if self.targets_collection.contains_key(symbol):
quantities[symbol] = self.targets_collection[symbol].quantity
absolute_holdings_value = (security.value.price * abs(quantities[symbol]) *
security.value.symbol_properties.contract_multiplier *
security.value.quote_currency.conversion_rate)
sector_absolute_holdings_value += absolute_holdings_value
# If the ratio between the sector absolute holdings value and the maximum sector exposure value
# exceeds the unity, it means we need to reduce each security of that sector by that ratio
# Otherwise, it means that the sector exposure is below the maximum and there is nothing to do.
ratio = float(sector_absolute_holdings_value) / maximum_sector_exposure_value
if ratio > 1:
for symbol, quantity in quantities.items():
if quantity != 0:
risk_targets.append(PortfolioTarget(symbol, float(quantity) / ratio))
return risk_targets
def on_securities_changed(self, algorithm, changes):
'''Event fired each time the we add/remove securities from the data feed
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
any_fundamental_data = any([
kvp.value.fundamentals is not None and
kvp.value.fundamentals.has_fundamental_data for kvp in algorithm.active_securities
])
if not any_fundamental_data:
raise Exception("MaximumSectorExposureRiskManagementModel.on_securities_changed: Please select a portfolio selection model that selects securities with fundamental data.")
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN RiskManagementModel that can be described like this
: Provides an implementation of IRiskManagementModel that limits the maximum possible loss
|
```python
from AlgorithmImports import *
class TrailingStopRiskManagementModel(RiskManagementModel):
'''Provides an implementation of IRiskManagementModel that limits the maximum possible loss
measured from the highest unrealized profit'''
def __init__(self, maximum_drawdown_percent = 0.05):
'''Initializes a new instance of the TrailingStopRiskManagementModel class
Args:
maximum_drawdown_percent: The maximum percentage drawdown allowed for algorithm portfolio compared with the highest unrealized profit, defaults to 5% drawdown'''
self.maximum_drawdown_percent = abs(maximum_drawdown_percent)
self.trailing_absolute_holdings_state = dict()
def manage_risk(self, algorithm, targets):
'''Manages the algorithm's risk at each time step
Args:
algorithm: The algorithm instance
targets: The current portfolio targets to be assessed for risk'''
risk_adjusted_targets = list()
for kvp in algorithm.securities:
symbol = kvp.key
security = kvp.value
# Remove if not invested
if not security.invested:
self.trailing_absolute_holdings_state.pop(symbol, None)
continue
position = PositionSide.LONG if security.holdings.is_long else PositionSide.SHORT
absolute_holdings_value = security.holdings.absolute_holdings_value
trailing_absolute_holdings_state = self.trailing_absolute_holdings_state.get(symbol)
# Add newly invested security (if doesn't exist) or reset holdings state (if position changed)
if trailing_absolute_holdings_state == None or position != trailing_absolute_holdings_state.position:
self.trailing_absolute_holdings_state[symbol] = trailing_absolute_holdings_state = self.HoldingsState(position, security.holdings.absolute_holdings_cost)
trailing_absolute_holdings_value = trailing_absolute_holdings_state.absolute_holdings_value
# Check for new max (for long position) or min (for short position) absolute holdings value
if ((position == PositionSide.LONG and trailing_absolute_holdings_value < absolute_holdings_value) or
(position == PositionSide.SHORT and trailing_absolute_holdings_value > absolute_holdings_value)):
self.trailing_absolute_holdings_state[symbol].absolute_holdings_value = absolute_holdings_value
continue
drawdown = abs((trailing_absolute_holdings_value - absolute_holdings_value) / trailing_absolute_holdings_value)
if self.maximum_drawdown_percent < drawdown:
# Cancel insights
algorithm.insights.cancel([ symbol ]);
self.trailing_absolute_holdings_state.pop(symbol, None)
# liquidate
risk_adjusted_targets.append(PortfolioTarget(symbol, 0))
return risk_adjusted_targets
class HoldingsState:
def __init__(self, position, absolute_holdings_value):
self.position = position
self.absolute_holdings_value = absolute_holdings_value
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN RiskManagementModel that can be described like this
: Provides an implementation of IRiskManagementModel that limits the drawdown of the portfolio to the specified percentage.
|
```python
from AlgorithmImports import *
class MaximumDrawdownPercentPortfolio(RiskManagementModel):
'''Provides an implementation of IRiskManagementModel that limits the drawdown of the portfolio to the specified percentage.'''
def __init__(self, maximum_drawdown_percent = 0.05, is_trailing = False):
'''Initializes a new instance of the MaximumDrawdownPercentPortfolio class
Args:
maximum_drawdown_percent: The maximum percentage drawdown allowed for algorithm portfolio compared with starting value, defaults to 5% drawdown</param>
is_trailing: If "false", the drawdown will be relative to the starting value of the portfolio.
If "true", the drawdown will be relative the last maximum portfolio value'''
self.maximum_drawdown_percent = -abs(maximum_drawdown_percent)
self.is_trailing = is_trailing
self.initialised = False
self.portfolio_high = 0
def manage_risk(self, algorithm, targets):
'''Manages the algorithm's risk at each time step
Args:
algorithm: The algorithm instance
targets: The current portfolio targets to be assessed for risk'''
current_value = algorithm.portfolio.total_portfolio_value
if not self.initialised:
self.portfolio_high = current_value # Set initial portfolio value
self.initialised = True
# Update trailing high value if in trailing mode
if self.is_trailing and self.portfolio_high < current_value:
self.portfolio_high = current_value
return [] # return if new high reached
pnl = self.get_total_drawdown_percent(current_value)
if pnl < self.maximum_drawdown_percent and len(targets) != 0:
self.initialised = False # reset the trailing high value for restart investing on next rebalcing period
risk_adjusted_targets = []
for target in targets:
symbol = target.symbol
# Cancel insights
algorithm.insights.cancel([symbol])
# liquidate
risk_adjusted_targets.append(PortfolioTarget(symbol, 0))
return risk_adjusted_targets
return []
def get_total_drawdown_percent(self, current_value):
return (float(current_value) / float(self.portfolio_high)) - 1.0
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN UniverseSelectionModel that can be described like this
: Provides a base class for defining equity coarse/fine fundamental selection models
|
```python
from AlgorithmImports import *
class FundamentalUniverseSelectionModel:
'''Provides a base class for defining equity coarse/fine fundamental selection models'''
def __init__(self,
filterFineData = None,
universeSettings = None):
'''Initializes a new instance of the FundamentalUniverseSelectionModel class
Args:
filterFineData: [Obsolete] Fine and Coarse selection are merged
universeSettings: The settings used when adding symbols to the algorithm, specify null to use algorithm.UniverseSettings'''
self.filter_fine_data = filterFineData
if self.filter_fine_data == None:
self.fundamental_data = True
else:
self.fundamental_data = False
self.market = Market.USA
self.universe_settings = universeSettings
def create_universes(self, algorithm: QCAlgorithm) -> list[Universe]:
'''Creates a new fundamental universe using this class's selection functions
Args:
algorithm: The algorithm instance to create universes for
Returns:
The universe defined by this model'''
if self.fundamental_data:
universe_settings = algorithm.universe_settings if self.universe_settings is None else self.universe_settings
# handle both 'Select' and 'select' for backwards compatibility
selection = lambda fundamental: self.select(algorithm, fundamental)
if hasattr(self, "Select") and callable(self.Select):
selection = lambda fundamental: self.Select(algorithm, fundamental)
universe = FundamentalUniverseFactory(self.market, universe_settings, selection)
return [universe]
else:
universe = self.create_coarse_fundamental_universe(algorithm)
if self.filter_fine_data:
if universe.universe_settings.asynchronous:
raise ValueError("Asynchronous universe setting is not supported for coarse & fine selections, please use the new Fundamental single pass selection")
selection = lambda fine: self.select_fine(algorithm, fine)
if hasattr(self, "SelectFine") and callable(self.SelectFine):
selection = lambda fine: self.SelectFine(algorithm, fine)
universe = FineFundamentalFilteredUniverse(universe, selection)
return [universe]
def create_coarse_fundamental_universe(self, algorithm: QCAlgorithm) -> Universe:
'''Creates the coarse fundamental universe object.
This is provided to allow more flexibility when creating coarse universe.
Args:
algorithm: The algorithm instance
Returns:
The coarse fundamental universe'''
universe_settings = algorithm.universe_settings if self.universe_settings is None else self.universe_settings
return CoarseFundamentalUniverse(universe_settings, lambda coarse: self.filtered_select_coarse(algorithm, coarse))
def filtered_select_coarse(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:
'''Defines the coarse fundamental selection function.
If we're using fine fundamental selection than exclude symbols without fine data
Args:
algorithm: The algorithm instance
coarse: The coarse fundamental data used to perform filtering
Returns:
An enumerable of symbols passing the filter'''
if self.filter_fine_data:
fundamental = filter(lambda c: c.has_fundamental_data, fundamental)
if hasattr(self, "SelectCoarse") and callable(self.SelectCoarse):
# handle both 'select_coarse' and 'SelectCoarse' for backwards compatibility
return self.SelectCoarse(algorithm, fundamental)
return self.select_coarse(algorithm, fundamental)
def select(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:
'''Defines the fundamental selection function.
Args:
algorithm: The algorithm instance
fundamental: The fundamental data used to perform filtering
Returns:
An enumerable of symbols passing the filter'''
raise NotImplementedError("Please overrride the 'select' fundamental function")
def select_coarse(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:
'''Defines the coarse fundamental selection function.
Args:
algorithm: The algorithm instance
coarse: The coarse fundamental data used to perform filtering
Returns:
An enumerable of symbols passing the filter'''
raise NotImplementedError("Please overrride the 'select' fundamental function")
def select_fine(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:
'''Defines the fine fundamental selection function.
Args:
algorithm: The algorithm instance
fine: The fine fundamental data used to perform filtering
Returns:
An enumerable of symbols passing the filter'''
return [f.symbol for f in fundamental]
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN UniverseSelectionModel that can be described like this
: Provides an implementation of IUniverseSelectionMode that subscribes to option chains
|
```python
from AlgorithmImports import *
from Selection.UniverseSelectionModel import UniverseSelectionModel
class OptionUniverseSelectionModel(UniverseSelectionModel):
'''Provides an implementation of IUniverseSelectionMode that subscribes to option chains'''
def __init__(self,
refreshInterval,
optionChainSymbolSelector,
universeSettings = None):
'''Creates a new instance of OptionUniverseSelectionModel
Args:
refreshInterval: Time interval between universe refreshes</param>
optionChainSymbolSelector: Selects symbols from the provided option chain
universeSettings: Universe settings define attributes of created subscriptions, such as their resolution and the minimum time in universe before they can be removed'''
self.next_refresh_time_utc = datetime.min
self.refresh_interval = refreshInterval
self.option_chain_symbol_selector = optionChainSymbolSelector
self.universe_settings = universeSettings
def get_next_refresh_time_utc(self):
'''Gets the next time the framework should invoke the `CreateUniverses` method to refresh the set of universes.'''
return self.next_refresh_time_utc
def create_universes(self, algorithm: QCAlgorithm) -> list[Universe]:
'''Creates a new fundamental universe using this class's selection functions
Args:
algorithm: The algorithm instance to create universes for
Returns:
The universe defined by this model'''
self.next_refresh_time_utc = (algorithm.utc_time + self.refresh_interval).date()
uniqueUnderlyingSymbols = set()
for option_symbol in self.option_chain_symbol_selector(algorithm.utc_time):
if not Extensions.is_option(option_symbol.security_type):
raise ValueError("optionChainSymbolSelector must return option, index options, or futures options symbols.")
# prevent creating duplicate option chains -- one per underlying
if option_symbol.underlying not in uniqueUnderlyingSymbols:
uniqueUnderlyingSymbols.add(option_symbol.underlying)
selection = self.filter
if hasattr(self, "Filter") and callable(self.Filter):
selection = self.Filter
yield Extensions.create_option_chain(algorithm, option_symbol, selection, self.universe_settings)
def filter(self, filter):
'''Defines the option chain universe filter'''
# NOP
return filter
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN UniverseSelectionModel that can be described like this
: Universe selection model that selects the constituents of an ETF.
|
```python
from AlgorithmImports import *
from Selection.UniverseSelectionModel import UniverseSelectionModel
class ETFConstituentsUniverseSelectionModel(UniverseSelectionModel):
'''Universe selection model that selects the constituents of an ETF.'''
def __init__(self,
etf_symbol,
universe_settings = None,
universe_filter_func = None):
'''Initializes a new instance of the ETFConstituentsUniverseSelectionModel class
Args:
etfSymbol: Symbol of the ETF to get constituents for
universeSettings: Universe settings
universeFilterFunc: Function to filter universe results'''
if type(etf_symbol) is str:
symbol = SymbolCache.try_get_symbol(etf_symbol, None)
if symbol[0] and symbol[1].security_type == SecurityType.EQUITY:
self.etf_symbol = symbol[1]
else:
self.etf_symbol = Symbol.create(etf_symbol, SecurityType.EQUITY, Market.USA)
else:
self.etf_symbol = etf_symbol
self.universe_settings = universe_settings
self.universe_filter_function = universe_filter_func
self.universe = None
def create_universes(self, algorithm: QCAlgorithm) -> list[Universe]:
'''Creates a new ETF constituents universe using this class's selection function
Args:
algorithm: The algorithm instance to create universes for
Returns:
The universe defined by this model'''
if self.universe is None:
self.universe = algorithm.universe.etf(self.etf_symbol, self.universe_settings, self.universe_filter_function)
return [self.universe]
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN UniverseSelectionModel that can be described like this
: Defines the QC500 universe as a universe selection model for framework algorithm
|
```python
from AlgorithmImports import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel
from itertools import groupby
from math import ceil
class QC500UniverseSelectionModel(FundamentalUniverseSelectionModel):
'''Defines the QC500 universe as a universe selection model for framework algorithm
For details: https://github.com/QuantConnect/Lean/pull/1663'''
def __init__(self, filterFineData = True, universeSettings = None):
'''Initializes a new default instance of the QC500UniverseSelectionModel'''
super().__init__(filterFineData, universeSettings)
self.number_of_symbols_coarse = 1000
self.number_of_symbols_fine = 500
self.dollar_volume_by_symbol = {}
self.last_month = -1
def select_coarse(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]):
'''Performs coarse selection for the QC500 constituents.
The stocks must have fundamental data
The stock must have positive previous-day close price
The stock must have positive volume on the previous trading day'''
if algorithm.time.month == self.last_month:
return Universe.UNCHANGED
sorted_by_dollar_volume = sorted([x for x in fundamental if x.has_fundamental_data and x.volume > 0 and x.price > 0],
key = lambda x: x.dollar_volume, reverse=True)[:self.number_of_symbols_coarse]
self.dollar_volume_by_symbol = {x.Symbol:x.dollar_volume for x in sorted_by_dollar_volume}
# If no security has met the QC500 criteria, the universe is unchanged.
# A new selection will be attempted on the next trading day as self.lastMonth is not updated
if len(self.dollar_volume_by_symbol) == 0:
return Universe.UNCHANGED
# return the symbol objects our sorted collection
return list(self.dollar_volume_by_symbol.keys())
def select_fine(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]):
'''Performs fine selection for the QC500 constituents
The company's headquarter must in the U.S.
The stock must be traded on either the NYSE or NASDAQ
At least half a year since its initial public offering
The stock's market cap must be greater than 500 million'''
sorted_by_sector = sorted([x for x in fundamental if x.company_reference.country_id == "USA"
and x.company_reference.primary_exchange_id in ["NYS","NAS"]
and (algorithm.time - x.security_reference.ipo_date).days > 180
and x.market_cap > 5e8],
key = lambda x: x.company_reference.industry_template_code)
count = len(sorted_by_sector)
# If no security has met the QC500 criteria, the universe is unchanged.
# A new selection will be attempted on the next trading day as self.lastMonth is not updated
if count == 0:
return Universe.UNCHANGED
# Update self.lastMonth after all QC500 criteria checks passed
self.last_month = algorithm.time.month
percent = self.number_of_symbols_fine / count
sorted_by_dollar_volume = []
# select stocks with top dollar volume in every single sector
for code, g in groupby(sorted_by_sector, lambda x: x.company_reference.industry_template_code):
y = sorted(g, key = lambda x: self.dollar_volume_by_symbol[x.Symbol], reverse = True)
c = ceil(len(y) * percent)
sorted_by_dollar_volume.extend(y[:c])
sorted_by_dollar_volume = sorted(sorted_by_dollar_volume, key = lambda x: self.dollar_volume_by_symbol[x.Symbol], reverse=True)
return [x.Symbol for x in sorted_by_dollar_volume[:self.number_of_symbols_fine]]
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN UniverseSelectionModel that can be described like this
: Provides an implementation of IUniverseSelectionMode that subscribes to future chains
|
```python
from AlgorithmImports import *
from Selection.UniverseSelectionModel import UniverseSelectionModel
class FutureUniverseSelectionModel(UniverseSelectionModel):
'''Provides an implementation of IUniverseSelectionMode that subscribes to future chains'''
def __init__(self,
refreshInterval,
futureChainSymbolSelector,
universeSettings = None):
'''Creates a new instance of FutureUniverseSelectionModel
Args:
refreshInterval: Time interval between universe refreshes</param>
futureChainSymbolSelector: Selects symbols from the provided future chain
universeSettings: Universe settings define attributes of created subscriptions, such as their resolution and the minimum time in universe before they can be removed'''
self.next_refresh_time_utc = datetime.min
self.refresh_interval = refreshInterval
self.future_chain_symbol_selector = futureChainSymbolSelector
self.universe_settings = universeSettings
def get_next_refresh_time_utc(self):
'''Gets the next time the framework should invoke the `CreateUniverses` method to refresh the set of universes.'''
return self.next_refresh_time_utc
def create_universes(self, algorithm: QCAlgorithm) -> list[Universe]:
'''Creates a new fundamental universe using this class's selection functions
Args:
algorithm: The algorithm instance to create universes for
Returns:
The universe defined by this model'''
self.next_refresh_time_utc = algorithm.utc_time + self.refresh_interval
unique_symbols = set()
for future_symbol in self.future_chain_symbol_selector(algorithm.utc_time):
if future_symbol.SecurityType != SecurityType.FUTURE:
raise ValueError("futureChainSymbolSelector must return future symbols.")
# prevent creating duplicate future chains -- one per symbol
if future_symbol not in unique_symbols:
unique_symbols.add(future_symbol)
selection = self.filter
if hasattr(self, "Filter") and callable(self.Filter):
selection = self.Filter
for universe in Extensions.create_future_chain(algorithm, future_symbol, selection, self.universe_settings):
yield universe
def filter(self, filter):
'''Defines the future chain universe filter'''
# NOP
return filter
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN UniverseSelectionModel that can be described like this
: Provides an implementation of FundamentalUniverseSelectionModel that subscribes to
|
```python
from AlgorithmImports import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel
class EmaCrossUniverseSelectionModel(FundamentalUniverseSelectionModel):
'''Provides an implementation of FundamentalUniverseSelectionModel that subscribes to
symbols with the larger delta by percentage between the two exponential moving average'''
def __init__(self,
fastPeriod = 100,
slowPeriod = 300,
universeCount = 500,
universeSettings = None):
'''Initializes a new instance of the EmaCrossUniverseSelectionModel class
Args:
fastPeriod: Fast EMA period
slowPeriod: Slow EMA period
universeCount: Maximum number of members of this universe selection
universeSettings: The settings used when adding symbols to the algorithm, specify null to use algorithm.UniverseSettings'''
super().__init__(False, universeSettings)
self.fast_period = fastPeriod
self.slow_period = slowPeriod
self.universe_count = universeCount
self.tolerance = 0.01
# holds our coarse fundamental indicators by symbol
self.averages = {}
def select_coarse(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:
'''Defines the coarse fundamental selection function.
Args:
algorithm: The algorithm instance
fundamental: The coarse fundamental data used to perform filtering</param>
Returns:
An enumerable of symbols passing the filter'''
filtered = []
for cf in fundamental:
if cf.symbol not in self.averages:
self.averages[cf.symbol] = self.SelectionData(cf.symbol, self.fast_period, self.slow_period)
# grab th SelectionData instance for this symbol
avg = self.averages.get(cf.symbol)
# Update returns true when the indicators are ready, so don't accept until they are
# and only pick symbols who have their fastPeriod-day ema over their slowPeriod-day ema
if avg.update(cf.end_time, cf.adjusted_price) and avg.fast > avg.slow * (1 + self.tolerance):
filtered.append(avg)
# prefer symbols with a larger delta by percentage between the two averages
filtered = sorted(filtered, key=lambda avg: avg.scaled_delta, reverse = True)
# we only need to return the symbol and return 'universeCount' symbols
return [x.symbol for x in filtered[:self.universe_count]]
# class used to improve readability of the coarse selection function
class SelectionData:
def __init__(self, symbol, fast_period, slow_period):
self.symbol = symbol
self.fast_ema = ExponentialMovingAverage(fast_period)
self.slow_ema = ExponentialMovingAverage(slow_period)
@property
def fast(self):
return float(self.fast_ema.current.value)
@property
def slow(self):
return float(self.slow_ema.current.value)
# computes an object score of how much large the fast is than the slow
@property
def scaled_delta(self):
return (self.fast - self.slow) / ((self.fast + self.slow) / 2)
# updates the EMAFast and EMASlow indicators, returning true when they're both ready
def update(self, time, value):
return self.slow_ema.update(time, value) & self.fast_ema.update(time, value)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN PortfolioConstructionModel that can be described like this
: Provides an implementation of Mean-Variance portfolio optimization based on modern portfolio theory.
The default model uses the MinimumVariancePortfolioOptimizer that accepts a 63-row matrix of 1-day returns.
|
```python
from AlgorithmImports import *
from Portfolio.MinimumVariancePortfolioOptimizer import MinimumVariancePortfolioOptimizer
class MeanVarianceOptimizationPortfolioConstructionModel(PortfolioConstructionModel):
def __init__(self,
rebalance = Resolution.DAILY,
portfolio_bias = PortfolioBias.LONG_SHORT,
lookback = 1,
period = 63,
resolution = Resolution.DAILY,
target_return = 0.02,
optimizer = None):
"""Initialize the model
Args:
rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.
If None will be ignored.
The function returns the next expected rebalance time for a given algorithm UTC DateTime.
The function returns null if unknown, in which case the function will be called again in the
next loop. Returning current time will trigger rebalance.
portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)
lookback(int): Historical return lookback period
period(int): The time interval of history price to calculate the weight
resolution: The resolution of the history price
optimizer(class): Method used to compute the portfolio weights"""
super().__init__()
self.lookback = lookback
self.period = period
self.resolution = resolution
self.portfolio_bias = portfolio_bias
self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)
lower = 0 if portfolio_bias == PortfolioBias.LONG else -1
upper = 0 if portfolio_bias == PortfolioBias.SHORT else 1
self.optimizer = MinimumVariancePortfolioOptimizer(lower, upper, target_return) if optimizer is None else optimizer
self.symbol_data_by_symbol = {}
# If the argument is an instance of Resolution or Timedelta
# Redefine rebalancing_func
rebalancing_func = rebalance
if isinstance(rebalance, Resolution):
rebalance = Extensions.to_time_span(rebalance)
if isinstance(rebalance, timedelta):
rebalancing_func = lambda dt: dt + rebalance
if rebalancing_func:
self.set_rebalancing_func(rebalancing_func)
def should_create_target_for_insight(self, insight):
if len(PortfolioConstructionModel.filter_invalid_insight_magnitude(self.algorithm, [insight])) == 0:
return False
symbol_data = self.symbol_data_by_symbol.get(insight.symbol)
if insight.magnitude is None:
self.algorithm.set_run_time_error(ArgumentNullException('MeanVarianceOptimizationPortfolioConstructionModel does not accept \'None\' as Insight.magnitude. Please checkout the selected Alpha Model specifications.'))
return False
symbol_data.add(self.algorithm.time, insight.magnitude)
return True
def determine_target_percent(self, active_insights):
"""
Will determine the target percent for each insight
Args:
Returns:
"""
targets = {}
# If we have no insights just return an empty target list
if len(active_insights) == 0:
return targets
symbols = [insight.symbol for insight in active_insights]
# Create a dictionary keyed by the symbols in the insights with an pandas.series as value to create a data frame
returns = { str(symbol.id) : data.return_ for symbol, data in self.symbol_data_by_symbol.items() if symbol in symbols }
returns = pd.DataFrame(returns)
# The portfolio optimizer finds the optional weights for the given data
weights = self.optimizer.optimize(returns)
weights = pd.Series(weights, index = returns.columns)
# Create portfolio targets from the specified insights
for insight in active_insights:
weight = weights[str(insight.symbol.id)]
# don't trust the optimizer
if self.portfolio_bias != PortfolioBias.LONG_SHORT and self.sign(weight) != self.portfolio_bias:
weight = 0
targets[insight] = weight
return targets
def on_securities_changed(self, algorithm, changes):
'''Event fired each time the we add/remove securities from the data feed
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
# clean up data for removed securities
super().on_securities_changed(algorithm, changes)
for removed in changes.removed_securities:
symbol_data = self.symbol_data_by_symbol.pop(removed.symbol, None)
symbol_data.reset()
# initialize data for added securities
symbols = [x.symbol for x in changes.added_securities]
for symbol in [x for x in symbols if x not in self.symbol_data_by_symbol]:
self.symbol_data_by_symbol[symbol] = self.MeanVarianceSymbolData(symbol, self.lookback, self.period)
history = algorithm.history[TradeBar](symbols, self.lookback * self.period, self.resolution)
for bars in history:
for symbol, bar in bars.items():
symbol_data = self.symbol_data_by_symbol.get(symbol).update(bar.end_time, bar.value)
class MeanVarianceSymbolData:
'''Contains data specific to a symbol required by this model'''
def __init__(self, symbol, lookback, period):
self._symbol = symbol
self.roc = RateOfChange(f'{symbol}.roc({lookback})', lookback)
self.roc.updated += self.on_rate_of_change_updated
self.window = RollingWindow(period)
def reset(self):
self.roc.updated -= self.on_rate_of_change_updated
self.roc.reset()
self.window.reset()
def update(self, time, value):
return self.roc.update(time, value)
def on_rate_of_change_updated(self, roc, value):
if roc.is_ready:
self.window.add(value)
def add(self, time, value):
item = IndicatorDataPoint(self._symbol, time, value)
self.window.add(item)
# Get symbols' returns, we use simple return according to
# Meucci, Attilio, Quant Nugget 2: Linear vs. Compounded Returns – Common Pitfalls in Portfolio Management (May 1, 2010).
# GARP Risk Professional, pp. 49-51, April 2010 , Available at SSRN: https://ssrn.com/abstract=1586656
@property
def return_(self):
return pd.Series(
data = [x.value for x in self.window],
index = [x.end_time for x in self.window])
@property
def is_ready(self):
return self.window.is_ready
def __str__(self, **kwargs):
return '{}: {:.2%}'.format(self.roc.name, self.window[0])
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN PortfolioConstructionModel that can be described like this
: Provides an implementation of Black-Litterman portfolio optimization. The model adjusts equilibrium market
returns by incorporating views from multiple alpha models and therefore to get the optimal risky portfolio
reflecting those views. If insights of all alpha models have None magnitude or there are linearly dependent
vectors in link matrix of views, the expected return would be the implied excess equilibrium return.
The interval of weights in optimization method can be changed based on the long-short algorithm.
The default model uses the 0.0025 as weight-on-views scalar parameter tau and
MaximumSharpeRatioPortfolioOptimizer that accepts a 63-row matrix of 1-day returns.
|
```python
from AlgorithmImports import *
from Portfolio.MaximumSharpeRatioPortfolioOptimizer import MaximumSharpeRatioPortfolioOptimizer
from itertools import groupby
from numpy import dot, transpose
from numpy.linalg import inv
class BlackLittermanOptimizationPortfolioConstructionModel(PortfolioConstructionModel):
def __init__(self,
rebalance = Resolution.DAILY,
portfolio_bias = PortfolioBias.LONG_SHORT,
lookback = 1,
period = 63,
resolution = Resolution.DAILY,
risk_free_rate = 0,
delta = 2.5,
tau = 0.05,
optimizer = None):
"""Initialize the model
Args:
rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.
If None will be ignored.
The function returns the next expected rebalance time for a given algorithm UTC DateTime.
The function returns null if unknown, in which case the function will be called again in the
next loop. Returning current time will trigger rebalance.
portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)
lookback(int): Historical return lookback period
period(int): The time interval of history price to calculate the weight
resolution: The resolution of the history price
risk_free_rate(float): The risk free rate
delta(float): The risk aversion coeffficient of the market portfolio
tau(float): The model parameter indicating the uncertainty of the CAPM prior"""
super().__init__()
self.lookback = lookback
self.period = period
self.resolution = resolution
self.risk_free_rate = risk_free_rate
self.delta = delta
self.tau = tau
self.portfolio_bias = portfolio_bias
lower = 0 if portfolio_bias == PortfolioBias.LONG else -1
upper = 0 if portfolio_bias == PortfolioBias.SHORT else 1
self.optimizer = MaximumSharpeRatioPortfolioOptimizer(lower, upper, risk_free_rate) if optimizer is None else optimizer
self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)
self.symbol_data_by_symbol = {}
# If the argument is an instance of Resolution or Timedelta
# Redefine rebalancing_func
rebalancing_func = rebalance
if isinstance(rebalance, Resolution):
rebalance = Extensions.to_time_span(rebalance)
if isinstance(rebalance, timedelta):
rebalancing_func = lambda dt: dt + rebalance
if rebalancing_func:
self.set_rebalancing_func(rebalancing_func)
def should_create_target_for_insight(self, insight):
return PortfolioConstructionModel.filter_invalid_insight_magnitude(self.algorithm, [ insight ])
def determine_target_percent(self, last_active_insights):
targets = {}
# Get view vectors
p, q = self.get_views(last_active_insights)
if p is not None:
returns = dict()
# Updates the BlackLittermanSymbolData with insights
# Create a dictionary keyed by the symbols in the insights with an pandas.Series as value to create a data frame
for insight in last_active_insights:
symbol = insight.symbol
symbol_data = self.symbol_data_by_symbol.get(symbol, self.BlackLittermanSymbolData(symbol, self.lookback, self.period))
if insight.magnitude is None:
self.algorithm.set_run_time_error(ArgumentNullException('BlackLittermanOptimizationPortfolioConstructionModel does not accept \'None\' as Insight.magnitude. Please make sure your Alpha Model is generating Insights with the Magnitude property set.'))
return targets
symbol_data.add(insight.generated_time_utc, insight.magnitude)
returns[symbol] = symbol_data.return_
returns = pd.DataFrame(returns)
# Calculate prior estimate of the mean and covariance
pi, sigma = self.get_equilibrium_return(returns)
# Calculate posterior estimate of the mean and covariance
pi, sigma = self.apply_blacklitterman_master_formula(pi, sigma, p, q)
# Create portfolio targets from the specified insights
weights = self.optimizer.optimize(returns, pi, sigma)
weights = pd.Series(weights, index = sigma.columns)
for symbol, weight in weights.items():
for insight in last_active_insights:
if str(insight.symbol) == str(symbol):
# don't trust the optimizer
if self.portfolio_bias != PortfolioBias.LONG_SHORT and self.sign(weight) != self.portfolio_bias:
weight = 0
targets[insight] = weight
break
return targets
def get_target_insights(self):
# Get insight that haven't expired of each symbol that is still in the universe
active_insights = filter(self.should_create_target_for_insight,
self.algorithm.insights.get_active_insights(self.algorithm.utc_time))
# Get the last generated active insight for each symbol
last_active_insights = []
for source_model, f in groupby(sorted(active_insights, key = lambda ff: ff.source_model), lambda fff: fff.source_model):
for symbol, g in groupby(sorted(list(f), key = lambda gg: gg.symbol), lambda ggg: ggg.symbol):
last_active_insights.append(sorted(g, key = lambda x: x.generated_time_utc)[-1])
return last_active_insights
def on_securities_changed(self, algorithm, changes):
'''Event fired each time the we add/remove securities from the data feed
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
# Get removed symbol and invalidate them in the insight collection
super().on_securities_changed(algorithm, changes)
for security in changes.removed_securities:
symbol = security.symbol
symbol_data = self.symbol_data_by_symbol.pop(symbol, None)
if symbol_data is not None:
symbol_data.reset()
# initialize data for added securities
added_symbols = { x.symbol: x.exchange.time_zone for x in changes.added_securities }
history = algorithm.history(list(added_symbols.keys()), self.lookback * self.period, self.resolution)
if history.empty:
return
history = history.close.unstack(0)
symbols = history.columns
for symbol, timezone in added_symbols.items():
if str(symbol) not in symbols:
continue
symbol_data = self.symbol_data_by_symbol.get(symbol, self.BlackLittermanSymbolData(symbol, self.lookback, self.period))
for time, close in history[symbol].items():
utc_time = Extensions.convert_to_utc(time, timezone)
symbol_data.update(utc_time, close)
self.symbol_data_by_symbol[symbol] = symbol_data
def apply_blacklitterman_master_formula(self, Pi, Sigma, P, Q):
'''Apply Black-Litterman master formula
http://www.blacklitterman.org/cookbook.html
Args:
Pi: Prior/Posterior mean array
Sigma: Prior/Posterior covariance matrix
P: A matrix that identifies the assets involved in the views (size: K x N)
Q: A view vector (size: K x 1)'''
ts = self.tau * Sigma
# Create the diagonal Sigma matrix of error terms from the expressed views
omega = np.dot(np.dot(P, ts), P.T) * np.eye(Q.shape[0])
if np.linalg.det(omega) == 0:
return Pi, Sigma
A = np.dot(np.dot(ts, P.T), inv(np.dot(np.dot(P, ts), P.T) + omega))
Pi = np.squeeze(np.asarray((
np.expand_dims(Pi, axis=0).T +
np.dot(A, (Q - np.expand_dims(np.dot(P, Pi.T), axis=1))))
))
M = ts - np.dot(np.dot(A, P), ts)
Sigma = (Sigma + M) * self.delta
return Pi, Sigma
def get_equilibrium_return(self, returns):
'''Calculate equilibrium returns and covariance
Args:
returns: Matrix of returns where each column represents a security and each row returns for the given date/time (size: K x N)
Returns:
equilibrium_return: Array of double of equilibrium returns
cov: Multi-dimensional array of double with the portfolio covariance of returns (size: K x K)'''
size = len(returns.columns)
# equal weighting scheme
W = np.array([1/size]*size)
# the covariance matrix of excess returns (N x N matrix)
cov = returns.cov()*252
# annualized return
annual_return = np.sum(((1 + returns.mean())**252 -1) * W)
# annualized variance of return
annual_variance = dot(W.T, dot(cov, W))
# the risk aversion coefficient
risk_aversion = (annual_return - self.risk_free_rate ) / annual_variance
# the implied excess equilibrium return Vector (N x 1 column vector)
equilibrium_return = dot(dot(risk_aversion, cov), W)
return equilibrium_return, cov
def get_views(self, insights):
'''Generate views from multiple alpha models
Args
insights: Array of insight that represent the investors' views
Returns
P: A matrix that identifies the assets involved in the views (size: K x N)
Q: A view vector (size: K x 1)'''
try:
P = {}
Q = {}
symbols = set(insight.symbol for insight in insights)
for model, group in groupby(insights, lambda x: x.source_model):
group = list(group)
up_insights_sum = 0.0
dn_insights_sum = 0.0
for insight in group:
if insight.direction == InsightDirection.UP:
up_insights_sum = up_insights_sum + np.abs(insight.magnitude)
if insight.direction == InsightDirection.DOWN:
dn_insights_sum = dn_insights_sum + np.abs(insight.magnitude)
q = up_insights_sum if up_insights_sum > dn_insights_sum else dn_insights_sum
if q == 0:
continue
Q[model] = q
# generate the link matrix of views: P
P[model] = dict()
for insight in group:
value = insight.direction * np.abs(insight.magnitude)
P[model][insight.symbol] = value / q
# Add zero for other symbols that are listed but active insight
for symbol in symbols:
if symbol not in P[model]:
P[model][symbol] = 0
Q = np.array([[x] for x in Q.values()])
if len(Q) > 0:
P = np.array([list(x.values()) for x in P.values()])
return P, Q
except:
pass
return None, None
class BlackLittermanSymbolData:
'''Contains data specific to a symbol required by this model'''
def __init__(self, symbol, lookback, period):
self._symbol = symbol
self.roc = RateOfChange(f'{symbol}.roc({lookback})', lookback)
self.roc.updated += self.on_rate_of_change_updated
self.window = RollingWindow(period)
def reset(self):
self.roc.updated -= self.on_rate_of_change_updated
self.roc.reset()
self.window.reset()
def update(self, utc_time, close):
self.roc.update(utc_time, close)
def on_rate_of_change_updated(self, roc, value):
if roc.is_ready:
self.window.add(value)
def add(self, time, value):
if self.window.samples > 0 and self.window[0].end_time == time:
return
item = IndicatorDataPoint(self._symbol, time, value)
self.window.add(item)
@property
def return_(self):
return pd.Series(
data = [x.value for x in self.window],
index = [x.end_time for x in self.window])
@property
def is_ready(self):
return self.window.is_ready
def __str__(self, **kwargs):
return f'{self.roc.name}: {(1 + self.window[0])**252 - 1:.2%}'
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN PortfolioConstructionModel that can be described like this
: Provides an implementation of IPortfolioConstructionModel that gives equal weighting to all securities.
|
```python
from AlgorithmImports import *
class EqualWeightingPortfolioConstructionModel(PortfolioConstructionModel):
'''Provides an implementation of IPortfolioConstructionModel that gives equal weighting to all securities.
The target percent holdings of each security is 1/N where N is the number of securities.
For insights of direction InsightDirection.UP, long targets are returned and
for insights of direction InsightDirection.DOWN, short targets are returned.'''
def __init__(self, rebalance = Resolution.DAILY, portfolio_bias = PortfolioBias.LONG_SHORT):
'''Initialize a new instance of EqualWeightingPortfolioConstructionModel
Args:
rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.
If None will be ignored.
The function returns the next expected rebalance time for a given algorithm UTC DateTime.
The function returns null if unknown, in which case the function will be called again in the
next loop. Returning current time will trigger rebalance.
portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)'''
super().__init__()
self.portfolio_bias = portfolio_bias
# If the argument is an instance of Resolution or Timedelta
# Redefine rebalancing_func
rebalancing_func = rebalance
if isinstance(rebalance, Resolution):
rebalance = Extensions.to_time_span(rebalance)
if isinstance(rebalance, timedelta):
rebalancing_func = lambda dt: dt + rebalance
if rebalancing_func:
self.set_rebalancing_func(rebalancing_func)
def determine_target_percent(self, active_insights):
'''Will determine the target percent for each insight
Args:
active_insights: The active insights to generate a target for'''
result = {}
# give equal weighting to each security
count = sum(x.direction != InsightDirection.FLAT and self.respect_portfolio_bias(x) for x in active_insights)
percent = 0 if count == 0 else 1.0 / count
for insight in active_insights:
result[insight] = (insight.direction if self.respect_portfolio_bias(insight) else InsightDirection.FLAT) * percent
return result
def respect_portfolio_bias(self, insight):
'''Method that will determine if a given insight respects the portfolio bias
Args:
insight: The insight to create a target for
'''
return self.portfolio_bias == PortfolioBias.LONG_SHORT or insight.direction == self.portfolio_bias
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN PortfolioConstructionModel that can be described like this
: Provides an implementation of IPortfolioConstructionModel that allocates percent of account
|
```python
from AlgorithmImports import *
from EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
class AccumulativeInsightPortfolioConstructionModel(EqualWeightingPortfolioConstructionModel):
'''Provides an implementation of IPortfolioConstructionModel that allocates percent of account
to each insight, defaulting to 3%.
For insights of direction InsightDirection.UP, long targets are returned and
for insights of direction InsightDirection.DOWN, short targets are returned.
By default, no rebalancing shall be done.
Rules:
1. On active Up insight, increase position size by percent
2. On active Down insight, decrease position size by percent
3. On active Flat insight, move by percent towards 0
4. On expired insight, and no other active insight, emits a 0 target'''
def __init__(self, rebalance = None, portfolio_bias = PortfolioBias.LONG_SHORT, percent = 0.03):
'''Initialize a new instance of AccumulativeInsightPortfolioConstructionModel
Args:
rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.
If None will be ignored.
The function returns the next expected rebalance time for a given algorithm UTC DateTime.
The function returns null if unknown, in which case the function will be called again in the
next loop. Returning current time will trigger rebalance.
portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)
percent: percent of portfolio to allocate to each position'''
super().__init__(rebalance)
self.portfolio_bias = portfolio_bias
self.percent = abs(percent)
self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)
def determine_target_percent(self, active_insights):
'''Will determine the target percent for each insight
Args:
active_insights: The active insights to generate a target for'''
percent_per_symbol = {}
insights = sorted(self.algorithm.insights.get_active_insights(self.current_utc_time), key=lambda insight: insight.generated_time_utc)
for insight in insights:
target_percent = 0
if insight.symbol in percent_per_symbol:
target_percent = percent_per_symbol[insight.symbol]
if insight.direction == InsightDirection.FLAT:
# We received a Flat
# if adding or subtracting will push past 0, then make it 0
if abs(target_percent) < self.percent:
target_percent = 0
else:
# otherwise, we flatten by percent
target_percent += (-self.percent if target_percent > 0 else self.percent)
target_percent += self.percent * insight.direction
# adjust to respect portfolio bias
if self.portfolio_bias != PortfolioBias.LONG_SHORT and self.sign(target_percent) != self.portfolio_bias:
target_percent = 0
percent_per_symbol[insight.symbol] = target_percent
return dict((insight, percent_per_symbol[insight.symbol]) for insight in active_insights)
def create_targets(self, algorithm, insights):
'''Create portfolio targets from the specified insights
Args:
algorithm: The algorithm instance
insights: The insights to create portfolio targets from
Returns:
An enumerable of portfolio targets to be sent to the execution model'''
self.current_utc_time = algorithm.utc_time
return super().create_targets(algorithm, insights)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN PortfolioConstructionModel that can be described like this
: Provides an implementation of IPortfolioConstructionModel that generates percent targets based on the
|
```python
from AlgorithmImports import *
from EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
class InsightWeightingPortfolioConstructionModel(EqualWeightingPortfolioConstructionModel):
'''Provides an implementation of IPortfolioConstructionModel that generates percent targets based on the
Insight.WEIGHT. The target percent holdings of each Symbol is given by the Insight.WEIGHT from the last
active Insight for that symbol.
For insights of direction InsightDirection.UP, long targets are returned and for insights of direction
InsightDirection.DOWN, short targets are returned.
If the sum of all the last active Insight per symbol is bigger than 1, it will factor down each target
percent holdings proportionally so the sum is 1.
It will ignore Insight that have no Insight.WEIGHT value.'''
def __init__(self, rebalance = Resolution.DAILY, portfolio_bias = PortfolioBias.LONG_SHORT):
'''Initialize a new instance of InsightWeightingPortfolioConstructionModel
Args:
rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.
If None will be ignored.
The function returns the next expected rebalance time for a given algorithm UTC DateTime.
The function returns null if unknown, in which case the function will be called again in the
next loop. Returning current time will trigger rebalance.
portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)'''
super().__init__(rebalance, portfolio_bias)
def should_create_target_for_insight(self, insight):
'''Method that will determine if the portfolio construction model should create a
target for this insight
Args:
insight: The insight to create a target for'''
# Ignore insights that don't have Weight value
return insight.weight is not None
def determine_target_percent(self, active_insights):
'''Will determine the target percent for each insight
Args:
active_insights: The active insights to generate a target for'''
result = {}
# We will adjust weights proportionally in case the sum is > 1 so it sums to 1.
weight_sums = sum(self.get_value(insight) for insight in active_insights if self.respect_portfolio_bias(insight))
weight_factor = 1.0
if weight_sums > 1:
weight_factor = 1 / weight_sums
for insight in active_insights:
result[insight] = (insight.direction if self.respect_portfolio_bias(insight) else InsightDirection.FLAT) * self.get_value(insight) * weight_factor
return result
def get_value(self, insight):
'''Method that will determine which member will be used to compute the weights and gets its value
Args:
insight: The insight to create a target for
Returns:
The value of the selected insight member'''
return abs(insight.weight)
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN PortfolioConstructionModel that can be described like this
: Provides an implementation of IPortfolioConstructionModel that
|
```python
from AlgorithmImports import *
from EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
class SectorWeightingPortfolioConstructionModel(EqualWeightingPortfolioConstructionModel):
'''Provides an implementation of IPortfolioConstructionModel that
generates percent targets based on the CompanyReference.industry_template_code.
The target percent holdings of each sector is 1/S where S is the number of sectors and
the target percent holdings of each security is 1/N where N is the number of securities of each sector.
For insights of direction InsightDirection.UP, long targets are returned and for insights of direction
InsightDirection.DOWN, short targets are returned.
It will ignore Insight for symbols that have no CompanyReference.industry_template_code'''
def __init__(self, rebalance = Resolution.DAILY):
'''Initialize a new instance of InsightWeightingPortfolioConstructionModel
Args:
rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.
If None will be ignored.
The function returns the next expected rebalance time for a given algorithm UTC DateTime.
The function returns null if unknown, in which case the function will be called again in the
next loop. Returning current time will trigger rebalance.'''
super().__init__(rebalance)
self.sector_code_by_symbol = dict()
def should_create_target_for_insight(self, insight):
'''Method that will determine if the portfolio construction model should create a
target for this insight
Args:
insight: The insight to create a target for'''
return insight.symbol in self.sector_code_by_symbol
def determine_target_percent(self, active_insights):
'''Will determine the target percent for each insight
Args:
active_insights: The active insights to generate a target for'''
result = dict()
insight_by_sector_code = dict()
for insight in active_insights:
if insight.direction == InsightDirection.FLAT:
result[insight] = 0
continue
sector_code = self.sector_code_by_symbol.get(insight.symbol)
insights = insight_by_sector_code.pop(sector_code, list())
insights.append(insight)
insight_by_sector_code[sector_code] = insights
# give equal weighting to each sector
sector_percent = 0 if len(insight_by_sector_code) == 0 else 1.0 / len(insight_by_sector_code)
for _, insights in insight_by_sector_code.items():
# give equal weighting to each security
count = len(insights)
percent = 0 if count == 0 else sector_percent / count
for insight in insights:
result[insight] = insight.direction * percent
return result
def on_securities_changed(self, algorithm, changes):
'''Event fired each time the we add/remove securities from the data feed
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
for security in changes.removed_securities:
# Removes the symbol from the self.sector_code_by_symbol dictionary
# since we cannot emit PortfolioTarget for removed securities
self.sector_code_by_symbol.pop(security.symbol, None)
for security in changes.added_securities:
sector_code = self.get_sector_code(security)
if sector_code:
self.sector_code_by_symbol[security.symbol] = sector_code
super().on_securities_changed(algorithm, changes)
def get_sector_code(self, security):
'''Gets the sector code
Args:
security: The security to create a sector code for
Returns:
The value of the sector code for the security
Remarks:
Other sectors can be defined using AssetClassification'''
fundamentals = security.fundamentals
company_reference = security.fundamentals.company_reference if fundamentals else None
return company_reference.industry_template_code if company_reference else None
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN PortfolioConstructionModel that can be described like this
: Implementation of On-Line Moving Average Reversion (OLMAR)
|
```python
from AlgorithmImports import *
class MeanReversionPortfolioConstructionModel(PortfolioConstructionModel):
def __init__(self,
rebalance = Resolution.Daily,
portfolioBias = PortfolioBias.LongShort,
reversion_threshold = 1,
window_size = 20,
resolution = Resolution.Daily):
"""Initialize the model
Args:
rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.
If None will be ignored.
The function returns the next expected rebalance time for a given algorithm UTC DateTime.
The function returns null if unknown, in which case the function will be called again in the
next loop. Returning current time will trigger rebalance.
portfolioBias: Specifies the bias of the portfolio (Short, Long/Short, Long)
reversion_threshold: Reversion threshold
window_size: Window size of mean price calculation
resolution: The resolution of the history price and rebalancing
"""
super().__init__()
if portfolioBias == PortfolioBias.Short:
raise ArgumentException("Long position must be allowed in MeanReversionPortfolioConstructionModel.")
self.reversion_threshold = reversion_threshold
self.window_size = window_size
self.resolution = resolution
self.num_of_assets = 0
# Initialize a dictionary to store stock data
self.symbol_data = {}
# If the argument is an instance of Resolution or Timedelta
# Redefine rebalancingFunc
rebalancingFunc = rebalance
if isinstance(rebalance, int):
rebalance = Extensions.ToTimeSpan(rebalance)
if isinstance(rebalance, timedelta):
rebalancingFunc = lambda dt: dt + rebalance
if rebalancingFunc:
self.SetRebalancingFunc(rebalancingFunc)
def DetermineTargetPercent(self, activeInsights):
"""Will determine the target percent for each insight
Args:
activeInsights: list of active insights
Returns:
dictionary of insight and respective target weight
"""
targets = {}
# If we have no insights or non-ready just return an empty target list
if len(activeInsights) == 0 or not all([self.symbol_data[x.Symbol].IsReady for x in activeInsights]):
return targets
num_of_assets = len(activeInsights)
if self.num_of_assets != num_of_assets:
self.num_of_assets = num_of_assets
# Initialize portfolio weightings vector
self.weight_vector = np.ones(num_of_assets) * (1/num_of_assets)
### Get price relatives vs expected price (SMA)
price_relatives = self.GetPriceRelatives(activeInsights) # \tilde{x}_{t+1}
### Get step size of next portfolio
# \bar{x}_{t+1} = 1^T * \tilde{x}_{t+1} / m
# \lambda_{t+1} = max( 0, ( b_t * \tilde{x}_{t+1} - \epsilon ) / ||\tilde{x}_{t+1} - \bar{x}_{t+1} * 1|| ^ 2 )
next_prediction = price_relatives.mean() # \bar{x}_{t+1}
assets_mean_dev = price_relatives - next_prediction
second_norm = (np.linalg.norm(assets_mean_dev)) ** 2
if second_norm == 0.0:
step_size = 0
else:
step_size = (np.dot(self.weight_vector, price_relatives) - self.reversion_threshold) / second_norm
step_size = max(0, step_size) # \lambda_{t+1}
### Get next portfolio weightings
# b_{t+1} = b_t - step_size * ( \tilde{x}_{t+1} - \bar{x}_{t+1} * 1 )
next_portfolio = self.weight_vector - step_size * assets_mean_dev
# Normalize
normalized_portfolio_weight_vector = self.SimplexProjection(next_portfolio)
# Save normalized result for the next portfolio step
self.weight_vector = normalized_portfolio_weight_vector
# Update portfolio state
for i, insight in enumerate(activeInsights):
targets[insight] = normalized_portfolio_weight_vector[i]
return targets
def GetPriceRelatives(self, activeInsights):
"""Get price relatives with reference level of SMA
Args:
activeInsights: list of active insights
Returns:
array of price relatives vector
"""
# Initialize a price vector of the next prices relatives' projection
next_price_relatives = np.zeros(len(activeInsights))
### Get next price relative predictions
# Using the previous price to simulate assumption of instant reversion
for i, insight in enumerate(activeInsights):
symbol_data = self.symbol_data[insight.Symbol]
next_price_relatives[i] = 1 + insight.Magnitude * insight.Direction \
if insight.Magnitude is not None \
else symbol_data.Identity.Current.Value / symbol_data.Sma.Current.Value
return next_price_relatives
def OnSecuritiesChanged(self, algorithm, changes):
"""Event fired each time the we add/remove securities from the data feed
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm
"""
# clean up data for removed securities
super().OnSecuritiesChanged(algorithm, changes)
for removed in changes.RemovedSecurities:
symbol_data = self.symbol_data.pop(removed.Symbol, None)
symbol_data.Reset()
# initialize data for added securities
symbols = [ x.Symbol for x in changes.AddedSecurities ]
for symbol in symbols:
if symbol not in self.symbol_data:
self.symbol_data[symbol] = self.MeanReversionSymbolData(algorithm, symbol, self.window_size, self.resolution)
def SimplexProjection(self, vector, total=1):
"""Normalize the updated portfolio into weight vector:
v_{t+1} = arg min || v - v_{t+1} || ^ 2
Implementation from:
Duchi, J., Shalev-Shwartz, S., Singer, Y., & Chandra, T. (2008, July).
Efficient projections onto the l 1-ball for learning in high dimensions.
In Proceedings of the 25th international conference on Machine learning
(pp. 272-279).
Args:
vector: unnormalized weight vector
total: total weight of output, default to be 1, making it a probabilistic simplex
"""
if total <= 0:
raise ArgumentException("Total must be > 0 for Euclidean Projection onto the Simplex.")
vector = np.asarray(vector)
# Sort v into u in descending order
mu = np.sort(vector)[::-1]
sv = np.cumsum(mu)
rho = np.where(mu > (sv - total) / np.arange(1, len(vector) + 1))[0][-1]
theta = (sv[rho] - total) / (rho + 1)
w = (vector - theta)
w[w < 0] = 0
return w
class MeanReversionSymbolData:
def __init__(self, algo, symbol, window_size, resolution):
# Indicator of price
self.Identity = algo.Identity(symbol, resolution)
# Moving average indicator for mean reversion level
self.Sma = algo.SMA(symbol, window_size, resolution)
# Warmup indicator
algo.WarmUpIndicator(symbol, self.Identity, resolution)
algo.WarmUpIndicator(symbol, self.Sma, resolution)
def Reset(self):
self.Identity.Reset()
self.Sma.Reset()
@property
def IsReady(self):
return self.Identity.IsReady and self.Sma.IsReady
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN PortfolioConstructionModel that can be described like this
: Risk Parity Portfolio Construction Model
|
```python
from AlgorithmImports import *
from Portfolio.RiskParityPortfolioOptimizer import RiskParityPortfolioOptimizer
class RiskParityPortfolioConstructionModel(PortfolioConstructionModel):
def __init__(self,
rebalance = Resolution.DAILY,
portfolio_bias = PortfolioBias.LONG_SHORT,
lookback = 1,
period = 252,
resolution = Resolution.DAILY,
optimizer = None):
"""Initialize the model
Args:
rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.
If None will be ignored.
The function returns the next expected rebalance time for a given algorithm UTC DateTime.
The function returns null if unknown, in which case the function will be called again in the
next loop. Returning current time will trigger rebalance.
portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)
lookback(int): Historical return lookback period
period(int): The time interval of history price to calculate the weight
resolution: The resolution of the history price
optimizer(class): Method used to compute the portfolio weights"""
super().__init__()
if portfolio_bias == PortfolioBias.SHORT:
raise ArgumentException("Long position must be allowed in RiskParityPortfolioConstructionModel.")
self.lookback = lookback
self.period = period
self.resolution = resolution
self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)
self.optimizer = RiskParityPortfolioOptimizer() if optimizer is None else optimizer
self._symbol_data_by_symbol = {}
# If the argument is an instance of Resolution or Timedelta
# Redefine rebalancing_func
rebalancing_func = rebalance
if isinstance(rebalance, int):
rebalance = Extensions.to_time_span(rebalance)
if isinstance(rebalance, timedelta):
rebalancing_func = lambda dt: dt + rebalance
if rebalancing_func:
self.set_rebalancing_func(rebalancing_func)
def determine_target_percent(self, active_insights):
"""Will determine the target percent for each insight
Args:
active_insights: list of active insights
Returns:
dictionary of insight and respective target weight
"""
targets = {}
# If we have no insights just return an empty target list
if len(active_insights) == 0:
return targets
symbols = [insight.symbol for insight in active_insights]
# Create a dictionary keyed by the symbols in the insights with an pandas.series as value to create a data frame
returns = { str(symbol) : data.return_ for symbol, data in self._symbol_data_by_symbol.items() if symbol in symbols }
returns = pd.DataFrame(returns)
# The portfolio optimizer finds the optional weights for the given data
weights = self.optimizer.optimize(returns)
weights = pd.Series(weights, index = returns.columns)
# Create portfolio targets from the specified insights
for insight in active_insights:
targets[insight] = weights[str(insight.symbol)]
return targets
def on_securities_changed(self, algorithm, changes):
'''Event fired each time the we add/remove securities from the data feed
Args:
algorithm: The algorithm instance that experienced the change in securities
changes: The security additions and removals from the algorithm'''
# clean up data for removed securities
super().on_securities_changed(algorithm, changes)
for removed in changes.removed_securities:
symbol_data = self._symbol_data_by_symbol.pop(removed.symbol, None)
symbol_data.reset()
algorithm.unregister_indicator(symbol_data.roc)
# initialize data for added securities
symbols = [ x.symbol for x in changes.added_securities ]
history = algorithm.history(symbols, self.lookback * self.period, self.resolution)
if history.empty: return
tickers = history.index.levels[0]
for ticker in tickers:
symbol = SymbolCache.get_symbol(ticker)
if symbol not in self._symbol_data_by_symbol:
symbol_data = self.RiskParitySymbolData(symbol, self.lookback, self.period)
symbol_data.warm_up_indicators(history.loc[ticker])
self._symbol_data_by_symbol[symbol] = symbol_data
algorithm.register_indicator(symbol, symbol_data.roc, self.resolution)
class RiskParitySymbolData:
'''Contains data specific to a symbol required by this model'''
def __init__(self, symbol, lookback, period):
self._symbol = symbol
self.roc = RateOfChange(f'{symbol}.roc({lookback})', lookback)
self.roc.updated += self.on_rate_of_change_updated
self.window = RollingWindow(period)
def reset(self):
self.roc.updated -= self.on_rate_of_change_updated
self.roc.reset()
self.window.reset()
def warm_up_indicators(self, history):
for tuple in history.itertuples():
self.roc.update(tuple.Index, tuple.close)
def on_rate_of_change_updated(self, roc, value):
if roc.is_ready:
self.window.add(value)
def add(self, time, value):
item = IndicatorDataPoint(self._symbol, time, value)
self.window.add(item)
@property
def return_(self):
return pd.Series(
data = [x.value for x in self.window],
index = [x.end_time for x in self.window])
@property
def is_ready(self):
return self.window.is_ready
def __str__(self, **kwargs):
return '{}: {:.2%}'.format(self.roc.name, self.window[0])
```
|
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
|
Generate a LEAN PortfolioConstructionModel that can be described like this
: Provides an implementation of IPortfolioConstructionModel that generates percent targets based on the
|
```python
from AlgorithmImports import *
from InsightWeightingPortfolioConstructionModel import InsightWeightingPortfolioConstructionModel
class ConfidenceWeightedPortfolioConstructionModel(InsightWeightingPortfolioConstructionModel):
'''Provides an implementation of IPortfolioConstructionModel that generates percent targets based on the
Insight.CONFIDENCE. The target percent holdings of each Symbol is given by the Insight.CONFIDENCE from the last
active Insight for that symbol.
For insights of direction InsightDirection.UP, long targets are returned and for insights of direction
InsightDirection.DOWN, short targets are returned.
If the sum of all the last active Insight per symbol is bigger than 1, it will factor down each target
percent holdings proportionally so the sum is 1.
It will ignore Insight that have no Insight.CONFIDENCE value.'''
def __init__(self, rebalance = Resolution.DAILY, portfolio_bias = PortfolioBias.LONG_SHORT):
'''Initialize a new instance of ConfidenceWeightedPortfolioConstructionModel
Args:
rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.
If None will be ignored.
The function returns the next expected rebalance time for a given algorithm UTC DateTime.
The function returns null if unknown, in which case the function will be called again in the
next loop. Returning current time will trigger rebalance.
portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)'''
super().__init__(rebalance, portfolio_bias)
def should_create_target_for_insight(self, insight):
'''Method that will determine if the portfolio construction model should create a
target for this insight
Args:
insight: The insight to create a target for'''
# Ignore insights that don't have Confidence value
return insight.confidence is not None
def get_value(self, insight):
'''Method that will determine which member will be used to compute the weights and gets its value
Args:
insight: The insight to create a target for
Returns:
The value of the selected insight member'''
return insight.confidence
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.