Commit Graph

85 Commits

Author SHA1 Message Date
Gerardo Salazar eb1181f5f7 Adds Futures Options Asset Class w/ IB Support (#4928)
* 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
2020-12-02 21:49:59 -03:00
Gerardo Salazar 0f0a2bc9a8 Fixes weeklies parsing, causing certain futures to be inaccessible in QCAlgorithm (#4936)
* Fixes weeklies parsing, causing certain futures to be inaccessible in Algorithm

  The FuturesExpiryFunction expects the contract month of the Future,
  not the expiration. As a result, the contract gets filtered as a
  weekly contract, rather than as a standard due to the discrepancy
  between the expiry dates when the contract month differs from the
  expiry date's month.

  A very important fact to note is that futures can and do expire prior
  to the contract month. BZ,(brent crude financial futures) expire two
  months prior to the contract month, CL one month prior, etc.

  There has been an addition that contains a "reverse" futures expiry function
  lookup table. We use this to lookup the contract month to re-calculate
  the Future expiry.

  This PR also fixes dairy and adds extra expiry dates. Dairy can have
  an expiry *after* the contract month, so a new path was added to the
  SymbolRepresentation to ensure that these contracts are loaded
  correctly.

* Address review: Adds tests and fixes bug in SymbolRepresentation

  * Updates SID comment on `Date` property to reflect fact that we use
    future expiry for its value

  * Fixes bug in SymbolRepresentation where expiration day would always
    be 01 when parsing a contract with an expiration after the contract
    month

  * Fixes bug in SybmolRepresentation where expiration year would be
    four digits long when parsing a contract with an expiration after
    the contract month

  * Fixes some bad dairy expiry dates

  * Adds tests for SymbolRepresentation and the futures filtering for
    standard contracts

  * Renames method used to extract delta between contract month and
    expiry date

* Removes GH comment and restores Futures contract month expiry param
2020-11-20 11:58:49 -03:00
Martin Molinero cd2ef13d38 Update FuturesExpiryFunctions
- Update FuturesExpiryFunctions to be keyed by symbol. Updating unit
  tests
2020-04-28 16:29:14 -03:00
Martin Molinero 499248fe12 Revert "Revert "Adding Support for Equity L1 Quote Data""
This reverts commit 8cd8d206ca.
2020-04-06 10:32:59 -03:00
Jared 8cd8d206ca Revert "Adding Support for Equity L1 Quote Data" 2020-03-11 19:16:05 -07:00
Juan José D'Ambrosio fd9de5895a Consolidate only trades, low resolution reads trades only, update tests
Crypto and Equities will consolidate trades by default

Daily and hourly resolution will return only trades for crypto and equities. 
Update equity TAQ regression test 

Add minute sample files

Updating regression algorithms

Update SpotMarket test cases

Add regression test for equity trades and quotes
- History request.
- Trades and quotes pumped into OnData.
- Subscriptions are added correctly.

Add sample data

Checks low resolution only subscribes to trade bars
2020-03-11 14:34:05 -03:00
Juan José D'Ambrosio 228aad658b Process Equity quotes
This is just a draft for supporting Equity quotes in Lean
2020-03-11 14:34:05 -03:00
Adam May 5d2378b826 Fixes for expiries which occur more than a month prior to the contract month 2020-01-22 18:22:16 +11:00
Martin Molinero 5b85d1edbf Address review
- Add `alternative` LeanData unit tests
- Fix implementation so new unit tests pass
2019-10-08 16:00:08 -03:00
Martin Molinero a063eb2a5f Match alternative to SecurityType.Base
- 'alternative' is used in Lean data paths and should be matched to
SecurityType.Base
- Adding unit tests
2019-10-08 11:51:22 -03:00
Michael Handschuh d709d1c4e0 Update Common to respect CA1304 and CA1305
Updates all occurrences of parsing/ToString-ing to go through the new
StringExtensions methods that use CultureInfo.InvariantCulture

See #3045
2019-09-12 14:13:24 -04:00
Michael Handschuh 3e93158713 Use proper exception types
The `NullReferenceException` type is intended to only be thrown by the CLR.
In most cases, it should be converted to an `ArgumentException` or an
`InvalidOperationException`, depending on if the null value is a parameter
to the current method or not.

The `Exception` type should never really be thrown as it doesn't provide any
additional information or hints as to the issue. It also forces users that
would like to handle expected exceptions to catch all exceptions. These are
converted to an exception type that more accurately describes the reason for
raising the exception: `KeyNotFoundException`, `InvalidOperationException`
2019-08-16 18:07:30 -03:00
Juan José D'Ambrosio c274ca92a3 Fix bug in quotes lines generation 2019-07-31 19:45:50 +00:00
Juan José D'Ambrosio bb295d5ceb Equity trades and quotes processing support 2019-07-30 21:29:34 +00:00
Stefano Raggi f7e06510d4 Fix missing front month contract in energy futures backtesting
Energy futures (CL, HO, RB, NG) expire in the month before the contract month.

To handle these properly, the following changes have been implemented:
- the AlgoSeekFuturesReader has been updated to create the future symbol with the correct expiry date
- the zip entry names in futures data files now contain the full expiry date (in addition to the contract month)
- the sample data files have been updated to use the new zip entry names
- new unit tests have been added and existing ones updated
2019-04-29 09:40:59 +02:00
Martin Molinero c39638668c Overall performance improvements
- `FactorFile` will keep an ordered reversed list with the dates.
Calling `Reverse()` on the `SortedList` is expensive.
- `MapFiles` will keep first and last date, so we don't need to call
`First()` and `Last()` multiple times.
- `Liquidate` will go through all the algorithms securities only if
necessary
- `TradeBar` parsing will not call `new T` for pure `TradeBar` which is
expensive
- Removing `Lazy` hash code and security type for the
`SecurityIdentifier`, replacing for direct initialization. Accessing the
`Lazy` value adds an overhead.
- Replacing `Enum` to string for hardcoded switch statement. `Enum.ToString` is expensive.
- `DataManager` will be lazy for counting the subscriptions for
determining if its above the limit
- Adding `AlgorithmSecurityValuesProvider.GetAllValues()`, removes the
need to fetch all the security keys twice.
- During universe selection, will not try to re add already added symbol
2019-04-22 10:47:27 -03:00
Jared d367dbd025 Revert; unit test coverage.
Annoying spin off affects. Won't update now but flag for later standardization.
2019-01-14 19:44:49 -08:00
Jared 5e8d43df1a Sanity check for consistency with new method
Missing toLower
2019-01-14 16:03:27 -08:00
Gerardo Salazar c9d5764a4b Fix issue #2826 in which we were unable to write to write Futures or Options data to disk 2019-01-14 11:24:26 -08:00
Juan José D'Ambrosio 4ace8cb255 Lean Visualizer C# toolbox project and Python Wrapper working 2018-04-27 11:49:52 -03:00
AlexCatarino 6bbdbcb8fe Fixes LeanData.cs hard-coded Market.USA
It prevents support for new markets.
2018-01-19 18:09:52 +00:00
Andrew 18e2857e78 Don't include tick type in the filename
Update LeanDataTests to reflect correct crypto hour/daily filenames
2017-11-10 16:27:00 -05:00
Andrew 02278ef519 Add btcusd daily data in updated format
Now lean expects both trades and quotes as seperate files. This commit adds the data in the updated format
2017-10-27 16:22:28 -04:00
Andrew 076bb1627c Added KaikoDataConverter Toolbox project
This project can take trade as well as orderbook information from Kaiko
and convert the data into Lean compatible data at all resolutions in
modeled as both trades and quotes.
2017-10-27 15:50:47 -04:00
Andrew 9d90ff1cb1 Hourly and daily crypto files need their tick type specified in their zip archive filename 2017-10-26 15:13:48 -04:00
Andrew 8264cc4a9f LeanDataTests passing for crypto securities
The Crypto security can be modeled with both trades and quotes easily, therefore it is necessary to make sure that the LeanData, LeanDataWriter and associated BaseData.Reader() methods can read/write both Trades and Quotes.
2017-10-25 16:52:31 -04:00
Andrew 406eef196b Specify crypto only switch statement in LeanData.GenerateLine
Because cryptocurrencies can be either Trades or Quotes, the Crypto security type needs it's own switch statement in LeanData.GenerateLine. This produces non-scaled TradeBars or QuoteBarrs.
2017-10-25 16:50:48 -04:00
Jared 72b66501eb Merge pull request #1131 from QuantConnect/crypto-security
Crypto security
2017-09-14 10:48:31 -04:00
Jared Broad e8b117ad2a Throw meaningful exceptions when type incorrect 2017-08-31 17:19:36 -04:00
jameschch@outlook.com 578efe843f Further changes for crypto type 2017-08-29 12:19:15 +01:00
12112 3c4715ef99 Fixes bad merge 2017-08-29 10:52:56 +01:00
12112 921ec8f983 merge from upstream 2017-08-22 16:56:35 +01:00
12112 83fdf9c386 crypto wip 2017-07-14 16:53:42 +01:00
Andrew 35cdd07897 Update zip entry path of equity Tick files 2017-07-10 11:55:54 -04:00
smartquant 74a0163b73 Fix for OpenInterest daily/hourly file format in LeandData.GenerateLine to be yyyyMMdd HH:mm 2017-06-19 19:30:29 +02:00
smartquant fb2cf7deaf Fix for using daily or hourly resolution market data for futures.
- Open interest should use yyyyMMdd HH:mm in csv file when frequency is daily or hourly
- Filename should be [baseticker]_[quote|openinterest|trade]_yyyyMM.csv
2017-06-19 11:15:12 +02:00
Andrew 48da7a217f Removed boolean from LeanData writing futures files 2017-05-09 10:53:34 -04:00
Andrew 9fcf90fe60 Remove optional boolean in LeanData.ToCsv() 2017-05-08 13:18:54 -04:00
Andrew 33793ce1c4 Expiry calculated when futures symbol is created 2017-04-28 16:52:04 -04:00
Andrew cd4cd041d5 Futures data has no scaling applied when data is generated 2017-04-25 16:17:21 -04:00
Andrew 00fce19c80 Options and futures have seperate cases in LeanData.GenerateLine 2017-04-25 16:17:21 -04:00
Stefano Raggi e1710e9031 Remove BaseData underlying symbol from Future symbol 2017-04-17 13:52:23 +02:00
Andrew 5cedbeae3f Leveraging existing extension method to remove trailing 0s 2017-04-05 12:49:28 -04:00
Andrew ae188c58c5 Trim all trailing 0s when generating Lean formatted lines
Remove all trailing 0s in LeanData.GenerateLine(). This creates smaller data files and prevents large numbers of trailing zeros on data points.  This change will apply to all data written with LeanData.GenerateLine.
2017-04-05 11:41:48 -04:00
Stefano Raggi 44d9008cd0 Merge branch 'master' into OptionsBacktesting-UseQuote 2017-03-31 22:50:05 +02:00
Andrew bf82fdb4f7 Return Quotebars for FX and CFD line generation 2017-03-27 11:57:04 -04:00
Andrew d0d5385618 LeanData uses QuoteBars to generate Cfd and Forex lines 2017-03-24 16:59:24 -04:00
Ray Bohac 1dd2d6d351 Use TickType.Quote instead of TickType.Trade 2017-03-24 07:46:20 -04:00
Andrew eb9d78470c LeanData.TryParsePath now returns a symbol
Instead of returning a heavier Security object, LeanData.TryParsePath will return a symbol, datetime and resolution.
2017-03-09 14:44:17 -05:00
Andrew 8e3a0715fc Added LeanData.TryParsePath() and associated tests
This method takes a path and will return a Security and DateTime.  This is useful in the ApiDataProvider that uses the api to retrieve files that are not present on disc.  The IDataProvider only ha a path to the file.  Using this method, the ApiDataProvider can extract the useful information from the path to communicate with the api.
2017-03-09 11:34:36 -05:00