-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Trade mapped contract for canonical Future order requests #9467
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
AlexCatarino
wants to merge
3
commits into
QuantConnect:master
from
AlexCatarino:bug-9463-trade-mapped-on-canonical-future
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
199 changes: 199 additions & 0 deletions
199
Algorithm.CSharp/SetHoldingsContinuousFutureRegressionAlgorithm.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,199 @@ | ||
| /* | ||
| * 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.Interfaces; | ||
| using QuantConnect.Orders; | ||
| using QuantConnect.Securities.Future; | ||
| using System.Collections.Generic; | ||
| using Futures = QuantConnect.Securities.Futures; | ||
|
|
||
| namespace QuantConnect.Algorithm.CSharp | ||
| { | ||
| /// <summary> | ||
| /// End-to-end regression algorithm asserting that calling <see cref="QCAlgorithm.SetHoldings(Symbol, decimal, bool, string, IOrderProperties)"/> | ||
| /// directly with the canonical (continuous) Future Symbol routes the order to the currently mapped contract, | ||
| /// sizes the order using the mapped contract's price, and lets portfolio queries on the continuous symbol | ||
| /// reflect the active position both before and after a contract roll. | ||
| /// </summary> | ||
| public class SetHoldingsContinuousFutureRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition | ||
| { | ||
| private Future _continuousContract; | ||
| private Symbol _filledContract; | ||
| private DateTime _liquidateAfter; | ||
| private bool _liquidated; | ||
|
|
||
| public override void Initialize() | ||
| { | ||
| SetStartDate(2013, 7, 1); | ||
| SetEndDate(2014, 1, 1); | ||
|
|
||
| _continuousContract = AddFuture(Futures.Indices.SP500EMini, | ||
| dataNormalizationMode: DataNormalizationMode.BackwardsRatio, | ||
| dataMappingMode: DataMappingMode.LastTradingDay, | ||
| contractDepthOffset: 0, | ||
| extendedMarketHours: true); | ||
| // A wide filter exercises the case where many future contracts are already in the chain universe across rolls | ||
| _continuousContract.SetFilter(0, 90); | ||
| } | ||
|
|
||
| public override void OnData(Slice slice) | ||
| { | ||
| // The continuous Future is not tradable until a contract is mapped to it | ||
| if (_liquidated || !_continuousContract.IsTradable) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| // Reading Invested off the canonical's Holdings relies on the universe linking it to the mapped contract | ||
| var invested = _continuousContract.Holdings.Invested; | ||
|
|
||
| if (!invested) | ||
| { | ||
| // Pass the canonical Symbol — the engine should route the order to the mapped contract | ||
| SetHoldings(_continuousContract.Symbol, 0.5m); | ||
| _liquidateAfter = Time.AddDays(30); | ||
| } | ||
| else if (Time >= _liquidateAfter) | ||
| { | ||
| // Set the flag before Liquidate so OnOrderEvent (called synchronously on fill) sees the post-liquidation state | ||
| _liquidated = true; | ||
| Liquidate(_continuousContract.Symbol); | ||
| } | ||
| } | ||
|
|
||
| public override void OnOrderEvent(OrderEvent orderEvent) | ||
| { | ||
| if (orderEvent.Status != OrderStatus.Filled) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| // The order must have been placed against the currently mapped contract, never the canonical | ||
| if (orderEvent.Symbol.IsCanonical()) | ||
| { | ||
| throw new RegressionTestException($"Order filled against canonical symbol {orderEvent.Symbol}; expected the mapped contract"); | ||
| } | ||
|
|
||
| if (!_liquidated) | ||
| { | ||
| _filledContract = orderEvent.Symbol; | ||
|
|
||
| // After the fill, querying the canonical should reflect the active position from the mapped contract | ||
| if (!Portfolio[_continuousContract.Symbol].Invested) | ||
| { | ||
| throw new RegressionTestException($"Portfolio[{_continuousContract.Symbol}].Invested is false after fill on {orderEvent.Symbol}"); | ||
| } | ||
| if (Portfolio[_continuousContract.Symbol].Quantity != Portfolio[orderEvent.Symbol].Quantity) | ||
| { | ||
| throw new RegressionTestException( | ||
| $"Continuous holdings quantity {Portfolio[_continuousContract.Symbol].Quantity} does not match mapped contract " + | ||
| $"{orderEvent.Symbol} quantity {Portfolio[orderEvent.Symbol].Quantity}"); | ||
| } | ||
| } | ||
| else | ||
| { | ||
| // After liquidation via the canonical symbol, both the canonical view and the mapped contract should be flat | ||
| if (Portfolio[_continuousContract.Symbol].Invested) | ||
| { | ||
| throw new RegressionTestException($"Portfolio[{_continuousContract.Symbol}].Invested is true after liquidating via the canonical symbol"); | ||
| } | ||
| if (Portfolio[orderEvent.Symbol].Invested) | ||
| { | ||
| throw new RegressionTestException($"Portfolio[{orderEvent.Symbol}].Invested is true after liquidation"); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public override void OnEndOfAlgorithm() | ||
| { | ||
| if (_filledContract == null) | ||
| { | ||
| throw new RegressionTestException("Expected at least one filled order during the backtest"); | ||
| } | ||
|
|
||
| if (!_liquidated) | ||
| { | ||
| throw new RegressionTestException("Expected the canonical position to have been liquidated before end of algorithm"); | ||
| } | ||
|
|
||
| if (Portfolio[_continuousContract.Symbol].Invested) | ||
| { | ||
| throw new RegressionTestException($"Portfolio[{_continuousContract.Symbol}].Invested is true at end of algorithm; expected flat after Liquidate"); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. | ||
| /// </summary> | ||
| public bool CanRunLocally { get; } = true; | ||
|
|
||
| /// <summary> | ||
| /// This is used by the regression test system to indicate which languages this algorithm is written in. | ||
| /// </summary> | ||
| public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python }; | ||
|
|
||
| /// <summary> | ||
| /// Data Points count of all timeslices of algorithm | ||
| /// </summary> | ||
| public long DataPoints => 727503; | ||
|
|
||
| /// <summary> | ||
| /// Data Points count of the algorithm history | ||
| /// </summary> | ||
| public int AlgorithmHistoryDataPoints => 0; | ||
|
|
||
| /// <summary> | ||
| /// Final status of the algorithm | ||
| /// </summary> | ||
| public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed; | ||
|
|
||
| /// <summary> | ||
| /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm | ||
| /// </summary> | ||
| public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> | ||
| { | ||
| {"Total Orders", "2"}, | ||
| {"Average Win", "16.59%"}, | ||
| {"Average Loss", "0%"}, | ||
| {"Compounding Annual Return", "35.584%"}, | ||
| {"Drawdown", "28.400%"}, | ||
| {"Expectancy", "0"}, | ||
| {"Start Equity", "100000"}, | ||
| {"End Equity", "116590.2"}, | ||
| {"Net Profit", "16.590%"}, | ||
| {"Sharpe Ratio", "1.068"}, | ||
| {"Sortino Ratio", "0.503"}, | ||
| {"Probabilistic Sharpe Ratio", "48.712%"}, | ||
| {"Loss Rate", "0%"}, | ||
| {"Win Rate", "100%"}, | ||
| {"Profit-Loss Ratio", "0"}, | ||
| {"Alpha", "0.024"}, | ||
| {"Beta", "1.096"}, | ||
| {"Annual Standard Deviation", "0.245"}, | ||
| {"Annual Variance", "0.06"}, | ||
| {"Information Ratio", "0.194"}, | ||
| {"Tracking Error", "0.229"}, | ||
| {"Treynor Ratio", "0.239"}, | ||
| {"Total Fees", "$47.30"}, | ||
| {"Estimated Strategy Capacity", "$160000000.00"}, | ||
| {"Lowest Capacity Asset", "ES VMKLFZIH2MTD"}, | ||
| {"Portfolio Turnover", "10.22%"}, | ||
| {"Drawdown Recovery", "2"}, | ||
| {"OrderListHash", "8c87879bcbeb3b139dc112bb0e4f199e"} | ||
| }; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
88 changes: 88 additions & 0 deletions
88
Algorithm.Python/SetHoldingsContinuousFutureRegressionAlgorithm.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. | ||
| # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from AlgorithmImports import * | ||
|
|
||
| ### <summary> | ||
| ### End-to-end regression algorithm asserting that calling set_holdings directly with the canonical (continuous) Future | ||
| ### Symbol routes the order to the currently mapped contract, sizes the order using the mapped contract's price, and lets | ||
| ### portfolio queries on the continuous symbol reflect the active position both before and after a contract roll. | ||
| ### </summary> | ||
| class SetHoldingsContinuousFutureRegressionAlgorithm(QCAlgorithm): | ||
|
|
||
| def initialize(self): | ||
| self.set_start_date(2013, 7, 1) | ||
| self.set_end_date(2014, 1, 1) | ||
|
|
||
| self._continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI, | ||
| data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO, | ||
| data_mapping_mode = DataMappingMode.LAST_TRADING_DAY, | ||
| contract_depth_offset = 0, | ||
| extended_market_hours = True) | ||
| # A wide filter exercises the case where many future contracts are already in the chain universe across rolls | ||
| self._continuous_contract.set_filter(0, 90) | ||
| self._filled_contract = None | ||
| self._liquidate_after = None | ||
| self._liquidated = False | ||
|
|
||
| def on_data(self, slice): | ||
| # The continuous Future is not tradable until a contract is mapped to it | ||
| if self._liquidated or not self._continuous_contract.is_tradable: | ||
| return | ||
|
|
||
| # Reading invested off the canonical's Holdings relies on the universe linking it to the mapped contract | ||
| invested = self._continuous_contract.holdings.invested | ||
|
|
||
| if not invested: | ||
| # Pass the canonical Symbol — the engine should route the order to the mapped contract | ||
| self.set_holdings(self._continuous_contract.symbol, 0.5) | ||
| self._liquidate_after = self.time + timedelta(days=30) | ||
| elif self.time >= self._liquidate_after: | ||
| # Set the flag before liquidate so on_order_event (called synchronously on fill) sees the post-liquidation state | ||
| self._liquidated = True | ||
| self.liquidate(self._continuous_contract.symbol) | ||
|
|
||
| def on_order_event(self, order_event): | ||
| if order_event.status != OrderStatus.FILLED: | ||
| return | ||
|
|
||
| # The order must have been placed against the currently mapped contract, never the canonical | ||
| if order_event.symbol.is_canonical(): | ||
| raise AssertionError(f"Order filled against canonical symbol {order_event.symbol}; expected the mapped contract") | ||
|
|
||
| if not self._liquidated: | ||
| self._filled_contract = order_event.symbol | ||
|
|
||
| # After the fill, querying the canonical should reflect the active position from the mapped contract | ||
| if not self.portfolio[self._continuous_contract.symbol].invested: | ||
| raise AssertionError(f"Portfolio[{self._continuous_contract.symbol}].invested is false after fill on {order_event.symbol}") | ||
| if self.portfolio[self._continuous_contract.symbol].quantity != self.portfolio[order_event.symbol].quantity: | ||
| raise AssertionError( | ||
| f"Continuous holdings quantity {self.portfolio[self._continuous_contract.symbol].quantity} does not match mapped contract " | ||
| f"{order_event.symbol} quantity {self.portfolio[order_event.symbol].quantity}") | ||
| else: | ||
| # After liquidation via the canonical symbol, both the canonical view and the mapped contract should be flat | ||
| if self.portfolio[self._continuous_contract.symbol].invested: | ||
| raise AssertionError(f"Portfolio[{self._continuous_contract.symbol}].invested is true after liquidating via the canonical symbol") | ||
| if self.portfolio[order_event.symbol].invested: | ||
| raise AssertionError(f"Portfolio[{order_event.symbol}].invested is true after liquidation") | ||
|
|
||
| def on_end_of_algorithm(self): | ||
| if self._filled_contract is None: | ||
| raise AssertionError("Expected at least one filled order during the backtest") | ||
|
|
||
| if not self._liquidated: | ||
| raise AssertionError("Expected the canonical position to have been liquidated before end of algorithm") | ||
|
|
||
| if self.portfolio[self._continuous_contract.symbol].invested: | ||
| raise AssertionError(f"Portfolio[{self._continuous_contract.symbol}].invested is true at end of algorithm; expected flat after Liquidate") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
❤️ Nice keeps it simple.