Skip to content

Commit 9d99517

Browse files
committed
Address security re-utilization only
1 parent 265e9a5 commit 9d99517

8 files changed

Lines changed: 36 additions & 137 deletions

Algorithm.CSharp/RawPricesUniverseRegressionAlgorithm.cs

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -91,12 +91,12 @@ public override void OnSecuritiesChanged(SecurityChanges changes)
9191
/// <summary>
9292
/// Data Points count of all timeslices of algorithm
9393
/// </summary>
94-
public long DataPoints => 144;
94+
public long DataPoints => 135;
9595

9696
/// <summary>
9797
/// Data Points count of the algorithm history
9898
/// </summary>
99-
public int AlgorithmHistoryDataPoints => 90;
99+
public int AlgorithmHistoryDataPoints => 30;
100100

101101
/// <summary>
102102
/// Final status of the algorithm
@@ -108,33 +108,33 @@ public override void OnSecuritiesChanged(SecurityChanges changes)
108108
/// </summary>
109109
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
110110
{
111-
{"Total Orders", "33"},
112-
{"Average Win", "0.22%"},
113-
{"Average Loss", "-0.31%"},
114-
{"Compounding Annual Return", "-25.889%"},
115-
{"Drawdown", "2.200%"},
116-
{"Expectancy", "-0.199"},
111+
{"Total Orders", "12"},
112+
{"Average Win", "0.34%"},
113+
{"Average Loss", "-0.14%"},
114+
{"Compounding Annual Return", "4.586%"},
115+
{"Drawdown", "0.700%"},
116+
{"Expectancy", "0.158"},
117117
{"Start Equity", "50000"},
118-
{"End Equity", "49401.67"},
119-
{"Net Profit", "-1.197%"},
120-
{"Sharpe Ratio", "-1.036"},
121-
{"Sortino Ratio", "-0.681"},
122-
{"Probabilistic Sharpe Ratio", "31.423%"},
123-
{"Loss Rate", "53%"},
124-
{"Win Rate", "47%"},
125-
{"Profit-Loss Ratio", "0.72"},
126-
{"Alpha", "-0.02"},
127-
{"Beta", "0.682"},
128-
{"Annual Standard Deviation", "0.086"},
129-
{"Annual Variance", "0.007"},
130-
{"Information Ratio", "0.195"},
131-
{"Tracking Error", "0.063"},
132-
{"Treynor Ratio", "-0.131"},
118+
{"End Equity", "50090.17"},
119+
{"Net Profit", "0.180%"},
120+
{"Sharpe Ratio", "5.991"},
121+
{"Sortino Ratio", "0"},
122+
{"Probabilistic Sharpe Ratio", "99.393%"},
123+
{"Loss Rate", "67%"},
124+
{"Win Rate", "33%"},
125+
{"Profit-Loss Ratio", "2.47"},
126+
{"Alpha", "0.17"},
127+
{"Beta", "0.029"},
128+
{"Annual Standard Deviation", "0.028"},
129+
{"Annual Variance", "0.001"},
130+
{"Information Ratio", "2.734"},
131+
{"Tracking Error", "0.098"},
132+
{"Treynor Ratio", "5.803"},
133133
{"Total Fees", "$0.00"},
134-
{"Estimated Strategy Capacity", "$220000000.00"},
134+
{"Estimated Strategy Capacity", "$99000000.00"},
135135
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
136-
{"Portfolio Turnover", "44.69%"},
137-
{"OrderListHash", "93b3a1c9d6234bf616f0a69a5129a781"}
136+
{"Portfolio Turnover", "15.96%"},
137+
{"OrderListHash", "d915ae36ce856457b32ebbfce4581281"}
138138
};
139139
}
140140
}

Algorithm.CSharp/SecurityInitializationOnReAdditionForEquityRegressionAlgorithm.cs

Lines changed: 1 addition & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -27,31 +27,15 @@ namespace QuantConnect.Algorithm.CSharp
2727
/// </summary>
2828
public class SecurityInitializationOnReAdditionForEquityRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
2929
{
30-
private Symbol _symbol = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
31-
3230
private Security _equity;
3331
private Queue<DateTime> _tradableDates;
3432
private bool _securityWasRemoved;
35-
private int _securityInitializationCount;
3633

3734
public override void Initialize()
3835
{
3936
SetStartDate(2013, 10, 04);
4037
SetEndDate(2013, 10, 30);
4138

42-
var seeder = new FuncSecuritySeeder((security) =>
43-
{
44-
if ((_equity != null && ReferenceEquals(security, _equity)) ||
45-
(_equity == null && security.Symbol == _symbol))
46-
{
47-
_securityInitializationCount++;
48-
}
49-
50-
Debug($"[{Time}] Seeding {security.Symbol}");
51-
return GetLastKnownPrices(security);
52-
});
53-
SetSecurityInitializer(security => seeder.SeedSecurity(security));
54-
5539
_equity = AddEquity();
5640

5741
_tradableDates = new(QuantConnect.Time.EachTradeableDay(_equity.Exchange.Hours, StartDate, EndDate));
@@ -69,13 +53,6 @@ public override void Initialize()
6953
return;
7054
}
7155

72-
// Before we remove the security let's check that it was not initialized again
73-
if (_securityInitializationCount != 1)
74-
{
75-
throw new RegressionTestException($"Expected the equity to be initialized once and once only, " +
76-
$"but was initialized {_securityInitializationCount} times");
77-
}
78-
7956
// Remove the security every day
8057
Debug($"[{Time}] Removing the equity");
8158
_securityWasRemoved = RemoveSecurity(_equity.Symbol);
@@ -89,15 +66,8 @@ public override void Initialize()
8966

9067
private Equity AddEquity()
9168
{
92-
_securityInitializationCount = 0;
9369
var equity = AddEquity("SPY");
9470

95-
if (_securityInitializationCount != 1)
96-
{
97-
throw new RegressionTestException($"Expected the equity to be initialized once and once only, " +
98-
$"but was initialized {_securityInitializationCount} times");
99-
}
100-
10171
return equity;
10272
}
10373

@@ -163,7 +133,7 @@ public override void OnEndOfAlgorithm()
163133
/// <summary>
164134
/// Data Points count of the algorithm history
165135
/// </summary>
166-
public int AlgorithmHistoryDataPoints => 3838;
136+
public int AlgorithmHistoryDataPoints => 0;
167137

168138
/// <summary>
169139
/// Final status of the algorithm

Algorithm.CSharp/SecurityInitializationOnReAdditionForManuallyAddedOptionRegressionAlgorithm.cs

Lines changed: 1 addition & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,6 @@ public class SecurityInitializationOnReAdditionForManuallyAddedOptionRegressionA
3939

4040
private bool _securityWasRemoved;
4141

42-
private int _securityInitializationCount;
43-
4442
private Queue<DateTime> _tradableDates;
4543

4644
public override void Initialize()
@@ -49,20 +47,6 @@ public override void Initialize()
4947
SetEndDate(2014, 06, 20);
5048
SetCash(100000);
5149

52-
var seeder = new FuncSecuritySeeder((security) =>
53-
{
54-
if ((_manuallyAddedContract != null && ReferenceEquals(security, _manuallyAddedContract)) ||
55-
(_manuallyAddedContract == null && security.Symbol == _optionContractSymbol))
56-
{
57-
_securityInitializationCount++;
58-
}
59-
60-
Debug($"[{Time}] Seeding {security.Symbol}");
61-
return GetLastKnownPrices(security);
62-
});
63-
64-
SetSecurityInitializer(security => seeder.SeedSecurity(security));
65-
6650
_manuallyAddedContract = AddOptionContract();
6751

6852
_tradableDates = new(QuantConnect.Time.EachTradeableDay(_manuallyAddedContract.Exchange.Hours, StartDate, EndDate));
@@ -80,13 +64,6 @@ public override void Initialize()
8064
return;
8165
}
8266

83-
// Before we remove the security let's check that it was not initialized again
84-
if (_securityInitializationCount != 1)
85-
{
86-
throw new RegressionTestException($"Expected the option to be initialized once and once only, " +
87-
$"but was initialized {_securityInitializationCount} times");
88-
}
89-
9067
// Remove the security every day
9168
Debug($"[{Time}] Removing the equity");
9269
_securityWasRemoved = RemoveSecurity(_manuallyAddedContract.Symbol);
@@ -100,15 +77,7 @@ public override void Initialize()
10077

10178
public Option AddOptionContract()
10279
{
103-
_securityInitializationCount = 0;
10480
var option = AddOptionContract(_optionContractSymbol, Resolution.Daily);
105-
106-
if (_securityInitializationCount != 1)
107-
{
108-
throw new RegressionTestException($"Expected the option to be initialized once and once only, " +
109-
$"but was initialized {_securityInitializationCount} times");
110-
}
111-
11281
return option;
11382
}
11483

@@ -179,7 +148,7 @@ public override void OnEndOfAlgorithm()
179148
/// <summary>
180149
/// Data Points count of the algorithm history
181150
/// </summary>
182-
public int AlgorithmHistoryDataPoints => 5;
151+
public int AlgorithmHistoryDataPoints => 0;
183152

184153
/// <summary>
185154
/// Final status of the algorithm

Algorithm.CSharp/SecurityInitializationOnReAdditionForSelectedOptionRegressionAlgorithm.cs

Lines changed: 1 addition & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -40,23 +40,6 @@ public override void Initialize()
4040
SetEndDate(2014, 06, 20);
4141
SetCash(100000);
4242

43-
var seeder = new FuncSecuritySeeder((security) =>
44-
{
45-
if (security is Option option)
46-
{
47-
if (!_initializedContracts.TryGetValue(security, out var count))
48-
{
49-
count = 0;
50-
}
51-
_initializedContracts[security] = count + 1;
52-
}
53-
54-
Debug($"[{Time}] Seeding {security.Symbol}");
55-
return GetLastKnownPrices(security);
56-
});
57-
58-
SetSecurityInitializer(security => seeder.SeedSecurity(security));
59-
6043
var equitySymbol = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
6144

6245
_contractsToSelect = new List<Symbol>()
@@ -107,12 +90,6 @@ public override void OnSecuritiesChanged(SecurityChanges changes)
10790
}
10891
}
10992

110-
var addedContracts = changes.AddedSecurities.OfType<Option>().ToList();
111-
if (addedContracts.Any(x => !_initializedContracts.TryGetValue(x, out var count) || count != 1))
112-
{
113-
throw new RegressionTestException($"Expected all contracts to be initialized. Added: {string.Join(", ", addedContracts.Select(x => x.Symbol.Value))}, Initialized: {string.Join(", ", _initializedContracts.Select(x => $"{x.Key.Symbol.Value} - {x.Value}"))}");
114-
}
115-
11693
// The first contract will be selected always, so we expect it to be added only once
11794
var firstAddedContract = changes.AddedSecurities.FirstOrDefault(x => x.Symbol == _contractsToSelect[0]) as Option;
11895
if (firstAddedContract == null)
@@ -183,7 +160,7 @@ public override void OnEndOfAlgorithm()
183160
/// <summary>
184161
/// Data Points count of the algorithm history
185162
/// </summary>
186-
public int AlgorithmHistoryDataPoints => 5;
163+
public int AlgorithmHistoryDataPoints => 0;
187164

188165
/// <summary>
189166
/// Final status of the algorithm

Common/Extensions.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3894,16 +3894,14 @@ public static void ProcessSecurityChanges(this IAlgorithm algorithm, SecurityCha
38943894
{
38953895
// uses TryAdd, so don't need to worry about duplicates here
38963896
algorithm.Securities.Add(security);
3897-
security.MakeTradable();
38983897
}
38993898

39003899
var activeSecurities = algorithm.UniverseManager.ActiveSecurities;
39013900
foreach (var security in securityChanges.RemovedSecurities)
39023901
{
39033902
if (!activeSecurities.ContainsKey(security.Symbol))
39043903
{
3905-
security.IsTradable = false;
3906-
security.IsInitialized = false;
3904+
security.Reset();
39073905
}
39083906
}
39093907
}

Common/Securities/Security.cs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,6 @@ public class Security : DynamicObject, ISecurityPrice
5454
/// <remarks>Just use a list + lock, not concurrent bag, avoid garbage it creates for features we don't need here. See https://github.com/dotnet/runtime/issues/23103</remarks>
5555
private readonly HashSet<SubscriptionDataConfig> _subscriptionsBag;
5656

57-
/// <summary>
58-
/// Flag to keep track of initialized securities, to avoid double initialization.
59-
/// </summary>
60-
internal bool IsInitialized { get; set; }
61-
6257
/// <summary>
6358
/// This securities <see cref="IShortableProvider"/>
6459
/// </summary>
@@ -1184,7 +1179,6 @@ internal virtual void UpdateSymbolProperties(SymbolProperties symbolProperties)
11841179
/// </summary>
11851180
public virtual void Reset()
11861181
{
1187-
IsInitialized = false;
11881182
IsTradable = false;
11891183

11901184
// Reset the subscriptions

Common/Securities/SecurityService.cs

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -84,12 +84,9 @@ private Security CreateSecurity(Symbol symbol,
8484
// If non-internal, mark as tradable if it was not already since this is an existing security but might include new subscriptions
8585
if (!configList.IsInternalFeed)
8686
{
87-
existingSecurity.MakeTradable();
87+
existingSecurity.MakeTradable();
8888
}
8989

90-
// invoke the security initializer
91-
InitializeSecurity(initializeSecurity, existingSecurity);
92-
9390
return existingSecurity;
9491
}
9592

@@ -223,7 +220,10 @@ private Security CreateSecurity(Symbol symbol,
223220
security.AddData(configList);
224221

225222
// invoke the security initializer
226-
InitializeSecurity(initializeSecurity, security);
223+
if (initializeSecurity)
224+
{
225+
_securityInitializerProvider.SecurityInitializer.Initialize(security);
226+
}
227227

228228
CheckCanonicalSecurityModels(security);
229229

@@ -319,14 +319,5 @@ private void CheckCanonicalSecurityModels(Security security)
319319
}
320320
}
321321
}
322-
323-
private void InitializeSecurity(bool initializeSecurity, Security security)
324-
{
325-
if (initializeSecurity && !security.IsInitialized)
326-
{
327-
_securityInitializerProvider.SecurityInitializer.Initialize(security);
328-
security.IsInitialized = true;
329-
}
330-
}
331322
}
332323
}

Engine/DataFeeds/UniverseSelection.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@ private void RemoveSecurityFromUniverse(
473473
// if not used by any universe
474474
if (!isActive)
475475
{
476-
member.IsTradable = false;
476+
member.Reset();
477477
// We need to mark this security as untradeable while it has no data subscription
478478
// it is expected that this function is called while in sync with the algo thread,
479479
// so we can make direct edits to the security here.

0 commit comments

Comments
 (0)