Skip to content

Commit

Permalink
Daily data time adjustment (QuantConnect#8001)
Browse files Browse the repository at this point in the history
* Daily data Time & EndTime Improvement

- Adjust daily data Time & EndTime to actually reflect the time of the
  data used, for example US Equity from 9.30 to 4PM. Adding new unit and
  regression tests

* Refactor solution to use enumerator

- Refactor daily strict end times solution to be through enumerator
  usage, so it applies for history providers too

* Minor fixes

* Revert fill forward enumerator change

- Revert FillForward enumerator causing stats changing, enhancing unit
  tests

* Some cleanup

* Improve handling of live trading FF enumerator

- Improve handling of live trading FF enumerator, by adding support for
  bars to arrive with a delay so we can handle auction close/option
  prices or data providers which might have some delay making the data
  available. Adding new unit tests asserting the behavior
  • Loading branch information
Martin-Molinero authored May 20, 2024
1 parent c30ea9d commit d4e7f58
Show file tree
Hide file tree
Showing 83 changed files with 2,205 additions and 486 deletions.
2 changes: 2 additions & 0 deletions Algorithm.CSharp/BasicTemplateIndexAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ public override void Initialize()

_emaSlow = EMA(Spx, 80);
_emaFast = EMA(Spx, 200);

Settings.DailyStrictEndTimeEnabled = true;
}

/// <summary>
Expand Down
66 changes: 48 additions & 18 deletions Algorithm.CSharp/BasicTemplateIndexDailyAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
*/

using System;
using System.Linq;
using QuantConnect.Data;
using System.Collections.Generic;
using QuantConnect.Data.Market;

namespace QuantConnect.Algorithm.CSharp
{
Expand Down Expand Up @@ -60,6 +62,34 @@ public override void OnEndOfAlgorithm()
{
throw new ArgumentException($"Bar Count {BarCounter} is not expected count of {ExpectedBarCount}");
}

if (Resolution != Resolution.Daily)
{
return;
}

var openInterest = Securities[SpxOption].Cache.GetAll<OpenInterest>();
if (openInterest.Single().EndTime != new DateTime(2021, 1, 15, 23, 0, 0))
{
throw new ArgumentException($"Unexpected open interest time: {openInterest.Single().EndTime}");
}

foreach (var symbol in new[] { SpxOption, Spx })
{
var history = History(symbol, 10).ToList();
if (history.Count != 10)
{
throw new Exception($"Unexpected history count: {history.Count}");
}
if (history.Any(x => x.Time.TimeOfDay != new TimeSpan(8, 30, 0)))
{
throw new Exception($"Unexpected history data start time");
}
if (history.Any(x => x.EndTime.TimeOfDay != new TimeSpan(15, 15, 0)))
{
throw new Exception($"Unexpected history data end time");
}
}
}

/// <summary>
Expand All @@ -70,7 +100,7 @@ public override void OnEndOfAlgorithm()
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override Language[] Languages { get; } = { Language.CSharp };
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };

/// <summary>
/// Data Points count of all timeslices of algorithm
Expand All @@ -80,40 +110,40 @@ public override void OnEndOfAlgorithm()
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 0;
public override int AlgorithmHistoryDataPoints => 30;

/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "4"},
{"Total Orders", "11"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Compounding Annual Return", "621.484%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000000"},
{"End Equity", "1000000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"End Equity", "1084600"},
{"Net Profit", "8.460%"},
{"Sharpe Ratio", "9.923"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Probabilistic Sharpe Ratio", "93.682%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.847"},
{"Tracking Error", "0.107"},
{"Treynor Ratio", "0"},
{"Alpha", "3.61"},
{"Beta", "-0.513"},
{"Annual Standard Deviation", "0.359"},
{"Annual Variance", "0.129"},
{"Information Ratio", "8.836"},
{"Tracking Error", "0.392"},
{"Treynor Ratio", "-6.937"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"OrderListHash", "3206cd506281be4ea0d0c6c193aea731"}
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
{"Portfolio Turnover", "2.42%"},
{"OrderListHash", "61e8517ac3da6bed414ef23d26736fef"}
};
}
}
2 changes: 2 additions & 0 deletions Algorithm.CSharp/BasicTemplateIndexOptionsAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ public override void Initialize()

_emaSlow = EMA(_spx, 80);
_emaFast = EMA(_spx, 200);

Settings.DailyStrictEndTimeEnabled = true;
}

/// <summary>
Expand Down
36 changes: 18 additions & 18 deletions Algorithm.CSharp/BasicTemplateIndexOptionsDailyAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public override void OnData(Slice slice)
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 168;
public override long DataPoints => 378;

/// <summary>
/// Data Points count of the algorithm history
Expand All @@ -79,33 +79,33 @@ public override void OnData(Slice slice)
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "0"},
{"Total Orders", "11"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-0.092%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Start Equity", "1000000"},
{"End Equity", "1000000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"End Equity", "999920"},
{"Net Profit", "-0.008%"},
{"Sharpe Ratio", "-19.865"},
{"Sortino Ratio", "-175397.15"},
{"Probabilistic Sharpe Ratio", "0.013%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Alpha", "-0.003"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.449"},
{"Information Ratio", "-0.454"},
{"Tracking Error", "0.138"},
{"Treynor Ratio", "0"},
{"Treynor Ratio", "-44.954"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
{"Lowest Capacity Asset", "SPX XL80P59H5E6M|SPX 31"},
{"Portfolio Turnover", "0.00%"},
{"OrderListHash", "285cec32c0947f0e8cf90ccb672cfa43"}
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* 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;

namespace QuantConnect.Algorithm.CSharp
{
public class FillForwardStrictEndTimeDailyRegressionAlgorithm : FillForwardStrictEndTimeHourRegressionAlgorithm
{
protected override int StartDate => 1;
protected override Resolution FillForwardResolution => Resolution.Daily;

/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 100;

/// </summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 0;

/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override 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.878"},
{"Tracking Error", "0.111"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}
135 changes: 135 additions & 0 deletions Algorithm.CSharp/FillForwardStrictEndTimeHourRegressionAlgorithm.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*
* 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.Text;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using System.Collections.Generic;

namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting the behavior of fill forward when using daily strict end times
/// </summary>
public class FillForwardStrictEndTimeHourRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private readonly bool _updateExpectedData = false;
private readonly StringBuilder _data = new();

protected virtual string ExpectedDataFile => $"../../TestData/{GetType().Name}.zip";
protected virtual int StartDate => 4;
protected virtual Resolution FillForwardResolution => Resolution.Hour;

/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
public override void Initialize()
{
SetStartDate(2021, 1, StartDate);
SetEndDate(2021, 1, 15);

AddIndex("SPX", Resolution.Daily);
AddEquity("SPY", FillForwardResolution);

Settings.DailyStrictEndTimeEnabled = true;
}

/// <summary>
/// Index EMA Cross trading index options of the index.
/// </summary>
public override void OnData(Slice data)
{
if (data.ContainsKey("SPX"))
{
var spxData = data.Bars["SPX"];
var message = $"{Time} ==== FF {spxData.IsFillForward}. {spxData} {spxData.Time:HH:mm:ss}->{spxData.EndTime:HH:mm:ss}";
_data.AppendLine(message);
Debug(message);
}
}

public override void OnEndOfAlgorithm()
{
var data = _data.ToString();
if (_updateExpectedData)
{
Compression.ZipData(ExpectedDataFile, new Dictionary<string, string>() { { "zip_entry_name.txt", data } });
return;
}

var expected = string.Join(';', Compression.ReadLines(ExpectedDataFile)).ReplaceLineEndings("");
if (expected != data.ReplaceLineEndings(";").RemoveFromEnd(";"))
{
throw new Exception($"Unexpected data: \"{data}\"{Environment.NewLine}Expected: \"{expected}\"");
}
}

/// <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 Language[] Languages { get; } = { Language.CSharp };

/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 222;

/// </summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;

/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public virtual 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", "-5.208"},
{"Tracking Error", "0.103"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}
Loading

0 comments on commit d4e7f58

Please sign in to comment.