chore: import upstream snapshot with attribution
This commit is contained in:
+200
@@ -0,0 +1,200 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests the delisting of the composite Symbol (ETF symbol) and the removal of
|
||||
/// the universe and the symbol from the algorithm.
|
||||
/// </summary>
|
||||
public class ETFConstituentUniverseCompositeDelistingRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
protected virtual bool AddETFSubscription { get; set; } = true;
|
||||
|
||||
private Symbol _gdvd;
|
||||
private Symbol _aapl;
|
||||
private DateTime _delistingDate;
|
||||
private int _universeSymbolCount;
|
||||
private bool _universeSelectionDone;
|
||||
private bool _universeAdded;
|
||||
private bool _universeRemoved;
|
||||
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 12, 1);
|
||||
SetEndDate(2021, 1, 31);
|
||||
SetCash(100000);
|
||||
|
||||
UniverseSettings.Resolution = Resolution.Hour;
|
||||
|
||||
_delistingDate = new DateTime(2021, 1, 21);
|
||||
|
||||
_aapl = AddEquity("AAPL", Resolution.Hour).Symbol;
|
||||
if (AddETFSubscription)
|
||||
{
|
||||
Log("Adding ETF constituent universe Symbol by using AddEquity(...)");
|
||||
_gdvd = AddEquity("GDVD", Resolution.Hour).Symbol;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log("Adding ETF constituent universe Symbol by using Symbol.Create(...)");
|
||||
_gdvd = QuantConnect.Symbol.Create("GDVD", SecurityType.Equity, Market.USA);
|
||||
}
|
||||
|
||||
AddUniverse(Universe.ETF(_gdvd, universeFilterFunc: FilterETFs));
|
||||
}
|
||||
|
||||
private IEnumerable<Symbol> FilterETFs(IEnumerable<ETFConstituentUniverse> constituents)
|
||||
{
|
||||
_universeSelectionDone = true;
|
||||
|
||||
if (UtcTime.Date > _delistingDate)
|
||||
{
|
||||
throw new RegressionTestException($"Performing constituent universe selection on {UtcTime:yyyy-MM-dd HH:mm:ss.fff} after composite ETF has been delisted");
|
||||
}
|
||||
|
||||
var constituentSymbols = constituents.Select(x => x.Symbol);
|
||||
_universeSymbolCount = constituentSymbols.Distinct().Count();
|
||||
|
||||
return constituentSymbols;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
/// </summary>
|
||||
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (UtcTime.Date > _delistingDate && slice.Keys.Any(x => x != _aapl))
|
||||
{
|
||||
throw new RegressionTestException($"Received unexpected slice in OnData(...) after universe was deselected");
|
||||
}
|
||||
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
SetHoldings(_aapl, 0.5m);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
if (changes.AddedSecurities.Count != 0 && UtcTime > _delistingDate)
|
||||
{
|
||||
throw new RegressionTestException("New securities added after ETF constituents were delisted");
|
||||
}
|
||||
|
||||
// if we added the etf subscription it will get added and delisted and send us a addition/removal event
|
||||
var expectedChangesCount = _universeSymbolCount;
|
||||
|
||||
if (_universeSelectionDone)
|
||||
{
|
||||
// manually added securities are added right away, the etf universe selection happens a few days later when data available
|
||||
// AAPL was already added so it wont be counted
|
||||
_universeAdded |= changes.AddedSecurities.Count == (expectedChangesCount - 1);
|
||||
}
|
||||
|
||||
// TODO: shouldn't be sending AAPL as a removed security since it was added by another universe
|
||||
_universeRemoved |= changes.RemovedSecurities.Count == (expectedChangesCount + (AddETFSubscription ? 1 : 0)) &&
|
||||
UtcTime.Date >= _delistingDate &&
|
||||
UtcTime.Date < EndDate;
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (!_universeAdded)
|
||||
{
|
||||
throw new RegressionTestException("ETF constituent universe was never added to the algorithm");
|
||||
}
|
||||
if (!_universeRemoved)
|
||||
{
|
||||
throw new RegressionTestException("ETF constituent universe was not removed from the algorithm after delisting");
|
||||
}
|
||||
if (ActiveSecurities.Count > 2)
|
||||
{
|
||||
throw new RegressionTestException($"Expected less than 2 securities after algorithm ended, found {Securities.Count}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 virtual long DataPoints => 826;
|
||||
|
||||
/// <summary>
|
||||
/// Data Points count of the algorithm history
|
||||
/// </summary>
|
||||
public virtual 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", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "26.315%"},
|
||||
{"Drawdown", "5.400%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Start Equity", "100000"},
|
||||
{"End Equity", "103892.62"},
|
||||
{"Net Profit", "3.893%"},
|
||||
{"Sharpe Ratio", "1.291"},
|
||||
{"Sortino Ratio", "1.876"},
|
||||
{"Probabilistic Sharpe Ratio", "53.581%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.13"},
|
||||
{"Beta", "0.697"},
|
||||
{"Annual Standard Deviation", "0.139"},
|
||||
{"Annual Variance", "0.019"},
|
||||
{"Information Ratio", "0.889"},
|
||||
{"Tracking Error", "0.122"},
|
||||
{"Treynor Ratio", "0.257"},
|
||||
{"Total Fees", "$2.04"},
|
||||
{"Estimated Strategy Capacity", "$260000000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
|
||||
{"Portfolio Turnover", "0.83%"},
|
||||
{"Drawdown Recovery", "23"},
|
||||
{"OrderListHash", "cdf9a800c8ec7d5f9f750f32c2622f5a"}
|
||||
};
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests the delisting of the composite Symbol (ETF symbol) and the removal of
|
||||
/// the universe and the symbol from the algorithm, without adding a subscription via AddEquity
|
||||
/// </summary>
|
||||
public class ETFConstituentUniverseCompositeDelistingRegressionAlgorithmNoAddEquityETF : ETFConstituentUniverseCompositeDelistingRegressionAlgorithm
|
||||
{
|
||||
protected override bool AddETFSubscription { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Data Points count of all timeslices of algorithm
|
||||
/// </summary>
|
||||
public override long DataPoints => 623;
|
||||
|
||||
/// <summary>
|
||||
/// Data Points count of the algorithm history
|
||||
/// </summary>
|
||||
public override int AlgorithmHistoryDataPoints => 0;
|
||||
|
||||
/// <summary>
|
||||
/// Final status of the algorithm
|
||||
/// </summary>
|
||||
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
|
||||
}
|
||||
}
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests a custom filter function when creating an ETF constituents universe for SPY
|
||||
/// </summary>
|
||||
public class ETFConstituentUniverseFilterFunctionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Dictionary<Symbol, ETFConstituentUniverse> _etfConstituentData = new Dictionary<Symbol, ETFConstituentUniverse>();
|
||||
|
||||
private Symbol _aapl;
|
||||
private Symbol _spy;
|
||||
private bool _filtered;
|
||||
private bool _securitiesChanged;
|
||||
private bool _receivedData;
|
||||
private bool _etfRebalanced;
|
||||
private int _rebalanceCount;
|
||||
private int _rebalanceAssetCount;
|
||||
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 12, 1);
|
||||
SetEndDate(2021, 1, 31);
|
||||
SetCash(100000);
|
||||
|
||||
UniverseSettings.Resolution = Resolution.Hour;
|
||||
|
||||
_spy = AddEquity("SPY", Resolution.Hour).Symbol;
|
||||
_aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
|
||||
|
||||
AddUniverse(Universe.ETF(_spy, universeFilterFunc: FilterETFs));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Filters ETFs, performing some sanity checks
|
||||
/// </summary>
|
||||
/// <param name="constituents">Constituents of the ETF universe added above</param>
|
||||
/// <returns>Constituent Symbols to add to algorithm</returns>
|
||||
/// <exception cref="ArgumentException">Constituents collection was not structured as expected</exception>
|
||||
private IEnumerable<Symbol> FilterETFs(IEnumerable<ETFConstituentUniverse> constituents)
|
||||
{
|
||||
var constituentsData = constituents.ToList();
|
||||
_etfConstituentData = constituentsData.ToDictionary(x => x.Symbol, x => x);
|
||||
|
||||
var constituentsSymbols = constituentsData.Select(x => x.Symbol).ToList();
|
||||
if (constituentsData.Count == 0)
|
||||
{
|
||||
throw new ArgumentException($"Constituents collection is empty on {UtcTime:yyyy-MM-dd HH:mm:ss.fff}");
|
||||
}
|
||||
if (!constituentsSymbols.Contains(_aapl))
|
||||
{
|
||||
throw new ArgumentException("AAPL is not in the constituents data provided to the algorithm");
|
||||
}
|
||||
|
||||
var aaplData = constituentsData.Single(x => x.Symbol == _aapl);
|
||||
if (aaplData.Weight == 0m)
|
||||
{
|
||||
throw new ArgumentException("AAPL weight is expected to be a non-zero value");
|
||||
}
|
||||
|
||||
_filtered = true;
|
||||
_etfRebalanced = true;
|
||||
|
||||
return constituentsSymbols;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
/// </summary>
|
||||
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!_filtered && slice.Bars.Count != 0 && slice.Bars.ContainsKey(_aapl))
|
||||
{
|
||||
throw new RegressionTestException("AAPL TradeBar data added to algorithm before constituent universe selection took place");
|
||||
}
|
||||
|
||||
if (slice.Bars.Count == 1 && slice.Bars.ContainsKey(_spy))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (slice.Bars.Count != 0 && !slice.Bars.ContainsKey(_aapl))
|
||||
{
|
||||
throw new RegressionTestException($"Expected AAPL TradeBar data in OnData on {UtcTime:yyyy-MM-dd HH:mm:ss}");
|
||||
}
|
||||
|
||||
_receivedData = true;
|
||||
// If the ETF hasn't changed its weights, then let's not update our holdings
|
||||
if (!_etfRebalanced)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var bar in slice.Bars.Values)
|
||||
{
|
||||
if (_etfConstituentData.TryGetValue(bar.Symbol, out var constituentData) &&
|
||||
constituentData.Weight != null &&
|
||||
constituentData.Weight >= 0.0001m)
|
||||
{
|
||||
// If the weight of the constituent is less than 1%, then it will be set to 1%
|
||||
// If the weight of the constituent exceeds more than 5%, then it will be capped to 5%
|
||||
// Otherwise, if the weight falls in between, then we use that value.
|
||||
var boundedWeight = Math.Max(0.01m, Math.Min(constituentData.Weight.Value, 0.05m));
|
||||
SetHoldings(bar.Symbol, boundedWeight);
|
||||
|
||||
if (_etfRebalanced)
|
||||
{
|
||||
_rebalanceCount++;
|
||||
}
|
||||
_etfRebalanced = false;
|
||||
_rebalanceAssetCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if new securities have been added to the algorithm after universe selection has occurred
|
||||
/// </summary>
|
||||
/// <param name="changes">Security changes</param>
|
||||
/// <exception cref="ArgumentException">Expected number of stocks were not added to the algorithm</exception>
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
if (_filtered && !_securitiesChanged && changes.AddedSecurities.Count < 500)
|
||||
{
|
||||
throw new ArgumentException($"Added SPY S&P 500 ETF to algorithm, but less than 500 equities were loaded (added {changes.AddedSecurities.Count} securities)");
|
||||
}
|
||||
|
||||
_securitiesChanged = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ensures that all expected events were triggered by the end of the algorithm
|
||||
/// </summary>
|
||||
/// <exception cref="RegressionTestException">An expected event didn't happen</exception>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (_rebalanceCount != 2)
|
||||
{
|
||||
throw new RegressionTestException($"Expected 2 rebalances, instead rebalanced: {_rebalanceCount}");
|
||||
}
|
||||
if (_rebalanceAssetCount != 8)
|
||||
{
|
||||
throw new RegressionTestException($"Invested in {_rebalanceAssetCount} assets (expected 8)");
|
||||
}
|
||||
if (!_filtered)
|
||||
{
|
||||
throw new RegressionTestException("Universe selection was never triggered");
|
||||
}
|
||||
if (!_securitiesChanged)
|
||||
{
|
||||
throw new RegressionTestException("Security changes never propagated to the algorithm");
|
||||
}
|
||||
if (!_receivedData)
|
||||
{
|
||||
throw new RegressionTestException("Data was never loaded for the S&P 500 constituent AAPL");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 => 2722;
|
||||
|
||||
/// <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", "4"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "1.989%"},
|
||||
{"Drawdown", "0.600%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Start Equity", "100000"},
|
||||
{"End Equity", "100322.52"},
|
||||
{"Net Profit", "0.323%"},
|
||||
{"Sharpe Ratio", "0.838"},
|
||||
{"Sortino Ratio", "1.122"},
|
||||
{"Probabilistic Sharpe Ratio", "46.747%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.005"},
|
||||
{"Beta", "0.098"},
|
||||
{"Annual Standard Deviation", "0.014"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.614"},
|
||||
{"Tracking Error", "0.096"},
|
||||
{"Treynor Ratio", "0.123"},
|
||||
{"Total Fees", "$4.00"},
|
||||
{"Estimated Strategy Capacity", "$130000000.00"},
|
||||
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
|
||||
{"Portfolio Turnover", "0.13%"},
|
||||
{"Drawdown Recovery", "16"},
|
||||
{"OrderListHash", "7231bcc4d5304546a25e4dcc9f11ed5f"}
|
||||
};
|
||||
}
|
||||
}
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Algorithm.Framework.Alphas;
|
||||
using QuantConnect.Algorithm.Framework.Execution;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests ETF constituents universe selection with the algorithm framework models (Alpha, PortfolioConstruction, Execution)
|
||||
/// </summary>
|
||||
public class ETFConstituentUniverseFrameworkRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private List<ETFConstituentUniverse> ConstituentData = new List<ETFConstituentUniverse>();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the algorithm, setting up the framework classes and ETF constituent universe settings
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 12, 1);
|
||||
SetEndDate(2021, 1, 31);
|
||||
SetCash(100000);
|
||||
|
||||
SetAlpha(new ETFConstituentAlphaModel());
|
||||
SetPortfolioConstruction(new ETFConstituentPortfolioModel());
|
||||
SetExecution(new ETFConstituentExecutionModel());
|
||||
|
||||
var spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
|
||||
|
||||
UniverseSettings.Resolution = Resolution.Hour;
|
||||
AddUniverseWrapper(spy);
|
||||
}
|
||||
|
||||
protected virtual void AddUniverseWrapper(Symbol symbol)
|
||||
{
|
||||
var universe = AddUniverse(Universe.ETF(symbol, UniverseSettings, FilterETFConstituents));
|
||||
|
||||
var historicalData = History(universe, 1).ToList();
|
||||
if (historicalData.Count != 1)
|
||||
{
|
||||
throw new RegressionTestException($"Unexpected history count {historicalData.Count}! Expected 1");
|
||||
}
|
||||
foreach (var universeDataCollection in historicalData)
|
||||
{
|
||||
if (universeDataCollection.Data.Count < 200)
|
||||
{
|
||||
throw new RegressionTestException($"Unexpected universe DataCollection count {universeDataCollection.Data.Count}! Expected > 200");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Filters ETF constituents
|
||||
/// </summary>
|
||||
/// <param name="constituents">ETF constituents</param>
|
||||
/// <returns>ETF constituent Symbols that we want to include in the algorithm</returns>
|
||||
public IEnumerable<Symbol> FilterETFConstituents(IEnumerable<ETFConstituentUniverse> constituents)
|
||||
{
|
||||
var constituentData = constituents
|
||||
.Where(x => (x.Weight ?? 0m) >= 0.001m)
|
||||
.ToList();
|
||||
|
||||
ConstituentData = constituentData;
|
||||
|
||||
return constituentData
|
||||
.Select(x => x.Symbol)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// no-op for performance
|
||||
/// </summary>
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Alpha model for ETF constituents, where we generate insights based on the weighting
|
||||
/// of the ETF constituent
|
||||
/// </summary>
|
||||
private class ETFConstituentAlphaModel : IAlphaModel
|
||||
{
|
||||
public void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates new insights based on constituent data and their weighting
|
||||
/// in their respective ETF
|
||||
/// </summary>
|
||||
public IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
|
||||
{
|
||||
var algo = (ETFConstituentUniverseFrameworkRegressionAlgorithm) algorithm;
|
||||
|
||||
foreach (var constituent in algo.ConstituentData)
|
||||
{
|
||||
if (!data.Bars.ContainsKey(constituent.Symbol) &&
|
||||
!data.QuoteBars.ContainsKey(constituent.Symbol))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var insightDirection = constituent.Weight != null && constituent.Weight >= 0.01m
|
||||
? InsightDirection.Up
|
||||
: InsightDirection.Down;
|
||||
|
||||
yield return new Insight(
|
||||
algorithm.UtcTime,
|
||||
constituent.Symbol,
|
||||
TimeSpan.FromDays(1),
|
||||
InsightType.Price,
|
||||
insightDirection,
|
||||
1 * (double)insightDirection,
|
||||
1.0,
|
||||
weight: (double)(constituent.Weight ?? 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates targets for ETF constituents, which will be set to the weighting
|
||||
/// of the constituent in their respective ETF
|
||||
/// </summary>
|
||||
private class ETFConstituentPortfolioModel : IPortfolioConstructionModel
|
||||
{
|
||||
private bool _hasAdded;
|
||||
|
||||
/// <summary>
|
||||
/// Securities changed, detects if we've got new additions to the universe
|
||||
/// so that we don't try to trade every loop
|
||||
/// </summary>
|
||||
public void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
|
||||
{
|
||||
_hasAdded = changes.AddedSecurities.Count != 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates portfolio targets based on the insights provided to us by the alpha model.
|
||||
/// Emits portfolio targets setting the quantity to the weight of the constituent
|
||||
/// in its respective ETF.
|
||||
/// </summary>
|
||||
public IEnumerable<IPortfolioTarget> CreateTargets(QCAlgorithm algorithm, Insight[] insights)
|
||||
{
|
||||
if (!_hasAdded)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
foreach (var insight in insights)
|
||||
{
|
||||
yield return new PortfolioTarget(insight.Symbol, (decimal) (insight.Weight ?? 0));
|
||||
_hasAdded = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes based on ETF constituent weighting
|
||||
/// </summary>
|
||||
private class ETFConstituentExecutionModel : IExecutionModel
|
||||
{
|
||||
/// <summary>
|
||||
/// Liquidates if constituents have been removed from the universe
|
||||
/// </summary>
|
||||
public void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
|
||||
{
|
||||
foreach (var change in changes.RemovedSecurities)
|
||||
{
|
||||
algorithm.Liquidate(change.Symbol);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates orders for constituents that attempts to add
|
||||
/// the weighting of the constituent in our portfolio. The
|
||||
/// resulting algorithm portfolio weight might not be equal
|
||||
/// to the leverage of the ETF (1x, 2x, 3x, etc.)
|
||||
/// </summary>
|
||||
public void Execute(QCAlgorithm algorithm, IPortfolioTarget[] targets)
|
||||
{
|
||||
foreach (var target in targets)
|
||||
{
|
||||
algorithm.SetHoldings(target.Symbol, target.Quantity);
|
||||
}
|
||||
}
|
||||
|
||||
public void OnOrderEvent(QCAlgorithm algorithm, OrderEvent orderEvent)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 virtual List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// Data Points count of all timeslices of algorithm
|
||||
/// </summary>
|
||||
public long DataPoints => 2436;
|
||||
|
||||
/// <summary>
|
||||
/// Data Points count of the algorithm history
|
||||
/// </summary>
|
||||
public virtual int AlgorithmHistoryDataPoints => 1;
|
||||
|
||||
/// <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", "3"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "3.006%"},
|
||||
{"Drawdown", "0.700%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Start Equity", "100000"},
|
||||
{"End Equity", "100485.34"},
|
||||
{"Net Profit", "0.485%"},
|
||||
{"Sharpe Ratio", "1.055"},
|
||||
{"Sortino Ratio", "1.53"},
|
||||
{"Probabilistic Sharpe Ratio", "50.834%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.012"},
|
||||
{"Beta", "0.096"},
|
||||
{"Annual Standard Deviation", "0.017"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.544"},
|
||||
{"Tracking Error", "0.096"},
|
||||
{"Treynor Ratio", "0.191"},
|
||||
{"Total Fees", "$3.00"},
|
||||
{"Estimated Strategy Capacity", "$1400000000.00"},
|
||||
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
|
||||
{"Portfolio Turnover", "0.12%"},
|
||||
{"Drawdown Recovery", "22"},
|
||||
{"OrderListHash", "5d1e80a607d65ba4c7329f6f0b86999f"}
|
||||
};
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* 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 QuantConnect.Algorithm.Framework.Selection;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests ETF constituents universe selection with the algorithm framework models (Alpha, PortfolioConstruction, Execution)
|
||||
/// </summary>
|
||||
public class ETFConstituentUniverseFrameworkRegressionAlgorithmNewUniverseModel : ETFConstituentUniverseFrameworkRegressionAlgorithm
|
||||
{
|
||||
protected override void AddUniverseWrapper(Symbol symbol)
|
||||
{
|
||||
AddUniverseSelection(new ETFConstituentsUniverseSelectionModel(symbol, universeFilterFunc: FilterETFConstituents));
|
||||
}
|
||||
|
||||
public override List<Language> Languages { get; } = new() { Language.CSharp };
|
||||
|
||||
public override int AlgorithmHistoryDataPoints => 0;
|
||||
|
||||
/// <summary>
|
||||
/// Final status of the algorithm
|
||||
/// </summary>
|
||||
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
|
||||
}
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Assert that ETF universe selection happens right away after algorithm starts
|
||||
/// </summary>
|
||||
public class ETFConstituentUniverseImmediateSelectionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private List<Symbol> _constituents = new();
|
||||
|
||||
private Symbol _spy;
|
||||
private bool _filtered;
|
||||
private bool _securitiesChanged;
|
||||
|
||||
private bool _firstOnData = true;
|
||||
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 12, 1);
|
||||
SetEndDate(2021, 1, 31);
|
||||
SetCash(100000);
|
||||
|
||||
UniverseSettings.Resolution = Resolution.Hour;
|
||||
|
||||
_spy = AddEquity("SPY", Resolution.Hour).Symbol;
|
||||
AddUniverse(Universe.ETF(_spy, universeFilterFunc: FilterETFs));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Filters ETFs, performing some sanity checks
|
||||
/// </summary>
|
||||
/// <param name="constituents">Constituents of the ETF universe added above</param>
|
||||
/// <returns>Constituent Symbols to add to algorithm</returns>
|
||||
/// <exception cref="ArgumentException">Constituents collection was not structured as expected</exception>
|
||||
private IEnumerable<Symbol> FilterETFs(IEnumerable<ETFConstituentUniverse> constituents)
|
||||
{
|
||||
_filtered = true;
|
||||
_constituents = constituents.Select(x => x.Symbol).Distinct().ToList();
|
||||
|
||||
return _constituents;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
/// </summary>
|
||||
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (_firstOnData)
|
||||
{
|
||||
if (!_filtered)
|
||||
{
|
||||
throw new RegressionTestException("Universe selection should have been triggered right away. " +
|
||||
"The first OnData call should have had happened after the universe selection");
|
||||
}
|
||||
|
||||
_firstOnData = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if new securities have been added to the algorithm after universe selection has occurred
|
||||
/// </summary>
|
||||
/// <param name="changes">Security changes</param>
|
||||
/// <exception cref="ArgumentException">Expected number of stocks were not added to the algorithm</exception>
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
if (!_filtered)
|
||||
{
|
||||
throw new RegressionTestException("Universe selection should have been triggered right away");
|
||||
}
|
||||
|
||||
if (!_securitiesChanged)
|
||||
{
|
||||
// Selection should be happening right on algorithm start
|
||||
if (Time != StartDate)
|
||||
{
|
||||
throw new RegressionTestException("Universe selection should have been triggered right away");
|
||||
}
|
||||
|
||||
// All constituents should have been added to the algorithm.
|
||||
// Plus the ETF itself.
|
||||
if (changes.AddedSecurities.Count != _constituents.Count + 1)
|
||||
{
|
||||
throw new RegressionTestException($"Expected {_constituents.Count + 1} stocks to be added to the algorithm, " +
|
||||
$"instead added: {changes.AddedSecurities.Count}");
|
||||
}
|
||||
|
||||
if (!_constituents.All(constituent => changes.AddedSecurities.Any(security => security.Symbol == constituent)))
|
||||
{
|
||||
throw new RegressionTestException("Not all constituents were added to the algorithm");
|
||||
}
|
||||
|
||||
_securitiesChanged = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ensures that all expected events were triggered by the end of the algorithm
|
||||
/// </summary>
|
||||
/// <exception cref="RegressionTestException">An expected event didn't happen</exception>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (_firstOnData || !_filtered || !_securitiesChanged)
|
||||
{
|
||||
throw new RegressionTestException("Expected events didn't happen");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 };
|
||||
|
||||
/// <summary>
|
||||
/// Data Points count of all timeslices of algorithm
|
||||
/// </summary>
|
||||
public long DataPoints => 2722;
|
||||
|
||||
/// <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", "0"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Start Equity", "100000"},
|
||||
{"End Equity", "100000"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Sortino Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.695"},
|
||||
{"Tracking Error", "0.105"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", ""},
|
||||
{"Portfolio Turnover", "0%"},
|
||||
{"Drawdown Recovery", "0"},
|
||||
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests the mapping of the ETF symbol that has a constituent universe attached to it and ensures
|
||||
/// that data is loaded after the mapping event takes place.
|
||||
/// </summary>
|
||||
public class ETFConstituentUniverseMappedCompositeRegressionAlgorithm: QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _aapl;
|
||||
private Symbol _qqq;
|
||||
private Dictionary<DateTime, int> _filterDateConstituentSymbolCount = new Dictionary<DateTime, int>();
|
||||
private Dictionary<DateTime, bool> _constituentDataEncountered = new Dictionary<DateTime, bool>();
|
||||
private HashSet<Symbol> _constituentSymbols = new HashSet<Symbol>();
|
||||
private bool _mappingEventOccurred;
|
||||
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2011, 2, 1);
|
||||
SetEndDate(2011, 4, 4);
|
||||
SetCash(100000);
|
||||
|
||||
UniverseSettings.Resolution = Resolution.Hour;
|
||||
|
||||
_aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
|
||||
_qqq = AddEquity("QQQ", Resolution.Daily).Symbol;
|
||||
AddUniverse(Universe.ETF(_qqq, universeFilterFunc: FilterETFs));
|
||||
}
|
||||
|
||||
private IEnumerable<Symbol> FilterETFs(IEnumerable<ETFConstituentUniverse> constituents)
|
||||
{
|
||||
var constituentSymbols = constituents.Select(x => x.Symbol).ToHashSet();
|
||||
if (!constituentSymbols.Contains(_aapl))
|
||||
{
|
||||
throw new RegressionTestException("AAPL not found in QQQ constituents");
|
||||
}
|
||||
|
||||
_filterDateConstituentSymbolCount[UtcTime.Date] = constituentSymbols.Count;
|
||||
foreach (var symbol in constituentSymbols)
|
||||
{
|
||||
_constituentSymbols.Add(symbol);
|
||||
}
|
||||
|
||||
return constituentSymbols;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
/// </summary>
|
||||
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (slice.SymbolChangedEvents.Count != 0)
|
||||
{
|
||||
foreach (var symbolChanged in slice.SymbolChangedEvents.Values)
|
||||
{
|
||||
if (symbolChanged.Symbol != _qqq)
|
||||
{
|
||||
throw new RegressionTestException($"Mapped symbol is not QQQ. Instead, found: {symbolChanged.Symbol}");
|
||||
}
|
||||
if (symbolChanged.OldSymbol != "QQQQ")
|
||||
{
|
||||
throw new RegressionTestException($"Old QQQ Symbol is not QQQQ. Instead, found: {symbolChanged.OldSymbol}");
|
||||
}
|
||||
if (symbolChanged.NewSymbol != "QQQ")
|
||||
{
|
||||
throw new RegressionTestException($"New QQQ Symbol is not QQQ. Instead, found: {symbolChanged.NewSymbol}");
|
||||
}
|
||||
|
||||
_mappingEventOccurred = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (slice.Keys.Count == 1 && slice.ContainsKey(_qqq))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_constituentDataEncountered.ContainsKey(UtcTime.Date))
|
||||
{
|
||||
_constituentDataEncountered[UtcTime.Date] = false;
|
||||
}
|
||||
|
||||
if (_constituentSymbols.Intersect(slice.Keys).Any())
|
||||
{
|
||||
_constituentDataEncountered[UtcTime.Date] = true;
|
||||
}
|
||||
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
SetHoldings(_aapl, 0.5m);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (_filterDateConstituentSymbolCount.Count != 2)
|
||||
{
|
||||
throw new RegressionTestException($"ETF constituent filtering function was not called 2 times (actual: {_filterDateConstituentSymbolCount.Count}");
|
||||
}
|
||||
if (!_mappingEventOccurred)
|
||||
{
|
||||
throw new RegressionTestException("No mapping/SymbolChangedEvent occurred. Expected for QQQ to be mapped from QQQQ -> QQQ");
|
||||
}
|
||||
|
||||
foreach (var kvp in _filterDateConstituentSymbolCount)
|
||||
{
|
||||
if (kvp.Value < 25)
|
||||
{
|
||||
throw new RegressionTestException($"Expected 25 or more constituents in filter function on {kvp.Key:yyyy-MM-dd HH:mm:ss.fff}, found {kvp.Value}");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var kvp in _constituentDataEncountered)
|
||||
{
|
||||
if (!kvp.Value)
|
||||
{
|
||||
throw new RegressionTestException($"Received data in OnData(...) but it did not contain any constituent data on {kvp.Key:yyyy-MM-dd HH:mm:ss.fff}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 => 751;
|
||||
|
||||
/// <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", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "-9.739%"},
|
||||
{"Drawdown", "4.200%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Start Equity", "100000"},
|
||||
{"End Equity", "98257.31"},
|
||||
{"Net Profit", "-1.743%"},
|
||||
{"Sharpe Ratio", "-0.95"},
|
||||
{"Sortino Ratio", "-0.832"},
|
||||
{"Probabilistic Sharpe Ratio", "15.715%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.118"},
|
||||
{"Beta", "0.445"},
|
||||
{"Annual Standard Deviation", "0.078"},
|
||||
{"Annual Variance", "0.006"},
|
||||
{"Information Ratio", "-2.01"},
|
||||
{"Tracking Error", "0.086"},
|
||||
{"Treynor Ratio", "-0.166"},
|
||||
{"Total Fees", "$22.93"},
|
||||
{"Estimated Strategy Capacity", "$74000000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
|
||||
{"Portfolio Turnover", "0.80%"},
|
||||
{"Drawdown Recovery", "2"},
|
||||
{"OrderListHash", "0737aa7f8928927464e9068b1d500e7f"}
|
||||
};
|
||||
}
|
||||
}
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Algorithm.Framework.Alphas;
|
||||
using QuantConnect.Algorithm.Framework.Execution;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Example algorithm demonstrating the usage of the RSI indicator
|
||||
/// in combination with ETF constituents data to replicate the weighting
|
||||
/// of the ETF's assets in our own account.
|
||||
/// </summary>
|
||||
public class ETFConstituentUniverseRSIAlphaModelAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
/// <summary>
|
||||
/// Initialize the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 12, 1);
|
||||
SetEndDate(2021, 1, 31);
|
||||
SetCash(100000);
|
||||
|
||||
SetAlpha(new ConstituentWeightedRsiAlphaModel());
|
||||
SetPortfolioConstruction(new InsightWeightingPortfolioConstructionModel());
|
||||
SetExecution(new ImmediateExecutionModel());
|
||||
|
||||
var spy = AddEquity("SPY", Resolution.Hour).Symbol;
|
||||
|
||||
// We load hourly data for ETF constituents in this algorithm
|
||||
UniverseSettings.Resolution = Resolution.Hour;
|
||||
Settings.MinimumOrderMarginPortfolioPercentage = 0.01m;
|
||||
|
||||
AddUniverse(Universe.ETF(spy, UniverseSettings, FilterETFConstituents));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Filters ETF constituents and adds the resulting Symbols to the ETF constituent universe
|
||||
/// </summary>
|
||||
/// <param name="constituents">ETF constituents, i.e. the components of the ETF and their weighting</param>
|
||||
/// <returns>Symbols to add to universe</returns>
|
||||
public IEnumerable<Symbol> FilterETFConstituents(IEnumerable<ETFConstituentUniverse> constituents)
|
||||
{
|
||||
return constituents
|
||||
.Where(x => x.Weight != null && x.Weight >= 0.001m)
|
||||
.Select(x => x.Symbol);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Alpha model making use of the RSI indicator and ETF constituent weighting to determine
|
||||
/// which assets we should invest in and the direction of investment
|
||||
/// </summary>
|
||||
private class ConstituentWeightedRsiAlphaModel : AlphaModel
|
||||
{
|
||||
private Dictionary<Symbol, SymbolData> _rsiSymbolData = new Dictionary<Symbol, SymbolData>();
|
||||
|
||||
/// <summary>
|
||||
/// Receives new data and emits new <see cref="Insight"/> instances
|
||||
/// </summary>
|
||||
/// <param name="algorithm">Algorithm</param>
|
||||
/// <param name="data">Current data</param>
|
||||
/// <returns>Enumerable of insights for assets to invest with a specific weight</returns>
|
||||
public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
|
||||
{
|
||||
// Cast first, and then access the constituents collection defined in our algorithm.
|
||||
var algoConstituents = data.Bars.Keys
|
||||
.Where(x => algorithm.Securities[x].Cache.HasData(typeof(ETFConstituentUniverse)))
|
||||
.Select(x => algorithm.Securities[x].Cache.GetData<ETFConstituentUniverse>())
|
||||
.ToList();
|
||||
|
||||
if (algoConstituents.Count == 0 || data.Bars.Count == 0)
|
||||
{
|
||||
// Don't do anything if we have no data we can work with
|
||||
yield break;
|
||||
}
|
||||
|
||||
var constituents = algoConstituents
|
||||
.ToDictionary(x => x.Symbol, x => x);
|
||||
|
||||
foreach (var bar in data.Bars.Values)
|
||||
{
|
||||
if (!constituents.ContainsKey(bar.Symbol))
|
||||
{
|
||||
// Dealing with a manually added equity, which in this case is SPY
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!_rsiSymbolData.ContainsKey(bar.Symbol))
|
||||
{
|
||||
// First time we're initializing the RSI.
|
||||
// It won't be ready now, but it will be
|
||||
// after 7 data points.
|
||||
var constituent = constituents[bar.Symbol];
|
||||
_rsiSymbolData[bar.Symbol] = new SymbolData(bar.Symbol, algorithm, constituent, 7);
|
||||
}
|
||||
}
|
||||
|
||||
// Let's make sure all RSI indicators are ready before we emit any insights.
|
||||
var allReady = _rsiSymbolData.All(kvp => kvp.Value.Rsi.IsReady);
|
||||
if (!allReady)
|
||||
{
|
||||
// We're still warming up the RSI indicators.
|
||||
yield break;
|
||||
}
|
||||
|
||||
foreach (var kvp in _rsiSymbolData)
|
||||
{
|
||||
var symbol = kvp.Key;
|
||||
var symbolData = kvp.Value;
|
||||
|
||||
var averageLoss = symbolData.Rsi.AverageLoss.Current.Value;
|
||||
var averageGain = symbolData.Rsi.AverageGain.Current.Value;
|
||||
|
||||
// If we've lost more than gained, then we think it's going to go down more
|
||||
var direction = averageLoss > averageGain
|
||||
? InsightDirection.Down
|
||||
: InsightDirection.Up;
|
||||
|
||||
// Set the weight of the insight as the weight of the ETF's
|
||||
// holding. The InsightWeightingPortfolioConstructionModel
|
||||
// will rebalance our portfolio to have the same percentage
|
||||
// of holdings in our algorithm that the ETF has.
|
||||
yield return Insight.Price(
|
||||
symbol,
|
||||
TimeSpan.FromDays(1),
|
||||
direction,
|
||||
(double)(direction == InsightDirection.Down
|
||||
? averageLoss
|
||||
: averageGain),
|
||||
weight: (double?) symbolData.Constituent.Weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper class to access ETF constituent data and RSI indicators
|
||||
/// for a single Symbol
|
||||
/// </summary>
|
||||
private class SymbolData
|
||||
{
|
||||
/// <summary>
|
||||
/// Symbol this data belongs to
|
||||
/// </summary>
|
||||
public Symbol Symbol { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Symbol's constituent data for the ETF it belongs to
|
||||
/// </summary>
|
||||
public ETFConstituentUniverse Constituent { get; }
|
||||
|
||||
/// <summary>
|
||||
/// RSI indicator for the Symbol's price data
|
||||
/// </summary>
|
||||
public RelativeStrengthIndex Rsi { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of SymbolData
|
||||
/// </summary>
|
||||
/// <param name="symbol">The symbol to add data for</param>
|
||||
/// <param name="constituent">ETF constituent data</param>
|
||||
/// <param name="period">RSI period</param>
|
||||
public SymbolData(Symbol symbol, QCAlgorithm algorithm, ETFConstituentUniverse constituent, int period)
|
||||
{
|
||||
Symbol = symbol;
|
||||
Constituent = constituent;
|
||||
Rsi = algorithm.RSI(symbol, period, MovingAverageType.Exponential, Resolution.Hour);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 => 2722;
|
||||
|
||||
/// <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", "55"},
|
||||
{"Average Win", "0.09%"},
|
||||
{"Average Loss", "-0.05%"},
|
||||
{"Compounding Annual Return", "3.321%"},
|
||||
{"Drawdown", "0.500%"},
|
||||
{"Expectancy", "0.047"},
|
||||
{"Start Equity", "100000"},
|
||||
{"End Equity", "100535.45"},
|
||||
{"Net Profit", "0.535%"},
|
||||
{"Sharpe Ratio", "1.377"},
|
||||
{"Sortino Ratio", "1.963"},
|
||||
{"Probabilistic Sharpe Ratio", "56.920%"},
|
||||
{"Loss Rate", "63%"},
|
||||
{"Win Rate", "37%"},
|
||||
{"Profit-Loss Ratio", "1.83"},
|
||||
{"Alpha", "0.022"},
|
||||
{"Beta", "-0.024"},
|
||||
{"Annual Standard Deviation", "0.015"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.46"},
|
||||
{"Tracking Error", "0.109"},
|
||||
{"Treynor Ratio", "-0.878"},
|
||||
{"Total Fees", "$55.00"},
|
||||
{"Estimated Strategy Capacity", "$440000000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
|
||||
{"Portfolio Turnover", "11.16%"},
|
||||
{"Drawdown Recovery", "19"},
|
||||
{"OrderListHash", "8a25d215ea8cd5781953695e8ae93e56"}
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user