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
255 lines
12 KiB
C#
255 lines
12 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 System.Collections.Generic;
|
|
using System.Data;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using Fasterflect;
|
|
|
|
namespace QuantConnect.Securities
|
|
{
|
|
/// <summary>
|
|
/// Provides access to specific properties for various symbols
|
|
/// </summary>
|
|
public class SymbolPropertiesDatabase
|
|
{
|
|
private static SymbolPropertiesDatabase _dataFolderSymbolPropertiesDatabase;
|
|
private static readonly object DataFolderSymbolPropertiesDatabaseLock = new object();
|
|
|
|
private readonly IReadOnlyDictionary<SecurityDatabaseKey, SymbolProperties> _entries;
|
|
private readonly IReadOnlyDictionary<SecurityDatabaseKey, SecurityDatabaseKey> _keyBySecurityType;
|
|
|
|
private SymbolPropertiesDatabase(string file)
|
|
{
|
|
var allEntries = new Dictionary<SecurityDatabaseKey, SymbolProperties>();
|
|
var entriesBySecurityType = new Dictionary<SecurityDatabaseKey, SecurityDatabaseKey>();
|
|
|
|
foreach (var keyValuePair in FromCsvFile(file))
|
|
{
|
|
if (allEntries.ContainsKey(keyValuePair.Key))
|
|
{
|
|
throw new DuplicateNameException($"Encountered duplicate key while processing file: {file}. Key: {keyValuePair.Key}");
|
|
}
|
|
// we wildcard the market, so per security type and symbol we will keep the *first* instance
|
|
// this allows us to fetch deterministically, in O(1), an entry without knowing the market, see 'TryGetMarket()'
|
|
var key = new SecurityDatabaseKey(SecurityDatabaseKey.Wildcard, keyValuePair.Key.Symbol, keyValuePair.Key.SecurityType);
|
|
if (!entriesBySecurityType.ContainsKey(key))
|
|
{
|
|
entriesBySecurityType[key] = keyValuePair.Key;
|
|
}
|
|
allEntries[keyValuePair.Key] = keyValuePair.Value;
|
|
}
|
|
|
|
_entries = allEntries;
|
|
_keyBySecurityType = entriesBySecurityType;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Check whether symbol properties exists for the specified market/symbol/security-type
|
|
/// </summary>
|
|
/// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
|
|
/// <param name="symbol">The particular symbol being traded</param>
|
|
/// <param name="securityType">The security type of the symbol</param>
|
|
public bool ContainsKey(string market, string symbol, SecurityType securityType)
|
|
{
|
|
var key = new SecurityDatabaseKey(market, symbol, securityType);
|
|
return _entries.ContainsKey(key);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Check whether symbol properties exists for the specified market/symbol/security-type
|
|
/// </summary>
|
|
/// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
|
|
/// <param name="symbol">The particular symbol being traded (Symbol class)</param>
|
|
/// <param name="securityType">The security type of the symbol</param>
|
|
public bool ContainsKey(string market, Symbol symbol, SecurityType securityType)
|
|
{
|
|
return ContainsKey(
|
|
market,
|
|
MarketHoursDatabase.GetDatabaseSymbolKey(symbol),
|
|
securityType);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Tries to get the market for the provided symbol/security type
|
|
/// </summary>
|
|
/// <param name="symbol">The particular symbol being traded</param>
|
|
/// <param name="securityType">The security type of the symbol</param>
|
|
/// <param name="market">The market the exchange resides in <see cref="Market"/></param>
|
|
/// <returns>True if market was retrieved, false otherwise</returns>
|
|
public bool TryGetMarket(string symbol, SecurityType securityType, out string market)
|
|
{
|
|
SecurityDatabaseKey result;
|
|
var key = new SecurityDatabaseKey(SecurityDatabaseKey.Wildcard, symbol, securityType);
|
|
if (_keyBySecurityType.TryGetValue(key, out result))
|
|
{
|
|
market = result.Market;
|
|
return true;
|
|
}
|
|
|
|
market = null;
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the symbol properties for the specified market/symbol/security-type
|
|
/// </summary>
|
|
/// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
|
|
/// <param name="symbol">The particular symbol being traded (Symbol class)</param>
|
|
/// <param name="securityType">The security type of the symbol</param>
|
|
/// <param name="defaultQuoteCurrency">Specifies the quote currency to be used when returning a default instance of an entry is not found in the database</param>
|
|
/// <returns>The symbol properties matching the specified market/symbol/security-type or null if not found</returns>
|
|
/// <remarks>For any derivative options asset that is not for equities, we default to the underlying symbol's properties if no entry is found in the database</remarks>
|
|
public SymbolProperties GetSymbolProperties(string market, Symbol symbol, SecurityType securityType, string defaultQuoteCurrency)
|
|
{
|
|
SymbolProperties symbolProperties;
|
|
var lookupTicker = MarketHoursDatabase.GetDatabaseSymbolKey(symbol);
|
|
var key = new SecurityDatabaseKey(market, lookupTicker, securityType);
|
|
|
|
if (!_entries.TryGetValue(key, out symbolProperties))
|
|
{
|
|
if (symbol != null && symbol.SecurityType == SecurityType.FutureOption)
|
|
{
|
|
// Default to looking up the underlying symbol's properties and using those instead if there's
|
|
// no existing entry for the future option.
|
|
lookupTicker = MarketHoursDatabase.GetDatabaseSymbolKey(symbol.Underlying);
|
|
key = new SecurityDatabaseKey(market, lookupTicker, symbol.Underlying.SecurityType);
|
|
|
|
if (_entries.TryGetValue(key, out symbolProperties))
|
|
{
|
|
return symbolProperties;
|
|
}
|
|
}
|
|
|
|
// now check with null symbol key
|
|
if (!_entries.TryGetValue(new SecurityDatabaseKey(market, null, securityType), out symbolProperties))
|
|
{
|
|
// no properties found, return object with default property values
|
|
return SymbolProperties.GetDefault(defaultQuoteCurrency);
|
|
}
|
|
}
|
|
|
|
return symbolProperties;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets a list of symbol properties for the specified market/security-type
|
|
/// </summary>
|
|
/// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
|
|
/// <param name="securityType">The security type of the symbol</param>
|
|
/// <returns>An IEnumerable of symbol properties matching the specified market/security-type</returns>
|
|
public IEnumerable<KeyValuePair<SecurityDatabaseKey, SymbolProperties>> GetSymbolPropertiesList(string market, SecurityType securityType)
|
|
{
|
|
foreach (var entry in _entries)
|
|
{
|
|
var key = entry.Key;
|
|
var symbolProperties = entry.Value;
|
|
|
|
if (key.Market == market && key.SecurityType == securityType)
|
|
{
|
|
yield return new KeyValuePair<SecurityDatabaseKey, SymbolProperties>(key, symbolProperties);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets a list of symbol properties for the specified market
|
|
/// </summary>
|
|
/// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
|
|
/// <returns>An IEnumerable of symbol properties matching the specified market</returns>
|
|
public IEnumerable<KeyValuePair<SecurityDatabaseKey, SymbolProperties>> GetSymbolPropertiesList(string market)
|
|
{
|
|
foreach (var entry in _entries)
|
|
{
|
|
var key = entry.Key;
|
|
var symbolProperties = entry.Value;
|
|
|
|
if (key.Market == market)
|
|
{
|
|
yield return new KeyValuePair<SecurityDatabaseKey, SymbolProperties>(key, symbolProperties);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the instance of the <see cref="SymbolPropertiesDatabase"/> class produced by reading in the symbol properties
|
|
/// data found in /Data/symbol-properties/
|
|
/// </summary>
|
|
/// <returns>A <see cref="SymbolPropertiesDatabase"/> class that represents the data in the symbol-properties folder</returns>
|
|
public static SymbolPropertiesDatabase FromDataFolder()
|
|
{
|
|
lock (DataFolderSymbolPropertiesDatabaseLock)
|
|
{
|
|
if (_dataFolderSymbolPropertiesDatabase == null)
|
|
{
|
|
var directory = Path.Combine(Globals.DataFolder, "symbol-properties");
|
|
_dataFolderSymbolPropertiesDatabase = new SymbolPropertiesDatabase(Path.Combine(directory, "symbol-properties-database.csv"));
|
|
}
|
|
}
|
|
return _dataFolderSymbolPropertiesDatabase;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a new instance of the <see cref="SymbolPropertiesDatabase"/> class by reading the specified csv file
|
|
/// </summary>
|
|
/// <param name="file">The csv file to be read</param>
|
|
/// <returns>A new instance of the <see cref="SymbolPropertiesDatabase"/> class representing the data in the specified file</returns>
|
|
private static IEnumerable<KeyValuePair<SecurityDatabaseKey, SymbolProperties>> FromCsvFile(string file)
|
|
{
|
|
if (!File.Exists(file))
|
|
{
|
|
throw new FileNotFoundException("Unable to locate symbol properties file: " + file);
|
|
}
|
|
|
|
// skip the first header line, also skip #'s as these are comment lines
|
|
foreach (var line in File.ReadLines(file).Where(x => !x.StartsWith("#") && !string.IsNullOrWhiteSpace(x)).Skip(1))
|
|
{
|
|
SecurityDatabaseKey key;
|
|
var entry = FromCsvLine(line, out key);
|
|
|
|
yield return new KeyValuePair<SecurityDatabaseKey, SymbolProperties>(key, entry);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a new instance of <see cref="SymbolProperties"/> from the specified csv line
|
|
/// </summary>
|
|
/// <param name="line">The csv line to be parsed</param>
|
|
/// <param name="key">The key used to uniquely identify this security</param>
|
|
/// <returns>A new <see cref="SymbolProperties"/> for the specified csv line</returns>
|
|
private static SymbolProperties FromCsvLine(string line, out SecurityDatabaseKey key)
|
|
{
|
|
var csv = line.Split(',');
|
|
|
|
key = new SecurityDatabaseKey(
|
|
market: csv[0],
|
|
symbol: csv[1],
|
|
securityType: (SecurityType)Enum.Parse(typeof(SecurityType), csv[2], true));
|
|
|
|
return new SymbolProperties(
|
|
description: csv[3],
|
|
quoteCurrency: csv[4],
|
|
contractMultiplier: csv[5].ToDecimal(),
|
|
minimumPriceVariation: csv[6].ToDecimalAllowExponent(),
|
|
lotSize: csv[7].ToDecimal(),
|
|
marketTicker: csv.Length > 8 ? csv[8] : string.Empty);
|
|
}
|
|
|
|
|
|
}
|
|
}
|