eb1181f5f7
* Adds preliminary universe selection for Future Options
* Fixes scaling issues with Future Options
* Fixes scaling multiplying by 10000x instead of using _scaleFactor
* Fixes scaling for Tick
* Revert changes to Tick since it divides the scaling factor
* Changes stale method name to new method name after rebase
* Fixes selection bugs, adds new methods, and adds unit tests
* Fixes bug where Equity Symbol was created for an underlying
non-equity Symbol, resulting in equity data trying to be loaded
* Adds unit tests covering changes to Tick, QuoteBar, TradeBar and
LeanData
* Adds regression test for AddUniverseOption filter contract selection
for Future Options
* Addresses review - modifies the AddFutureOption signature
* Adds new AddUniverseOptions method overload
* Removes and adds a new unit test
* Misc. modifications to account for new changes
* Fixes bug where futures were loaded using default SID Date
* Refactors and removes unnecessary work
* Fixes regression algorithm, which previously made no trades
* Adds future option data
* Adds the corresponding underlying data, in this case, futures data
to enable usage of future options data
* Replaces data with new data (ES18Z20)
* Improves Future chain filtering and updates regression stats
* Add AddFutureOptionContract API
* Expands regression and unit tests to test in finer detail
* Adds Python regression algorithms for AddFutureOption[Contract] methods
* Adds new unit test for BacktestingOptionChainProvider
* Fixes bug with BacktesingOptionChainProvider where we
attempted to load the Trades option chain first, resulting
in breakage of backwards compatibility and limitation of the
option chain.
* Adds new regression algorithms (Py) to Algorithm.Python project
* Adds FutureOptionMarginBuyingPowerModel
* Modifies code paths used to select margin model
* Adds related unit tests for margin model
* Fixes issue with unit test and MHDB/SPDB lookup for Future Options
* Preliminary regression algorithm testing ITM call/put option buying
* Fixes bug where fee model used did not find non-US market
options fee model. We now use the futures fee model for future
options because IB charges the same commissions per contract
between futures and futures options
* Adds proper regression algorithm for ITM future options expiration
* Pushing broken algorithm for review
* Currently, algorithm does not fill forward, causing
a single future option to not get exercised when it is delisted.
* Adds FutureOptionPutITMExpiryRegressionAlgorithm
* Improves existing regression algorithm for call side
* Fixes bug in existing regression algorithm
* Adds AAPL daily data to advance enumerator for ^^^ fix
* Adds additional future option regression algorithms
* Adds Buy OTM expiration regression algorithms
* Adds Sell ITM/OTM expiration regression algorithms
* Adds missing Python regression algorithms
* Adds remaining Python regression algorithms and fixes issues
* Fixes naming issues and statistics
* Adds short option OTM regression algorithms (Py)
* Add license header and class comments to python algorithms
* Cleans up comments and docstrings
* Create Buy/Sell call intraday regression algo
* Redirects future options symbol properties to futures symbol properties
* Asserts exercise/assignment price and updates stats in regression algos
* Adds new unit test covering changes to SecurityService
* Adds comments and fixes failing test
* Partially fixes future option mis-calculated profit/loss
* Adjusts portfolio model to calculate FOP as a no upfront pay asset class
* Updates regression algorithm statistics
* Begin IB FOP support
* Initial support for FOP IB data streaming, live í¾
* Adds additional functionality to LiveOptionChainProvider
- Allows querying CME API to retrieve option chains for CME products
- Ultimately, it's also the groundwork for the CME
LiveFutureChainProvider
* Edits IDataQueueUniverseProvider interface to provide greater
control to implementors of it
* Misc. bug fixes required to get FOP data streaming through IB
* Adds comments, adds missing rategate call, and cleans up code
* Force exchange for FOP and Futures when no exchange is provided
* Fixes bug with Portfolio modeling across all asset classes
* Adds LiveOptionChainProvider tests for Future Options
* IB brokerage option symbol bug fixes and improvements
* Fixes contract multiplier lookup bug
* Fixes issue where we attempted to subscribe to IB data feed with canonical security
* Adds ES MHDB entry
* Reverts portfolio modeling changes for Futures Options
* Since IB eats into our account's cash balance when
a new FOP contract is purchased, we must model by applying funds
to our cash whenever a new purchase/sell occurs.
If we choose to model FOPs exactly as we do with futures, we
will end up with an invalid TotalPortfolioValue on algorithm
restart. By all means and purposes, FOPs are modeled exactly
the same as equity options with respect to the portfolio.
* Adds comments clarifying portfolio modeling and clarifies
existing portfolio modeling comments with additional context.
* Fixes IB symbol lookup for future options
* Fixes LiveOptionChainProvider looping 5 times per option chain
request, even on success
* Sets OptionChainedUniverseSelectionModel to produce a canonical
future/future option/option Symbol to avoid creating two Symbols
* Adds GLOBEX future option symbol mapping from future -> fop
* Fixes LiveOptionChainProvider loading wrong contract option chains
* Fixes loading of futures options ZIP files when backtesting
* Adds a string -> decimal JSON converter
* Additional fixes/refactoring to the LiveOptionChainProvider
* Adds tests for changes to Symbol and LeanData
* Reverts changes to IB-symbol-map
* Fixes Value for mapped future options tickers
* Fixes Symbol test
* Changes path of future options to future's expiry date
* Extra changes made to remove scaling from writing CSV
* Added method to map from FOP Globex -> FUT Globex
* Fixes MOO and MOC orders for future options
* Note: this order type might not be supported by IB or CME.
* Bug fixes and updates unit tests
* Update regression tests and data format
* Rebase changes
* 1. Multiple bug fixes for LiveOptionChainProvider, reverts IQFeed changes
2. Address review (partial): Code reuse and cleanup
1.
* Modifies check in
`AddFutureOptionShort(Call|Put)ITMExpiryRegressionAlgorithm`
to ensure no buys have negative quantity
* Code reuse changes in IB brokerage
* Bug fix in IB brokerage where we assigned the FOP expiry
as the futures expiry (requires verification)
* Doc changes and adds missing summaries/license banners
* Disposes of HTTP client resources in LiveOptionChainProvider
* Renames classes and adds FutureOption folder in Common/Securities
2.
* We revert back to the quotes API for the option chain,
since the settlement API sometimes had missing strikes.
* Fixes future option expiry being set as future's expiry
in LiveOptionChainProvider
* Fixes bug where wrong option chain was selected because of bad
expiry lookup in the futures expiries returned from CME
* Fixes multiple looping bug in LiveOptionChainProvider
* Adds strike price scaling for LiveOptionChainProvider
* Reverts IQFeed changes and simplifies interface upgrade changes
Some additional challenges we'll have to solve as part of FOPs:
- The `OptionSymbol.IsStandard` method makes the assumption that
weeklies contracts follow the pattern equities follows, which
does not apply to Futures Options
- The Subscription created in:
`OptionChainUniverseSubscriptionEnumeratorFactory`
...adds a Trade config. For illiquid contracts, this
will delay universe selection for the option symbol
until we get a trade. However, if we add a quote config,
the data would instead be loaded based on the first quote
we received from the brokerage.
But since we're currently using a trade config, illiquid
contracts won't start streaming data until it receives a trade.
NOTE: this commit is a WIP to addressing the reviews received in the PR,
but has been committed early for efficiency in the review process
* Fixes regression algorithms and misc. bugs
* Fixes map file lookup for non-equity options
* Adds extra assertion at end of algorithm to ensure no holdings are
left when the algorithm ends.
* Adds FutureOptionSymbol, allowing all contracts through as standard
* Changes SPDB to allow defaulting to underlying future symbol
properties if no entry is found for the given FOP
* Fixes calls to SPDB in SecurityService, IBBrokerage
* Reverts AAPL daily ZIP file to fix majority of regression algorithms
* Adds FOPs symbol properties
* Fixes existing symbol properties for a few futures
* Adds tests for changes to Symbol Properties Database
* Removes string SPDB lookup method
* Updates tests and misc callees of previous method
* Updates all regression tests to use data of already expired contracts
* Adds Futures Options Expiry Functions tests
* Adds required futures data for 2020-01-05
* Address review (partial): Expands test coverage and fixes tests
* Set option chain tests parallelism to fixture only
* Fixes broken test for contract month delta for FuturesOptionsExpiryFunctions
* Changes delisting date logic for Futures Options
* Address review: removes duplicate code, misc code fixes
* Bug fix in MarketHoursDatabase.GetDatabaseSymbolKey() where
we would use the underlying's Symbol for lookup in the MHDB
* Adds missing license banner
* Removes Futures Options entries from MHDB
* Adds new tests
* Adds SecurityType.FutureOption
* Converts any underlying comparisons and uses SecurityType directly
instead for FOP specific behavior
* Extra code modifications to acommodate new SecurityType
* Addresses review: fixes order fee bug on exercise
* Additional bug fixes and adding of SecurityType.FutureOption
* Updates regression algorithms OrderListHash
* Fixes various bugs in IB live implementation
* Fixes bug setting the right contract expiration date for FOP
generated by LiveOptionChainProvider
* Adds new function to FuturesOptionsExpiryFunctions
* Clarifies parameter names better in some functions/methods
* Fixes bugs in IB brokerage for FOPs
* Address review - code cleanup and refactor
* Remove MappingEventProvider, SplitEventProvider, and
DividendEventProvider for Futures Options in
CorporateEventEnumeratorFactory
* Address review: Use MHDB key resolver in SPDB
* Makes regression tests pass and adds comment for expiry issue
* Fixes MHDB lookup on string symbol method
* Adds Futures Options greeks regression algorithm (C# only)
* Adds explanitory comment on MHDB FOP lookup
* Remove python from FutureOptionCallITMGreeksExpiryRegressionAlgorithm
569 lines
24 KiB
C#
569 lines
24 KiB
C#
/*
|
|
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
|
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
|
*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*/
|
|
|
|
using System;
|
|
using QuantConnect.Data;
|
|
using QuantConnect.Orders.Fees;
|
|
using QuantConnect.Orders.Fills;
|
|
using QuantConnect.Orders.Slippage;
|
|
using QuantConnect.Orders.OptionExercise;
|
|
using Python.Runtime;
|
|
using QuantConnect.Data.Market;
|
|
using QuantConnect.Interfaces;
|
|
using System.Collections.Generic;
|
|
using QuantConnect.Orders;
|
|
using QuantConnect.Securities.Interfaces;
|
|
|
|
namespace QuantConnect.Securities.Option
|
|
{
|
|
/// <summary>
|
|
/// Option Security Object Implementation for Option Assets
|
|
/// </summary>
|
|
/// <seealso cref="Security"/>
|
|
public class Option : Security, IDerivativeSecurity, IOptionPrice
|
|
{
|
|
/// <summary>
|
|
/// The default number of days required to settle an equity sale
|
|
/// </summary>
|
|
public const int DefaultSettlementDays = 1;
|
|
|
|
/// <summary>
|
|
/// The default time of day for settlement
|
|
/// </summary>
|
|
public static readonly TimeSpan DefaultSettlementTime = new TimeSpan(8, 0, 0);
|
|
|
|
/// <summary>
|
|
/// Constructor for the option security
|
|
/// </summary>
|
|
/// <param name="exchangeHours">Defines the hours this exchange is open</param>
|
|
/// <param name="quoteCurrency">The cash object that represent the quote currency</param>
|
|
/// <param name="config">The subscription configuration for this security</param>
|
|
/// <param name="symbolProperties">The symbol properties for this security</param>
|
|
/// <param name="currencyConverter">Currency converter used to convert <see cref="CashAmount"/>
|
|
/// instances into units of the account currency</param>
|
|
/// <param name="registeredTypes">Provides all data types registered in the algorithm</param>
|
|
public Option(SecurityExchangeHours exchangeHours,
|
|
SubscriptionDataConfig config,
|
|
Cash quoteCurrency,
|
|
OptionSymbolProperties symbolProperties,
|
|
ICurrencyConverter currencyConverter,
|
|
IRegisteredSecurityDataTypesProvider registeredTypes)
|
|
: base(config,
|
|
quoteCurrency,
|
|
symbolProperties,
|
|
new OptionExchange(exchangeHours),
|
|
new OptionCache(),
|
|
new OptionPortfolioModel(),
|
|
new ImmediateFillModel(),
|
|
new InteractiveBrokersFeeModel(),
|
|
new ConstantSlippageModel(0),
|
|
new ImmediateSettlementModel(),
|
|
Securities.VolatilityModel.Null,
|
|
new OptionMarginModel(),
|
|
new OptionDataFilter(),
|
|
new SecurityPriceVariationModel(),
|
|
currencyConverter,
|
|
registeredTypes
|
|
)
|
|
{
|
|
ExerciseSettlement = SettlementType.PhysicalDelivery;
|
|
SetDataNormalizationMode(DataNormalizationMode.Raw);
|
|
OptionExerciseModel = new DefaultExerciseModel();
|
|
PriceModel = new CurrentPriceOptionPriceModel();
|
|
Holdings = new OptionHolding(this, currencyConverter);
|
|
_symbolProperties = symbolProperties;
|
|
SetFilter(-1, 1, TimeSpan.Zero, TimeSpan.FromDays(35));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Constructor for the option security
|
|
/// </summary>
|
|
/// <param name="symbol">The symbol of the security</param>
|
|
/// <param name="exchangeHours">Defines the hours this exchange is open</param>
|
|
/// <param name="quoteCurrency">The cash object that represent the quote currency</param>
|
|
/// <param name="symbolProperties">The symbol properties for this security</param>
|
|
/// <param name="currencyConverter">Currency converter used to convert <see cref="CashAmount"/>
|
|
/// instances into units of the account currency</param>
|
|
/// <param name="registeredTypes">Provides all data types registered in the algorithm</param>
|
|
public Option(Symbol symbol,
|
|
SecurityExchangeHours exchangeHours,
|
|
Cash quoteCurrency,
|
|
OptionSymbolProperties symbolProperties,
|
|
ICurrencyConverter currencyConverter,
|
|
IRegisteredSecurityDataTypesProvider registeredTypes,
|
|
SecurityCache securityCache)
|
|
: base(symbol,
|
|
quoteCurrency,
|
|
symbolProperties,
|
|
new OptionExchange(exchangeHours),
|
|
securityCache,
|
|
new OptionPortfolioModel(),
|
|
new ImmediateFillModel(),
|
|
new InteractiveBrokersFeeModel(),
|
|
new ConstantSlippageModel(0),
|
|
new ImmediateSettlementModel(),
|
|
Securities.VolatilityModel.Null,
|
|
new OptionMarginModel(),
|
|
new OptionDataFilter(),
|
|
new SecurityPriceVariationModel(),
|
|
currencyConverter,
|
|
registeredTypes
|
|
)
|
|
{
|
|
ExerciseSettlement = SettlementType.PhysicalDelivery;
|
|
SetDataNormalizationMode(DataNormalizationMode.Raw);
|
|
OptionExerciseModel = new DefaultExerciseModel();
|
|
PriceModel = new CurrentPriceOptionPriceModel();
|
|
Holdings = new OptionHolding(this, currencyConverter);
|
|
_symbolProperties = symbolProperties;
|
|
SetFilter(-1, 1, TimeSpan.Zero, TimeSpan.FromDays(35));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates instance of the Option class.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Allows for the forwarding of the security configuration to the
|
|
/// base Security constructor
|
|
/// </remarks>
|
|
protected Option(Symbol symbol,
|
|
Cash quoteCurrency,
|
|
SymbolProperties symbolProperties,
|
|
SecurityExchange exchange,
|
|
SecurityCache cache,
|
|
ISecurityPortfolioModel portfolioModel,
|
|
IFillModel fillModel,
|
|
IFeeModel feeModel,
|
|
ISlippageModel slippageModel,
|
|
ISettlementModel settlementModel,
|
|
IVolatilityModel volatilityModel,
|
|
IBuyingPowerModel buyingPowerModel,
|
|
ISecurityDataFilter dataFilter,
|
|
IPriceVariationModel priceVariationModel,
|
|
ICurrencyConverter currencyConverter,
|
|
IRegisteredSecurityDataTypesProvider registeredTypesProvider
|
|
) : base(
|
|
symbol,
|
|
quoteCurrency,
|
|
symbolProperties,
|
|
exchange,
|
|
cache,
|
|
portfolioModel,
|
|
fillModel,
|
|
feeModel,
|
|
slippageModel,
|
|
settlementModel,
|
|
volatilityModel,
|
|
buyingPowerModel,
|
|
dataFilter,
|
|
priceVariationModel,
|
|
currencyConverter,
|
|
registeredTypesProvider
|
|
)
|
|
{
|
|
ExerciseSettlement = SettlementType.PhysicalDelivery;
|
|
SetDataNormalizationMode(DataNormalizationMode.Raw);
|
|
OptionExerciseModel = new DefaultExerciseModel();
|
|
PriceModel = new CurrentPriceOptionPriceModel();
|
|
Holdings = new OptionHolding(this, currencyConverter);
|
|
_symbolProperties = (OptionSymbolProperties)symbolProperties;
|
|
SetFilter(-1, 1, TimeSpan.Zero, TimeSpan.FromDays(35));
|
|
}
|
|
|
|
// save off a strongly typed version of symbol properties
|
|
private readonly OptionSymbolProperties _symbolProperties;
|
|
|
|
/// <summary>
|
|
/// Returns true if this is the option chain security, false if it is a specific option contract
|
|
/// </summary>
|
|
public bool IsOptionChain => Symbol.IsCanonical();
|
|
|
|
/// <summary>
|
|
/// Returns true if this is a specific option contract security, false if it is the option chain security
|
|
/// </summary>
|
|
public bool IsOptionContract => !Symbol.IsCanonical();
|
|
|
|
/// <summary>
|
|
/// Gets the strike price
|
|
/// </summary>
|
|
public decimal StrikePrice
|
|
{
|
|
get { return Symbol.ID.StrikePrice; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the expiration date
|
|
/// </summary>
|
|
public DateTime Expiry
|
|
{
|
|
get { return Symbol.ID.Date; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the right being purchased (call [right to buy] or put [right to sell])
|
|
/// </summary>
|
|
public OptionRight Right
|
|
{
|
|
get { return Symbol.ID.OptionRight; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the option style
|
|
/// </summary>
|
|
public OptionStyle Style
|
|
{
|
|
get { return Symbol.ID.OptionStyle; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the most recent bid price if available
|
|
/// </summary>
|
|
public override decimal BidPrice => Cache.BidPrice;
|
|
|
|
/// <summary>
|
|
/// Gets the most recent ask price if available
|
|
/// </summary>
|
|
public override decimal AskPrice => Cache.AskPrice;
|
|
|
|
/// <summary>
|
|
/// When the holder of an equity option exercises one contract, or when the writer of an equity option is assigned
|
|
/// an exercise notice on one contract, this unit of trade, usually 100 shares of the underlying security, changes hands.
|
|
/// </summary>
|
|
public int ContractUnitOfTrade
|
|
{
|
|
get
|
|
{
|
|
return _symbolProperties.ContractUnitOfTrade;
|
|
}
|
|
set
|
|
{
|
|
_symbolProperties.SetContractUnitOfTrade(value);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The contract multiplier for the option security
|
|
/// </summary>
|
|
public int ContractMultiplier
|
|
{
|
|
get
|
|
{
|
|
return (int)_symbolProperties.ContractMultiplier;
|
|
}
|
|
set
|
|
{
|
|
_symbolProperties.SetContractMultiplier(value);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Aggregate exercise amount or aggregate contract value. It is the total amount of cash one will pay (or receive) for the shares of the
|
|
/// underlying stock if he/she decides to exercise (or is assigned an exercise notice). This amount is not the premium paid or received for an equity option.
|
|
/// </summary>
|
|
public decimal GetAggregateExerciseAmount()
|
|
{
|
|
return StrikePrice * ContractMultiplier;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns the directional quantity of underlying shares that are going to change hands on exercise/assignment of all
|
|
/// contracts held by this account, taking into account the contract's <see cref="Right"/> as well as the contract's current
|
|
/// <see cref="ContractUnitOfTrade"/>, which may have recently changed due to a split/reverse split in the underlying security.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Long option positions result in exercise while short option positions result in assignment. This function uses the term
|
|
/// exercise loosely to refer to both situations.
|
|
/// </remarks>
|
|
public decimal GetExerciseQuantity()
|
|
{
|
|
// negate Holdings.Quantity to match an equivalent order
|
|
return GetExerciseQuantity(-Holdings.Quantity);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns the directional quantity of underlying shares that are going to change hands on exercise/assignment of the
|
|
/// specified <paramref name="exerciseOrderQuantity"/>, taking into account the contract's <see cref="Right"/> as well
|
|
/// as the contract's current <see cref="ContractUnitOfTrade"/>, which may have recently changed due to a split/reverse
|
|
/// split in the underlying security.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Long option positions result in exercise while short option positions result in assignment. This function uses the term
|
|
/// exercise loosely to refer to both situations.
|
|
/// </remarks>
|
|
/// <paramref name="exerciseOrderQuantity">The quantity of contracts being exercised as provided by the <see cref="OptionExerciseOrder"/>.
|
|
/// A negative value indicates exercise (we are long and the order quantity is negative to bring us (closer) to zero.
|
|
/// A positive value indicates assignment (we are short and the order quantity is positive to bring us (closer) to zero.</paramref>
|
|
public decimal GetExerciseQuantity(decimal exerciseOrderQuantity)
|
|
{
|
|
// when exerciseOrderQuantity > 0 [ we are short ]
|
|
// && right == call => we sell to contract holder => negative
|
|
// && right == put => we buy from contract holder => positive
|
|
|
|
// when exerciseOrderQuantity < 0 [ we are long ]
|
|
// && right == call => we buy from contract holder => positive
|
|
// && right == put => we sell to contract holder => negative
|
|
|
|
var sign = Right == OptionRight.Call ? -1 : 1;
|
|
return sign * exerciseOrderQuantity * ContractUnitOfTrade;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Checks if option is eligible for automatic exercise on expiration
|
|
/// </summary>
|
|
public bool IsAutoExercised(decimal underlyingPrice)
|
|
{
|
|
return GetIntrinsicValue(underlyingPrice) >= 0.01m;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Intrinsic value function of the option
|
|
/// </summary>
|
|
public decimal GetIntrinsicValue(decimal underlyingPrice)
|
|
{
|
|
return Math.Max(0.0m, GetPayOff(underlyingPrice));
|
|
}
|
|
/// <summary>
|
|
/// Option payoff function at expiration time
|
|
/// </summary>
|
|
/// <param name="underlyingPrice">The price of the underlying</param>
|
|
/// <returns></returns>
|
|
public decimal GetPayOff(decimal underlyingPrice)
|
|
{
|
|
return Right == OptionRight.Call ? underlyingPrice - StrikePrice : StrikePrice - underlyingPrice;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Specifies if option contract has physical or cash settlement on exercise
|
|
/// </summary>
|
|
public SettlementType ExerciseSettlement
|
|
{
|
|
get; set;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets or sets the underlying security object.
|
|
/// </summary>
|
|
public Security Underlying
|
|
{
|
|
get; set;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets a reduced interface of the underlying security object.
|
|
/// </summary>
|
|
ISecurityPrice IOptionPrice.Underlying => Underlying;
|
|
|
|
/// <summary>
|
|
/// For this option security object, evaluates the specified option
|
|
/// contract to compute a theoretical price, IV and greeks
|
|
/// </summary>
|
|
/// <param name="slice">The current data slice. This can be used to access other information
|
|
/// available to the algorithm</param>
|
|
/// <param name="contract">The option contract to evaluate</param>
|
|
/// <returns>An instance of <see cref="OptionPriceModelResult"/> containing the theoretical
|
|
/// price of the specified option contract</returns>
|
|
public OptionPriceModelResult EvaluatePriceModel(Slice slice, OptionContract contract)
|
|
{
|
|
return PriceModel.Evaluate(this, slice, contract);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets or sets the price model for this option security
|
|
/// </summary>
|
|
public IOptionPriceModel PriceModel
|
|
{
|
|
get; set;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Fill model used to produce fill events for this security
|
|
/// </summary>
|
|
public IOptionExerciseModel OptionExerciseModel
|
|
{
|
|
get; set;
|
|
}
|
|
|
|
/// <summary>
|
|
/// When enabled, approximates Greeks if corresponding pricing model didn't calculate exact numbers
|
|
/// </summary>
|
|
[Obsolete("This property has been deprecated. Please use QLOptionPriceModel.EnableGreekApproximation instead.")]
|
|
public bool EnableGreekApproximation
|
|
{
|
|
get
|
|
{
|
|
var model = PriceModel as QLOptionPriceModel;
|
|
if (model != null)
|
|
{
|
|
return model.EnableGreekApproximation;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
set
|
|
{
|
|
var model = PriceModel as QLOptionPriceModel;
|
|
if (model != null)
|
|
{
|
|
model.EnableGreekApproximation = value;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets or sets the contract filter
|
|
/// </summary>
|
|
public IDerivativeSecurityFilter ContractFilter
|
|
{
|
|
get; set;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets the <see cref="ContractFilter"/> to a new instance of the filter
|
|
/// using the specified min and max strike values. Contracts with expirations further than 35
|
|
/// days out will also be filtered.
|
|
/// </summary>
|
|
/// <param name="minStrike">The min strike rank relative to market price, for example, -1 would put
|
|
/// a lower bound of one strike under market price, where a +1 would put a lower bound of one strike
|
|
/// over market price</param>
|
|
/// <param name="maxStrike">The max strike rank relative to market place, for example, -1 would put
|
|
/// an upper bound of on strike under market price, where a +1 would be an upper bound of one strike
|
|
/// over market price</param>
|
|
public void SetFilter(int minStrike, int maxStrike)
|
|
{
|
|
SetFilter(universe => universe.Strikes(minStrike, maxStrike));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets the <see cref="ContractFilter"/> to a new instance of the filter
|
|
/// using the specified min and max strike and expiration range values
|
|
/// </summary>
|
|
/// <param name="minExpiry">The minimum time until expiry to include, for example, TimeSpan.FromDays(10)
|
|
/// would exclude contracts expiring in more than 10 days</param>
|
|
/// <param name="maxExpiry">The maxmium time until expiry to include, for example, TimeSpan.FromDays(10)
|
|
/// would exclude contracts expiring in less than 10 days</param>
|
|
public void SetFilter(TimeSpan minExpiry, TimeSpan maxExpiry)
|
|
{
|
|
SetFilter(universe => universe.Expiration(minExpiry, maxExpiry));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets the <see cref="ContractFilter"/> to a new instance of the filter
|
|
/// using the specified min and max strike and expiration range values
|
|
/// </summary>
|
|
/// <param name="minStrike">The min strike rank relative to market price, for example, -1 would put
|
|
/// a lower bound of one strike under market price, where a +1 would put a lower bound of one strike
|
|
/// over market price</param>
|
|
/// <param name="maxStrike">The max strike rank relative to market place, for example, -1 would put
|
|
/// an upper bound of on strike under market price, where a +1 would be an upper bound of one strike
|
|
/// over market price</param>
|
|
/// <param name="minExpiry">The minimum time until expiry to include, for example, TimeSpan.FromDays(10)
|
|
/// would exclude contracts expiring in more than 10 days</param>
|
|
/// <param name="maxExpiry">The maxmium time until expiry to include, for example, TimeSpan.FromDays(10)
|
|
/// would exclude contracts expiring in less than 10 days</param>
|
|
public void SetFilter(int minStrike, int maxStrike, TimeSpan minExpiry, TimeSpan maxExpiry)
|
|
{
|
|
SetFilter(universe => universe
|
|
.Strikes(minStrike, maxStrike)
|
|
.Expiration(minExpiry, maxExpiry));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets the <see cref="ContractFilter"/> to a new instance of the filter
|
|
/// using the specified min and max strike and expiration range values
|
|
/// </summary>
|
|
/// <param name="minStrike">The min strike rank relative to market price, for example, -1 would put
|
|
/// a lower bound of one strike under market price, where a +1 would put a lower bound of one strike
|
|
/// over market price</param>
|
|
/// <param name="maxStrike">The max strike rank relative to market place, for example, -1 would put
|
|
/// an upper bound of on strike under market price, where a +1 would be an upper bound of one strike
|
|
/// over market price</param>
|
|
/// <param name="minExpiryDays">The minimum time, expressed in days, until expiry to include, for example, 10
|
|
/// would exclude contracts expiring in more than 10 days</param>
|
|
/// <param name="maxExpiryDays">The maximum time, expressed in days, until expiry to include, for example, 10
|
|
/// would exclude contracts expiring in less than 10 days</param>
|
|
public void SetFilter(int minStrike, int maxStrike, int minExpiryDays, int maxExpiryDays)
|
|
{
|
|
SetFilter(universe => universe
|
|
.Strikes(minStrike, maxStrike)
|
|
.Expiration(minExpiryDays, maxExpiryDays));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets the <see cref="ContractFilter"/> to a new universe selection function
|
|
/// </summary>
|
|
/// <param name="universeFunc">new universe selection function</param>
|
|
public void SetFilter(Func<OptionFilterUniverse, OptionFilterUniverse> universeFunc)
|
|
{
|
|
ContractFilter = new FuncSecurityDerivativeFilter(universe =>
|
|
{
|
|
var optionUniverse = universe as OptionFilterUniverse;
|
|
var result = universeFunc(optionUniverse);
|
|
return result.ApplyTypesFilter();
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets the <see cref="ContractFilter"/> to a new universe selection function
|
|
/// </summary>
|
|
/// <param name="universeFunc">new universe selection function</param>
|
|
public void SetFilter(PyObject universeFunc)
|
|
{
|
|
ContractFilter = new FuncSecurityDerivativeFilter(universe =>
|
|
{
|
|
var optionUniverse = universe as OptionFilterUniverse;
|
|
using (Py.GIL())
|
|
{
|
|
PyObject result = (universeFunc as dynamic)(optionUniverse);
|
|
|
|
//Try to convert it to the possible outcomes and process it
|
|
//Must try filter first, if it is a filter and you try and convert it to
|
|
//list, TryConvert() with catch an exception. Later Python algo will break on
|
|
//this exception because we are using Py.GIL() and it will see the error set
|
|
OptionFilterUniverse filter;
|
|
List<Symbol> list;
|
|
|
|
if ((result).TryConvert(out filter))
|
|
{
|
|
optionUniverse = filter;
|
|
}
|
|
else if ((result).TryConvert(out list))
|
|
{
|
|
optionUniverse = optionUniverse.WhereContains(list);
|
|
}
|
|
else
|
|
{
|
|
throw new ArgumentException($"QCAlgorithm.SetFilter: result type {result.GetPythonType()} from " +
|
|
$"filter function is not a valid argument, please return either a OptionFilterUniverse or a list of symbols");
|
|
}
|
|
}
|
|
return optionUniverse.ApplyTypesFilter();
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets the data normalization mode to be used by this security
|
|
/// </summary>
|
|
public override void SetDataNormalizationMode(DataNormalizationMode mode)
|
|
{
|
|
if (mode != DataNormalizationMode.Raw)
|
|
{
|
|
throw new ArgumentException("DataNormalizationMode.Raw must be used with options");
|
|
}
|
|
|
|
base.SetDataNormalizationMode(mode);
|
|
}
|
|
}
|
|
}
|