/*
* 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.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
///
/// Regression algorithm asserting that the security cache open interest is set from the chain universe data open interest
///
public class OptionUniverseOpenInterestRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
///
/// The number of times the open interest was successfully asserted against the chain universe data
///
protected int AssertionCount { get; private set; }
public override void Initialize()
{
SetStartDate(2015, 12, 24);
SetEndDate(2015, 12, 24);
SetCash(100000);
AddEquity("GOOG");
var option = AddOption("GOOG");
option.SetFilter(universe => universe.Contracts(contracts => contracts.Where(x => x.OpenInterest != 0).Take(10)));
}
///
/// Gets the chain universe data point stored in the given security cache if any
///
protected virtual BaseChainUniverseData GetChainUniverseData(Security security)
{
return security.Cache.GetData();
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
// The securities are added in the same time slice as the chain universe data that selected them,
// which the algorithm manager stores in the security cache before any user code is called,
// so the cache open interest must already be set here
foreach (var security in changes.AddedSecurities)
{
AssertOpenInterest(security, checkOpenInterestTick: false);
}
}
public override void OnData(Slice slice)
{
foreach (var security in Securities.Values)
{
AssertOpenInterest(security, checkOpenInterestTick: true);
}
}
private void AssertOpenInterest(Security security, bool checkOpenInterestTick)
{
var securityType = security.Symbol.SecurityType;
if (security.Symbol.IsCanonical() || !securityType.IsOption() && securityType != SecurityType.Future)
{
return;
}
var chainUniverseData = GetChainUniverseData(security);
if (chainUniverseData == null || chainUniverseData.OpenInterest == 0)
{
return;
}
// If a more recent open interest tick was received from the data feed, the cache will reflect it instead
if (checkOpenInterestTick)
{
var lastOpenInterestTick = security.Cache.GetData();
if (lastOpenInterestTick != null && lastOpenInterestTick.EndTime > chainUniverseData.EndTime)
{
return;
}
}
var expectedOpenInterest = (long)chainUniverseData.OpenInterest;
if (security.Cache.OpenInterest != expectedOpenInterest)
{
throw new RegressionTestException($"Unexpected open interest value for {security.Symbol}. " +
$"Expected {expectedOpenInterest} from the chain universe data but found {security.Cache.OpenInterest}");
}
AssertionCount++;
}
public override void OnEndOfAlgorithm()
{
if (AssertionCount == 0)
{
throw new RegressionTestException("The security cache open interest was never set from the chain universe data.");
}
Log($"Open interest was asserted {AssertionCount} times against the chain universe data");
}
///
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
///
public virtual bool CanRunLocally { get; } = true;
///
/// This is used by the regression test system to indicate which languages this algorithm is written in.
///
public virtual List Languages { get; } = new() { Language.CSharp };
///
/// Data Points count of all timeslices of algorithm
///
public virtual long DataPoints => 8886;
///
/// Data Points count of the algorithm history
///
public virtual int AlgorithmHistoryDataPoints => 0;
///
/// Final status of the algorithm
///
public virtual AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
///
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
///
public virtual Dictionary ExpectedStatistics => new Dictionary
{
{"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"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}