Compare commits

..

4 Commits
16632 ... 15880

Author SHA1 Message Date
Martin Molinero
5b0405830c Minor coarse fundamental adjustment 2023-09-29 18:41:23 -03:00
Martin Molinero
14a02afd70 Handle live mode & delete unexisting properties 2023-09-29 11:12:53 -03:00
Martin Molinero
dfe706d8e8 Minor CIK lookup fix 2023-09-27 15:15:04 -03:00
Martin Molinero
a5d1011fe1 New Fundamental Data 2023-09-27 15:15:04 -03:00
3263 changed files with 60956 additions and 286342 deletions

View File

@@ -1,30 +0,0 @@
name: API Tests
on:
push:
branches: ['*']
tags: ['*']
pull_request:
branches: [master]
jobs:
build:
runs-on: ubuntu-20.04
# Only run on push events (not on pull_request) for security reasons in order to be able to use secrets
if: ${{ github.event_name == 'push' }}
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Free space
run: df -h && rm -rf /usr/share/dotnet && sudo rm -rf /usr/local/lib/android && sudo rm -rf /opt/ghc && rm -rf /opt/hostedtoolcache* && df -h
- name: Run API Tests
uses: addnab/docker-run-action@v3
with:
image: quantconnect/lean:foundation
options: --workdir /__w/Lean/Lean -v /home/runner/work:/__w -e GITHUB_REF=${{ github.ref }} -e QC_JOB_USER_ID=${{ secrets.QC_JOB_USER_ID }} -e QC_API_ACCESS_TOKEN=${{ secrets.QC_API_ACCESS_TOKEN }} -e QC_JOB_ORGANIZATION_ID=${{ secrets.QC_JOB_ORGANIZATION_ID }}
shell: bash
run: |
# Build
dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
# Run Projects tests
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --blame-hang-timeout 300seconds --blame-crash --filter "FullyQualifiedName=QuantConnect.Tests.API.ProjectTests|ObjectStoreTests" -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\)

View File

@@ -14,7 +14,7 @@ jobs:
- name: Checkout
uses: actions/checkout@v2
- name: Free space
run: df -h && rm -rf /usr/share/dotnet && sudo rm -rf /usr/local/lib/android && sudo rm -rf /opt/ghc && rm -rf /opt/hostedtoolcache* && df -h
run: df -h && rm -rf /opt/hostedtoolcache* && df -h
- uses: addnab/docker-run-action@v3
with:
@@ -27,4 +27,4 @@ jobs:
# Run Tests
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --blame-hang-timeout 300seconds --blame-crash --filter "TestCategory!=TravisExclude&TestCategory!=ResearchRegressionTests" -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\) && \
# Generate & Publish python stubs
echo "GITHUB_REF $GITHUB_REF" && if [[ $GITHUB_REF = refs/tags/* ]]; then (chmod +x ci_build_stubs.sh && ./ci_build_stubs.sh -t -g -p); else echo "Skipping stub generation"; fi
echo "GITHUB_REF $GITHUB_REF" && if [[ $GITHUB_REF = refs/tags/* ]]; then (chmod +x ci_build_stubs.sh && ./ci_build_stubs.sh -t -g -p); else echo "Skipping stub generation"; fi

View File

@@ -14,7 +14,7 @@ jobs:
- name: Checkout
uses: actions/checkout@v2
- name: Free space
run: df -h && rm -rf /usr/share/dotnet && sudo rm -rf /usr/local/lib/android && sudo rm -rf /opt/ghc && rm -rf /opt/hostedtoolcache* && df -h
run: df -h && rm -rf /opt/hostedtoolcache* && df -h
- uses: addnab/docker-run-action@v3
with:

View File

@@ -1,30 +0,0 @@
name: Report Generator Tests
on:
push:
branches: ['*']
tags: ['*']
pull_request:
branches: [master]
jobs:
build:
runs-on: ubuntu-20.04
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Free space
run: df -h && rm -rf /usr/share/dotnet && sudo rm -rf /usr/local/lib/android && sudo rm -rf /opt/ghc && rm -rf /opt/hostedtoolcache* && df -h
- uses: addnab/docker-run-action@v3
with:
image: quantconnect/lean:foundation
options: --workdir /__w/Lean/Lean -v /home/runner/work:/__w
shell: bash
run: |
# Build
dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
# Run Backtest
cd ./Launcher/bin/Release && dotnet QuantConnect.Lean.Launcher.dll && cd ../../../
# Run Report
cd ./Report/bin/Release && dotnet ./QuantConnect.Report.dll --backtest-data-source-file ../../../Launcher/bin/Release/BasicTemplateFrameworkAlgorithm.json --close-automatically true

View File

@@ -14,7 +14,7 @@ jobs:
- name: Checkout
uses: actions/checkout@v2
- name: Free space
run: df -h && rm -rf /usr/share/dotnet && sudo rm -rf /usr/local/lib/android && sudo rm -rf /opt/ghc && rm -rf /opt/hostedtoolcache* && df -h
run: df -h && rm -rf /opt/hostedtoolcache* && df -h
- uses: addnab/docker-run-action@v3
with:

View File

@@ -14,7 +14,7 @@ jobs:
- name: Checkout
uses: actions/checkout@v2
- name: Free space
run: df -h && rm -rf /usr/share/dotnet && sudo rm -rf /usr/local/lib/android && sudo rm -rf /opt/ghc && rm -rf /opt/hostedtoolcache* && df -h
run: df -h && rm -rf /opt/hostedtoolcache* && df -h
- uses: addnab/docker-run-action@v3
with:
@@ -23,35 +23,40 @@ jobs:
shell: bash
run: |
# Build
dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln && \
dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
# Python Virtual Environment System Packages
python -m venv /lean-testenv --system-site-packages && . /lean-testenv/bin/activate && pip install --no-cache-dir lean==1.0.185 && deactivate && \
python -m venv /lean-testenv --system-site-packages && . /lean-testenv/bin/activate && pip install --no-cache-dir lean==1.0.99 && deactivate
# Run Virtual Environment Test System Packages
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonVirtualEnvironmentTests.AssertVirtualEnvironment" && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonVirtualEnvironmentTests.AssertVirtualEnvironment"
# Python Virtual Environment
rm -rf /lean-testenv && python -m venv /lean-testenv && . /lean-testenv/bin/activate && pip install --no-cache-dir lean==1.0.185 && deactivate && \
rm -rf /lean-testenv && python -m venv /lean-testenv && . /lean-testenv/bin/activate && pip install --no-cache-dir lean==1.0.99 && deactivate
# Run Virtual Environment Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonVirtualEnvironmentTests.AssertVirtualEnvironment" && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonVirtualEnvironmentTests.AssertVirtualEnvironment"
# Run Python Package Tests
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests" --blame-hang-timeout 120seconds --blame-crash
# Run Pomegranate & Neuralprophet Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.PomegranateTest|Neuralprophet" --blame-hang-timeout 120seconds --blame-crash
# Run StableBaselines Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.StableBaselinesTest" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.StableBaselinesTest" --blame-hang-timeout 120seconds --blame-crash
# Run AxPlatform Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.AxPlatformTest" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.AxPlatformTest" --blame-hang-timeout 120seconds --blame-crash
# Run NBeats Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.NBeatsTest" --blame-hang-timeout 120seconds --blame-crash
# Run TensorlyTest Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorlyTest" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorlyTest" --blame-hang-timeout 120seconds --blame-crash
# Run NeuralTangents, Ignite Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.NeuralTangentsTest|IgniteTest" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.NeuralTangentsTest|IgniteTest" --blame-hang-timeout 120seconds --blame-crash
# Run TensorflowTest
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorflowTest" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorflowTest" --blame-hang-timeout 120seconds --blame-crash
# Run TensorflowProbability
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorflowProbabilityTest" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorflowProbabilityTest" --blame-hang-timeout 120seconds --blame-crash
# Run Hvplot Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.HvplotTest" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.HvplotTest" --blame-hang-timeout 120seconds --blame-crash
# Run Stellargraph Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.StellargraphTest" --blame-hang-timeout 120seconds --blame-crash
# Run Keras Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.KerasTest" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.KerasTest" --blame-hang-timeout 120seconds --blame-crash
# Run Scikeras Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.ScikerasTest" --blame-hang-timeout 120seconds --blame-crash
# Run Transformers
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.Transformers" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.XTransformers" --blame-hang-timeout 120seconds --blame-crash && \
# Run Shap
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.ShapTest" --blame-hang-timeout 120seconds --blame-crash
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.Transformers" --blame-hang-timeout 120seconds --blame-crash

3
.gitignore vendored
View File

@@ -1,6 +1,3 @@
# OS Files
.DS_Store
# Object files
*.o
*.ko

View File

@@ -55,7 +55,7 @@ namespace QuantConnect.Algorithm.CSharp
||
Portfolio.TotalHoldingsValue < Portfolio.TotalPortfolioValue * 0.01m)
{
throw new RegressionTestException($"Unexpected Total Holdings Value: {Portfolio.TotalHoldingsValue}");
throw new Exception($"Unexpected Total Holdings Value: {Portfolio.TotalHoldingsValue}");
}
}
@@ -67,7 +67,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -79,43 +79,35 @@ namespace QuantConnect.Algorithm.CSharp
/// </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", "199"},
{"Total Trades", "199"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-12.611%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-0.585"},
{"Start Equity", "100000"},
{"End Equity", "99827.80"},
{"Net Profit", "-0.172%"},
{"Sharpe Ratio", "-11.13"},
{"Sortino Ratio", "-16.704"},
{"Sharpe Ratio", "-10.169"},
{"Probabilistic Sharpe Ratio", "12.075%"},
{"Loss Rate", "78%"},
{"Win Rate", "22%"},
{"Profit-Loss Ratio", "0.87"},
{"Alpha", "-0.156"},
{"Alpha", "-0.149"},
{"Beta", "0.035"},
{"Annual Standard Deviation", "0.008"},
{"Annual Variance", "0"},
{"Information Ratio", "-9.603"},
{"Tracking Error", "0.215"},
{"Treynor Ratio", "-2.478"},
{"Treynor Ratio", "-2.264"},
{"Total Fees", "$199.00"},
{"Estimated Strategy Capacity", "$26000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "119.89%"},
{"OrderListHash", "d06c26f557b83d8d42ac808fe2815a1e"}
{"OrderListHash", "3c4c4085810cc5ecdb927d3647b9bbf3"}
};
}
}

View File

@@ -66,7 +66,7 @@ namespace QuantConnect.Algorithm.CSharp
|| insightsCollection.Insights.Count(insight => insight.Symbol == _spy) != 1
|| insightsCollection.Insights.Count(insight => insight.Symbol == _ibm) != 1)
{
throw new RegressionTestException("Unexpected insights were emitted");
throw new Exception("Unexpected insights were emitted");
}
}
@@ -103,7 +103,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -115,43 +115,35 @@ namespace QuantConnect.Algorithm.CSharp
/// </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", "9"},
{"Total Trades", "9"},
{"Average Win", "0.86%"},
{"Average Loss", "-0.27%"},
{"Compounding Annual Return", "206.404%"},
{"Compounding Annual Return", "184.364%"},
{"Drawdown", "1.700%"},
{"Expectancy", "1.781"},
{"Start Equity", "100000"},
{"End Equity", "101441.92"},
{"Net Profit", "1.442%"},
{"Sharpe Ratio", "4.836"},
{"Sortino Ratio", "10.481"},
{"Sharpe Ratio", "4.86"},
{"Probabilistic Sharpe Ratio", "59.497%"},
{"Loss Rate", "33%"},
{"Win Rate", "67%"},
{"Profit-Loss Ratio", "3.17"},
{"Alpha", "4.164"},
{"Alpha", "4.181"},
{"Beta", "-1.322"},
{"Annual Standard Deviation", "0.321"},
{"Annual Variance", "0.103"},
{"Information Ratio", "-0.795"},
{"Tracking Error", "0.532"},
{"Treynor Ratio", "-1.174"},
{"Treynor Ratio", "-1.18"},
{"Total Fees", "$14.78"},
{"Estimated Strategy Capacity", "$120000000.00"},
{"Estimated Strategy Capacity", "$47000000.00"},
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
{"Portfolio Turnover", "41.18%"},
{"OrderListHash", "713c956deb193bed2290e9f379c0f9f9"}
{"OrderListHash", "9da9afe1e9137638a55db1676adc2be1"}
};
}
}

View File

@@ -40,8 +40,8 @@ namespace QuantConnect.Algorithm.CSharp
var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
_contract = OptionChain(aapl)
.OrderBy(x => x.ID.Symbol)
_contract = OptionChainProvider.GetOptionContractList(aapl, Time)
.OrderBy(symbol => symbol.ID.Symbol)
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American);
AddOptionContract(_contract);
@@ -59,7 +59,7 @@ namespace QuantConnect.Algorithm.CSharp
}
else
{
throw new RegressionTestException("Expect a single call to OnData where we removed the option and underlying");
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
}
}
}
@@ -68,7 +68,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!_hasRemoved)
{
throw new RegressionTestException("Expect a single call to OnData where we removed the option and underlying");
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
}
}
@@ -80,7 +80,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -90,29 +90,21 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 1;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
public 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 Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "0"},
{"Total Trades", "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%"},

View File

@@ -39,8 +39,8 @@ namespace QuantConnect.Algorithm.CSharp
var aapl = AddEquity("AAPL").Symbol;
_contract = OptionChain(aapl)
.OrderBy(x => x.ID.Symbol)
_contract = OptionChainProvider.GetOptionContractList(aapl, Time)
.OrderBy(symbol => symbol.ID.Symbol)
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American);
}
@@ -49,7 +49,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (_hasRemoved)
{
throw new RegressionTestException("Expect a single call to OnData where we removed the option and underlying");
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
}
_hasRemoved = true;
@@ -65,7 +65,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!_hasRemoved)
{
throw new RegressionTestException("We did not remove the option contract!");
throw new Exception("We did not remove the option contract!");
}
}
@@ -77,7 +77,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -87,29 +87,21 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 1;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
public 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 Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "0"},
{"Total Trades", "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%"},

View File

@@ -47,15 +47,15 @@ namespace QuantConnect.Algorithm.CSharp
if (!_beta.IsReady)
{
throw new RegressionTestException("_beta indicator was expected to be ready");
throw new Exception("_beta indicator was expected to be ready");
}
}
public override void OnData(Slice slice)
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
var price = slice["IBM"].Close;
var price = data["IBM"].Close;
Buy("IBM", 10);
LimitOrder("IBM", 10, price * 0.1m);
StopMarketOrder("IBM", 10, price / 0.1m);
@@ -63,7 +63,7 @@ namespace QuantConnect.Algorithm.CSharp
if (_beta.Current.Value < 0m || _beta.Current.Value > 2.80m)
{
throw new RegressionTestException($"_beta value was expected to be between 0 and 2.80 but was {_beta.Current.Value}");
throw new Exception($"_beta value was expected to be between 0 and 2.80 but was {_beta.Current.Value}");
}
Log($"Beta between IBM and SPY is: {_beta.Current.Value}");
@@ -97,7 +97,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual Language[] Languages { get; } = { Language.CSharp};
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -109,43 +109,35 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 11;
/// <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"},
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "12.939%"},
{"Drawdown", "0.300%"},
{"Expectancy", "0"},
{"Start Equity", "10000"},
{"End Equity", "10028.93"},
{"Net Profit", "0.289%"},
{"Sharpe Ratio", "3.924"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "4.233"},
{"Probabilistic Sharpe Ratio", "68.349%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.028"},
{"Alpha", "0.035"},
{"Beta", "0.122"},
{"Annual Standard Deviation", "0.024"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-3.181"},
{"Tracking Error", "0.142"},
{"Treynor Ratio", "0.78"},
{"Treynor Ratio", "0.842"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$35000000.00"},
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
{"Portfolio Turnover", "1.51%"},
{"OrderListHash", "1db1ce949db995bba20ed96ea5e2438a"}
{"OrderListHash", "bd88c6a0e10c7e146b05377205101a12"}
};
}
}

View File

@@ -31,6 +31,7 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public class AddFutureContractWithContinuousRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _currentMappedSymbol;
private Future _continuousContract;
private Future _futureContract;
private bool _ended;
@@ -55,20 +56,20 @@ namespace QuantConnect.Algorithm.CSharp
/// <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)
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (_ended)
{
throw new RegressionTestException($"Algorithm should of ended!");
throw new Exception($"Algorithm should of ended!");
}
if (slice.Keys.Count > 2)
if (data.Keys.Count > 2)
{
throw new RegressionTestException($"Getting data for more than 2 symbols! {string.Join(",", slice.Keys.Select(symbol => symbol))}");
throw new Exception($"Getting data for more than 2 symbols! {string.Join(",", data.Keys.Select(symbol => symbol))}");
}
if (UniverseManager.Count != 3)
{
throw new RegressionTestException($"Expecting 3 universes (chain, continuous and user defined) but have {UniverseManager.Count}");
throw new Exception($"Expecting 3 universes (chain, continuous and user defined) but have {UniverseManager.Count}");
}
if (!Portfolio.Invested)
@@ -98,7 +99,7 @@ namespace QuantConnect.Algorithm.CSharp
if (changes.AddedSecurities.Any(security => security.Symbol != _continuousContract.Symbol && security.Symbol != _futureContract.Symbol)
|| changes.RemovedSecurities.Any(security => security.Symbol != _continuousContract.Symbol && security.Symbol != _futureContract.Symbol))
{
throw new RegressionTestException($"We got an unexpected security changes {changes}");
throw new Exception($"We got an unexpected security changes {changes}");
}
}
@@ -110,55 +111,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 73;
public long DataPoints => 63;
/// <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", "3"},
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "-0.03%"},
{"Compounding Annual Return", "-2.594%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "99966.4"},
{"Net Profit", "-0.034%"},
{"Sharpe Ratio", "-10.666"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "-7.854"},
{"Probabilistic Sharpe Ratio", "1.216%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.029"},
{"Alpha", "-0.022"},
{"Beta", "0.004"},
{"Annual Standard Deviation", "0.003"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.768"},
{"Tracking Error", "0.241"},
{"Treynor Ratio", "-6.368"},
{"Treynor Ratio", "-4.689"},
{"Total Fees", "$8.60"},
{"Estimated Strategy Capacity", "$5500000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Portfolio Turnover", "66.80%"},
{"OrderListHash", "579e2e83dd7e5e7648c47e9eff132460"}
{"OrderListHash", "802a335b5c355e83b8cd2174f053c1b9"}
};
}
}

View File

@@ -66,9 +66,9 @@ namespace QuantConnect.Algorithm.CSharp
}
}
public override void OnData(Slice slice)
public override void OnData(Slice data)
{
if (!slice.HasData)
if (!data.HasData)
{
return;
}
@@ -76,7 +76,7 @@ namespace QuantConnect.Algorithm.CSharp
_onDataReached = true;
var hasOptionQuoteBars = false;
foreach (var qb in slice.QuoteBars.Values)
foreach (var qb in data.QuoteBars.Values)
{
if (qb.Symbol.SecurityType != SecurityType.FutureOption)
{
@@ -99,7 +99,7 @@ namespace QuantConnect.Algorithm.CSharp
return;
}
if (slice.ContainsKey(_es20h20) && slice.ContainsKey(_es19m20))
if (data.ContainsKey(_es20h20) && data.ContainsKey(_es19m20))
{
SetHoldings(_es20h20, 0.2);
SetHoldings(_es19m20, 0.2);
@@ -114,7 +114,7 @@ namespace QuantConnect.Algorithm.CSharp
if (!_onDataReached)
{
throw new RegressionTestException("OnData() was never called.");
throw new Exception("OnData() was never called.");
}
if (_symbolsReceived.Count != _expectedSymbolsReceived.Count)
{
@@ -132,7 +132,7 @@ namespace QuantConnect.Algorithm.CSharp
if (missingSymbols.Count > 0)
{
throw new RegressionTestException($"Symbols: \"{string.Join(", ", missingSymbols)}\" were not found in OnData");
throw new Exception($"Symbols: \"{string.Join(", ", missingSymbols)}\" were not found in OnData");
}
foreach (var expectedSymbol in _expectedSymbolsReceived)
@@ -146,7 +146,7 @@ namespace QuantConnect.Algorithm.CSharp
if (nonDupeDataCount < 1000)
{
throw new RegressionTestException($"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}");
throw new Exception($"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}");
}
}
}
@@ -159,7 +159,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -171,43 +171,35 @@ namespace QuantConnect.Algorithm.CSharp
/// </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", "2"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "5512.811%"},
{"Drawdown", "1.000%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "105332.8"},
{"Net Profit", "5.333%"},
{"Sharpe Ratio", "64.084"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "64.137"},
{"Probabilistic Sharpe Ratio", "95.977%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "25.763"},
{"Alpha", "25.72"},
{"Beta", "2.914"},
{"Annual Standard Deviation", "0.423"},
{"Annual Variance", "0.179"},
{"Information Ratio", "66.11"},
{"Tracking Error", "0.403"},
{"Treynor Ratio", "9.308"},
{"Treynor Ratio", "9.315"},
{"Total Fees", "$8.60"},
{"Estimated Strategy Capacity", "$22000000.00"},
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
{"Portfolio Turnover", "122.11%"},
{"OrderListHash", "d744fa8beaa60546c84924ed68d945d9"}
{"OrderListHash", "e7021bd385f366771ae00abd3a46a22e"}
};
}
}

View File

@@ -40,16 +40,16 @@ namespace QuantConnect.Algorithm.CSharp
});
}
public override void OnData(Slice slice)
public override void OnData(Slice data)
{
if (!_addedOptions)
{
_addedOptions = true;
foreach (var futuresContracts in slice.FutureChains.Values)
foreach (var futuresContracts in data.FutureChains.Values)
{
foreach (var contract in futuresContracts)
{
var option_contract_symbols = OptionChain(contract.Symbol).ToList();
var option_contract_symbols = OptionChainProvider.GetOptionContractList(contract.Symbol, Time).ToList();
if(option_contract_symbols.Count == 0)
{
continue;
@@ -70,7 +70,7 @@ namespace QuantConnect.Algorithm.CSharp
return;
}
foreach (var chain in slice.OptionChains.Values)
foreach (var chain in data.OptionChains.Values)
{
foreach (var option in chain.Contracts.Keys)
{
@@ -88,44 +88,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 12169;
public long DataPoints => 12164;
/// <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", "20"},
{"Total Trades", "20"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "386219349.202%"},
{"Drawdown", "5.200%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "111911.55"},
{"Net Profit", "11.912%"},
{"Sharpe Ratio", "1604181.904"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "1604181.92"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "2144882.02"},
{"Alpha", "2144881.34"},
{"Beta", "31.223"},
{"Annual Standard Deviation", "1.337"},
{"Annual Variance", "1.788"},
@@ -136,7 +128,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$2600000.00"},
{"Lowest Capacity Asset", "ES 31C3JQS9D84PW|ES XCZJLC9NOB29"},
{"Portfolio Turnover", "495.15%"},
{"OrderListHash", "85257286f088992d599c1ad0799a6237"}
{"OrderListHash", "64221a660525c4259d5bd852eef1299c"}
};
}
}

View File

@@ -55,10 +55,10 @@ namespace QuantConnect.Algorithm.CSharp
{
_optionFilterRan = true;
var expiry = new HashSet<DateTime>(optionContracts.Select(x => x.Symbol.Underlying.ID.Date)).SingleOrDefault();
// Cast to List<Symbol> because OptionFilterContract overrides some LINQ operators like `Select` and `Where`
var expiry = new HashSet<DateTime>(optionContracts.Select(x => x.Underlying.ID.Date)).SingleOrDefault();
// Cast to IEnumerable<Symbol> because OptionFilterContract overrides some LINQ operators like `Select` and `Where`
// and cause it to mutate the underlying Symbol collection when using those operators.
var symbol = new HashSet<Symbol>(((List<Symbol>)optionContracts).Select(x => x.Underlying)).SingleOrDefault();
var symbol = new HashSet<Symbol>(((IEnumerable<Symbol>)optionContracts).Select(x => x.Underlying)).SingleOrDefault();
if (expiry == null || symbol == null)
{
@@ -75,9 +75,9 @@ namespace QuantConnect.Algorithm.CSharp
});
}
public override void OnData(Slice slice)
public override void OnData(Slice data)
{
if (!slice.HasData)
if (!data.HasData)
{
return;
}
@@ -85,7 +85,7 @@ namespace QuantConnect.Algorithm.CSharp
_onDataReached = true;
var hasOptionQuoteBars = false;
foreach (var qb in slice.QuoteBars.Values)
foreach (var qb in data.QuoteBars.Values)
{
if (qb.Symbol.SecurityType != SecurityType.FutureOption)
{
@@ -108,7 +108,7 @@ namespace QuantConnect.Algorithm.CSharp
return;
}
foreach (var chain in slice.OptionChains.Values)
foreach (var chain in data.OptionChains.Values)
{
var futureInvested = false;
var optionInvested = false;
@@ -122,7 +122,7 @@ namespace QuantConnect.Algorithm.CSharp
var future = option.Underlying;
if (!optionInvested && slice.ContainsKey(option))
if (!optionInvested && data.ContainsKey(option))
{
var optionContract = Securities[option];
var marginModel = optionContract.BuyingPowerModel as FuturesOptionsMarginModel;
@@ -131,16 +131,16 @@ namespace QuantConnect.Algorithm.CSharp
|| marginModel.MaintenanceIntradayMarginRequirement == 0
|| marginModel.MaintenanceOvernightMarginRequirement == 0)
{
throw new RegressionTestException("Unexpected margin requirements");
throw new Exception("Unexpected margin requirements");
}
if (marginModel.GetInitialMarginRequirement(optionContract, 1) == 0)
{
throw new RegressionTestException("Unexpected Initial Margin requirement");
throw new Exception("Unexpected Initial Margin requirement");
}
if (marginModel.GetMaintenanceMargin(optionContract) != 0)
{
throw new RegressionTestException("Unexpected Maintenance Margin requirement");
throw new Exception("Unexpected Maintenance Margin requirement");
}
MarketOrder(option, 1);
@@ -149,10 +149,10 @@ namespace QuantConnect.Algorithm.CSharp
if (marginModel.GetMaintenanceMargin(optionContract) == 0)
{
throw new RegressionTestException("Unexpected Maintenance Margin requirement");
throw new Exception("Unexpected Maintenance Margin requirement");
}
}
if (!futureInvested && slice.ContainsKey(future))
if (!futureInvested && data.ContainsKey(future))
{
MarketOrder(future, 1);
_invested = true;
@@ -170,7 +170,7 @@ namespace QuantConnect.Algorithm.CSharp
}
if (!_onDataReached)
{
throw new RegressionTestException("OnData() was never called.");
throw new Exception("OnData() was never called.");
}
if (_symbolsReceived.Count != _expectedSymbolsReceived.Count)
{
@@ -188,7 +188,7 @@ namespace QuantConnect.Algorithm.CSharp
if (missingSymbols.Count > 0)
{
throw new RegressionTestException($"Symbols: \"{string.Join(", ", missingSymbols)}\" were not found in OnData");
throw new Exception($"Symbols: \"{string.Join(", ", missingSymbols)}\" were not found in OnData");
}
foreach (var expectedSymbol in _expectedSymbolsReceived)
@@ -202,7 +202,7 @@ namespace QuantConnect.Algorithm.CSharp
if (nonDupeDataCount < 1000)
{
throw new RegressionTestException($"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}");
throw new Exception($"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}");
}
}
}
@@ -215,55 +215,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 608377;
public long DataPoints => 608372;
/// <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", "2"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "347.065%"},
{"Drawdown", "0.900%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "101950.53"},
{"Net Profit", "1.951%"},
{"Sharpe Ratio", "15.402"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "15.548"},
{"Probabilistic Sharpe Ratio", "95.977%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.886"},
{"Alpha", "1.885"},
{"Beta", "1.066"},
{"Annual Standard Deviation", "0.155"},
{"Annual Variance", "0.024"},
{"Information Ratio", "13.528"},
{"Tracking Error", "0.142"},
{"Treynor Ratio", "2.237"},
{"Treynor Ratio", "2.258"},
{"Total Fees", "$3.57"},
{"Estimated Strategy Capacity", "$760000.00"},
{"Lowest Capacity Asset", "ES XCZJLDQX2SRO|ES XCZJLC9NOB29"},
{"Portfolio Turnover", "32.31%"},
{"OrderListHash", "7a04f66a30d793bf187c2695781ad3ee"}
{"OrderListHash", "738240babf741f1bf79f85ea5026ec4c"}
};
}
}

View File

@@ -42,12 +42,12 @@ namespace QuantConnect.Algorithm.CSharp
AddUniverse("my-daily-universe-name", time => new List<string> { "AAPL" });
}
public override void OnData(Slice slice)
public override void OnData(Slice data)
{
if (_option == null)
{
var option = OptionChain(_twx)
.OrderBy(x => x.ID.Symbol)
var option = OptionChainProvider.GetOptionContractList(_twx, Time)
.OrderBy(symbol => symbol.ID.Symbol)
.FirstOrDefault(optionContract => optionContract.ID.Date == _expiration
&& optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American);
@@ -68,11 +68,11 @@ namespace QuantConnect.Algorithm.CSharp
if (!config.Any())
{
throw new RegressionTestException($"Was expecting configurations for {symbol}");
throw new Exception($"Was expecting configurations for {symbol}");
}
if (config.Any(dataConfig => dataConfig.DataNormalizationMode != DataNormalizationMode.Raw))
{
throw new RegressionTestException($"Was expecting DataNormalizationMode.Raw configurations for {symbol}");
throw new Exception($"Was expecting DataNormalizationMode.Raw configurations for {symbol}");
}
}
}
@@ -81,14 +81,14 @@ namespace QuantConnect.Algorithm.CSharp
{
if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_option).Any())
{
throw new RegressionTestException($"Unexpected configurations for {_option} after it has been delisted");
throw new Exception($"Unexpected configurations for {_option} after it has been delisted");
}
if (Securities[_twx].Invested)
{
if (!SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_twx).Any())
{
throw new RegressionTestException($"Was expecting configurations for {_twx}");
throw new Exception($"Was expecting configurations for {_twx}");
}
// first we liquidate the option exercised position
@@ -99,7 +99,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_twx).Any())
{
throw new RegressionTestException($"Unexpected configurations for {_twx} after it has been liquidated");
throw new Exception($"Unexpected configurations for {_twx} after it has been liquidated");
}
}
}
@@ -112,7 +112,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -122,45 +122,37 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 1;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
public 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 Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "3"},
{"Total Trades", "3"},
{"Average Win", "2.73%"},
{"Average Loss", "-2.98%"},
{"Compounding Annual Return", "-4.619%"},
{"Drawdown", "0.300%"},
{"Expectancy", "-0.042"},
{"Start Equity", "100000"},
{"End Equity", "99668"},
{"Net Profit", "-0.332%"},
{"Sharpe Ratio", "-4.614"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "-3.149"},
{"Probabilistic Sharpe Ratio", "0.427%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.92"},
{"Alpha", "-0.022"},
{"Alpha", "-0.015"},
{"Beta", "-0.012"},
{"Annual Standard Deviation", "0.005"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.823"},
{"Tracking Error", "0.049"},
{"Treynor Ratio", "2.01"},
{"Treynor Ratio", "1.372"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$5700000.00"},
{"Lowest Capacity Asset", "AOL VRKS95ENLBYE|AOL R735QTJ8XC9X"},
{"Portfolio Turnover", "0.55%"},
{"OrderListHash", "24191a4a3bf11c07622a21266618193d"}
{"OrderListHash", "568fe7c2a11960436660db1231f2cfd2"}
};
}
}

View File

@@ -13,12 +13,12 @@
* limitations under the License.
*/
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
@@ -50,7 +50,7 @@ namespace QuantConnect.Algorithm.CSharp
enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl });
}
public override void OnData(Slice slice)
public override void OnData(Slice data)
{
if (_option != null && Securities[_option].Price != 0 && !_traded)
{
@@ -66,7 +66,7 @@ namespace QuantConnect.Algorithm.CSharp
// assert underlying still there after the universe selection removed it, still used by the manually added option contract
if (!configs.Any())
{
throw new RegressionTestException($"Was expecting configurations for {_twx}" +
throw new Exception($"Was expecting configurations for {_twx}" +
$" even after it has been deselected from coarse universe because we still have the option contract.");
}
}
@@ -83,7 +83,7 @@ namespace QuantConnect.Algorithm.CSharp
var configs = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol);
if (configs.Any())
{
throw new RegressionTestException($"Unexpected configuration for {symbol} after it has been deselected from coarse universe and option contract is removed.");
throw new Exception($"Unexpected configuration for {symbol} after it has been deselected from coarse universe and option contract is removed.");
}
}
}
@@ -94,11 +94,11 @@ namespace QuantConnect.Algorithm.CSharp
{
if (_securityChanges.RemovedSecurities.Intersect(changes.RemovedSecurities).Any())
{
throw new RegressionTestException($"SecurityChanges.RemovedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!");
throw new Exception($"SecurityChanges.RemovedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!");
}
if (_securityChanges.AddedSecurities.Intersect(changes.AddedSecurities).Any())
{
throw new RegressionTestException($"SecurityChanges.AddedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!");
throw new Exception($"SecurityChanges.AddedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!");
}
// keep track of all removed and added securities
_securityChanges += changes;
@@ -110,24 +110,24 @@ namespace QuantConnect.Algorithm.CSharp
foreach (var addedSecurity in changes.AddedSecurities)
{
var option = OptionChain(addedSecurity.Symbol)
.OrderBy(contractData => contractData.ID.Symbol)
var option = OptionChainProvider.GetOptionContractList(addedSecurity.Symbol, Time)
.OrderBy(symbol => symbol.ID.Symbol)
.First(optionContract => optionContract.ID.Date == _expiration
&& optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American);
AddOptionContract(option);
foreach (var symbol in new[] { option.Symbol, option.Underlying.Symbol })
foreach (var symbol in new[] { option, option.Underlying })
{
var config = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol).ToList();
if (!config.Any())
{
throw new RegressionTestException($"Was expecting configurations for {symbol}");
throw new Exception($"Was expecting configurations for {symbol}");
}
if (config.Any(dataConfig => dataConfig.DataNormalizationMode != DataNormalizationMode.Raw))
{
throw new RegressionTestException($"Was expecting DataNormalizationMode.Raw configurations for {symbol}");
throw new Exception($"Was expecting DataNormalizationMode.Raw configurations for {symbol}");
}
}
@@ -143,16 +143,16 @@ namespace QuantConnect.Algorithm.CSharp
{
if (SubscriptionManager.Subscriptions.Any(dataConfig => dataConfig.Symbol == _twx || dataConfig.Symbol.Underlying == _twx))
{
throw new RegressionTestException($"Was NOT expecting any configurations for {_twx} or it's options, since we removed the contract");
throw new Exception($"Was NOT expecting any configurations for {_twx} or it's options, since we removed the contract");
}
if (SubscriptionManager.Subscriptions.All(dataConfig => dataConfig.Symbol != _aapl))
{
throw new RegressionTestException($"Was expecting configurations for {_aapl}");
throw new Exception($"Was expecting configurations for {_aapl}");
}
if (SubscriptionManager.Subscriptions.All(dataConfig => dataConfig.Symbol.Underlying != _aapl))
{
throw new RegressionTestException($"Was expecting options configurations for {_aapl}");
throw new Exception($"Was expecting options configurations for {_aapl}");
}
}
@@ -164,7 +164,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -174,45 +174,37 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 2;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
public 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 Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "2"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.23%"},
{"Compounding Annual Return", "-15.596%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "99768"},
{"Net Profit", "-0.232%"},
{"Sharpe Ratio", "-8.903"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "-7.739"},
{"Probabilistic Sharpe Ratio", "1.216%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.015"},
{"Alpha", "0.024"},
{"Beta", "-0.171"},
{"Annual Standard Deviation", "0.006"},
{"Annual Variance", "0"},
{"Information Ratio", "-11.082"},
{"Tracking Error", "0.043"},
{"Treynor Ratio", "0.335"},
{"Treynor Ratio", "0.291"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$2800000.00"},
{"Lowest Capacity Asset", "AOL VRKS95ENLBYE|AOL R735QTJ8XC9X"},
{"Portfolio Turnover", "1.14%"},
{"OrderListHash", "cde7b518b7ad6d86cff6e5e092d9a413"}
{"OrderListHash", "ae0b430e9c728966e3736fb352a689c6"}
};
}
}

View File

@@ -39,12 +39,12 @@ namespace QuantConnect.Algorithm.CSharp
UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero;
UniverseSettings.FillForward = false;
AddEquity("SPY", Resolution.Hour);
AddEquity("SPY", Resolution.Daily);
var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
_contract = OptionChain(aapl)
.OrderBy(x => x.ID.StrikePrice)
_contract = OptionChainProvider.GetOptionContractList(aapl, Time)
.OrderBy(symbol => symbol.ID.Symbol)
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American);
AddOptionContract(_contract);
@@ -56,7 +56,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!_reAdded && slice.ContainsKey(_contract) && slice.ContainsKey(_contract.Underlying))
{
throw new RegressionTestException("Getting data for removed option and underlying!");
throw new Exception("Getting data for removed option and underlying!");
}
if (!Portfolio.Invested && _reAdded)
@@ -95,11 +95,11 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!_hasRemoved)
{
throw new RegressionTestException("We did not remove the option contract!");
throw new Exception("We did not remove the option contract!");
}
if (!_reAdded)
{
throw new RegressionTestException("We did not re add the option contract!");
throw new Exception("We did not re add the option contract!");
}
}
@@ -111,39 +111,31 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 3814;
public long DataPoints => 4677;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 1;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
public 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 Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "2"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.50%"},
{"Compounding Annual Return", "-39.406%"},
{"Drawdown", "0.700%"},
{"Average Loss", "-0.05%"},
{"Compounding Annual Return", "-4.548%"},
{"Drawdown", "0.100%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "99498"},
{"Net Profit", "-0.502%"},
{"Net Profit", "-0.051%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
@@ -156,10 +148,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.008"},
{"Treynor Ratio", "0"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$5000000.00"},
{"Lowest Capacity Asset", "AAPL VXBK4R62CXGM|AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "22.70%"},
{"OrderListHash", "29fd1b75f6db05dd823a6db7e8bd90a9"}
{"Estimated Strategy Capacity", "$30000.00"},
{"Lowest Capacity Asset", "AAPL VXBK4Q9ZIFD2|AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "0.07%"},
{"OrderListHash", "546b6182e1df2d222178454d8f311566"}
};
}
}

View File

@@ -13,6 +13,7 @@
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data.UniverseSelection;
@@ -58,9 +59,19 @@ namespace QuantConnect.Algorithm.CSharp
var changeOptions = changes.AddedSecurities.Concat(changes.RemovedSecurities)
.Where(s => s.Type == SecurityType.Option);
if (Time != Time.Date)
// Susbtract one minute to get the actual market open. If market open is at 9:30am, this will be invoked at 9:31am
var expectedTime = Time.TimeOfDay - TimeSpan.FromMinutes(1);
var allOptionsWereChangedOnMarketOpen = changeOptions.All(s =>
{
throw new RegressionTestException($"Expected options filter to be run only at midnight. Actual was {Time}");
var firstMarketSegment = s.Exchange.Hours.MarketHours[Time.DayOfWeek].Segments
.First(segment => segment.State == MarketHoursState.Market);
return firstMarketSegment.Start == expectedTime;
});
if (!allOptionsWereChangedOnMarketOpen)
{
throw new Exception("Expected options filter to be run only on market open");
}
}
@@ -72,39 +83,31 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all time slices of algorithm
/// </summary>
public long DataPoints => 470217;
public long DataPoints => 5952220;
/// <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"},
{"Total Trades", "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%"},

View File

@@ -29,21 +29,20 @@ namespace QuantConnect.Algorithm.CSharp
public class AddRemoveOptionUniverseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "GOOG";
private readonly Symbol Underlying = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Equity, Market.USA);
private readonly Symbol OptionChainSymbol = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Option, Market.USA);
public readonly Symbol Underlying = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Equity, Market.USA);
public readonly Symbol OptionChainSymbol = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Option, Market.USA);
private readonly HashSet<Symbol> _expectedSecurities = new HashSet<Symbol>();
private readonly HashSet<Symbol> _expectedData = new HashSet<Symbol>();
private readonly HashSet<Symbol> _expectedUniverses = new HashSet<Symbol>();
private bool _expectUniverseSubscription;
private DateTime _universeSubscriptionTime;
// order of expected contract additions as price moves
private int _expectedContractIndex;
private readonly List<Symbol> _expectedContracts = new List<Symbol>
{
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00747500"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00750000"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00752500"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00755000")
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00752500")
};
public override void Initialize()
@@ -60,16 +59,16 @@ namespace QuantConnect.Algorithm.CSharp
_expectedUniverses.Add(UserDefinedUniverse.CreateSymbol(SecurityType.Equity, Market.USA));
}
public override void OnData(Slice slice)
public override void OnData(Slice data)
{
// verify expectations
if (SubscriptionManager.Subscriptions.Count(x => x.Symbol == OptionChainSymbol)
!= (_expectUniverseSubscription ? 1 : 0))
{
Log($"SubscriptionManager.Subscriptions: {string.Join(" -- ", SubscriptionManager.Subscriptions)}");
throw new RegressionTestException($"Unexpected {OptionChainSymbol} subscription presence");
throw new Exception($"Unexpected {OptionChainSymbol} subscription presence");
}
if (Time != _universeSubscriptionTime && !slice.ContainsKey(Underlying))
if (!data.ContainsKey(Underlying))
{
// TODO : In fact, we're unable to properly detect whether or not we auto-added or it was manually added
// this is because when we auto-add the underlying we don't mark it as an internal security like we do with other auto adds
@@ -78,46 +77,46 @@ namespace QuantConnect.Algorithm.CSharp
// of the internal flag's purpose, so kicking this issue for now with a big fat note here about it :) to be considerd for any future
// refactorings of how we manage subscription/security data and track various aspects about the security (thinking a flags enum with
// things like manually added, auto added, internal, and any other boolean state we need to track against a single security)
throw new RegressionTestException("The underlying equity data should NEVER be removed in this algorithm because it was manually added");
throw new Exception("The underlying equity data should NEVER be removed in this algorithm because it was manually added");
}
if (_expectedSecurities.AreDifferent(Securities.Total.Select(x => x.Symbol).ToHashSet()))
if (_expectedSecurities.AreDifferent(Securities.Keys.ToHashSet()))
{
var expected = string.Join(Environment.NewLine, _expectedSecurities.OrderBy(s => s.ToString()));
var actual = string.Join(Environment.NewLine, Securities.Keys.OrderBy(s => s.ToString()));
throw new RegressionTestException($"{Time}:: Detected differences in expected and actual securities{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
throw new Exception($"{Time}:: Detected differences in expected and actual securities{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
}
if (_expectedUniverses.AreDifferent(UniverseManager.Keys.ToHashSet()))
{
var expected = string.Join(Environment.NewLine, _expectedUniverses.OrderBy(s => s.ToString()));
var actual = string.Join(Environment.NewLine, UniverseManager.Keys.OrderBy(s => s.ToString()));
throw new RegressionTestException($"{Time}:: Detected differences in expected and actual universes{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
throw new Exception($"{Time}:: Detected differences in expected and actual universes{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
}
if (Time != _universeSubscriptionTime && _expectedData.AreDifferent(slice.Keys.ToHashSet()))
if (_expectedData.AreDifferent(data.Keys.ToHashSet()))
{
var expected = string.Join(Environment.NewLine, _expectedData.OrderBy(s => s.ToString()));
var actual = string.Join(Environment.NewLine, slice.Keys.OrderBy(s => s.ToString()));
throw new RegressionTestException($"{Time}:: Detected differences in expected and actual slice data keys{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
var actual = string.Join(Environment.NewLine, data.Keys.OrderBy(s => s.ToString()));
throw new Exception($"{Time}:: Detected differences in expected and actual slice data keys{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
}
// 10AM add GOOG option chain
if (Time.TimeOfDay.Hours == 10 && Time.TimeOfDay.Minutes == 0 && !_expectUniverseSubscription)
if (Time.TimeOfDay.Hours == 10 && Time.TimeOfDay.Minutes == 0)
{
if (Securities.ContainsKey(OptionChainSymbol))
{
throw new RegressionTestException("The option chain security should not have been added yet");
throw new Exception("The option chain security should not have been added yet");
}
var googOptionChain = AddOption(UnderlyingTicker);
googOptionChain.SetFilter(u =>
{
// we added the universe at 10, the universe selection data should not be from before
if (u.LocalTime.Hour < 10)
if (u.Underlying.EndTime.Hour < 10)
{
throw new RegressionTestException($"Unexpected selection time {u.LocalTime}");
throw new Exception($"Unexpected underlying data point {u.Underlying.EndTime} {u.Underlying}");
}
// find first put above market price
return u.IncludeWeeklys()
.Strikes(+1, +3)
.Strikes(+1, +1)
.Expiration(TimeSpan.Zero, TimeSpan.FromDays(1))
.Contracts(c => c.Where(s => s.ID.OptionRight == OptionRight.Put));
});
@@ -125,7 +124,6 @@ namespace QuantConnect.Algorithm.CSharp
_expectedSecurities.Add(OptionChainSymbol);
_expectedUniverses.Add(OptionChainSymbol);
_expectUniverseSubscription = true;
_universeSubscriptionTime = Time;
}
// 11:30AM remove GOOG option chain
@@ -143,6 +141,16 @@ namespace QuantConnect.Algorithm.CSharp
public override void OnSecuritiesChanged(SecurityChanges changes)
{
if (changes.AddedSecurities.Count > 1)
{
// added event fired for underlying since it was added to the option chain universe
if (changes.AddedSecurities.All(s => s.Symbol != Underlying))
{
var securities = string.Join(Environment.NewLine, changes.AddedSecurities.Select(s => s.Symbol));
throw new Exception($"This algorithm intends to add a single security at a time but added: {changes.AddedSecurities.Count}{Environment.NewLine}{securities}");
}
}
if (changes.AddedSecurities.Any())
{
foreach (var added in changes.AddedSecurities)
@@ -153,7 +161,7 @@ namespace QuantConnect.Algorithm.CSharp
var expectedContract = _expectedContracts[_expectedContractIndex];
if (added.Symbol != expectedContract)
{
throw new RegressionTestException($"Expected option contract {expectedContract.Value} to be added but received {added.Symbol}");
throw new Exception($"Expected option contract {expectedContract} to be added but received {added.Symbol}");
}
_expectedContractIndex++;
@@ -174,7 +182,7 @@ namespace QuantConnect.Algorithm.CSharp
// receive removed event next timestep at 11:31AM
if (Time.TimeOfDay.Hours != 11 || Time.TimeOfDay.Minutes != 31)
{
throw new RegressionTestException($"Expected option contracts to be removed at 11:31AM, instead removed at: {Time}");
throw new Exception($"Expected option contracts to be removed at 11:31AM, instead removed at: {Time}");
}
if (changes.RemovedSecurities
@@ -182,13 +190,13 @@ namespace QuantConnect.Algorithm.CSharp
.ToHashSet(s => s.Symbol)
.AreDifferent(_expectedContracts.ToHashSet()))
{
throw new RegressionTestException("Expected removed securities to equal expected contracts added");
throw new Exception("Expected removed securities to equal expected contracts added");
}
}
if (Securities.ContainsKey(Underlying))
{
Log($"{Time:o}:: PRICE:: {Securities[Underlying].Price} CHANGES:: {changes}");
Console.WriteLine($"{Time:o}:: PRICE:: {Securities[Underlying].Price} CHANGES:: {changes}");
}
}
@@ -200,39 +208,31 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 3502;
public long DataPoints => 200618;
/// <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", "6"},
{"Total Trades", "6"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "98784"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -245,10 +245,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$6.00"},
{"Estimated Strategy Capacity", "$4000.00"},
{"Lowest Capacity Asset", "GOOCV 305RBQ2BZBZT2|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "2.58%"},
{"OrderListHash", "09f766c470a8bcf4bb6862da52bf25a7"}
{"Estimated Strategy Capacity", "$2000.00"},
{"Lowest Capacity Asset", "GOOCV 305RBR0BSWIX2|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "1.19%"},
{"OrderListHash", "550a99c482106defd8ba15f48183768e"}
};
}
}

View File

@@ -41,8 +41,8 @@ namespace QuantConnect.Algorithm.CSharp
/// <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)
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
@@ -61,7 +61,7 @@ namespace QuantConnect.Algorithm.CSharp
if (ticket.Status != OrderStatus.Invalid)
{
throw new RegressionTestException("Expected order to always be invalid because there is no data yet!");
throw new Exception("Expected order to always be invalid because there is no data yet!");
}
}
else
@@ -78,7 +78,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -90,43 +90,35 @@ namespace QuantConnect.Algorithm.CSharp
/// </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", "19"},
{"Total Trades", "19"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "271.720%"},
{"Drawdown", "2.500%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "101753.84"},
{"Net Profit", "1.754%"},
{"Sharpe Ratio", "11.954"},
{"Sortino Ratio", "29.606"},
{"Sharpe Ratio", "11.994"},
{"Probabilistic Sharpe Ratio", "74.160%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.616"},
{"Alpha", "0.618"},
{"Beta", "0.81"},
{"Annual Standard Deviation", "0.185"},
{"Annual Variance", "0.034"},
{"Information Ratio", "3.961"},
{"Tracking Error", "0.061"},
{"Treynor Ratio", "2.737"},
{"Treynor Ratio", "2.746"},
{"Total Fees", "$21.45"},
{"Estimated Strategy Capacity", "$830000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "20.49%"},
{"OrderListHash", "6ebe462373e2ecc22de8eb2fe114d704"}
{"OrderListHash", "6ee62edf1ac883882b0fcef8cb3e9bae"}
};
}
}

View File

@@ -18,7 +18,6 @@ using System.Collections.Generic;
using QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Data;
namespace QuantConnect.Algorithm.CSharp
{
@@ -52,7 +51,7 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public void OnData(TradeBars data)
{
if (lastAction.Date == Time.Date) return;
@@ -105,7 +104,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -117,43 +116,35 @@ namespace QuantConnect.Algorithm.CSharp
/// </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", "5"},
{"Total Trades", "5"},
{"Average Win", "0.46%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "296.356%"},
{"Drawdown", "1.400%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "101776.32"},
{"Net Profit", "1.776%"},
{"Sharpe Ratio", "12.966"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "13.013"},
{"Probabilistic Sharpe Ratio", "80.409%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.678"},
{"Alpha", "0.68"},
{"Beta", "0.707"},
{"Annual Standard Deviation", "0.16"},
{"Annual Variance", "0.026"},
{"Information Ratio", "1.378"},
{"Tracking Error", "0.072"},
{"Treynor Ratio", "2.935"},
{"Treynor Ratio", "2.946"},
{"Total Fees", "$28.30"},
{"Estimated Strategy Capacity", "$4700000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Portfolio Turnover", "29.88%"},
{"OrderListHash", "6061ecfbb89eb365dff913410d279b7c"}
{"OrderListHash", "ac3f4dfcdeb98b488b715412ad2d6c4f"}
};
}
}

View File

@@ -57,7 +57,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -69,43 +69,35 @@ namespace QuantConnect.Algorithm.CSharp
/// </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", "3"},
{"Total Trades", "3"},
{"Average Win", "1.02%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "296.066%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "101775.37"},
{"Net Profit", "1.775%"},
{"Sharpe Ratio", "9.34"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "9.373"},
{"Probabilistic Sharpe Ratio", "68.302%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.106"},
{"Alpha", "0.105"},
{"Beta", "1.021"},
{"Annual Standard Deviation", "0.227"},
{"Annual Variance", "0.052"},
{"Information Ratio", "25.083"},
{"Tracking Error", "0.006"},
{"Treynor Ratio", "2.079"},
{"Treynor Ratio", "2.086"},
{"Total Fees", "$10.33"},
{"Estimated Strategy Capacity", "$38000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "59.74%"},
{"OrderListHash", "5d7657ec9954875eca633bed711085d3"}
{"OrderListHash", "af3a9c98c190d1b6b36fad184e796b0b"}
};
}
}

View File

@@ -41,8 +41,8 @@ namespace QuantConnect.Algorithm.CSharp
var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
var contracts = OptionChain(aapl)
.OrderBy(x => x.ID.StrikePrice)
var contracts = OptionChainProvider.GetOptionContractList(aapl, Time)
.OrderBy(symbol => symbol.ID.Symbol)
.Where(optionContract => optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American)
.Take(2)
@@ -69,7 +69,7 @@ namespace QuantConnect.Algorithm.CSharp
SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs("AAPL");
if (subscriptions.Count == 0)
{
throw new RegressionTestException("No configuration for underlying was found!");
throw new Exception("No configuration for underlying was found!");
}
if (!Portfolio.Invested)
@@ -84,7 +84,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!_hasRemoved)
{
throw new RegressionTestException("Expect a single call to OnData where we removed the option and underlying");
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
}
}
@@ -96,7 +96,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -106,29 +106,21 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 1;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
public 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 Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "2"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "99238"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -141,10 +133,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$6200000.00"},
{"Lowest Capacity Asset", "AAPL VXBK4QA5EM92|AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "90.27%"},
{"OrderListHash", "a111609c2c64554268539b5798e5b31f"}
{"Estimated Strategy Capacity", "$230000.00"},
{"Lowest Capacity Asset", "AAPL VXBK4QQIRLZA|AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "0.25%"},
{"OrderListHash", "228194dcc6fd8689a67f383577ee2d85"}
};
}
}

View File

@@ -57,14 +57,14 @@ namespace QuantConnect.Algorithm.CSharp
{
if (UniverseManager.Count != 3)
{
throw new RegressionTestException("Unexpected universe count");
throw new Exception("Unexpected universe count");
}
if (UniverseManager.ActiveSecurities.Count != 3
|| UniverseManager.ActiveSecurities.Keys.All(symbol => symbol.Value != "SPY")
|| UniverseManager.ActiveSecurities.Keys.All(symbol => symbol.Value != "AAPL")
|| UniverseManager.ActiveSecurities.Keys.All(symbol => symbol.Value != "FB"))
{
throw new RegressionTestException("Unexpected active securities");
throw new Exception("Unexpected active securities");
}
}
@@ -76,55 +76,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 50;
public long DataPoints => 53;
/// <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", "6"},
{"Average Win", "0.01%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "1296.838%"},
{"Drawdown", "0.400%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "102684.23"},
{"Net Profit", "2.684%"},
{"Sharpe Ratio", "34.319"},
{"Sortino Ratio", "0"},
{"Total Trades", "10"},
{"Average Win", "0%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-14.233%"},
{"Drawdown", "3.300%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.168%"},
{"Sharpe Ratio", "62.499"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-5.738"},
{"Beta", "1.381"},
{"Annual Standard Deviation", "0.246"},
{"Annual Variance", "0.06"},
{"Information Ratio", "-26.937"},
{"Tracking Error", "0.068"},
{"Treynor Ratio", "6.106"},
{"Total Fees", "$18.61"},
{"Estimated Strategy Capacity", "$980000000.00"},
{"Alpha", "1.116"},
{"Beta", "1.19"},
{"Annual Standard Deviation", "0.213"},
{"Annual Variance", "0.046"},
{"Information Ratio", "70.778"},
{"Tracking Error", "0.043"},
{"Treynor Ratio", "11.206"},
{"Total Fees", "$22.21"},
{"Estimated Strategy Capacity", "$340000000.00"},
{"Lowest Capacity Asset", "FB V6OIPNZEM8V9"},
{"Portfolio Turnover", "25.56%"},
{"OrderListHash", "5ee20c8556d706ab0a63ae41b6579c62"}
{"Portfolio Turnover", "26.92%"},
{"OrderListHash", "a259afcf4ee1c65ce5d26588ab645dbf"}
};
}
}

View File

@@ -68,14 +68,14 @@ namespace QuantConnect.Algorithm.CSharp
{
if (UniverseManager.Count != 3)
{
throw new RegressionTestException("Unexpected universe count");
throw new Exception("Unexpected universe count");
}
if (UniverseManager.ActiveSecurities.Count != 3
|| UniverseManager.ActiveSecurities.Keys.All(symbol => symbol.Value != "SPY")
|| UniverseManager.ActiveSecurities.Keys.All(symbol => symbol.Value != "AAPL")
|| UniverseManager.ActiveSecurities.Keys.All(symbol => symbol.Value != "FB"))
{
throw new RegressionTestException("Unexpected active securities");
throw new Exception("Unexpected active securities");
}
}
@@ -87,55 +87,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 234015;
public long DataPoints => 234018;
/// <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", "21"},
{"Average Win", "0.01%"},
{"Total Trades", "21"},
{"Average Win", "0.00%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-77.566%"},
{"Drawdown", "6.000%"},
{"Expectancy", "-0.811"},
{"Start Equity", "100000"},
{"End Equity", "94042.73"},
{"Net Profit", "-5.957%"},
{"Sharpe Ratio", "-3.345"},
{"Sortino Ratio", "-3.766"},
{"Probabilistic Sharpe Ratio", "4.557%"},
{"Loss Rate", "89%"},
{"Win Rate", "11%"},
{"Profit-Loss Ratio", "0.70"},
{"Alpha", "-0.519"},
{"Beta", "1.491"},
{"Annual Standard Deviation", "0.2"},
{"Annual Variance", "0.04"},
{"Information Ratio", "-3.878"},
{"Tracking Error", "0.147"},
{"Treynor Ratio", "-0.449"},
{"Total Fees", "$29.11"},
{"Estimated Strategy Capacity", "$680000000.00"},
{"Compounding Annual Return", "-75.275%"},
{"Drawdown", "5.800%"},
{"Expectancy", "-0.609"},
{"Net Profit", "-5.581%"},
{"Sharpe Ratio", "-3.25"},
{"Probabilistic Sharpe Ratio", "5.546%"},
{"Loss Rate", "73%"},
{"Win Rate", "27%"},
{"Profit-Loss Ratio", "0.43"},
{"Alpha", "-0.498"},
{"Beta", "1.484"},
{"Annual Standard Deviation", "0.196"},
{"Annual Variance", "0.039"},
{"Information Ratio", "-3.843"},
{"Tracking Error", "0.141"},
{"Treynor Ratio", "-0.43"},
{"Total Fees", "$31.25"},
{"Estimated Strategy Capacity", "$550000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "7.48%"},
{"OrderListHash", "2c814c55e7d7c56482411c065b861b33"}
{"Portfolio Turnover", "7.33%"},
{"OrderListHash", "6aab808e341ae46946b91ba378073531"}
};
}
}

View File

@@ -63,21 +63,21 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
SetHoldings(_aapl, 1);
}
if (slice.Splits.ContainsKey(_aapl))
if (data.Splits.ContainsKey(_aapl))
{
Log(slice.Splits[_aapl].ToString());
Log(data.Splits[_aapl].ToString());
}
if (slice.Bars.ContainsKey(_aapl))
if (data.Bars.ContainsKey(_aapl))
{
var aaplData = slice.Bars[_aapl];
var aaplData = data.Bars[_aapl];
// Assert our volume matches what we expect
if (_expectedAdjustedVolume.MoveNext() && _expectedAdjustedVolume.Current != aaplData.Volume)
@@ -99,9 +99,9 @@ namespace QuantConnect.Algorithm.CSharp
}
}
if (slice.QuoteBars.ContainsKey(_aapl))
if (data.QuoteBars.ContainsKey(_aapl))
{
var aaplQuoteData = slice.QuoteBars[_aapl];
var aaplQuoteData = data.QuoteBars[_aapl];
// Assert our askSize matches what we expect
if (_expectedAdjustedAskSize.MoveNext() && _expectedAdjustedAskSize.Current != aaplQuoteData.LastAskSize)
@@ -151,7 +151,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -163,27 +163,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </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"},
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100146.57"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -199,7 +191,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$42000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "99.56%"},
{"OrderListHash", "60f03c8c589a4f814dc4e8945df23207"}
{"OrderListHash", "18e41dded4f8cee548ee02b03ffb0814"}
};
}
}

View File

@@ -34,25 +34,25 @@ namespace QuantConnect.Algorithm.CSharp
if (AlgorithmMode != AlgorithmMode.Backtesting)
{
throw new RegressionTestException($"Algorithm mode is not backtesting. Actual: {AlgorithmMode}");
throw new Exception($"Algorithm mode is not backtesting. Actual: {AlgorithmMode}");
}
if (LiveMode)
{
throw new RegressionTestException("Algorithm should not be live");
throw new Exception("Algorithm should not be live");
}
if (DeploymentTarget != DeploymentTarget.LocalPlatform)
{
throw new RegressionTestException($"Algorithm deployment target is not local. Actual{DeploymentTarget}");
throw new Exception($"Algorithm deployment target is not local. Actual{DeploymentTarget}");
}
// For a live deployment these checks should pass:
//if (AlgorithmMode != AlgorithmMode.Live) throw new RegressionTestException("Algorithm mode is not live");
//if (!LiveMode) throw new RegressionTestException("Algorithm should be live");
//if (AlgorithmMode != AlgorithmMode.Live) throw new Exception("Algorithm mode is not live");
//if (!LiveMode) throw new Exception("Algorithm should be live");
// For a cloud deployment these checks should pass:
//if (DeploymentTarget != DeploymentTarget.CloudPlatform) throw new RegressionTestException("Algorithm deployment target is not cloud");
//if (DeploymentTarget != DeploymentTarget.CloudPlatform) throw new Exception("Algorithm deployment target is not cloud");
Quit();
}
@@ -65,7 +65,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -77,27 +77,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </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"},
{"Total Trades", "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%"},

View File

@@ -100,25 +100,27 @@ namespace QuantConnect.Algorithm.CSharp
SetBrokerageModel(new AllShortableSymbolsRegressionAlgorithmBrokerageModel());
}
public override void OnData(Slice slice)
public override void OnData(Slice data)
{
if (Time.Date == _lastTradeDate)
{
return;
}
foreach (var (symbol, security) in ActiveSecurities.Where(kvp => !kvp.Value.Invested).OrderBy(kvp => kvp.Key))
foreach (var symbol in ActiveSecurities.Keys.OrderBy(symbol => symbol))
{
var shortableQuantity = security.ShortableProvider.ShortableQuantity(symbol, Time);
if (shortableQuantity == null)
if (!Portfolio.ContainsKey(symbol) || !Portfolio[symbol].Invested)
{
throw new RegressionTestException($"Expected {symbol} to be shortable on {Time:yyyy-MM-dd}");
}
if (!Shortable(symbol))
{
throw new Exception($"Expected {symbol} to be shortable on {Time:yyyy-MM-dd}");
}
// Buy at least once into all Symbols. Since daily data will always use
// MOO orders, it makes the testing of liquidating buying into Symbols difficult.
MarketOrder(symbol, -(decimal)shortableQuantity);
_lastTradeDate = Time.Date;
// Buy at least once into all Symbols. Since daily data will always use
// MOO orders, it makes the testing of liquidating buying into Symbols difficult.
MarketOrder(symbol, -(decimal)ShortableQuantity(symbol));
_lastTradeDate = Time.Date;
}
}
}
@@ -137,11 +139,11 @@ namespace QuantConnect.Algorithm.CSharp
var gme = QuantConnect.Symbol.Create("GME", SecurityType.Equity, Market.USA);
if (!shortableSymbols.ContainsKey(gme))
{
throw new RegressionTestException("Expected unmapped GME in shortable symbols list on 2014-03-27");
throw new Exception("Expected unmapped GME in shortable symbols list on 2014-03-27");
}
if (!coarse.Select(x => x.Symbol.Value).Contains("GME"))
{
throw new RegressionTestException("Expected mapped GME in coarse symbols on 2014-03-27");
throw new Exception("Expected mapped GME in coarse symbols on 2014-03-27");
}
expectedMissing = 1;
@@ -150,7 +152,7 @@ namespace QuantConnect.Algorithm.CSharp
var missing = _expectedSymbols[Time.Date].Except(selectedSymbols).ToList();
if (missing.Count != expectedMissing)
{
throw new RegressionTestException($"Expected Symbols selected on {Time.Date:yyyy-MM-dd} to match expected Symbols, but the following Symbols were missing: {string.Join(", ", missing.Select(s => s.ToString()))}");
throw new Exception($"Expected Symbols selected on {Time.Date:yyyy-MM-dd} to match expected Symbols, but the following Symbols were missing: {string.Join(", ", missing.Select(s => s.ToString()))}");
}
_coarseSelected[Time.Date] = true;
@@ -169,16 +171,13 @@ namespace QuantConnect.Algorithm.CSharp
{
public AllShortableSymbolsRegressionAlgorithmBrokerageModel() : base()
{
}
public override IShortableProvider GetShortableProvider(Security security)
{
return new RegressionTestShortableProvider();
ShortableProvider = new RegressionTestShortableProvider();
}
}
private class RegressionTestShortableProvider : LocalDiskShortableProvider
{
public RegressionTestShortableProvider() : base("testbrokerage")
public RegressionTestShortableProvider() : base(SecurityType.Equity, "testbrokerage", Market.USA)
{
}
@@ -189,7 +188,6 @@ namespace QuantConnect.Algorithm.CSharp
/// <returns>Symbol/quantity shortable as a Dictionary. Returns null if no entry data exists for this date or brokerage</returns>
public Dictionary<Symbol, long> AllShortableSymbols(DateTime localTime)
{
var shortableDataDirectory = Path.Combine(Globals.DataFolder, SecurityType.Equity.SecurityTypeToLower(), Market.USA, "shortable", Brokerage);
var allSymbols = new Dictionary<Symbol, long>();
// Check backwards up to one week to see if we can source a previous file.
@@ -197,7 +195,7 @@ namespace QuantConnect.Algorithm.CSharp
var i = 0;
while (i <= 7)
{
var shortableListFile = Path.Combine(shortableDataDirectory, "dates", $"{localTime.AddDays(-i):yyyyMMdd}.csv");
var shortableListFile = Path.Combine(ShortableDataDirectory.FullName, "dates", $"{localTime.AddDays(-i):yyyyMMdd}.csv");
foreach (var line in DataProvider.ReadLines(shortableListFile))
{
@@ -233,55 +231,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp};
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 36573;
public long DataPoints => 37754;
/// <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", "8"},
{"Total Trades", "5"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "11.027%"},
{"Drawdown", "0.000%"},
{"Compounding Annual Return", "19.147%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "10000000"},
{"End Equity", "10011469.88"},
{"Net Profit", "0.115%"},
{"Sharpe Ratio", "11.963"},
{"Sortino Ratio", "0"},
{"Net Profit", "0.192%"},
{"Sharpe Ratio", "231.673"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.07"},
{"Beta", "-0.077"},
{"Annual Standard Deviation", "0.008"},
{"Alpha", "0.163"},
{"Beta", "-0.007"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "3.876"},
{"Tracking Error", "0.105"},
{"Treynor Ratio", "-1.215"},
{"Total Fees", "$282.50"},
{"Estimated Strategy Capacity", "$61000000000.00"},
{"Lowest Capacity Asset", "NB R735QTJ8XC9X"},
{"Portfolio Turnover", "3.62%"},
{"OrderListHash", "0ea806c53bfa2bdca2504ba7155ef130"}
{"Information Ratio", "4.804"},
{"Tracking Error", "0.098"},
{"Treynor Ratio", "-22.526"},
{"Total Fees", "$307.50"},
{"Estimated Strategy Capacity", "$2600000.00"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "10.61%"},
{"OrderListHash", "0069f402ffcd2d91b9018b81badfab81"}
};
}
}

View File

@@ -13,39 +13,46 @@
* limitations under the License.
*/
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using System;
using QuantConnect.Securities;
using System.Collections.Generic;
using QuantConnect.Data.Custom.AlphaStreams;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Asserts we can use a C# function as a FuncRiskFreeRateInterestRateModel
/// Example algorithm consuming an alpha streams portfolio state and trading based on it
/// </summary>
public class FuncRiskFreeRateInterestRateModelWithPythonLambda: QCAlgorithm, IRegressionAlgorithmDefinition
public class AlphaStreamsBasicTemplateAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
FuncRiskFreeRateInterestRateModel _model;
/// <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, 5, 28);
SetEndDate(2020, 6, 28);
SetStartDate(2018, 04, 04);
SetEndDate(2018, 04, 06);
AddEquity("SPY", Resolution.Daily);
_model = new FuncRiskFreeRateInterestRateModel(dt => dt.Date == new DateTime(2020, 5, 28) ? 0 : 1);
SetAlpha(new AlphaStreamAlphaModule());
SetExecution(new ImmediateExecutionModel());
Settings.MinimumOrderMarginPortfolioPercentage = 0.01m;
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
SetSecurityInitializer(new BrokerageModelSecurityInitializer(BrokerageModel,
new FuncSecuritySeeder(GetLastKnownPrices)));
foreach (var alphaId in new [] { "623b06b231eb1cc1aa3643a46", "9fc8ef73792331b11dbd5429a" })
{
AddData<AlphaStreamsPortfolioState>(alphaId);
}
}
public override void OnData(Slice slice)
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (Time.Date == (new DateTime(2020, 5, 28)) && _model.GetInterestRate(Time) != 0)
{
throw new RegressionTestException($"Risk Free interest rate should be 0, but was {_model.GetInterestRate(Time)}");
}
else if (Time.Date != (new DateTime(2020, 5, 28)) && _model.GetInterestRate(Time) != 1)
{
throw new RegressionTestException($"Risk Free interest rate should be 1, but was {_model.GetInterestRate(Time)}");
}
Log($"OnOrderEvent: {orderEvent}");
}
/// <summary>
@@ -56,55 +63,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 185;
public virtual long DataPoints => 890;
/// <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;
public virtual int AlgorithmHistoryDataPoints => 12;
/// <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>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "0"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100000"},
{"Net Profit", "0%"},
{"Average Loss", "-0.12%"},
{"Compounding Annual Return", "-14.722%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.116%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0.069"},
{"Tracking Error", "0.243"},
{"Information Ratio", "2.474"},
{"Tracking Error", "0.339"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
{"Estimated Strategy Capacity", "$83000.00"},
{"Lowest Capacity Asset", "BTCUSD XJ"},
{"Portfolio Turnover", "2.31%"},
{"OrderListHash", "2b94bc50a74caebe06c075cdab1bc6da"}
};
}
}

View File

@@ -0,0 +1,85 @@
/*
* 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
{
/// <summary>
/// Example algorithm with existing holdings consuming an alpha streams portfolio state and trading based on it
/// </summary>
public class AlphaStreamsDifferentAccountCurrencyBasicTemplateAlgorithm : AlphaStreamsWithHoldingsBasicTemplateAlgorithm
{
/// <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()
{
SetAccountCurrency("EUR");
base.Initialize();
}
/// <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 override long DataPoints => 6202;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 61;
/// <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 Trades", "2"},
{"Average Win", "0.01%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-78.519%"},
{"Drawdown", "3.100%"},
{"Expectancy", "7.797"},
{"Net Profit", "-1.134%"},
{"Sharpe Ratio", "-2.456"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "16.59"},
{"Alpha", "0.006"},
{"Beta", "1.011"},
{"Annual Standard Deviation", "0.343"},
{"Annual Variance", "0.117"},
{"Information Ratio", "-0.859"},
{"Tracking Error", "0.004"},
{"Treynor Ratio", "-0.832"},
{"Total Fees", "€2.89"},
{"Estimated Strategy Capacity", "€8900000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "33.78%"},
{"OrderListHash", "a9dd0a0ab6070455479d1b9caaa4e69c"}
};
}
}

View File

@@ -0,0 +1,122 @@
/*
* 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 QuantConnect.Interfaces;
using System.Collections.Generic;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Data.Custom.AlphaStreams;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Selection;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Example algorithm consuming an alpha streams portfolio state and trading based on it
/// </summary>
public class AlphaStreamsUniverseSelectionTemplateAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
/// <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(2018, 04, 04);
SetEndDate(2018, 04, 06);
SetAlpha(new AlphaStreamAlphaModule());
SetExecution(new ImmediateExecutionModel());
Settings.MinimumOrderMarginPortfolioPercentage = 0.01m;
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
SetUniverseSelection(new ScheduledUniverseSelectionModel(
DateRules.EveryDay(),
TimeRules.Midnight,
SelectAlphas,
new UniverseSettings(UniverseSettings)
{
SubscriptionDataTypes = new List<Tuple<Type, TickType>>
{new(typeof(AlphaStreamsPortfolioState), TickType.Trade)},
FillForward = false,
}
));
}
private IEnumerable<Symbol> SelectAlphas(DateTime dateTime)
{
Log($"SelectAlphas() {Time}");
foreach (var alphaId in new[] {"623b06b231eb1cc1aa3643a46", "9fc8ef73792331b11dbd5429a"})
{
var alphaSymbol = new Symbol(SecurityIdentifier.GenerateBase(typeof(AlphaStreamsPortfolioState), alphaId, Market.USA),
alphaId);
yield return alphaSymbol;
}
}
/// <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 long DataPoints => 893;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 2;
/// <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 Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.12%"},
{"Compounding Annual Return", "-13.200%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.116%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "2.474"},
{"Tracking Error", "0.339"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$83000.00"},
{"Lowest Capacity Asset", "BTCUSD XJ"},
{"Portfolio Turnover", "2.31%"},
{"OrderListHash", "2b94bc50a74caebe06c075cdab1bc6da"}
};
}
}

View File

@@ -0,0 +1,136 @@
/*
* 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 QuantConnect.Orders;
using System.Collections.Generic;
using QuantConnect.Data.Custom.AlphaStreams;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Example algorithm with existing holdings consuming an alpha streams portfolio state and trading based on it
/// </summary>
public class AlphaStreamsWithHoldingsBasicTemplateAlgorithm : AlphaStreamsBasicTemplateAlgorithm
{
private decimal _expectedSpyQuantity;
/// <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(2018, 04, 04);
SetEndDate(2018, 04, 06);
SetCash(100000);
SetExecution(new ImmediateExecutionModel());
UniverseSettings.Resolution = Resolution.Hour;
Settings.MinimumOrderMarginPortfolioPercentage = 0.001m;
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
// AAPL should be liquidated since it's not hold by the alpha
// This is handled by the PCM
var aapl = AddEquity("AAPL", Resolution.Hour);
aapl.Holdings.SetHoldings(40, 10);
// SPY will be bought following the alpha streams portfolio
// This is handled by the PCM + Execution Model
var spy = AddEquity("SPY", Resolution.Hour);
spy.Holdings.SetHoldings(246, -10);
AddData<AlphaStreamsPortfolioState>("94d820a93fff127fa46c15231d");
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (_expectedSpyQuantity == 0 && orderEvent.Symbol == "SPY" && orderEvent.Status == OrderStatus.Filled)
{
var security = Securities["SPY"];
var priceInAccountCurrency = Portfolio.CashBook.ConvertToAccountCurrency(security.AskPrice, security.QuoteCurrency.Symbol);
_expectedSpyQuantity = Portfolio.TotalPortfolioValueLessFreeBuffer / priceInAccountCurrency;
_expectedSpyQuantity = _expectedSpyQuantity.DiscretelyRoundBy(1, MidpointRounding.ToZero);
}
base.OnOrderEvent(orderEvent);
}
public override void OnEndOfAlgorithm()
{
if (Securities["AAPL"].HoldStock)
{
throw new Exception("We should no longer hold AAPL since the alpha does not");
}
// we allow some padding for small price differences
if (Math.Abs(Securities["SPY"].Holdings.Quantity - _expectedSpyQuantity) > _expectedSpyQuantity * 0.03m)
{
throw new Exception($"Unexpected SPY holdings. Expected {_expectedSpyQuantity} was {Securities["SPY"].Holdings.Quantity}");
}
}
/// <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 override long DataPoints => 2313;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 1;
/// <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 Trades", "2"},
{"Average Win", "0.01%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-87.617%"},
{"Drawdown", "3.100%"},
{"Expectancy", "8.518"},
{"Net Profit", "-1.515%"},
{"Sharpe Ratio", "-2.45"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "18.04"},
{"Alpha", "0.008"},
{"Beta", "1.015"},
{"Annual Standard Deviation", "0.344"},
{"Annual Variance", "0.118"},
{"Information Ratio", "-0.856"},
{"Tracking Error", "0.005"},
{"Treynor Ratio", "-0.83"},
{"Total Fees", "$3.09"},
{"Estimated Strategy Capacity", "$8900000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "34.12%"},
{"OrderListHash", "788eb2c74715a78476ba0db3b2654eb6"}
};
}
}

View File

@@ -80,7 +80,7 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -92,17 +92,12 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
/// </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", "2465"},
{"Total Trades", "2465"},
{"Average Win", "0.26%"},
{"Average Loss", "-0.24%"},
{"Compounding Annual Return", "7.848%"},

View File

@@ -1,33 +0,0 @@
/*
* 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>
/// Example algorithm using the asynchronous universe selection functionality
/// </summary>
public class AsynchronousUniverseRegressionAlgorithm : FundamentalRegressionAlgorithm
{
/// <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()
{
base.Initialize();
UniverseSettings.Asynchronous = true;
}
}
}

View File

@@ -37,7 +37,7 @@ namespace QuantConnect.Algorithm.CSharp
SetStartDate(2013, 1, 07);
SetEndDate(2013, 12, 11);
Settings.AutomaticIndicatorWarmUp = true;
EnableAutomaticIndicatorWarmUp = true;
AddEquity("SPY", Resolution.Daily);
_arima = ARIMA("SPY", 1, 1, 1, 50);
_ar = ARIMA("SPY", 1, 1, 0, 50);
@@ -71,7 +71,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -83,43 +83,35 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 100;
/// <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", "53"},
{"Total Trades", "52"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "0.076%"},
{"Compounding Annual Return", "0.096%"},
{"Drawdown", "0.100%"},
{"Expectancy", "2.933"},
{"Start Equity", "100000"},
{"End Equity", "100070.90"},
{"Net Profit", "0.071%"},
{"Sharpe Ratio", "-9.164"},
{"Sortino Ratio", "-9.852"},
{"Probabilistic Sharpe Ratio", "36.417%"},
{"Loss Rate", "27%"},
{"Win Rate", "73%"},
{"Profit-Loss Ratio", "4.41"},
{"Alpha", "-0.008"},
{"Expectancy", "3.321"},
{"Net Profit", "0.089%"},
{"Sharpe Ratio", "0.798"},
{"Probabilistic Sharpe Ratio", "40.893%"},
{"Loss Rate", "24%"},
{"Win Rate", "76%"},
{"Profit-Loss Ratio", "4.67"},
{"Alpha", "-0.001"},
{"Beta", "0.008"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.961"},
{"Tracking Error", "0.092"},
{"Treynor Ratio", "-0.911"},
{"Total Fees", "$53.00"},
{"Estimated Strategy Capacity", "$16000000000.00"},
{"Treynor Ratio", "0.08"},
{"Total Fees", "$52.00"},
{"Estimated Strategy Capacity", "$32000000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "0.02%"},
{"OrderListHash", "685c37df6e4c49b75792c133be189094"}
{"OrderListHash", "cf43585a8d1781f04b53a4f1ee3380cb"}
};
}
}

View File

@@ -33,7 +33,7 @@ namespace QuantConnect.Algorithm.CSharp
public override void Initialize()
{
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
Settings.AutomaticIndicatorWarmUp = true;
EnableAutomaticIndicatorWarmUp = true;
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 10);
@@ -82,7 +82,7 @@ namespace QuantConnect.Algorithm.CSharp
if (!sma11.Current.Equals(sma1.Current))
{
throw new RegressionTestException("Expected SMAs warmed up before and after adding the Future to the algorithm to have the same current value. " +
throw new Exception("Expected SMAs warmed up before and after adding the Future to the algorithm to have the same current value. " +
"The result of 'WarmUpIndicator' shouldn't change if the symbol is or isn't subscribed");
}
@@ -94,7 +94,7 @@ namespace QuantConnect.Algorithm.CSharp
if (!smaSpy.Current.Equals(sma.Current))
{
throw new RegressionTestException("Expected SMAs warmed up before and after adding the Equity to the algorithm to have the same current value. " +
throw new Exception("Expected SMAs warmed up before and after adding the Equity to the algorithm to have the same current value. " +
"The result of 'WarmUpIndicator' shouldn't change if the symbol is or isn't subscribed");
}
}
@@ -103,7 +103,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (indicator.IsReady != isReady)
{
throw new RegressionTestException($"Expected indicator state, expected {isReady} but was {indicator.IsReady}");
throw new Exception($"Expected indicator state, expected {isReady} but was {indicator.IsReady}");
}
}
@@ -111,7 +111,7 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
@@ -141,7 +141,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -153,43 +153,35 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 84;
/// <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"},
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "733913.744%"},
{"Drawdown", "15.900%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "106827.7"},
{"Net Profit", "6.828%"},
{"Sharpe Ratio", "203744786353.299"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "203744786353.302"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "456382350698.622"},
{"Alpha", "456382350698.561"},
{"Beta", "9.229"},
{"Annual Standard Deviation", "2.24"},
{"Annual Variance", "5.017"},
{"Information Ratio", "228504036840.953"},
{"Tracking Error", "1.997"},
{"Treynor Ratio", "49450701625.717"},
{"Treynor Ratio", "49450701625.718"},
{"Total Fees", "$23.65"},
{"Estimated Strategy Capacity", "$200000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Portfolio Turnover", "351.80%"},
{"OrderListHash", "dfd9a280d3c6470b305c03e0b72c234e"}
{"OrderListHash", "dd38e7b94027d20942a5aa9ac31a9a7f"}
};
}
}

View File

@@ -1,126 +0,0 @@
/*
* 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 QuantConnect.Indicators;
using QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting the behavior of the AutomaticIndicatorWarmUp on option greeks
/// </summary>
public class AutomaticIndicatorWarmupOptionIndicatorsMirrorContractsRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2015, 12, 24);
SetEndDate(2015, 12, 24);
Settings.AutomaticIndicatorWarmUp = true;
var underlying = "GOOG";
var resolution = Resolution.Minute;
var expiration = new DateTime(2015, 12, 24);
var strike = 650m;
var equity = AddEquity(underlying, resolution).Symbol;
var option = QuantConnect.Symbol.CreateOption(underlying, Market.USA, OptionStyle.American, OptionRight.Put, strike, expiration);
AddOptionContract(option, resolution);
// add the call counter side of the mirrored pair
var mirrorOption = QuantConnect.Symbol.CreateOption(underlying, Market.USA, OptionStyle.American, OptionRight.Call, strike, expiration);
AddOptionContract(mirrorOption, resolution);
var impliedVolatility = IV(option, mirrorOption);
var delta = D(option, mirrorOption, optionModel: OptionPricingModelType.BinomialCoxRossRubinstein, ivModel: OptionPricingModelType.BlackScholes);
var gamma = G(option, mirrorOption, optionModel: OptionPricingModelType.ForwardTree, ivModel: OptionPricingModelType.BlackScholes);
var vega = V(option, mirrorOption, optionModel: OptionPricingModelType.ForwardTree, ivModel: OptionPricingModelType.BlackScholes);
var theta = T(option, mirrorOption, optionModel: OptionPricingModelType.ForwardTree, ivModel: OptionPricingModelType.BlackScholes);
var rho = R(option, mirrorOption, optionModel: OptionPricingModelType.ForwardTree, ivModel: OptionPricingModelType.BlackScholes);
if (impliedVolatility == 0m || delta == 0m || gamma == 0m || vega == 0m || theta == 0m || rho == 0m)
{
throw new RegressionTestException("Expected IV/greeks calculated");
}
if (!impliedVolatility.IsReady || !delta.IsReady || !gamma.IsReady || !vega.IsReady || !theta.IsReady || !rho.IsReady)
{
throw new RegressionTestException("Expected IV/greeks to be ready");
}
Quit($"Implied Volatility: {impliedVolatility}, Delta: {delta}, Gamma: {gamma}, Vega: {vega}, Theta: {theta}, Rho: {rho}");
}
/// <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 => 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 => 0;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 21;
/// <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"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -34,14 +34,14 @@ namespace QuantConnect.Algorithm.CSharp
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);
Settings.AutomaticIndicatorWarmUp = true;
EnableAutomaticIndicatorWarmUp = true;
// Test case 1
_spy = AddEquity("SPY").Symbol;
var sma = SMA(_spy, 10);
if (!sma.IsReady)
{
throw new RegressionTestException("Expected SMA to be warmed up");
throw new Exception("Expected SMA to be warmed up");
}
// Test case 2
@@ -50,20 +50,20 @@ namespace QuantConnect.Algorithm.CSharp
if (indicator.IsReady)
{
throw new RegressionTestException("Expected CustomIndicator Not to be warmed up");
throw new Exception("Expected CustomIndicator Not to be warmed up");
}
WarmUpIndicator(_spy, indicator);
if (!indicator.IsReady)
{
throw new RegressionTestException("Expected CustomIndicator to be warmed up");
throw new Exception("Expected CustomIndicator to be warmed up");
}
}
/// <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)
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
@@ -72,7 +72,7 @@ namespace QuantConnect.Algorithm.CSharp
// we expect 1 consolidator per indicator
if (subscription.Consolidators.Count != 2)
{
throw new RegressionTestException($"Unexpected consolidator count for subscription: {subscription.Consolidators.Count}");
throw new Exception($"Unexpected consolidator count for subscription: {subscription.Consolidators.Count}");
}
SetHoldings(_spy, 1);
}
@@ -88,7 +88,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (_previous != null && input.EndTime == _previous.EndTime)
{
throw new RegressionTestException($"Unexpected indicator double data point call: {_previous}");
throw new Exception($"Unexpected indicator double data point call: {_previous}");
}
_previous = input;
return base.ComputeNextValue(window, input);
@@ -103,7 +103,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -115,27 +115,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 40;
/// <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"},
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "271.453%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "101691.92"},
{"Net Profit", "1.692%"},
{"Sharpe Ratio", "8.854"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "8.888"},
{"Probabilistic Sharpe Ratio", "67.609%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -146,12 +138,12 @@ namespace QuantConnect.Algorithm.CSharp
{"Annual Variance", "0.049"},
{"Information Ratio", "-14.565"},
{"Tracking Error", "0.001"},
{"Treynor Ratio", "1.97"},
{"Treynor Ratio", "1.978"},
{"Total Fees", "$3.44"},
{"Estimated Strategy Capacity", "$56000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "19.93%"},
{"OrderListHash", "3da9fa60bf95b9ed148b95e02e0cfc9e"}
{"OrderListHash", "9e4bfd2eb0b81ee5bc1b197a87ccedbe"}
};
}
}

View File

@@ -1,168 +0,0 @@
/*
* 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 QuantConnect.Interfaces;
using QuantConnect.Data.Market;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Example algorithm using and asserting the behavior of auxiliary Data handlers
/// </summary>
public class AuxiliaryDataHandlersRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private bool _onSplits;
private bool _onDividends;
private bool _onDelistingsCalled;
private bool _onSymbolChangedEvents;
/// <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(2007, 05, 16);
SetEndDate(2015, 1, 1);
UniverseSettings.Resolution = Resolution.Daily;
// will get delisted
AddEquity("AAA.1");
// get's remapped
AddEquity("SPWR");
// has a split & dividends
AddEquity("AAPL");
}
public override void OnDelistings(Delistings delistings)
{
if (!delistings.ContainsKey("AAA.1"))
{
throw new RegressionTestException("Unexpected OnDelistings call");
}
_onDelistingsCalled = true;
}
public override void OnSymbolChangedEvents(SymbolChangedEvents symbolsChanged)
{
if (!symbolsChanged.ContainsKey("SPWR"))
{
throw new RegressionTestException("Unexpected OnSymbolChangedEvents call");
}
_onSymbolChangedEvents = true;
}
public override void OnSplits(Splits splits)
{
if (!splits.ContainsKey("AAPL"))
{
throw new RegressionTestException("Unexpected OnSplits call");
}
_onSplits = true;
}
public override void OnDividends(Dividends dividends)
{
if (!dividends.ContainsKey("AAPL"))
{
throw new RegressionTestException("Unexpected OnDividends call");
}
_onDividends = true;
}
public override void OnEndOfAlgorithm()
{
if (!_onDelistingsCalled)
{
throw new RegressionTestException("OnDelistings was not called!");
}
if (!_onSymbolChangedEvents)
{
throw new RegressionTestException("OnSymbolChangedEvents was not called!");
}
if (!_onSplits)
{
throw new RegressionTestException("OnSplits was not called!");
}
if (!_onDividends)
{
throw new RegressionTestException("OnDividends was not called!");
}
}
/// <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 => 126221;
/// <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.332"},
{"Tracking Error", "0.183"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -151,12 +151,12 @@ namespace QuantConnect.Algorithm.CSharp
case OrderStatus.PartiallyFilled:
if (order.LastFillTime == null)
{
throw new RegressionTestException("LastFillTime should not be null");
throw new Exception("LastFillTime should not be null");
}
if (order.Quantity / 2 != orderEvent.FillQuantity)
{
throw new RegressionTestException("Order size should be half");
throw new Exception("Order size should be half");
}
break;
@@ -164,7 +164,7 @@ namespace QuantConnect.Algorithm.CSharp
case OrderStatus.Filled:
if (order.SecurityType == SecurityType.Equity && order.CreatedTime == order.LastFillTime)
{
throw new RegressionTestException("Order should not finish during the CreatedTime bar");
throw new Exception("Order should not finish during the CreatedTime bar");
}
break;
@@ -182,12 +182,12 @@ namespace QuantConnect.Algorithm.CSharp
// If the option price isn't the same as the strike price, its incorrect
if (order.Price != _optionStrikePrice)
{
throw new RegressionTestException("OptionExercise order price should be strike price!!");
throw new Exception("OptionExercise order price should be strike price!!");
}
if (orderEvent.Quantity != -1)
{
throw new RegressionTestException("OrderEvent Quantity should be -1");
throw new Exception("OrderEvent Quantity should be -1");
}
}
@@ -198,14 +198,14 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!Portfolio.ContainsKey(_optionBuy.Symbol) || !Portfolio.ContainsKey(_optionBuy.Symbol.Underlying) || !Portfolio.ContainsKey(_equityBuy.Symbol))
{
throw new RegressionTestException("Portfolio does not contain the Symbols we purchased");
throw new Exception("Portfolio does not contain the Symbols we purchased");
}
//Check option holding, should not be invested since it expired, profit should be -400
var optionHolding = Portfolio[_optionBuy.Symbol];
if (optionHolding.Invested || optionHolding.Profit != -400)
{
throw new RegressionTestException("Options holding does not match expected outcome");
throw new Exception("Options holding does not match expected outcome");
}
//Check the option underlying symbol since we should have bought it at exercise
@@ -213,7 +213,7 @@ namespace QuantConnect.Algorithm.CSharp
var optionExerciseHolding = Portfolio[_optionBuy.Symbol.Underlying];
if (!optionExerciseHolding.Invested || optionExerciseHolding.Quantity != 100 || optionExerciseHolding.AveragePrice != _optionBuy.Symbol.ID.StrikePrice)
{
throw new RegressionTestException("Equity holding for exercised option does not match expected outcome");
throw new Exception("Equity holding for exercised option does not match expected outcome");
}
//Check equity holding, should be invested, profit should be
@@ -221,7 +221,7 @@ namespace QuantConnect.Algorithm.CSharp
var equityHolding = Portfolio[_equityBuy.Symbol];
if (!equityHolding.Invested || equityHolding.Quantity != 52 || equityHolding.AveragePrice != _equityBuy.AverageFillPrice)
{
throw new RegressionTestException("Equity holding does not match expected outcome");
throw new Exception("Equity holding does not match expected outcome");
}
}
@@ -291,55 +291,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 27071;
public long DataPoints => 1272232;
/// <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", "3"},
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "-0.40%"},
{"Compounding Annual Return", "-21.378%"},
{"Compounding Annual Return", "-22.717%"},
{"Drawdown", "0.400%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "99671.06"},
{"Net Profit", "-0.329%"},
{"Sharpe Ratio", "-14.095"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "-7.887"},
{"Probabilistic Sharpe Ratio", "1.216%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.01"},
{"Alpha", "-0.001"},
{"Beta", "0.097"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "7.39"},
{"Tracking Error", "0.015"},
{"Treynor Ratio", "-0.234"},
{"Treynor Ratio", "-0.131"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "17.02%"},
{"OrderListHash", "b1e5e72fb766ab894204bc4b1300912b"}
{"OrderListHash", "85cbf92f01c2c91b5f710b7eeefecbe1"}
};
}
}

View File

@@ -63,7 +63,7 @@ namespace QuantConnect.Algorithm.CSharp
var insightsCount = Insights.GetInsights(insight => insight.IsActive(UtcTime)).Count;
if (insightsCount != 0)
{
throw new RegressionTestException($"The number of active insights should be 0. Actual: {insightsCount}");
throw new Exception($"The number of active insights should be 0. Actual: {insightsCount}");
}
}
@@ -75,7 +75,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -87,11 +87,6 @@ namespace QuantConnect.Algorithm.CSharp
/// </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>

View File

@@ -49,7 +49,7 @@ namespace QuantConnect.Algorithm.CSharp
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// Slice object keyed by symbol containing the stock data
public override void OnData(Slice slice)
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
@@ -63,4 +63,4 @@ namespace QuantConnect.Algorithm.CSharp
}
}
}
}
}

View File

@@ -50,7 +50,7 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
@@ -67,7 +67,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -79,27 +79,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 120;
/// <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"},
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000.00"},
{"End Equity", "92395.59"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -113,9 +105,9 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "€298.35"},
{"Estimated Strategy Capacity", "€85000.00"},
{"Lowest Capacity Asset", "BTCEUR 2XR"},
{"Lowest Capacity Asset", "BTCEUR XJ"},
{"Portfolio Turnover", "107.64%"},
{"OrderListHash", "6819dc936b86af6e4b89b6017b7d5284"}
{"OrderListHash", "2ba443899dcccc79dc0f04441f797bf9"}
};
}
}

View File

@@ -37,7 +37,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -49,27 +49,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 120;
/// <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"},
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "200000.00"},
{"End Equity", "184791.19"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -83,9 +75,9 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "€596.71"},
{"Estimated Strategy Capacity", "€85000.00"},
{"Lowest Capacity Asset", "BTCEUR 2XR"},
{"Lowest Capacity Asset", "BTCEUR XJ"},
{"Portfolio Turnover", "107.64%"},
{"OrderListHash", "3d450fd418a0e845b3eaaac17fcd13fc"}
{"OrderListHash", "af1850fbc1faefaf2da98080e92c43a0"}
};
}
}

View File

@@ -53,7 +53,7 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
@@ -70,7 +70,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -82,27 +82,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </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"},
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "271.453%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "101691.92"},
{"Net Profit", "1.692%"},
{"Sharpe Ratio", "8.854"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "8.888"},
{"Probabilistic Sharpe Ratio", "67.609%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -113,12 +105,12 @@ namespace QuantConnect.Algorithm.CSharp
{"Annual Variance", "0.049"},
{"Information Ratio", "-14.565"},
{"Tracking Error", "0.001"},
{"Treynor Ratio", "1.97"},
{"Treynor Ratio", "1.978"},
{"Total Fees", "$3.44"},
{"Estimated Strategy Capacity", "$56000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "19.93%"},
{"OrderListHash", "3da9fa60bf95b9ed148b95e02e0cfc9e"}
{"OrderListHash", "9e4bfd2eb0b81ee5bc1b197a87ccedbe"}
};
}
}

View File

@@ -14,6 +14,7 @@
*/
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Brokerages;
using System.Collections.Generic;
@@ -21,12 +22,12 @@ using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Basic template algorithm for the Axos brokerage
/// Basic template algorithm for the Atreyu brokerage
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="using quantconnect" />
/// <meta name="tag" content="trading and orders" />
public class BasicTemplateAxosAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
public class BasicTemplateAtreyuAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
@@ -37,15 +38,21 @@ namespace QuantConnect.Algorithm.CSharp
SetEndDate(2013, 10, 11);
SetCash(100000);
SetBrokerageModel(BrokerageName.Axos);
SetBrokerageModel(BrokerageName.Atreyu);
AddEquity("SPY", Resolution.Minute);
DefaultOrderProperties = new AtreyuOrderProperties
{
// Currently only support order for the day
TimeInForce = TimeInForce.Day
};
}
/// <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)
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
@@ -64,7 +71,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -76,27 +83,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </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"},
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "39.143%"},
{"Drawdown", "0.500%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100423.24"},
{"Net Profit", "0.423%"},
{"Sharpe Ratio", "5.498"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "5.634"},
{"Probabilistic Sharpe Ratio", "67.498%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -112,7 +111,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$150000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "4.98%"},
{"OrderListHash", "8774049eb5141a2b6956d9432426f837"}
{"OrderListHash", "d549c64ee7f5e3866712b3c7dbd64caa"}
};
}
}

View File

@@ -59,14 +59,14 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice data)
{
foreach (var changedEvent in slice.SymbolChangedEvents.Values)
foreach (var changedEvent in data.SymbolChangedEvents.Values)
{
Debug($"{Time} - SymbolChanged event: {changedEvent}");
if (Time.TimeOfDay != TimeSpan.Zero)
{
throw new RegressionTestException($"{Time} unexpected symbol changed event {changedEvent}!");
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
@@ -113,55 +113,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 713369;
public long DataPoints => 703956;
/// <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", "5"},
{"Average Win", "2.48%"},
{"Total Trades", "3"},
{"Average Win", "5.51%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "11.325%"},
{"Compounding Annual Return", "12.437%"},
{"Drawdown", "1.500%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "105549.6"},
{"Net Profit", "5.550%"},
{"Sharpe Ratio", "1.332"},
{"Sortino Ratio", "879.904"},
{"Probabilistic Sharpe Ratio", "79.894%"},
{"Net Profit", "6.079%"},
{"Sharpe Ratio", "1.604"},
{"Probabilistic Sharpe Ratio", "88.038%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.075"},
{"Beta", "-0.017"},
{"Annual Standard Deviation", "0.053"},
{"Alpha", "0.091"},
{"Beta", "-0.02"},
{"Annual Standard Deviation", "0.054"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-1.48"},
{"Information Ratio", "-1.399"},
{"Tracking Error", "0.099"},
{"Treynor Ratio", "-4.187"},
{"Total Fees", "$10.75"},
{"Estimated Strategy Capacity", "$7100000.00"},
{"Treynor Ratio", "-4.276"},
{"Total Fees", "$6.45"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Portfolio Turnover", "2.33%"},
{"OrderListHash", "9c524830ffc7354327638142ae62acd2"}
{"Portfolio Turnover", "1.39%"},
{"OrderListHash", "624c51bc6451dfb74335b99c04e3ed16"}
};
}
}

View File

@@ -59,15 +59,15 @@ namespace QuantConnect.Algorithm.CSharp
/// <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)
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
foreach (var changedEvent in slice.SymbolChangedEvents.Values)
foreach (var changedEvent in data.SymbolChangedEvents.Values)
{
Debug($"{Time} - SymbolChanged event: {changedEvent}");
if (Time.TimeOfDay != TimeSpan.Zero)
{
throw new RegressionTestException($"{Time} unexpected symbol changed event {changedEvent}!");
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
@@ -118,55 +118,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 2217299;
public long DataPoints => 2169065;
/// <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", "5"},
{"Average Win", "2.86%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "12.959%"},
{"Drawdown", "1.100%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "106337.1"},
{"Net Profit", "6.337%"},
{"Sharpe Ratio", "1.41"},
{"Sortino Ratio", "1.242"},
{"Probabilistic Sharpe Ratio", "77.992%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.071"},
{"Beta", "0.054"},
{"Annual Standard Deviation", "0.059"},
{"Total Trades", "5"},
{"Average Win", "4.45%"},
{"Average Loss", "-0.26%"},
{"Compounding Annual Return", "8.423%"},
{"Drawdown", "0.800%"},
{"Expectancy", "8.202"},
{"Net Profit", "4.162%"},
{"Sharpe Ratio", "1.089"},
{"Probabilistic Sharpe Ratio", "53.568%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "17.40"},
{"Alpha", "0.06"},
{"Beta", "-0.005"},
{"Annual Standard Deviation", "0.054"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-1.392"},
{"Tracking Error", "0.097"},
{"Treynor Ratio", "1.518"},
{"Information Ratio", "-1.681"},
{"Tracking Error", "0.099"},
{"Treynor Ratio", "-11.74"},
{"Total Fees", "$10.75"},
{"Estimated Strategy Capacity", "$890000000.00"},
{"Estimated Strategy Capacity", "$190000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Portfolio Turnover", "2.32%"},
{"OrderListHash", "f60fc7dcba2c1ff077afeb191aee5008"}
{"Portfolio Turnover", "2.34%"},
{"OrderListHash", "2a0aa0c11df66d81ebf0f7b3e9048bbc"}
};
}
}

View File

@@ -79,8 +79,8 @@ namespace QuantConnect.Algorithm.CSharp
/// <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)
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (Portfolio.CashBook["EUR"].ConversionRate == 0
|| Portfolio.CashBook["BTC"].ConversionRate == 0
@@ -92,7 +92,7 @@ namespace QuantConnect.Algorithm.CSharp
Log($"LTC conversion rate: {Portfolio.CashBook["LTC"].ConversionRate}");
Log($"ETH conversion rate: {Portfolio.CashBook["ETH"].ConversionRate}");
throw new RegressionTestException("Conversion rate is 0");
throw new Exception("Conversion rate is 0");
}
if (Time.Hour == 1 && Time.Minute == 0)
{
@@ -196,7 +196,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -208,27 +208,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 240;
/// <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", "12"},
{"Total Trades", "10"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "31588.24"},
{"End Equity", "30866.71"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -242,9 +234,9 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "$85.34"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTCEUR 2XR"},
{"Lowest Capacity Asset", "BTCEUR XJ"},
{"Portfolio Turnover", "118.08%"},
{"OrderListHash", "26b9a07ace86b6a0e0eb2ff8c168cee0"}
{"OrderListHash", "1bf1a6d9dd921982b72a6178f9e50e68"}
};
}
}

View File

@@ -79,9 +79,9 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice data)
{
var interestRates = slice.Get<MarginInterestRate>();
var interestRates = data.Get<MarginInterestRate>();
foreach (var interestRate in interestRates)
{
_interestPerSymbol[interestRate.Key]++;
@@ -89,7 +89,7 @@ namespace QuantConnect.Algorithm.CSharp
var cachedInterestRate = Securities[interestRate.Key].Cache.GetData<MarginInterestRate>();
if (cachedInterestRate != interestRate.Value)
{
throw new RegressionTestException($"Unexpected cached margin interest rate for {interestRate.Key}!");
throw new Exception($"Unexpected cached margin interest rate for {interestRate.Key}!");
}
}
@@ -100,7 +100,7 @@ namespace QuantConnect.Algorithm.CSharp
var ticket = Buy(_btcUsd.Symbol, 50);
if (ticket.Status != OrderStatus.Invalid)
{
throw new RegressionTestException($"Unexpected valid order {ticket}, should fail due to margin not sufficient");
throw new Exception($"Unexpected valid order {ticket}, should fail due to margin not sufficient");
}
Buy(_btcUsd.Symbol, 1);
@@ -113,17 +113,17 @@ namespace QuantConnect.Algorithm.CSharp
if (Math.Abs(btcUsdHoldings.TotalSaleVolume - holdingsValueBtcUsd) > 1)
{
throw new RegressionTestException($"Unexpected TotalSaleVolume {btcUsdHoldings.TotalSaleVolume}");
throw new Exception($"Unexpected TotalSaleVolume {btcUsdHoldings.TotalSaleVolume}");
}
if (Math.Abs(btcUsdHoldings.AbsoluteHoldingsCost - holdingsValueBtcUsd) > 1)
{
throw new RegressionTestException($"Unexpected holdings cost {btcUsdHoldings.HoldingsCost}");
throw new Exception($"Unexpected holdings cost {btcUsdHoldings.HoldingsCost}");
}
// margin used is based on the maintenance rate
if (Math.Abs(btcUsdHoldings.AbsoluteHoldingsCost * 0.05m - marginUsed) > 1
|| _btcUsd.BuyingPowerModel.GetMaintenanceMargin(_btcUsd) != marginUsed)
{
throw new RegressionTestException($"Unexpected margin used {marginUsed}");
throw new Exception($"Unexpected margin used {marginUsed}");
}
Buy(_adaUsdt.Symbol, 1000);
@@ -136,28 +136,28 @@ namespace QuantConnect.Algorithm.CSharp
if (Math.Abs(adaUsdtHoldings.TotalSaleVolume - holdingsValueUsdt) > 1)
{
throw new RegressionTestException($"Unexpected TotalSaleVolume {adaUsdtHoldings.TotalSaleVolume}");
throw new Exception($"Unexpected TotalSaleVolume {adaUsdtHoldings.TotalSaleVolume}");
}
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost - holdingsValueUsdt) > 1)
{
throw new RegressionTestException($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
throw new Exception($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
}
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost * 0.05m - marginUsed) > 1
|| _adaUsdt.BuyingPowerModel.GetMaintenanceMargin(_adaUsdt) != marginUsed)
{
throw new RegressionTestException($"Unexpected margin used {marginUsed}");
throw new Exception($"Unexpected margin used {marginUsed}");
}
// position just opened should be just spread here
var profit = Portfolio.TotalUnrealizedProfit;
if ((5 - Math.Abs(profit)) < 0)
{
throw new RegressionTestException($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
throw new Exception($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
}
if (Portfolio.TotalProfit != 0)
{
throw new RegressionTestException($"Unexpected TotalProfit {Portfolio.TotalProfit}");
throw new Exception($"Unexpected TotalProfit {Portfolio.TotalProfit}");
}
}
}
@@ -172,7 +172,7 @@ namespace QuantConnect.Algorithm.CSharp
if (Math.Abs(btcUsdHoldings.AbsoluteHoldingsCost - 100 * 2) > 1)
{
throw new RegressionTestException($"Unexpected holdings cost {btcUsdHoldings.HoldingsCost}");
throw new Exception($"Unexpected holdings cost {btcUsdHoldings.HoldingsCost}");
}
Sell(_adaUsdt.Symbol, 3000);
@@ -184,19 +184,19 @@ namespace QuantConnect.Algorithm.CSharp
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost - holdingsValueUsdt) > 1)
{
throw new RegressionTestException($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
throw new Exception($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
}
// position just opened should be just spread here
var profit = Portfolio.TotalUnrealizedProfit;
if ((5 - Math.Abs(profit)) < 0)
{
throw new RegressionTestException($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
throw new Exception($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
}
// we barely did any difference on the previous trade
if ((5 - Math.Abs(Portfolio.TotalProfit)) < 0)
{
throw new RegressionTestException($"Unexpected TotalProfit {Portfolio.TotalProfit}");
throw new Exception($"Unexpected TotalProfit {Portfolio.TotalProfit}");
}
}
}
@@ -206,12 +206,12 @@ namespace QuantConnect.Algorithm.CSharp
{
if (_interestPerSymbol[_adaUsdt.Symbol] != 1)
{
throw new RegressionTestException($"Unexpected interest rate count {_interestPerSymbol[_adaUsdt.Symbol]}");
throw new Exception($"Unexpected interest rate count {_interestPerSymbol[_adaUsdt.Symbol]}");
}
if (_interestPerSymbol[_btcUsd.Symbol] != 3)
{
throw new RegressionTestException($"Unexpected interest rate count {_interestPerSymbol[_btcUsd.Symbol]}");
throw new Exception($"Unexpected interest rate count {_interestPerSymbol[_btcUsd.Symbol]}");
}
}
@@ -228,7 +228,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -240,27 +240,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </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", "5"},
{"Total Trades", "4"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000200.00"},
{"End Equity", "1000278.02"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -276,7 +268,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$500000000.00"},
{"Lowest Capacity Asset", "ADAUSDT 18R"},
{"Portfolio Turnover", "0.16%"},
{"OrderListHash", "dcc4f964b5549c753123848c32eaee41"}
{"OrderListHash", "254f39d98378b1e7aa397b1f1e49c6cc"}
};
}
}

View File

@@ -74,9 +74,9 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice data)
{
var interestRates = slice.Get<MarginInterestRate>();
var interestRates = data.Get<MarginInterestRate>();
foreach (var interestRate in interestRates)
{
_interestPerSymbol[interestRate.Key]++;
@@ -84,7 +84,7 @@ namespace QuantConnect.Algorithm.CSharp
var cachedInterestRate = Securities[interestRate.Key].Cache.GetData<MarginInterestRate>();
if (cachedInterestRate != interestRate.Value)
{
throw new RegressionTestException($"Unexpected cached margin interest rate for {interestRate.Key}!");
throw new Exception($"Unexpected cached margin interest rate for {interestRate.Key}!");
}
}
@@ -95,7 +95,7 @@ namespace QuantConnect.Algorithm.CSharp
var ticket = Buy(_adaUsdt.Symbol, 100000);
if(ticket.Status != OrderStatus.Invalid)
{
throw new RegressionTestException($"Unexpected valid order {ticket}, should fail due to margin not sufficient");
throw new Exception($"Unexpected valid order {ticket}, should fail due to margin not sufficient");
}
Buy(_adaUsdt.Symbol, 1000);
@@ -108,28 +108,28 @@ namespace QuantConnect.Algorithm.CSharp
if (Math.Abs(adaUsdtHoldings.TotalSaleVolume - holdingsValueUsdt) > 1)
{
throw new RegressionTestException($"Unexpected TotalSaleVolume {adaUsdtHoldings.TotalSaleVolume}");
throw new Exception($"Unexpected TotalSaleVolume {adaUsdtHoldings.TotalSaleVolume}");
}
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost - holdingsValueUsdt) > 1)
{
throw new RegressionTestException($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
throw new Exception($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
}
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost * 0.05m - marginUsed) > 1
|| _adaUsdt.BuyingPowerModel.GetMaintenanceMargin(_adaUsdt) != marginUsed)
{
throw new RegressionTestException($"Unexpected margin used {marginUsed}");
throw new Exception($"Unexpected margin used {marginUsed}");
}
// position just opened should be just spread here
var profit = Portfolio.TotalUnrealizedProfit;
if ((5 - Math.Abs(profit)) < 0)
{
throw new RegressionTestException($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
throw new Exception($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
}
if (Portfolio.TotalProfit != 0)
{
throw new RegressionTestException($"Unexpected TotalProfit {Portfolio.TotalProfit}");
throw new Exception($"Unexpected TotalProfit {Portfolio.TotalProfit}");
}
}
}
@@ -147,19 +147,19 @@ namespace QuantConnect.Algorithm.CSharp
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost - holdingsValueUsdt) > 1)
{
throw new RegressionTestException($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
throw new Exception($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
}
// position just opened should be just spread here
var profit = Portfolio.TotalUnrealizedProfit;
if ((5 - Math.Abs(profit)) < 0)
{
throw new RegressionTestException($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
throw new Exception($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
}
// we barely did any difference on the previous trade
if ((5 - Math.Abs(Portfolio.TotalProfit)) < 0)
{
throw new RegressionTestException($"Unexpected TotalProfit {Portfolio.TotalProfit}");
throw new Exception($"Unexpected TotalProfit {Portfolio.TotalProfit}");
}
}
@@ -174,7 +174,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (_interestPerSymbol[_adaUsdt.Symbol] != 1)
{
throw new RegressionTestException($"Unexpected interest rate count {_interestPerSymbol[_adaUsdt.Symbol]}");
throw new Exception($"Unexpected interest rate count {_interestPerSymbol[_adaUsdt.Symbol]}");
}
}
@@ -191,7 +191,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -203,27 +203,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </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", "3"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000200"},
{"End Equity", "1000189.47"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -239,7 +231,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$370000000.00"},
{"Lowest Capacity Asset", "ADAUSDT 18R"},
{"Portfolio Turnover", "0.12%"},
{"OrderListHash", "50a51d06d03a5355248a6bccef1ca521"}
{"OrderListHash", "d2c6198197a4d18fa0a81f5933d935a6"}
};
}
}

View File

@@ -43,8 +43,8 @@ namespace QuantConnect.Algorithm.CSharp
/// <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)
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
@@ -61,55 +61,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 72;
public long DataPoints => 73;
/// <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"},
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "424.375%"},
{"Drawdown", "0.800%"},
{"Compounding Annual Return", "246.546%"},
{"Drawdown", "1.200%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "104486.22"},
{"Net Profit", "4.486%"},
{"Sharpe Ratio", "17.304"},
{"Sortino Ratio", "35.217"},
{"Probabilistic Sharpe Ratio", "96.835%"},
{"Net Profit", "3.464%"},
{"Sharpe Ratio", "19.148"},
{"Probabilistic Sharpe Ratio", "97.754%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.249"},
{"Beta", "1.015"},
{"Annual Standard Deviation", "0.141"},
{"Annual Variance", "0.02"},
{"Information Ratio", "-19"},
{"Tracking Error", "0.011"},
{"Treynor Ratio", "2.403"},
{"Total Fees", "$3.49"},
{"Estimated Strategy Capacity", "$1200000000.00"},
{"Alpha", "-0.005"},
{"Beta", "0.998"},
{"Annual Standard Deviation", "0.138"},
{"Annual Variance", "0.019"},
{"Information Ratio", "-34.028"},
{"Tracking Error", "0"},
{"Treynor Ratio", "2.651"},
{"Total Fees", "$3.45"},
{"Estimated Strategy Capacity", "$970000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "10.01%"},
{"OrderListHash", "70f21e930175a2ec9d465b21edc1b6d9"}
{"Portfolio Turnover", "10.09%"},
{"OrderListHash", "33d01821923c397f999cfb2e5b5928ad"}
};
}
}

View File

@@ -1,239 +0,0 @@
/*
* 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 QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This algorithm tests and demonstrates EUREX futures subscription and trading:
/// - It tests contracts rollover by adding a continuous future and asserting that mapping happens at some point.
/// - It tests basic trading by buying a contract and holding it until expiration.
/// - It tests delisting and asserts the holdings are liquidated after that.
/// </summary>
public class BasicTemplateEurexFuturesAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Future _continuousContract;
private Symbol _mappedSymbol;
private Symbol _contractToTrade;
private int _mappingsCount;
private decimal _boughtQuantity;
private decimal _liquidatedQuantity;
private bool _delisted;
public override void Initialize()
{
SetStartDate(2024, 5, 30);
SetEndDate(2024, 6, 23);
SetAccountCurrency(Currencies.EUR);
SetCash(1000000);
_continuousContract = AddFuture(Futures.Indices.EuroStoxx50, Resolution.Minute,
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
dataMappingMode: DataMappingMode.FirstDayMonth,
contractDepthOffset: 0);
_continuousContract.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(180));
_mappedSymbol = _continuousContract.Mapped;
var benchmark = AddIndex("SX5E", market: Market.EUREX);
SetBenchmark(benchmark.Symbol);
var seeder = new FuncSecuritySeeder(GetLastKnownPrices);
SetSecurityInitializer(security => seeder.SeedSecurity(security));
}
public override void OnData(Slice slice)
{
foreach (var changedEvent in slice.SymbolChangedEvents.Values)
{
if (++_mappingsCount > 1)
{
throw new RegressionTestException($"{Time} - Unexpected number of symbol changed events (mappings): {_mappingsCount}. " +
$"Expected only 1.");
}
Debug($"{Time} - SymbolChanged event: {changedEvent}");
if (changedEvent.OldSymbol != _mappedSymbol.ID.ToString())
{
throw new RegressionTestException($"{Time} - Unexpected symbol changed event old symbol: {changedEvent}");
}
if (changedEvent.NewSymbol != _continuousContract.Mapped.ID.ToString())
{
throw new RegressionTestException($"{Time} - Unexpected symbol changed event new symbol: {changedEvent}");
}
// Let's trade the previous mapped contract, so we can hold it until expiration for testing
// (will be sooner than the new mapped contract)
_contractToTrade = _mappedSymbol;
_mappedSymbol = _continuousContract.Mapped;
}
// Let's trade after the mapping is done
if (_contractToTrade != null && _boughtQuantity == 0 && Securities[_contractToTrade].Exchange.ExchangeOpen)
{
Buy(_contractToTrade, 1);
}
if (_contractToTrade != null && slice.Delistings.TryGetValue(_contractToTrade, out var delisting))
{
if (delisting.Type == DelistingType.Delisted)
{
_delisted = true;
if (Portfolio.Invested)
{
throw new RegressionTestException($"{Time} - Portfolio should not be invested after the traded contract is delisted.");
}
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Symbol != _contractToTrade)
{
throw new RegressionTestException($"{Time} - Unexpected order event symbol: {orderEvent.Symbol}. Expected {_contractToTrade}");
}
if (orderEvent.Direction == OrderDirection.Buy)
{
if (orderEvent.Status == OrderStatus.Filled)
{
if (_boughtQuantity != 0 && _liquidatedQuantity != 0)
{
throw new RegressionTestException($"{Time} - Unexpected buy order event status: {orderEvent.Status}");
}
_boughtQuantity = orderEvent.Quantity;
}
}
else if (orderEvent.Direction == OrderDirection.Sell)
{
if (orderEvent.Status == OrderStatus.Filled)
{
if (_boughtQuantity <= 0 && _liquidatedQuantity != 0)
{
throw new RegressionTestException($"{Time} - Unexpected sell order event status: {orderEvent.Status}");
}
_liquidatedQuantity = orderEvent.Quantity;
if (_liquidatedQuantity != -_boughtQuantity)
{
throw new RegressionTestException($"{Time} - Unexpected liquidated quantity: {_liquidatedQuantity}. Expected: {-_boughtQuantity}");
}
}
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var addedSecurity in changes.AddedSecurities)
{
if (addedSecurity.Symbol.SecurityType == SecurityType.Future && addedSecurity.Symbol.IsCanonical())
{
_mappedSymbol = _continuousContract.Mapped;
}
}
}
public override void OnEndOfAlgorithm()
{
if (_mappingsCount == 0)
{
throw new RegressionTestException($"Unexpected number of symbol changed events (mappings): {_mappingsCount}. Expected 1.");
}
if (!_delisted)
{
throw new RegressionTestException("Contract was not delisted");
}
// Make sure we traded and that the position was liquidated on delisting
if (_boughtQuantity <= 0 || _liquidatedQuantity >= 0)
{
throw new RegressionTestException($"Unexpected sold quantity: {_boughtQuantity} and liquidated quantity: {_liquidatedQuantity}");
}
}
/// <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 => 133945;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 26;
/// <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", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.11%"},
{"Compounding Annual Return", "-1.667%"},
{"Drawdown", "0.100%"},
{"Expectancy", "-1"},
{"Start Equity", "1000000"},
{"End Equity", "998849.48"},
{"Net Profit", "-0.115%"},
{"Sharpe Ratio", "-34.455"},
{"Sortino Ratio", "-57.336"},
{"Probabilistic Sharpe Ratio", "0.002%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "-6.176"},
{"Tracking Error", "0.002"},
{"Treynor Ratio", "0"},
{"Total Fees", "€1.02"},
{"Estimated Strategy Capacity", "€2300000000.00"},
{"Lowest Capacity Asset", "FESX YJHOAMPYKRS5"},
{"Portfolio Turnover", "0.40%"},
{"OrderListHash", "54040d29a467becaedcf59d79323321b"}
};
}
}

View File

@@ -13,7 +13,6 @@
* limitations under the License.
*/
using QuantConnect.Data;
using QuantConnect.Data.Market;
namespace QuantConnect.Algorithm.CSharp
@@ -42,8 +41,8 @@ namespace QuantConnect.Algorithm.CSharp
/// <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)
/// <param name="data">TradeBars IDictionary object with your stock data</param>
public void OnData(TradeBars data)
{
if (!Portfolio.Invested)
{

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -59,14 +59,14 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
SetHoldings("EURUSD", .5);
SetHoldings("NZDUSD", .5);
Log(string.Join(", ", slice.Values));
Log(string.Join(", ", data.Values));
}
}
}
}
}

View File

@@ -82,7 +82,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -94,27 +94,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </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", "3"},
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "-1.01%"},
{"Compounding Annual Return", "261.134%"},
{"Drawdown", "2.200%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "101655.30"},
{"Net Profit", "1.655%"},
{"Sharpe Ratio", "8.472"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "8.505"},
{"Probabilistic Sharpe Ratio", "66.840%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
@@ -125,12 +117,12 @@ namespace QuantConnect.Algorithm.CSharp
{"Annual Variance", "0.05"},
{"Information Ratio", "-33.445"},
{"Tracking Error", "0.002"},
{"Treynor Ratio", "1.885"},
{"Treynor Ratio", "1.893"},
{"Total Fees", "$10.32"},
{"Estimated Strategy Capacity", "$27000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "59.86%"},
{"OrderListHash", "f209ed42701b0419858e0100595b40c0"}
{"OrderListHash", "ad2216297c759d8e5aef48ff065f8919"}
};
}
}

View File

@@ -92,4 +92,4 @@ namespace QuantConnect.Algorithm.CSharp
Debug($"{Time} {orderEvent.ToString()}");
}
}
}
}

View File

@@ -98,10 +98,10 @@ namespace QuantConnect.Algorithm.CSharp
{
private QCAlgorithm _algorithm;
private Future _future;
public ExponentialMovingAverage EMA { get; set; }
public decimal Price { get; set; }
public bool IsLong { get; set; }
public bool IsShort { get; set; }
public ExponentialMovingAverage EMA;
public decimal Price;
public bool IsLong;
public bool IsShort;
public Symbol Symbol => _future.Symbol;
public Symbol Mapped => _future.Mapped;
@@ -171,55 +171,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1190;
public long DataPoints => 1332;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 2;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
public int AlgorithmHistoryDataPoints => 4;
/// <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%"},
{"Total Trades", "2"},
{"Average Win", "0.53%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-0.010%"},
{"Compounding Annual Return", "3.011%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0"},
{"Start Equity", "1000000"},
{"End Equity", "999983.2"},
{"Net Profit", "-0.002%"},
{"Sharpe Ratio", "-225.214"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0.135%"},
{"Net Profit", "0.528%"},
{"Sharpe Ratio", "1.999"},
{"Probabilistic Sharpe Ratio", "83.704%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.008"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Alpha", "0.023"},
{"Beta", "-0.004"},
{"Annual Standard Deviation", "0.011"},
{"Annual Variance", "0"},
{"Information Ratio", "-5.146"},
{"Tracking Error", "0.083"},
{"Treynor Ratio", "-542.359"},
{"Total Fees", "$2.15"},
{"Estimated Strategy Capacity", "$0"},
{"Information Ratio", "-4.774"},
{"Tracking Error", "0.084"},
{"Treynor Ratio", "-4.853"},
{"Total Fees", "$4.30"},
{"Estimated Strategy Capacity", "$5900000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Portfolio Turnover", "0.13%"},
{"OrderListHash", "273dd05b937c075b75baf8af46d3c7de"}
{"Portfolio Turnover", "0.27%"},
{"OrderListHash", "40e4b91ec89383f6501d9ba324e50eb9"}
};
}
}

View File

@@ -39,9 +39,11 @@ namespace QuantConnect.Algorithm.CSharp
// S&P 500 EMini futures
private const string RootSP500 = Futures.Indices.SP500EMini;
public Symbol SP500 = QuantConnect.Symbol.Create(RootSP500, SecurityType.Future, Market.CME);
// Gold futures
private const string RootGold = Futures.Metals.Gold;
public Symbol Gold = QuantConnect.Symbol.Create(RootGold, SecurityType.Future, Market.COMEX);
/// <summary>
/// Initialize your algorithm and add desired assets.
@@ -79,7 +81,7 @@ namespace QuantConnect.Algorithm.CSharp
Debug($"{Time} - SymbolChanged event: {changedEvent}");
if (Time.TimeOfDay != TimeSpan.Zero)
{
throw new RegressionTestException($"{Time} unexpected symbol changed event {changedEvent}!");
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
@@ -115,7 +117,7 @@ namespace QuantConnect.Algorithm.CSharp
var futureMarginModel = buyingPowerModel as FutureMarginModel;
if (buyingPowerModel == null)
{
throw new RegressionTestException($"Invalid buying power model. Found: {buyingPowerModel.GetType().Name}. Expected: {nameof(FutureMarginModel)}");
throw new Exception($"Invalid buying power model. Found: {buyingPowerModel.GetType().Name}. Expected: {nameof(FutureMarginModel)}");
}
var initialOvernight = futureMarginModel.InitialOvernightMarginRequirement;
var maintenanceOvernight = futureMarginModel.MaintenanceOvernightMarginRequirement;
@@ -131,7 +133,7 @@ namespace QuantConnect.Algorithm.CSharp
&& !addedSecurity.Symbol.IsCanonical()
&& !addedSecurity.HasData)
{
throw new RegressionTestException($"Future contracts did not work up as expected: {addedSecurity.Symbol}");
throw new Exception($"Future contracts did not work up as expected: {addedSecurity.Symbol}");
}
}
}
@@ -144,55 +146,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 75403;
public long DataPoints => 75401;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 340;
/// <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", "2700"},
{"Total Trades", "2700"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-99.777%"},
{"Drawdown", "4.400%"},
{"Expectancy", "-0.724"},
{"Start Equity", "1000000"},
{"End Equity", "955700.5"},
{"Net Profit", "-4.430%"},
{"Sharpe Ratio", "-31.63"},
{"Sortino Ratio", "-31.63"},
{"Sharpe Ratio", "-31.389"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "83%"},
{"Win Rate", "17%"},
{"Profit-Loss Ratio", "0.65"},
{"Alpha", "-3.065"},
{"Alpha", "-3.059"},
{"Beta", "0.128"},
{"Annual Standard Deviation", "0.031"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-81.232"},
{"Tracking Error", "0.212"},
{"Treynor Ratio", "-7.677"},
{"Treynor Ratio", "-7.618"},
{"Total Fees", "$6237.00"},
{"Estimated Strategy Capacity", "$14000.00"},
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
{"Portfolio Turnover", "9912.69%"},
{"OrderListHash", "6e0f767a46a54365287801295cf7bb75"}
{"OrderListHash", "8f92e1528c6477a156449fd1e86527e7"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -33,6 +33,7 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateFuturesConsolidationAlgorithm : QCAlgorithm
{
private const string RootSP500 = Futures.Indices.SP500EMini;
public Symbol SP500 = QuantConnect.Symbol.Create(RootSP500, SecurityType.Future, Market.CME);
private HashSet<Symbol> _futureContracts = new HashSet<Symbol>();
public override void Initialize()
@@ -77,4 +78,4 @@ namespace QuantConnect.Algorithm.CSharp
Log(quoteBar.ToString());
}
}
}
}

View File

@@ -83,7 +83,7 @@ namespace QuantConnect.Algorithm.CSharp
// if found, trade it.
// Also check if exchange is open for regular or extended hours. Since daily data comes at 8PM, this allows us prevent the
// algorithm from trading on friday when there is not after-market.
if (contract != null)
if (contract != null && Securities[contract.Symbol].Exchange.Hours.IsOpen(Time, true))
{
MarketOrder(contract.Symbol, 1);
}
@@ -99,7 +99,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (Time.TimeOfDay != TimeSpan.Zero)
{
throw new RegressionTestException($"{Time} unexpected symbol changed event {changedEvent}!");
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
}
@@ -112,55 +112,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 12452;
public virtual long DataPoints => 13948;
/// <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 virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "32"},
{"Average Win", "0.33%"},
{"Average Loss", "-0.04%"},
{"Compounding Annual Return", "0.110%"},
{"Drawdown", "0.300%"},
{"Expectancy", "0.184"},
{"Start Equity", "1000000"},
{"End Equity", "1001108"},
{"Net Profit", "0.111%"},
{"Sharpe Ratio", "-1.688"},
{"Sortino Ratio", "-0.772"},
{"Probabilistic Sharpe Ratio", "14.944%"},
{"Loss Rate", "88%"},
{"Win Rate", "12%"},
{"Profit-Loss Ratio", "8.47"},
{"Alpha", "-0.007"},
{"Beta", "0.002"},
{"Annual Standard Deviation", "0.004"},
{"Total Trades", "122"},
{"Average Win", "0.09%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-0.486%"},
{"Drawdown", "0.500%"},
{"Expectancy", "-0.837"},
{"Net Profit", "-0.490%"},
{"Sharpe Ratio", "-1.968"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "98%"},
{"Win Rate", "2%"},
{"Profit-Loss Ratio", "8.94"},
{"Alpha", "-0.003"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.353"},
{"Information Ratio", "-1.397"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "-4.099"},
{"Total Fees", "$72.00"},
{"Estimated Strategy Capacity", "$0"},
{"Treynor Ratio", "5.001"},
{"Total Fees", "$272.54"},
{"Estimated Strategy Capacity", "$1000.00"},
{"Lowest Capacity Asset", "ES VRJST036ZY0X"},
{"Portfolio Turnover", "0.87%"},
{"OrderListHash", "168731c8f3a19f230cc1410818b3b573"}
{"Portfolio Turnover", "3.27%"},
{"OrderListHash", "61ad5bfa7e2135a85a82c986329335cf"}
};
}
}

View File

@@ -131,55 +131,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 57759;
public virtual long DataPoints => 57752;
/// <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 virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "2"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-81.734%"},
{"Drawdown", "4.100%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "97830.76"},
{"Net Profit", "-2.169%"},
{"Sharpe Ratio", "-10.299"},
{"Sortino Ratio", "-10.299"},
{"Sharpe Ratio", "-10.195"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-1.212"},
{"Alpha", "-1.206"},
{"Beta", "0.238"},
{"Annual Standard Deviation", "0.072"},
{"Annual Variance", "0.005"},
{"Information Ratio", "-15.404"},
{"Tracking Error", "0.176"},
{"Treynor Ratio", "-3.109"},
{"Treynor Ratio", "-3.077"},
{"Total Fees", "$4.62"},
{"Estimated Strategy Capacity", "$17000000.00"},
{"Lowest Capacity Asset", "GC VL5E74HP3EE5"},
{"Portfolio Turnover", "43.23%"},
{"OrderListHash", "c0fc1bcdc3008a8d263521bbc9d7cdbd"}
{"OrderListHash", "323b899ae80aa839e320806411665ce7"}
};
}
}

View File

@@ -36,45 +36,42 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 163415;
public override long DataPoints => 163392;
/// <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", "2"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-92.667%"},
{"Drawdown", "5.000%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "96685.76"},
{"Net Profit", "-3.314%"},
{"Sharpe Ratio", "-6.359"},
{"Sortino Ratio", "-11.237"},
{"Sharpe Ratio", "-6.303"},
{"Probabilistic Sharpe Ratio", "9.333%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-1.47"},
{"Alpha", "-1.465"},
{"Beta", "0.312"},
{"Annual Standard Deviation", "0.134"},
{"Annual Variance", "0.018"},
{"Information Ratio", "-14.77"},
{"Tracking Error", "0.192"},
{"Treynor Ratio", "-2.742"},
{"Treynor Ratio", "-2.718"},
{"Total Fees", "$4.62"},
{"Estimated Strategy Capacity", "$52000000.00"},
{"Lowest Capacity Asset", "GC VL5E74HP3EE5"},
{"Portfolio Turnover", "43.77%"},
{"OrderListHash", "dcdaafcefa47465962ace2759ed99c91"}
{"OrderListHash", "18ffd3a774c68da83d867e3b09e3e05d"}
};
}
}

View File

@@ -69,7 +69,7 @@ namespace QuantConnect.Algorithm.CSharp
var history = History(10, Resolution.Minute);
if (history.Count() < 10)
{
throw new RegressionTestException($"Empty history at {Time}");
throw new Exception($"Empty history at {Time}");
}
_successCount++;
}
@@ -78,7 +78,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (_successCount < ExpectedHistoryCallCount)
{
throw new RegressionTestException($"Scheduled Event did not assert history call as many times as expected: {_successCount}/49");
throw new Exception($"Scheduled Event did not assert history call as many times as expected: {_successCount}/49");
}
}
@@ -135,39 +135,31 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 48690;
public virtual long DataPoints => 48688;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 5305;
/// <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 virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "0"},
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000000"},
{"End Equity", "1000000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},

View File

@@ -42,39 +42,31 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 147771;
public override long DataPoints => 147769;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 6112;
/// <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 override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "0"},
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000000"},
{"End Equity", "1000000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},

View File

@@ -36,45 +36,42 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 87289;
public override long DataPoints => 86963;
/// <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", "716"},
{"Average Win", "0.03%"},
{"Total Trades", "636"},
{"Average Win", "0.02%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-1.716%"},
{"Drawdown", "1.700%"},
{"Expectancy", "-0.770"},
{"Start Equity", "1000000"},
{"End Equity", "982718.38"},
{"Net Profit", "-1.728%"},
{"Sharpe Ratio", "-8.845"},
{"Sortino Ratio", "-5.449"},
{"Compounding Annual Return", "-1.606%"},
{"Drawdown", "1.600%"},
{"Expectancy", "-0.841"},
{"Net Profit", "-1.617%"},
{"Sharpe Ratio", "-5.092"},
{"Probabilistic Sharpe Ratio", "0.000%"},
{"Loss Rate", "96%"},
{"Win Rate", "4%"},
{"Profit-Loss Ratio", "4.89"},
{"Alpha", "-0.018"},
{"Beta", "-0.002"},
{"Profit-Loss Ratio", "3.21"},
{"Alpha", "-0.01"},
{"Beta", "-0.003"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.483"},
{"Information Ratio", "-1.473"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "9.102"},
{"Total Fees", "$1634.12"},
{"Estimated Strategy Capacity", "$8000.00"},
{"Treynor Ratio", "3.137"},
{"Total Fees", "$1451.88"},
{"Estimated Strategy Capacity", "$9000.00"},
{"Lowest Capacity Asset", "ES VP274HSU1AF5"},
{"Portfolio Turnover", "20.10%"},
{"OrderListHash", "aa7e574f86b70428ca0afae381be80ba"}
{"Portfolio Turnover", "17.86%"},
{"OrderListHash", "de6a834d1b5e7aeb40f6cf9dba16782d"}
};
}
}

View File

@@ -39,9 +39,11 @@ namespace QuantConnect.Algorithm.CSharp
// S&P 500 EMini futures
private const string RootSP500 = Futures.Indices.SP500EMini;
public Symbol SP500 = QuantConnect.Symbol.Create(RootSP500, SecurityType.Future, Market.CME);
// Gold futures
private const string RootGold = Futures.Metals.Gold;
public Symbol Gold = QuantConnect.Symbol.Create(RootGold, SecurityType.Future, Market.COMEX);
/// <summary>
/// Initialize your algorithm and add desired assets.
@@ -79,7 +81,7 @@ namespace QuantConnect.Algorithm.CSharp
Debug($"{Time} - SymbolChanged event: {changedEvent}");
if (Time.TimeOfDay != TimeSpan.Zero)
{
throw new RegressionTestException($"{Time} unexpected symbol changed event {changedEvent}!");
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
@@ -115,7 +117,7 @@ namespace QuantConnect.Algorithm.CSharp
var futureMarginModel = buyingPowerModel as FutureMarginModel;
if (buyingPowerModel == null)
{
throw new RegressionTestException($"Invalid buying power model. Found: {buyingPowerModel.GetType().Name}. Expected: {nameof(FutureMarginModel)}");
throw new Exception($"Invalid buying power model. Found: {buyingPowerModel.GetType().Name}. Expected: {nameof(FutureMarginModel)}");
}
var initialOvernight = futureMarginModel.InitialOvernightMarginRequirement;
var maintenanceOvernight = futureMarginModel.MaintenanceOvernightMarginRequirement;
@@ -131,7 +133,7 @@ namespace QuantConnect.Algorithm.CSharp
&& !addedSecurity.Symbol.IsCanonical()
&& !addedSecurity.HasData)
{
throw new RegressionTestException($"Future contracts did not work up as expected: {addedSecurity.Symbol}");
throw new Exception($"Future contracts did not work up as expected: {addedSecurity.Symbol}");
}
}
}
@@ -144,55 +146,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 224662;
public long DataPoints => 224660;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 340;
/// <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", "8282"},
{"Total Trades", "8282"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "13.900%"},
{"Expectancy", "-0.824"},
{"Start Equity", "1000000"},
{"End Equity", "861260.7"},
{"Net Profit", "-13.874%"},
{"Sharpe Ratio", "-19.346"},
{"Sortino Ratio", "-19.346"},
{"Sharpe Ratio", "-19.202"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "89%"},
{"Win Rate", "11%"},
{"Profit-Loss Ratio", "0.64"},
{"Alpha", "2.468"},
{"Alpha", "2.477"},
{"Beta", "-0.215"},
{"Annual Standard Deviation", "0.052"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-58.37"},
{"Tracking Error", "0.295"},
{"Treynor Ratio", "4.695"},
{"Treynor Ratio", "4.66"},
{"Total Fees", "$19131.42"},
{"Estimated Strategy Capacity", "$130000.00"},
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
{"Portfolio Turnover", "32523.20%"},
{"OrderListHash", "0664a72652a19956ea3c4915269cc4b9"}
{"OrderListHash", "85cdd035d7c7a3da178d1c2dff31f1bd"}
};
}
}

View File

@@ -38,45 +38,42 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 14790;
public override long DataPoints => 16247;
/// <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", "36"},
{"Average Win", "0.33%"},
{"Average Loss", "-0.03%"},
{"Compounding Annual Return", "0.102%"},
{"Drawdown", "0.300%"},
{"Expectancy", "0.171"},
{"Start Equity", "1000000"},
{"End Equity", "1001024.4"},
{"Net Profit", "0.102%"},
{"Sharpe Ratio", "-1.702"},
{"Sortino Ratio", "-0.836"},
{"Probabilistic Sharpe Ratio", "14.653%"},
{"Loss Rate", "89%"},
{"Win Rate", "11%"},
{"Profit-Loss Ratio", "9.54"},
{"Alpha", "-0.007"},
{"Beta", "0.002"},
{"Annual Standard Deviation", "0.004"},
{"Total Trades", "152"},
{"Average Win", "0.09%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-0.644%"},
{"Drawdown", "0.600%"},
{"Expectancy", "-0.872"},
{"Net Profit", "-0.649%"},
{"Sharpe Ratio", "-2.343"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "99%"},
{"Win Rate", "1%"},
{"Profit-Loss Ratio", "8.76"},
{"Alpha", "-0.004"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.353"},
{"Information Ratio", "-1.409"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "-4.126"},
{"Total Fees", "$80.60"},
{"Estimated Strategy Capacity", "$0"},
{"Treynor Ratio", "3.76"},
{"Total Fees", "$338.96"},
{"Estimated Strategy Capacity", "$1000.00"},
{"Lowest Capacity Asset", "ES VRJST036ZY0X"},
{"Portfolio Turnover", "0.97%"},
{"OrderListHash", "52c852d720692fab1e12212b2aba03d4"}
{"Portfolio Turnover", "4.07%"},
{"OrderListHash", "e2d7f858dcad2d760f776bec1065b2f1"}
};
}
}

View File

@@ -36,45 +36,42 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 228834;
public override long DataPoints => 227220;
/// <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", "1992"},
{"Total Trades", "1970"},
{"Average Win", "0.01%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-4.687%"},
{"Compounding Annual Return", "-4.641%"},
{"Drawdown", "4.700%"},
{"Expectancy", "-0.911"},
{"Start Equity", "1000000"},
{"End Equity", "952789.22"},
{"Net Profit", "-4.721%"},
{"Sharpe Ratio", "-7.183"},
{"Sortino Ratio", "-5.14"},
{"Net Profit", "-4.675%"},
{"Sharpe Ratio", "-5.76"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "97%"},
{"Win Rate", "3%"},
{"Profit-Loss Ratio", "2.04"},
{"Alpha", "-0.038"},
{"Alpha", "-0.03"},
{"Beta", "-0.008"},
{"Annual Standard Deviation", "0.005"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.702"},
{"Information Ratio", "-1.699"},
{"Tracking Error", "0.09"},
{"Treynor Ratio", "5.054"},
{"Total Fees", "$4543.28"},
{"Treynor Ratio", "4.067"},
{"Total Fees", "$4495.98"},
{"Estimated Strategy Capacity", "$3000.00"},
{"Lowest Capacity Asset", "ES VP274HSU1AF5"},
{"Portfolio Turnover", "56.73%"},
{"OrderListHash", "424536177e9be5895bab50638ef43a9d"}
{"Portfolio Turnover", "56.20%"},
{"OrderListHash", "e65e1dace0d1679c2026155628ca3077"}
};
}
}

View File

@@ -52,8 +52,8 @@ namespace QuantConnect.Algorithm.CSharp
/// <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)
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
@@ -70,7 +70,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -82,27 +82,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </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"},
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "227.693%"},
{"Drawdown", "2.000%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "101529.08"},
{"Net Profit", "1.529%"},
{"Sharpe Ratio", "8.855"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "8.889"},
{"Probabilistic Sharpe Ratio", "67.609%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -113,12 +105,12 @@ namespace QuantConnect.Algorithm.CSharp
{"Annual Variance", "0.049"},
{"Information Ratio", "-14.564"},
{"Tracking Error", "0.001"},
{"Treynor Ratio", "1.971"},
{"Treynor Ratio", "1.978"},
{"Total Fees", "$3.44"},
{"Estimated Strategy Capacity", "$110000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "19.96%"},
{"OrderListHash", "966f8355817adbc8c724d1062691a60b"}
{"OrderListHash", "f409be3a7c63d9c1394c2e6c005a15ee"}
};
}
}

View File

@@ -30,8 +30,8 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="indexes" />
public class BasicTemplateIndexAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected Symbol Spx { get; set; }
protected Symbol SpxOption { get; set; }
protected Symbol Spx;
protected Symbol SpxOption;
private ExponentialMovingAverage _emaSlow;
private ExponentialMovingAverage _emaFast;
@@ -61,10 +61,8 @@ namespace QuantConnect.Algorithm.CSharp
AddIndexOptionContract(SpxOption, Resolution);
_emaSlow = EMA(Spx, Resolution > Resolution.Minute ? 6 : 80);
_emaFast = EMA(Spx, Resolution > Resolution.Minute ? 2 : 200);
Settings.DailyPreciseEndTime = true;
_emaSlow = EMA(Spx, 80);
_emaFast = EMA(Spx, 200);
}
/// <summary>
@@ -93,25 +91,12 @@ namespace QuantConnect.Algorithm.CSharp
}
}
/// <summary>
/// Asserts indicators are ready
/// </summary>
/// <exception cref="RegressionTestException"></exception>
protected void AssertIndicators()
{
if (!_emaSlow.IsReady || !_emaFast.IsReady)
{
throw new RegressionTestException("Indicators are not ready!");
}
}
public override void OnEndOfAlgorithm()
{
if (Portfolio[Spx].TotalSaleVolume > 0)
{
throw new RegressionTestException("Index is not tradable.");
throw new Exception("Index is not tradable.");
}
AssertIndicators();
}
/// <summary>
@@ -122,55 +107,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 16199;
public virtual long DataPoints => 16049;
/// <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 virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "3"},
{"Average Win", "7.08%"},
{"Total Trades", "3"},
{"Average Win", "6.15%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "603.355%"},
{"Compounding Annual Return", "435.569%"},
{"Drawdown", "3.400%"},
{"Expectancy", "0"},
{"Start Equity", "1000000"},
{"End Equity", "1064395"},
{"Net Profit", "6.440%"},
{"Sharpe Ratio", "-4.563"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0.781%"},
{"Net Profit", "5.516%"},
{"Sharpe Ratio", "-6.262"},
{"Probabilistic Sharpe Ratio", "0.011%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.169"},
{"Beta", "0.073"},
{"Annual Standard Deviation", "0.028"},
{"Alpha", "-0.223"},
{"Beta", "0.02"},
{"Annual Standard Deviation", "0.034"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-6.684"},
{"Tracking Error", "0.099"},
{"Treynor Ratio", "-1.771"},
{"Information Ratio", "-7.032"},
{"Tracking Error", "0.107"},
{"Treynor Ratio", "-10.779"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$3000.00"},
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
{"Portfolio Turnover", "23.97%"},
{"OrderListHash", "51f1bc2ea080df79748dc66c2520b782"}
{"Portfolio Turnover", "24.07%"},
{"OrderListHash", "5dbee236086bb2c39e2fbeac068280fd"}
};
}
}

View File

@@ -15,10 +15,8 @@
*/
using System;
using System.Linq;
using QuantConnect.Data;
using System.Collections.Generic;
using QuantConnect.Data.Market;
namespace QuantConnect.Algorithm.CSharp
{
@@ -32,7 +30,7 @@ namespace QuantConnect.Algorithm.CSharp
// two complete weeks starting from the 5th. The 18th bar is not included since it is a holiday
protected virtual int ExpectedBarCount => 2 * 5;
protected int BarCounter { get; set; }
protected int BarCounter = 0;
/// <summary>
/// Purchase a contract when we are not invested, liquidate otherwise
@@ -62,35 +60,6 @@ namespace QuantConnect.Algorithm.CSharp
{
throw new ArgumentException($"Bar Count {BarCounter} is not expected count of {ExpectedBarCount}");
}
AssertIndicators();
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 RegressionTestException($"Unexpected history count: {history.Count}");
}
if (history.Any(x => x.Time.TimeOfDay != new TimeSpan(8, 30, 0)))
{
throw new RegressionTestException($"Unexpected history data start time");
}
if (history.Any(x => x.EndTime.TimeOfDay != new TimeSpan(15, 15, 0)))
{
throw new RegressionTestException($"Unexpected history data end time");
}
}
}
/// <summary>
@@ -101,55 +70,24 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
public override Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 121;
public override long DataPoints => 0;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 30;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
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", "11"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "621.484%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000000"},
{"End Equity", "1084600"},
{"Net Profit", "8.460%"},
{"Sharpe Ratio", "9.923"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "93.682%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss 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", "SPX XL80P3GHDZXQ|SPX 31"},
{"Portfolio Turnover", "2.42%"},
{"OrderListHash", "61e8517ac3da6bed414ef23d26736fef"}
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -8,7 +8,7 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateIndexHourlyAlgorithm : BasicTemplateIndexDailyAlgorithm
{
protected override Resolution Resolution => Resolution.Hour;
protected override int ExpectedBarCount => base.ExpectedBarCount * 8;
protected override int ExpectedBarCount => base.ExpectedBarCount * 7;
/// <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.
@@ -18,55 +18,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override List<Language> Languages { get; } = new() { Language.CSharp };
public override Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 401;
public override long DataPoints => 391;
/// <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;
/// <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", "81"},
{"Total Trades", "71"},
{"Average Win", "1.28%"},
{"Average Loss", "-0.06%"},
{"Compounding Annual Return", "-20.546%"},
{"Drawdown", "1.800%"},
{"Expectancy", "-0.402"},
{"Start Equity", "1000000"},
{"End Equity", "990775"},
{"Net Profit", "-0.922%"},
{"Sharpe Ratio", "-2.903"},
{"Sortino Ratio", "-6.081"},
{"Sharpe Ratio", "-2.856"},
{"Probabilistic Sharpe Ratio", "22.230%"},
{"Loss Rate", "97%"},
{"Win Rate", "3%"},
{"Profit-Loss Ratio", "19.95"},
{"Alpha", "-0.157"},
{"Alpha", "-0.155"},
{"Beta", "0.025"},
{"Annual Standard Deviation", "0.053"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-2.07"},
{"Tracking Error", "0.121"},
{"Treynor Ratio", "-6.189"},
{"Treynor Ratio", "-6.089"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$300000.00"},
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
{"Portfolio Turnover", "24.63%"},
{"OrderListHash", "44325fc1fdebb8e54f64a3f6e8a4bcd7"}
{"OrderListHash", "9e974939d13fd3255c6291a65d2c1eb9"}
};
}
}

View File

@@ -14,6 +14,7 @@
*
*/
using System;
using QuantConnect.Data;
using System.Collections.Generic;
using QuantConnect.Indicators;
@@ -47,10 +48,8 @@ namespace QuantConnect.Algorithm.CSharp
var spxOptions = AddIndexOption(_spx, Resolution);
spxOptions.SetFilter(filterFunc => filterFunc.CallsOnly());
_emaSlow = EMA(_spx, Resolution > Resolution.Minute ? 6 : 80);
_emaFast = EMA(_spx, Resolution > Resolution.Minute ? 2 : 200);
Settings.DailyPreciseEndTime = true;
_emaSlow = EMA(_spx, 80);
_emaFast = EMA(_spx, 200);
}
/// <summary>
@@ -103,13 +102,12 @@ namespace QuantConnect.Algorithm.CSharp
{
if (Portfolio[_spx].TotalSaleVolume > 0)
{
throw new RegressionTestException("Index is not tradable.");
throw new Exception("Index is not tradable.");
}
if (Portfolio.TotalSaleVolume == 0)
{
throw new RegressionTestException("Trade volume should be greater than zero by the end of this algorithm");
throw new Exception("Trade volume should be greater than zero by the end of this algorithm");
}
AssertIndicators();
}
public Symbol InvertOption(Symbol symbol)
@@ -123,18 +121,6 @@ namespace QuantConnect.Algorithm.CSharp
symbol.ID.Date);
}
/// <summary>
/// Asserts indicators are ready
/// </summary>
/// <exception cref="RegressionTestException"></exception>
protected void AssertIndicators()
{
if (!_emaSlow.IsReady || !_emaFast.IsReady)
{
throw new RegressionTestException("Indicators are not ready!");
}
}
/// <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>
@@ -143,7 +129,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -155,17 +141,12 @@ namespace QuantConnect.Algorithm.CSharp
/// </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 virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "8220"},
{"Total Trades", "8220"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-100.000%"},

View File

@@ -62,55 +62,24 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override List<Language> Languages { get; } = new() { Language.CSharp };
public override Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 356;
public override long DataPoints => 0;
/// <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;
/// <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", "11"},
{"Average Win", "0%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-0.092%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Start Equity", "1000000"},
{"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.003"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.454"},
{"Tracking Error", "0.138"},
{"Treynor Ratio", "-44.954"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "SPX XL80P59H5E6M|SPX 31"},
{"Portfolio Turnover", "0.00%"},
{"OrderListHash", "285cec32c0947f0e8cf90ccb672cfa43"}
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -33,55 +33,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override List<Language> Languages { get; } = new() { Language.CSharp };
public override Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 1269;
public override long DataPoints => 2143;
/// <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;
/// <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", "81"},
{"Total Trades", "72"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-0.006%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-0.486"},
{"Start Equity", "1000000"},
{"End Equity", "999995"},
{"Net Profit", "0.000%"},
{"Sharpe Ratio", "-101.77"},
{"Sortino Ratio", "-9053542.758"},
{"Sharpe Ratio", "-1.628"},
{"Probabilistic Sharpe Ratio", "17.439%"},
{"Loss Rate", "97%"},
{"Win Rate", "3%"},
{"Profit-Loss Ratio", "17.50"},
{"Alpha", "-0.003"},
{"Alpha", "-0"},
{"Beta", "-0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.449"},
{"Tracking Error", "0.138"},
{"Treynor Ratio", "116.921"},
{"Treynor Ratio", "1.87"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "SPX XL80P59H5E6M|SPX 31"},
{"Portfolio Turnover", "0.00%"},
{"OrderListHash", "75e6584cb26058b09720c3a828b9fbda"}
{"OrderListHash", "0df3713aeb32e9c0738200f2a109e2f9"}
};
}
}

View File

@@ -56,7 +56,7 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
@@ -80,7 +80,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -92,27 +92,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </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"},
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-0.010%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "99992.45"},
{"Net Profit", "-0.008%"},
{"Sharpe Ratio", "-497.389"},
{"Sortino Ratio", "-73.22"},
{"Sharpe Ratio", "-1.183"},
{"Probabilistic Sharpe Ratio", "0.001%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -128,7 +120,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "₹61000000000.00"},
{"Lowest Capacity Asset", "YESBANK UL"},
{"Portfolio Turnover", "0.00%"},
{"OrderListHash", "7a0257f08e3bb9143b825e07ab47fea0"}
{"OrderListHash", "6cc69218edd7bd461678b9ee0c575db5"}
};
}
}

View File

@@ -31,8 +31,8 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="indexes" />
public class BasicTemplateIndiaIndexAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected Symbol Nifty { get; set; }
protected Symbol NiftyETF { get; set; }
protected Symbol Nifty;
protected Symbol NiftyETF;
private ExponentialMovingAverage _emaSlow;
private ExponentialMovingAverage _emaFast;
@@ -92,7 +92,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (Portfolio[Nifty].TotalSaleVolume > 0)
{
throw new RegressionTestException("Index is not tradable.");
throw new Exception("Index is not tradable.");
}
}
@@ -104,7 +104,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -116,27 +116,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </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 virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "6"},
{"Total Trades", "6"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-0.386%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Start Equity", "1000000"},
{"End Equity", "999961.17"},
{"Net Profit", "-0.004%"},
{"Sharpe Ratio", "-328.371"},
{"Sortino Ratio", "-328.371"},
{"Sharpe Ratio", "-23.595"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
@@ -152,7 +144,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "₹84000.00"},
{"Lowest Capacity Asset", "JUNIORBEES UL"},
{"Portfolio Turnover", "0.04%"},
{"OrderListHash", "79ab9ec506959c562be8b3cdbb174c39"}
{"OrderListHash", "57558324bc9b67b36ae33c3e1c191740"}
};
}
}

View File

@@ -32,8 +32,8 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateIntrinioEconomicData : QCAlgorithm
{
// Set your Intrinio user and password.
private string _user = string.Empty;
private string _password = string.Empty;
public string _user = "";
public string _password = "";
private Symbol _uso; // United States Oil Fund LP
private Symbol _bno; // United States Brent Oil Fund LP
@@ -81,9 +81,9 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice data)
{
var customData = slice.Get<IntrinioEconomicData>();
var customData = data.Get<IntrinioEconomicData>();
if (customData.Count == 0) return;
foreach (var economicData in customData.Values)
@@ -116,7 +116,7 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "91"},
{"Total Trades", "91"},
{"Average Win", "0.09%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "5.732%"},

View File

@@ -32,7 +32,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="trading and orders" />
public class BasicTemplateOptionEquityStrategyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _optionSymbol;
protected Symbol _optionSymbol;
public override void Initialize()
{
@@ -97,39 +97,31 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 15023;
public long DataPoints => 475788;
/// <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", "3"},
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "98024"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -142,10 +134,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$26.00"},
{"Estimated Strategy Capacity", "$69000.00"},
{"Estimated Strategy Capacity", "$70000.00"},
{"Lowest Capacity Asset", "GOOCV W78ZERHAOVVQ|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "61.31%"},
{"OrderListHash", "35d406df401e5b27244e20f5ec57346e"}
{"OrderListHash", "cee5cc2b0f80c308b496cac0b8668163"}
};
}
}

View File

@@ -107,39 +107,31 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 15130;
public long DataPoints => 475777;
/// <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", "420"},
{"Total Trades", "418"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000000"},
{"End Equity", "952636.6"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -152,10 +144,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$543.40"},
{"Estimated Strategy Capacity", "$4000.00"},
{"Estimated Strategy Capacity", "$3000.00"},
{"Lowest Capacity Asset", "GOOCV W78ZFMEBBB2E|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "338.60%"},
{"OrderListHash", "301c15063f6e269023d144ca69a765da"}
{"OrderListHash", "e0289a2989c91934656ff7e578f5e810"}
};
}
}

View File

@@ -35,7 +35,7 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateOptionsAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "GOOG";
private Symbol _optionSymbol;
public Symbol OptionSymbol;
public override void Initialize()
{
@@ -45,7 +45,7 @@ namespace QuantConnect.Algorithm.CSharp
var equity = AddEquity(UnderlyingTicker);
var option = AddOption(UnderlyingTicker);
_optionSymbol = option.Symbol;
OptionSymbol = option.Symbol;
// set our strike/expiry filter for this option chain
option.SetFilter(u => u.Strikes(-2, +2)
@@ -64,10 +64,10 @@ namespace QuantConnect.Algorithm.CSharp
/// <param name="slice">The current slice of data keyed by symbol string</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested && IsMarketOpen(_optionSymbol))
if (!Portfolio.Invested && IsMarketOpen(OptionSymbol))
{
OptionChain chain;
if (slice.OptionChains.TryGetValue(_optionSymbol, out chain))
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
{
// we find at the money (ATM) put contract with farthest expiration
var atmContract = chain
@@ -104,39 +104,31 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 15012;
public long DataPoints => 475777;
/// <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", "2"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "99718"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -152,7 +144,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$1300000.00"},
{"Lowest Capacity Asset", "GOOCV 30AKMEIPOSS1Y|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "10.71%"},
{"OrderListHash", "8a36462ee0349c04d01d464e592dd347"}
{"OrderListHash", "838e313ba57850227ec810ed8fb85a23"}
};
}
}

View File

@@ -1,151 +0,0 @@
/*
* 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.Data;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using System;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// A demonstration of consolidating options data into larger bars for your algorithm.
/// </summary>
public class BasicTemplateOptionsConsolidationAlgorithm: QCAlgorithm, IRegressionAlgorithmDefinition
{
private Dictionary<Symbol, IDataConsolidator> _consolidators = new();
public override void Initialize()
{
SetStartDate(2013, 10, 7);
SetEndDate(2013, 10, 11);
SetCash(1000000);
var option = AddOption("SPY");
option.SetFilter(-2, 2, 0, 189);
}
public void OnQuoteBarConsolidated(object sender, QuoteBar quoteBar)
{
Log($"OnQuoteBarConsolidated called on {Time}");
Log(quoteBar.ToString());
}
public void OnTradeBarConsolidated(object sender, TradeBar tradeBar)
{
Log($"OnTradeBarConsolidated called on {Time}");
Log(tradeBar.ToString());
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach(var security in changes.AddedSecurities)
{
IDataConsolidator consolidator;
if (security.Type == SecurityType.Equity)
{
consolidator = new TradeBarConsolidator(TimeSpan.FromMinutes(5));
(consolidator as TradeBarConsolidator).DataConsolidated += OnTradeBarConsolidated;
}
else
{
consolidator = new QuoteBarConsolidator(new TimeSpan(0, 5, 0));
(consolidator as QuoteBarConsolidator).DataConsolidated += OnQuoteBarConsolidated;
}
SubscriptionManager.AddConsolidator(security.Symbol, consolidator);
_consolidators[security.Symbol] = consolidator;
}
foreach(var security in changes.RemovedSecurities)
{
_consolidators.Remove(security.Symbol, out var consolidator);
SubscriptionManager.RemoveConsolidator(security.Symbol, consolidator);
if (security.Type == SecurityType.Equity)
{
(consolidator as TradeBarConsolidator).DataConsolidated -= OnTradeBarConsolidated;
}
else
{
(consolidator as QuoteBarConsolidator).DataConsolidated -= OnQuoteBarConsolidated;
}
}
}
/// <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 => 3943;
/// <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", "1000000"},
{"End Equity", "1000000"},
{"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", "-8.91"},
{"Tracking Error", "0.223"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -34,21 +34,21 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="filter selection" />
public class BasicTemplateOptionsDailyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "AAPL";
private Symbol _optionSymbol;
private const string UnderlyingTicker = "GOOG";
public Symbol OptionSymbol;
private bool _optionExpired;
public override void Initialize()
{
SetStartDate(2015, 12, 15);
SetEndDate(2016, 2, 1);
SetStartDate(2015, 12, 23);
SetEndDate(2016, 1, 20);
SetCash(100000);
var equity = AddEquity(UnderlyingTicker, Resolution.Daily);
var option = AddOption(UnderlyingTicker, Resolution.Daily);
_optionSymbol = option.Symbol;
OptionSymbol = option.Symbol;
option.SetFilter(x => x.CallsOnly().Expiration(0, 60));
option.SetFilter(x => x.CallsOnly().Strikes(0, 1).Expiration(0, 30));
// use the underlying equity as the benchmark
SetBenchmark(equity.Symbol);
@@ -63,7 +63,7 @@ namespace QuantConnect.Algorithm.CSharp
if (!Portfolio.Invested)
{
OptionChain chain;
if (slice.OptionChains.TryGetValue(_optionSymbol, out chain))
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
{
// Grab us the contract nearest expiry that is not today
var contractsByExpiration = chain.Where(x => x.Expiry != Time.Date).OrderBy(x => x.Expiry);
@@ -117,55 +117,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 308;
public long DataPoints => 36834;
/// <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", "2"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-1.16%"},
{"Compounding Annual Return", "-8.351%"},
{"Drawdown", "1.200%"},
{"Average Loss", "-1.31%"},
{"Compounding Annual Return", "-15.304%"},
{"Drawdown", "1.300%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "98844"},
{"Net Profit", "-1.156%"},
{"Sharpe Ratio", "-4.04"},
{"Sortino Ratio", "-2.422"},
{"Probabilistic Sharpe Ratio", "0.099%"},
{"Net Profit", "-1.311%"},
{"Sharpe Ratio", "-3.31"},
{"Probabilistic Sharpe Ratio", "0.035%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.058"},
{"Beta", "0.021"},
{"Annual Standard Deviation", "0.017"},
{"Annual Variance", "0"},
{"Information Ratio", "1.49"},
{"Tracking Error", "0.289"},
{"Treynor Ratio", "-3.212"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0.034"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-3.31"},
{"Tracking Error", "0.034"},
{"Treynor Ratio", "0"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$72000.00"},
{"Lowest Capacity Asset", "AAPL W78ZEO2985GM|AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "0.02%"},
{"OrderListHash", "b3125e0af79da0f5eea4cfda09806324"}
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "GOOCV W78ZFMML01JA|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "0.05%"},
{"OrderListHash", "0b52bbe98ade8e3aab943e64fcf4abfe"}
};
}
}

View File

@@ -14,6 +14,7 @@
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
@@ -35,7 +36,7 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateOptionsFilterUniverseAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "GOOG";
private Symbol _optionSymbol;
public Symbol OptionSymbol;
public override void Initialize()
{
@@ -45,7 +46,7 @@ namespace QuantConnect.Algorithm.CSharp
var equity = AddEquity(UnderlyingTicker);
var option = AddOption(UnderlyingTicker);
_optionSymbol = option.Symbol;
OptionSymbol = option.Symbol;
// Set our custom universe filter, Expires today, is a call, and is within 10 dollars of the current price
option.SetFilter(universe => from symbol in universe.WeeklysOnly().Expiration(0, 1)
@@ -63,7 +64,7 @@ namespace QuantConnect.Algorithm.CSharp
if (!Portfolio.Invested)
{
OptionChain chain;
if (slice.OptionChains.TryGetValue(_optionSymbol, out chain))
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
{
// Get the first ITM call expiring today
var contract = (
@@ -94,39 +95,31 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 12290;
public long DataPoints => 1253773;
/// <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", "2"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.40%"},
{"Compounding Annual Return", "-20.338%"},
{"Compounding Annual Return", "-21.622%"},
{"Drawdown", "0.300%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "99689"},
{"Net Profit", "-0.311%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
@@ -142,7 +135,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "15.08%"},
{"OrderListHash", "db6a1134ad325bce31c2bdd2e87ff5f4"}
{"OrderListHash", "0f8537495f5744c02191656d6b3f9205"}
};
}
}

View File

@@ -134,55 +134,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 17486;
public long DataPoints => 993927;
/// <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", "5"},
{"Average Win", "0.13%"},
{"Average Loss", "-0.30%"},
{"Compounding Annual Return", "-46.395%"},
{"Drawdown", "1.600%"},
{"Expectancy", "0.429"},
{"Start Equity", "100000"},
{"End Equity", "99149.50"},
{"Net Profit", "-0.850%"},
{"Sharpe Ratio", "-4.298"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "15.319%"},
{"Total Trades", "4"},
{"Average Win", "0.14%"},
{"Average Loss", "-0.28%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "385.400%"},
{"Expectancy", "0.502"},
{"Net Profit", "-386.489%"},
{"Sharpe Ratio", "-0.033"},
{"Probabilistic Sharpe Ratio", "1.235%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0.43"},
{"Alpha", "-0.84"},
{"Beta", "0.986"},
{"Annual Standard Deviation", "0.098"},
{"Annual Variance", "0.01"},
{"Information Ratio", "-9.299"},
{"Tracking Error", "0.091"},
{"Treynor Ratio", "-0.428"},
{"Total Fees", "$4.00"},
{"Profit-Loss Ratio", "0.50"},
{"Alpha", "-95.983"},
{"Beta", "263.726"},
{"Annual Standard Deviation", "30.617"},
{"Annual Variance", "937.371"},
{"Information Ratio", "-0.044"},
{"Tracking Error", "30.604"},
{"Treynor Ratio", "-0.004"},
{"Total Fees", "$3.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "13.50%"},
{"OrderListHash", "cf14a7ce9c86e6844051820fd4c9394c"}
{"Portfolio Turnover", "13.46%"},
{"OrderListHash", "83c9fb13ee32284702779eff8d11c608"}
};
}
}

View File

@@ -35,7 +35,7 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateOptionsHourlyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "AAPL";
private Symbol _optionSymbol;
public Symbol OptionSymbol;
public override void Initialize()
{
@@ -45,7 +45,7 @@ namespace QuantConnect.Algorithm.CSharp
var equity = AddEquity(UnderlyingTicker, Resolution.Hour);
var option = AddOption(UnderlyingTicker, Resolution.Hour);
_optionSymbol = option.Symbol;
OptionSymbol = option.Symbol;
// set our strike/expiry filter for this option chain
option.SetFilter(u => u.Strikes(-2, +2)
@@ -64,10 +64,10 @@ namespace QuantConnect.Algorithm.CSharp
/// <param name="slice">The current slice of data keyed by symbol string</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested && IsMarketOpen(_optionSymbol))
if (!Portfolio.Invested && IsMarketOpen(OptionSymbol))
{
OptionChain chain;
if (slice.OptionChains.TryGetValue(_optionSymbol, out chain))
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
{
// we find at the money (ATM) put contract with farthest expiration
var atmContract = chain
@@ -104,55 +104,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 9504;
public long DataPoints => 32492;
/// <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", "5"},
{"Total Trades", "4"},
{"Average Win", "0%"},
{"Average Loss", "-0.07%"},
{"Compounding Annual Return", "-11.517%"},
{"Compounding Annual Return", "-12.496%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "99866"},
{"Net Profit", "-0.134%"},
{"Sharpe Ratio", "-9.78"},
{"Sortino Ratio", "0"},
{"Sharpe Ratio", "-8.839"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.075"},
{"Alpha", "0.083"},
{"Beta", "-0.054"},
{"Annual Standard Deviation", "0.008"},
{"Annual Variance", "0"},
{"Information Ratio", "-18.699"},
{"Tracking Error", "0.155"},
{"Treynor Ratio", "1.434"},
{"Treynor Ratio", "1.296"},
{"Total Fees", "$4.00"},
{"Estimated Strategy Capacity", "$1000.00"},
{"Lowest Capacity Asset", "AAPL 2ZTXYMUAHCIAU|AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "2.28%"},
{"OrderListHash", "7804b3dcf20d3096a2265a289fa81cd3"}
{"OrderListHash", "81e8a822d43de2165c1d3f52964ec312"}
};
}
}

View File

@@ -43,12 +43,14 @@ namespace QuantConnect.Algorithm.CSharp
SetEndDate(2021, 1, 10);
SetCash(1000000);
var spx = AddIndex("SPX").Symbol;
// regular option SPX contracts
var spxOptions = AddIndexOption("SPX");
var spxOptions = AddIndexOption(spx);
spxOptions.SetFilter(u => u.Strikes(0, 1).Expiration(0, 30));
// weekly option SPX contracts
var spxw = AddIndexOption("SPX", "SPXW");
var spxw = AddIndexOption(spx, "SPXW");
spxw.SetFilter(u => u.Strikes(0, 1)
// single week ahead since there are many SPXW contracts and we want to preserve performance
.Expiration(0, 7)
@@ -98,55 +100,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 21467;
public virtual long DataPoints => 65536;
/// <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 virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "5"},
{"Total Trades", "5"},
{"Average Win", "0%"},
{"Average Loss", "-0.69%"},
{"Compounding Annual Return", "54.478%"},
{"Compounding Annual Return", "58.005%"},
{"Drawdown", "0.400%"},
{"Expectancy", "-0.5"},
{"Start Equity", "1000000"},
{"End Equity", "1006025"},
{"Net Profit", "0.602%"},
{"Sharpe Ratio", "2.62"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "63.221%"},
{"Net Profit", "0.588%"},
{"Sharpe Ratio", "1.448"},
{"Probabilistic Sharpe Ratio", "51.980%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.067"},
{"Beta", "-0.013"},
{"Alpha", "0.288"},
{"Beta", "-0.04"},
{"Annual Standard Deviation", "0.004"},
{"Annual Variance", "0"},
{"Information Ratio", "-50.808"},
{"Tracking Error", "0.086"},
{"Treynor Ratio", "-0.725"},
{"Information Ratio", "-98.963"},
{"Tracking Error", "0.072"},
{"Treynor Ratio", "-0.149"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$580000.00"},
{"Lowest Capacity Asset", "SPXW 31K54PVWHUJHQ|SPX 31"},
{"Portfolio Turnover", "0.40%"},
{"OrderListHash", "07a085baedb37bb7c8d460558ea77e88"}
{"Portfolio Turnover", "0.48%"},
{"OrderListHash", "174bd0a99916d58ca3f12139306940db"}
};
}
}

View File

@@ -48,7 +48,7 @@ namespace QuantConnect.Algorithm.CSharp
// weekly option SPX contracts
var spxw = AddIndexOption(spx, "SPXW");
spxw.SetFilter(u => u.Strikes(-1, +1)
spxw.SetFilter(u => u.Strikes(0, 1)
// single week ahead since there are many SPXW contracts and we want to preserve performance
.Expiration(0, 7)
.IncludeWeeklys());
@@ -66,7 +66,7 @@ namespace QuantConnect.Algorithm.CSharp
OptionChain chain;
if (slice.OptionChains.TryGetValue(_spxOption, out chain))
{
// we find the first expiration group of call options and order them in ascending strike
// we find the first expiration group of call options and order them in ascending strike
var contracts = chain
.Where(x => x.Right == OptionRight.Call)
.OrderBy(x => x.Expiry)
@@ -92,7 +92,7 @@ namespace QuantConnect.Algorithm.CSharp
Debug(orderEvent.ToString());
if (orderEvent.Symbol.ID.Symbol != "SPXW")
{
throw new RegressionTestException("Unexpected order event symbol!");
throw new Exception("Unexpected order event symbol!");
}
}
@@ -104,55 +104,47 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 16680;
public virtual long DataPoints => 35451;
/// <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 virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "10"},
{"Average Win", "0.47%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "101.998%"},
{"Total Trades", "4"},
{"Average Win", "0.12%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "8.975%"},
{"Drawdown", "0.100%"},
{"Expectancy", "24.484"},
{"Start Equity", "1000000"},
{"End Equity", "1009050"},
{"Net Profit", "0.905%"},
{"Sharpe Ratio", "8.44"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "95.546%"},
{"Expectancy", "62.078"},
{"Net Profit", "0.110%"},
{"Sharpe Ratio", "-7.925"},
{"Probabilistic Sharpe Ratio", "1.216%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "49.97"},
{"Alpha", "-2.01"},
{"Beta", "0.307"},
{"Annual Standard Deviation", "0.021"},
{"Profit-Loss Ratio", "125.16"},
{"Alpha", "-0.012"},
{"Beta", "0.001"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-144.654"},
{"Tracking Error", "0.048"},
{"Treynor Ratio", "0.589"},
{"Information Ratio", "-103.223"},
{"Tracking Error", "0.069"},
{"Treynor Ratio", "-2.449"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$13000000.00"},
{"Estimated Strategy Capacity", "$1800000.00"},
{"Lowest Capacity Asset", "SPXW XKX6S2GM9PGU|SPX 31"},
{"Portfolio Turnover", "0.28%"},
{"OrderListHash", "c1a9bc141ae25c9542b93a887e79dafe"}
{"Portfolio Turnover", "0.03%"},
{"OrderListHash", "38db27781e4df93687d0895df9796c7d"}
};
}
}

View File

@@ -1,95 +0,0 @@
/*
* 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 QuantConnect.Data;
using System.Collections.Generic;
using QuantConnect.Orders;
using System.Linq;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to add index asset types and change the tradable condition
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="benchmarks" />
/// <meta name="tag" content="indexes" />
public class BasicTemplateTradableIndexAlgorithm : BasicTemplateIndexAlgorithm
{
private OrderTicket _ticket;
/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
public override void Initialize()
{
base.Initialize();
Securities[Spx].IsTradable = true;
}
/// <summary>
/// Index EMA Cross trading underlying.
/// </summary>
public override void OnData(Slice slice)
{
base.OnData(slice);
_ticket ??= MarketOrder(Spx, 1);
}
public override void OnEndOfAlgorithm()
{
if (!_ticket.Status.IsFill())
{
throw new RegressionTestException("Index is tradable.");
}
}
/// <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()
{
{"Total Orders", "5"},
{"Average Win", "7.08%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "602.278%"},
{"Drawdown", "3.400%"},
{"Expectancy", "677.669"},
{"Start Equity", "1000000"},
{"End Equity", "1064342.82"},
{"Net Profit", "6.434%"},
{"Sharpe Ratio", "-4.563"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0.781%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "1356.34"},
{"Alpha", "-0.169"},
{"Beta", "0.073"},
{"Annual Standard Deviation", "0.028"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-6.684"},
{"Tracking Error", "0.099"},
{"Treynor Ratio", "-1.771"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$3000.00"},
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
{"Portfolio Turnover", "24.03%"},
{"OrderListHash", "fcd6fddb0a315e21095c2b35eb633e2b"}
};
}
}

View File

@@ -33,7 +33,7 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
AddEquity("SPY");
}
public override void OnData(Slice slice)
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{

View File

@@ -15,7 +15,6 @@
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Fundamental;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
@@ -69,8 +68,8 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
return topFine.Select(x => x.Symbol);
}
//Data Event Handler: New data arrives here.
public override void OnData(Slice slice)
//Data Event Handler: New data arrives here. "TradeBars" type is a dictionary of strings so you can access it by symbol.
public void OnData(TradeBars data)
{
// if we have no changes, do nothing
if (_changes == SecurityChanges.None) return;

View File

@@ -32,7 +32,7 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
AddEquity("SPY", Resolution.Second);
}
public override void OnData(Slice slice)
public override void OnData(Slice data)
{
}
}

View File

@@ -16,7 +16,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;
@@ -59,7 +58,7 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
}).ToArray();
}
public override void OnData(Slice slice)
public void OnData(TradeBars data)
{
// wait for our entire ribbon to be ready
if (!_ribbon.All(x => x.IsReady)) return;

View File

@@ -34,7 +34,7 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
}
}
public override void OnData(Slice slice) { }
public override void OnData(Slice data) { }
private void Rebalance() { }
}
}

View File

@@ -48,27 +48,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public override int AlgorithmHistoryDataPoints => 28;
/// <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 override Dictionary<string, string> ExpectedStatistics => new()
{
{"Total Orders", "49"},
{"Total Trades", "49"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000.00"},
{"End Equity", "99986.57"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -84,7 +76,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "₮220000.00"},
{"Lowest Capacity Asset", "BTCUSDT 18N"},
{"Portfolio Turnover", "22.80%"},
{"OrderListHash", "80711e4c1e3c0da20152da8fafc3fd66"}
{"OrderListHash", "7417649395922ff3791471b4f3b5c021"}
};
}
}

View File

@@ -48,27 +48,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public override int AlgorithmHistoryDataPoints => 28;
/// <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 override Dictionary<string, string> ExpectedStatistics => new()
{
{"Total Orders", "49"},
{"Total Trades", "49"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000.00"},
{"End Equity", "99986.57"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -84,7 +76,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "₮12000000.00"},
{"Lowest Capacity Asset", "BTCUSDT 18N"},
{"Portfolio Turnover", "22.80%"},
{"OrderListHash", "80711e4c1e3c0da20152da8fafc3fd66"}
{"OrderListHash", "7417649395922ff3791471b4f3b5c021"}
};
}
}

View File

@@ -47,27 +47,19 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public override int AlgorithmHistoryDataPoints => 28;
/// <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 override Dictionary<string, string> ExpectedStatistics => new()
{
{"Total Orders", "49"},
{"Total Trades", "49"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000.00"},
{"End Equity", "100001.31"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
@@ -83,7 +75,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$2000.00"},
{"Lowest Capacity Asset", "BTCUSD E3"},
{"Portfolio Turnover", "0.28%"},
{"OrderListHash", "899ef4e299a6cc73c1bd96fb9993db0e"}
{"OrderListHash", "7f892f0c42d8826ff770ee602fe207a2"}
};
}
}

Some files were not shown because too many files have changed in this diff Show More