Skip to content

Commit 9573eea

Browse files
authored
Use universe settings when adding derivatives (#9309)
* Use universe settings when adding derivatives Use resolution, fill forward and extended market hours settings from universe settings when adding derivative securities (options, index options, futures and future options) * Minor python syntax check fix * Minor change * Default resolution from universe settings for common lean types securities * Minor test fix * Cleanup
1 parent ffe31b8 commit 9573eea

12 files changed

Lines changed: 352 additions & 54 deletions

Algorithm.CSharp/AuxiliaryDataHandlersRegressionAlgorithm.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ public override void OnEndOfAlgorithm()
119119
/// <summary>
120120
/// Data Points count of all timeslices of algorithm
121121
/// </summary>
122-
public long DataPoints => 126222;
122+
public long DataPoints => 17270;
123123

124124
/// <summary>
125125
/// Data Points count of the algorithm history
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
/*
2+
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3+
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*
15+
*/
16+
17+
using System.Collections.Generic;
18+
using System.Linq;
19+
using QuantConnect.Data;
20+
using QuantConnect.Interfaces;
21+
using QuantConnect.Data.UniverseSelection;
22+
using QuantConnect.Securities;
23+
using System;
24+
25+
namespace QuantConnect.Algorithm.CSharp
26+
{
27+
/// <summary>
28+
/// Regression algorithm asserting that options from universe are added with the same resolution, fill forward and extended market hours settings as the universe settings.
29+
/// </summary>
30+
public class EquityOptionsUniverseSettingsRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
31+
{
32+
private SecurityType[] _securityTypes;
33+
private HashSet<SecurityType> _checkedSecurityTypes = new();
34+
35+
protected virtual DateTime TestStartDate => new DateTime(2015, 12, 24);
36+
37+
public override void Initialize()
38+
{
39+
SetStartDate(TestStartDate);
40+
SetEndDate(TestStartDate.AddDays(1));
41+
SetCash(100000);
42+
43+
UniverseSettings.Resolution = Resolution.Daily;
44+
UniverseSettings.FillForward = false;
45+
UniverseSettings.ExtendedMarketHours = true;
46+
47+
_securityTypes = AddSecurity();
48+
}
49+
50+
protected virtual SecurityType[] AddSecurity()
51+
{
52+
var equity = AddEquity("GOOG");
53+
var option = AddOption(equity.Symbol);
54+
option.SetFilter(u => u.StandardsOnly().Strikes(-2, +2).Expiration(0, 180));
55+
56+
return [option.Symbol.SecurityType];
57+
}
58+
59+
public override void OnSecuritiesChanged(SecurityChanges changes)
60+
{
61+
var securities = changes.AddedSecurities.Where(x => _securityTypes.Contains(x.Type) && !x.Symbol.IsCanonical()).Select(x => x.Symbol).ToList();
62+
var configs = SubscriptionManager.Subscriptions.Where(x => securities.Contains(x.Symbol));
63+
64+
foreach (var config in configs)
65+
{
66+
if (config.Resolution != UniverseSettings.Resolution)
67+
{
68+
throw new RegressionTestException($"Config '{config}' resolution {config.Resolution} does not match universe settings resolution {UniverseSettings.Resolution}");
69+
}
70+
71+
if (config.FillDataForward != UniverseSettings.FillForward)
72+
{
73+
throw new RegressionTestException($"Config '{config}' fill forward {config.FillDataForward} does not match universe settings fill forward {UniverseSettings.FillForward}");
74+
}
75+
76+
if (config.ExtendedMarketHours != UniverseSettings.ExtendedMarketHours)
77+
{
78+
throw new RegressionTestException($"Config '{config}' extended market hours {config.ExtendedMarketHours} does not match universe settings extended market hours {UniverseSettings.ExtendedMarketHours}");
79+
}
80+
81+
_checkedSecurityTypes.Add(config.SecurityType);
82+
}
83+
}
84+
85+
public override void OnEndOfAlgorithm()
86+
{
87+
if (_checkedSecurityTypes.Count != _securityTypes.Length || !_securityTypes.All(_checkedSecurityTypes.Contains))
88+
{
89+
throw new RegressionTestException($"Not all security types were checked. Expected: {string.Join(", ", _securityTypes)}. Checked: {string.Join(", ", _checkedSecurityTypes)}");
90+
}
91+
}
92+
93+
/// <summary>
94+
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
95+
/// </summary>
96+
public bool CanRunLocally { get; } = true;
97+
98+
/// <summary>
99+
/// This is used by the regression test system to indicate which languages this algorithm is written in.
100+
/// </summary>
101+
public List<Language> Languages { get; } = new() { Language.CSharp };
102+
103+
/// <summary>
104+
/// Data Points count of all timeslices of algorithm
105+
/// </summary>
106+
public virtual long DataPoints => 4276;
107+
108+
/// <summary>
109+
/// Data Points count of the algorithm history
110+
/// </summary>
111+
public int AlgorithmHistoryDataPoints => 0;
112+
113+
/// <summary>
114+
/// Final status of the algorithm
115+
/// </summary>
116+
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
117+
118+
/// <summary>
119+
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
120+
/// </summary>
121+
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
122+
{
123+
{"Total Orders", "0"},
124+
{"Average Win", "0%"},
125+
{"Average Loss", "0%"},
126+
{"Compounding Annual Return", "0%"},
127+
{"Drawdown", "0%"},
128+
{"Expectancy", "0"},
129+
{"Start Equity", "100000"},
130+
{"End Equity", "100000"},
131+
{"Net Profit", "0%"},
132+
{"Sharpe Ratio", "0"},
133+
{"Sortino Ratio", "0"},
134+
{"Probabilistic Sharpe Ratio", "0%"},
135+
{"Loss Rate", "0%"},
136+
{"Win Rate", "0%"},
137+
{"Profit-Loss Ratio", "0"},
138+
{"Alpha", "0"},
139+
{"Beta", "0"},
140+
{"Annual Standard Deviation", "0"},
141+
{"Annual Variance", "0"},
142+
{"Information Ratio", "0"},
143+
{"Tracking Error", "0"},
144+
{"Treynor Ratio", "0"},
145+
{"Total Fees", "$0.00"},
146+
{"Estimated Strategy Capacity", "$0"},
147+
{"Lowest Capacity Asset", ""},
148+
{"Portfolio Turnover", "0%"},
149+
{"Drawdown Recovery", "0"},
150+
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
151+
};
152+
}
153+
}

Algorithm.CSharp/FundamentalRegressionAlgorithm.cs

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ public override void OnSecuritiesChanged(SecurityChanges changes)
222222
/// <summary>
223223
/// Data Points count of all timeslices of algorithm
224224
/// </summary>
225-
public long DataPoints => 77169;
225+
public long DataPoints => 70972;
226226

227227
/// <summary>
228228
/// Data Points count of the algorithm history
@@ -239,34 +239,34 @@ public override void OnSecuritiesChanged(SecurityChanges changes)
239239
/// </summary>
240240
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
241241
{
242-
{"Total Orders", "2"},
242+
{"Total Orders", "3"},
243243
{"Average Win", "0%"},
244244
{"Average Loss", "0%"},
245-
{"Compounding Annual Return", "-1.016%"},
245+
{"Compounding Annual Return", "-1.169%"},
246246
{"Drawdown", "0.100%"},
247247
{"Expectancy", "0"},
248248
{"Start Equity", "100000"},
249-
{"End Equity", "99963.64"},
250-
{"Net Profit", "-0.036%"},
251-
{"Sharpe Ratio", "-4.731"},
252-
{"Sortino Ratio", "-6.776"},
253-
{"Probabilistic Sharpe Ratio", "24.373%"},
249+
{"End Equity", "99958.14"},
250+
{"Net Profit", "-0.042%"},
251+
{"Sharpe Ratio", "-3.451"},
252+
{"Sortino Ratio", "-4.933"},
253+
{"Probabilistic Sharpe Ratio", "27.530%"},
254254
{"Loss Rate", "0%"},
255255
{"Win Rate", "0%"},
256256
{"Profit-Loss Ratio", "0"},
257257
{"Alpha", "-0.013"},
258-
{"Beta", "0.023"},
259-
{"Annual Standard Deviation", "0.003"},
258+
{"Beta", "0.043"},
259+
{"Annual Standard Deviation", "0.005"},
260260
{"Annual Variance", "0"},
261261
{"Information Ratio", "0.607"},
262-
{"Tracking Error", "0.095"},
263-
{"Treynor Ratio", "-0.654"},
264-
{"Total Fees", "$2.00"},
262+
{"Tracking Error", "0.093"},
263+
{"Treynor Ratio", "-0.381"},
264+
{"Total Fees", "$3.00"},
265265
{"Estimated Strategy Capacity", "$1900000000.00"},
266266
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
267-
{"Portfolio Turnover", "0.30%"},
268-
{"Drawdown Recovery", "5"},
269-
{"OrderListHash", "9b3bf202c3d5707779f25e9c7f7fdc92"}
267+
{"Portfolio Turnover", "0.45%"},
268+
{"Drawdown Recovery", "4"},
269+
{"OrderListHash", "63a37fcfe86bca2e037d9dbb9c531e43"}
270270
};
271271
}
272272
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3+
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*
15+
*/
16+
17+
using QuantConnect.Securities;
18+
using System;
19+
20+
namespace QuantConnect.Algorithm.CSharp
21+
{
22+
/// <summary>
23+
/// Regression algorithm asserting that futures and future options from universe are added with the same resolution, fill forward and extended market hours settings as the universe settings.
24+
/// </summary>
25+
public class FuturesAndFutureOptionsUniverseSettingsRegressionAlgorithm : EquityOptionsUniverseSettingsRegressionAlgorithm
26+
{
27+
protected override DateTime TestStartDate => new DateTime(2020, 01, 03);
28+
29+
protected override SecurityType[] AddSecurity()
30+
{
31+
var futures = AddFuture(Futures.Indices.SP500EMini);
32+
futures.SetFilter(0, 180);
33+
34+
AddFutureOption(futures.Symbol, universe => universe.Strikes(-5, +5));
35+
36+
return [SecurityType.Future, SecurityType.FutureOption];
37+
}
38+
39+
/// <summary>
40+
/// Data Points count of all timeslices of algorithm
41+
/// </summary>
42+
public override long DataPoints => 456;
43+
}
44+
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3+
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*
15+
*/
16+
17+
using System;
18+
using System.Collections.Generic;
19+
20+
namespace QuantConnect.Algorithm.CSharp
21+
{
22+
/// <summary>
23+
/// Regression algorithm asserting that index options from universe are added with the same resolution, fill forward and extended market hours settings as the universe settings.
24+
/// </summary>
25+
public class IndexOptionsUniverseSettingsRegressionAlgorithm : EquityOptionsUniverseSettingsRegressionAlgorithm
26+
{
27+
protected override DateTime TestStartDate => new DateTime(2021, 01, 05);
28+
29+
protected override SecurityType[] AddSecurity()
30+
{
31+
var index = AddIndex("SPX");
32+
var indexOption = AddOption(index.Symbol);
33+
indexOption.SetFilter(u => u.Strikes(-2, +2).Expiration(0, 180));
34+
35+
return [indexOption.Symbol.SecurityType];
36+
}
37+
38+
/// <summary>
39+
/// Data Points count of all timeslices of algorithm
40+
/// </summary>
41+
public override long DataPoints => 46;
42+
43+
/// <summary>
44+
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
45+
/// </summary>
46+
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
47+
{
48+
{"Total Orders", "0"},
49+
{"Average Win", "0%"},
50+
{"Average Loss", "0%"},
51+
{"Compounding Annual Return", "0%"},
52+
{"Drawdown", "0%"},
53+
{"Expectancy", "0"},
54+
{"Start Equity", "100000"},
55+
{"End Equity", "100000"},
56+
{"Net Profit", "0%"},
57+
{"Sharpe Ratio", "0"},
58+
{"Sortino Ratio", "0"},
59+
{"Probabilistic Sharpe Ratio", "0%"},
60+
{"Loss Rate", "0%"},
61+
{"Win Rate", "0%"},
62+
{"Profit-Loss Ratio", "0"},
63+
{"Alpha", "0"},
64+
{"Beta", "0"},
65+
{"Annual Standard Deviation", "0"},
66+
{"Annual Variance", "0"},
67+
{"Information Ratio", "-16.713"},
68+
{"Tracking Error", "0.067"},
69+
{"Treynor Ratio", "0"},
70+
{"Total Fees", "$0.00"},
71+
{"Estimated Strategy Capacity", "$0"},
72+
{"Lowest Capacity Asset", ""},
73+
{"Portfolio Turnover", "0%"},
74+
{"Drawdown Recovery", "0"},
75+
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
76+
};
77+
}
78+
}

Algorithm.Python/IndexOptionCallButterflyAlgorithm.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,5 @@ def on_data(self, slice: Slice) -> None:
6565
call_butterfly = OptionStrategies.call_butterfly(self.spxw, otm_strike, atm_strike, itm_strike, expiry)
6666
price = sum([abs(self.securities[x.symbol].price * x.quantity) * self.multiplier for x in call_butterfly.underlying_legs])
6767
if price > 0:
68-
quantity = self.portfolio.total_portfolio_value // price
68+
quantity = int(self.portfolio.total_portfolio_value // price)
6969
self.tickets = self.buy(call_butterfly, quantity, asynchronous=True)
70-

Algorithm.Python/IndexOptionPutButterflyAlgorithm.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,5 @@ def on_data(self, slice: Slice) -> None:
6565
put_butterfly = OptionStrategies.put_butterfly(self.spxw, itm_strike, atm_strike, otm_strike, expiry)
6666
price = sum([abs(self.securities[x.symbol].price * x.quantity) * self.multiplier for x in put_butterfly.underlying_legs])
6767
if price > 0:
68-
quantity = self.portfolio.total_portfolio_value // price
68+
quantity = int(self.portfolio.total_portfolio_value // price)
6969
self.tickets = self.buy(put_butterfly, quantity, asynchronous=True)
70-

0 commit comments

Comments
 (0)