Compare commits
95 Commits
9550
...
feature-py
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be6ead75e9 | ||
|
|
25f7ccf0c2 | ||
|
|
afb0a86291 | ||
|
|
f5c5faa3d4 | ||
|
|
c471d1ced0 | ||
|
|
5c345faea7 | ||
|
|
11bed1f0c3 | ||
|
|
ec57799a5d | ||
|
|
4c8aa638eb | ||
|
|
7c3caec07f | ||
|
|
45f71543bd | ||
|
|
13b9d91ecb | ||
|
|
f239018e77 | ||
|
|
f1c98b848a | ||
|
|
2c7bde422a | ||
|
|
9e95bfea90 | ||
|
|
b820ff4de8 | ||
|
|
8218a2be99 | ||
|
|
9e3031c562 | ||
|
|
2cf9239b6e | ||
|
|
4c63c60a89 | ||
|
|
9a2e47b05c | ||
|
|
711d46d6e2 | ||
|
|
5d6625c1ea | ||
|
|
0a70611d81 | ||
|
|
43c6d5cc5a | ||
|
|
f39acceadc | ||
|
|
921ddced04 | ||
|
|
ff8563244f | ||
|
|
041f1d9db5 | ||
|
|
eb1181f5f7 | ||
|
|
9d4014b7db | ||
|
|
a4f66628fd | ||
|
|
b9974e6f54 | ||
|
|
474c5cd890 | ||
|
|
0dfb368cb4 | ||
|
|
fbf5300bb6 | ||
|
|
c67845bd45 | ||
|
|
54ddbfbe24 | ||
|
|
bd7be31ede | ||
|
|
041a111b92 | ||
|
|
fa94bcc46a | ||
|
|
2988f7ec3c | ||
|
|
b785877d33 | ||
|
|
5dbb0db2f9 | ||
|
|
a489436743 | ||
|
|
ff2013b0d0 | ||
|
|
567e7b7679 | ||
|
|
646f22a63f | ||
|
|
fd138ec397 | ||
|
|
e98b31fc4c | ||
|
|
d2eae2f652 | ||
|
|
0f0a2bc9a8 | ||
|
|
8ad81dca71 | ||
|
|
f965f34a3f | ||
|
|
06a7d54c38 | ||
|
|
7174fcb9d7 | ||
|
|
29e9d678f2 | ||
|
|
098ac7d0a9 | ||
|
|
6cb4411f6e | ||
|
|
46ef9a9dbb | ||
|
|
d8d8134437 | ||
|
|
9a30c9bd5f | ||
|
|
f76a0efb0e | ||
|
|
7238fcd0f3 | ||
|
|
91e8393aac | ||
|
|
5771635265 | ||
|
|
914486fdb6 | ||
|
|
61fda8b62c | ||
|
|
124ac3b98e | ||
|
|
9dca43bccb | ||
|
|
6efeee07dc | ||
|
|
c452dd3726 | ||
|
|
c602fd0a3f | ||
|
|
104071cda5 | ||
|
|
a5d9526d65 | ||
|
|
8e525c63fc | ||
|
|
d0e9134cc9 | ||
|
|
883d354a98 | ||
|
|
76a53eb096 | ||
|
|
c02ee1b0d8 | ||
|
|
9167882ab2 | ||
|
|
854b987cd0 | ||
|
|
a26414d273 | ||
|
|
84264ca7ef | ||
|
|
b2ed398687 | ||
|
|
e8c316cbcf | ||
|
|
724e52c0b3 | ||
|
|
4252c79e45 | ||
|
|
cbb40dfa43 | ||
|
|
8792fa2600 | ||
|
|
20e9fd7899 | ||
|
|
e05a6bffd0 | ||
|
|
c2f0fdc47a | ||
|
|
b1b8da1e17 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -271,3 +271,6 @@ QuantConnect.Lean.sln.DotSettings*
|
||||
|
||||
#User notebook files
|
||||
Research/Notebooks
|
||||
|
||||
#Docker result files
|
||||
Results/
|
||||
18
.idea/Lean.iml
generated
18
.idea/Lean.iml
generated
@@ -1,18 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/Algorithm.Python" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/Algorithm.Python/stubs" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
<component name="PyDocumentationSettings">
|
||||
<option name="format" value="PLAIN" />
|
||||
<option name="myDocStringFormat" value="Plain" />
|
||||
</component>
|
||||
<component name="TestRunnerService">
|
||||
<option name="PROJECT_TEST_RUNNER" value="pytest" />
|
||||
</component>
|
||||
</module>
|
||||
14
.idea/readme.md
generated
14
.idea/readme.md
generated
@@ -91,14 +91,14 @@ From a terminal; Pycharm has a built in terminal on the bottom taskbar labeled *
|
||||
|
||||
2. Using the **run_docker.cfg** to store args for repeated use; any blank entries will resort to default values! example: **_./run_docker.bat run_docker.cfg_**
|
||||
|
||||
image=quantconnect/lean:latest
|
||||
config_file=
|
||||
data_dir=
|
||||
results_dir=
|
||||
debugging=
|
||||
python_dir=
|
||||
IMAGE=quantconnect/lean:latest
|
||||
CONFIG_FILE=
|
||||
DATA_DIR=
|
||||
RESULTS_DIR=
|
||||
DEBUGGING=
|
||||
PYTHON_DIR=
|
||||
|
||||
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat debugging=y_**
|
||||
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat DEBUGGING=y_**
|
||||
* Accepted args for inline include all listed in the file in #2; must follow the **key=value** format
|
||||
|
||||
<br />
|
||||
|
||||
@@ -16,6 +16,7 @@ before_install:
|
||||
- conda install -y cython=0.29.15
|
||||
- conda install -y scipy=1.4.1
|
||||
- conda install -y wrapt=1.12.1
|
||||
- pip install pyarrow==1.0.1
|
||||
install:
|
||||
- nuget restore QuantConnect.Lean.sln
|
||||
- nuget install NUnit.Runners -Version 3.11.1 -OutputDirectory testrunner
|
||||
@@ -23,4 +24,4 @@ script:
|
||||
- msbuild /p:Configuration=Release /p:VbcToolExe=vbnc.exe QuantConnect.Lean.sln
|
||||
- mono ./testrunner/NUnit.ConsoleRunner.3.11.1/tools/nunit3-console.exe ./Tests/bin/Release/QuantConnect.Tests.dll --where "cat != TravisExclude" --labels=Off
|
||||
- chmod +x ci_build_stubs.sh
|
||||
- sudo -E ./ci_build_stubs.sh -ipy -g -p
|
||||
- sudo -E ./ci_build_stubs.sh -d -t -g -p
|
||||
|
||||
@@ -106,14 +106,14 @@ From a terminal launch the run_docker.bat/.sh script; there are a few choices on
|
||||
|
||||
2. Using the **run_docker.cfg** to store args for repeated use; any blank entries will resort to default values! example: **_./run_docker.bat run_docker.cfg_**
|
||||
|
||||
image=quantconnect/lean:latest
|
||||
config_file=
|
||||
data_dir=
|
||||
results_dir=
|
||||
debugging=
|
||||
python_dir=
|
||||
IMAGE=quantconnect/lean:latest
|
||||
CONFIG_FILE=
|
||||
DATA_DIR=
|
||||
RESULTS_DIR=
|
||||
DEBUGGING=
|
||||
PYTHON_DIR=
|
||||
|
||||
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat debugging=y_**
|
||||
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat DEBUGGING=y_**
|
||||
* Accepted args for inline include all listed in the file in #2
|
||||
|
||||
<br />
|
||||
|
||||
34
.vscode/readme.md
vendored
34
.vscode/readme.md
vendored
@@ -101,14 +101,14 @@ This section will cover how to actually launch Lean in the container with your d
|
||||
|
||||
<h3>Option 1 (Recommended)</h3>
|
||||
|
||||
In VS Code click on the debug/run icon on the left toolbar, at the top you should see a drop down menu with launch options, be sure to select **Debug in Container**. This option will kick off a launch script that will start the docker. With this specific launch option the parameters are already configured in VS Codes **tasks.json** under the **run-docker** task args. These set arguements are:
|
||||
In VS Code click on the debug/run icon on the left toolbar, at the top you should see a drop down menu with launch options, be sure to select **Debug in Container**. This option will kick off a launch script that will start the docker. With this specific launch option the parameters are already configured in VS Codes **tasks.json** under the **run-docker** task args. These set arguments are:
|
||||
|
||||
"image=quantconnect/lean:latest",
|
||||
"config_file=${workspaceFolder}/Launcher/config.json",
|
||||
"data_dir=${workspaceFolder}/Data",
|
||||
"results_dir=${workspaceFolder}/",
|
||||
"debugging=Y",
|
||||
"python_location=${workspaceFolder}/Algorithm.Python"
|
||||
"IMAGE=quantconnect/lean:latest",
|
||||
"CONFIG_FILE=${workspaceFolder}/Launcher/config.json",
|
||||
"DATA_DIR=${workspaceFolder}/Data",
|
||||
"RESULTS_DIR=${workspaceFolder}/Results",
|
||||
"DEBUGGING=Y",
|
||||
"PYHTON_DIR=${workspaceFolder}/Algorithm.Python"
|
||||
|
||||
As defaults these are all great! Feel free to change them as needed for your setup.
|
||||
|
||||
@@ -120,21 +120,21 @@ From a terminal launch the run_docker.bat/.sh script; there are a few choices on
|
||||
1. Launch with no parameters and answer the questions regarding configuration (Press enter for defaults)
|
||||
|
||||
* Enter docker image [default: quantconnect/lean:latest]:
|
||||
* Enter absolute path to Lean config file [default: _~currentDir_\Launcher\config.json]:
|
||||
* Enter absolute path to Data folder [default: ~_currentDir_\Data\]:
|
||||
* Enter absolute path to store results [default: ~_currentDir_\]:
|
||||
* Enter absolute path to Lean config file [default: .\Launcher\config.json]:
|
||||
* Enter absolute path to Data folder [default: .\Data\]:
|
||||
* Enter absolute path to store results [default: .\Results]:
|
||||
* Would you like to debug C#? (Requires mono debugger attachment) [default: N]:
|
||||
|
||||
2. Using the **run_docker.cfg** to store args for repeated use; any blank entries will resort to default values! example: **_./run_docker.bat run_docker.cfg_**
|
||||
|
||||
image=quantconnect/lean:latest
|
||||
config_file=
|
||||
data_dir=
|
||||
results_dir=
|
||||
debugging=
|
||||
python_dir=
|
||||
IMAGE=quantconnect/lean:latest
|
||||
CONFIG_FILE=
|
||||
DATA_DIR=
|
||||
RESULTS_DIR=
|
||||
DEBUGGING=
|
||||
PYTHON_DIR=
|
||||
|
||||
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat debugging=y_**
|
||||
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat DEBUGGING=y_**
|
||||
* Accepted args for inline include all listed in the file in #2
|
||||
|
||||
<br />
|
||||
|
||||
5
.vscode/settings.json
vendored
5
.vscode/settings.json
vendored
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"python.autoComplete.extraPaths": [
|
||||
"Algorithm.Python/stubs"
|
||||
]
|
||||
}
|
||||
14
.vscode/tasks.json
vendored
14
.vscode/tasks.json
vendored
@@ -51,13 +51,13 @@
|
||||
"command": "${workspaceFolder}/run_docker.sh"
|
||||
},
|
||||
"args": [
|
||||
"image=quantconnect/lean:latest",
|
||||
"config_file=${workspaceFolder}/Launcher/config.json",
|
||||
"data_dir=${workspaceFolder}/Data",
|
||||
"results_dir=${workspaceFolder}/",
|
||||
"debugging=Y",
|
||||
"python_dir=${workspaceFolder}/Algorithm.Python",
|
||||
"exit=Y"
|
||||
"IMAGE=quantconnect/lean:latest",
|
||||
"CONFIG_FILE=${workspaceFolder}/Launcher/config.json",
|
||||
"DATA_DIR=${workspaceFolder}/Data",
|
||||
"RESULTS_DIR=${workspaceFolder}/Results",
|
||||
"DEBUGGING=Y",
|
||||
"PYTHON_DIR=${workspaceFolder}/Algorithm.Python",
|
||||
"EXIT=Y"
|
||||
],
|
||||
"problemMatcher": [
|
||||
{
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests that we receive the expected data when
|
||||
/// we add future option contracts individually using <see cref="AddFutureOptionContract"/>
|
||||
/// </summary>
|
||||
public class AddFutureOptionContractDataStreamingRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private bool _onDataReached;
|
||||
private bool _invested;
|
||||
private Symbol _es20h20;
|
||||
private Symbol _es19m20;
|
||||
|
||||
private readonly HashSet<Symbol> _symbolsReceived = new HashSet<Symbol>();
|
||||
private readonly HashSet<Symbol> _expectedSymbolsReceived = new HashSet<Symbol>();
|
||||
private readonly Dictionary<Symbol, List<QuoteBar>> _dataReceived = new Dictionary<Symbol, List<QuoteBar>>();
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 1, 6);
|
||||
|
||||
_es20h20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 3, 20)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
_es19m20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
var optionChains = OptionChainProvider.GetOptionContractList(_es20h20, Time)
|
||||
.Concat(OptionChainProvider.GetOptionContractList(_es19m20, Time));
|
||||
|
||||
foreach (var optionContract in optionChains)
|
||||
{
|
||||
_expectedSymbolsReceived.Add(AddFutureOptionContract(optionContract, Resolution.Minute).Symbol);
|
||||
}
|
||||
|
||||
if (_expectedSymbolsReceived.Count == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Expected Symbols receive count is 0, expected >0");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!data.HasData)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_onDataReached = true;
|
||||
|
||||
var hasOptionQuoteBars = false;
|
||||
foreach (var qb in data.QuoteBars.Values)
|
||||
{
|
||||
if (qb.Symbol.SecurityType != SecurityType.FutureOption)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
hasOptionQuoteBars = true;
|
||||
|
||||
_symbolsReceived.Add(qb.Symbol);
|
||||
if (!_dataReceived.ContainsKey(qb.Symbol))
|
||||
{
|
||||
_dataReceived[qb.Symbol] = new List<QuoteBar>();
|
||||
}
|
||||
|
||||
_dataReceived[qb.Symbol].Add(qb);
|
||||
}
|
||||
|
||||
if (_invested || !hasOptionQuoteBars)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.ContainsKey(_es20h20) && data.ContainsKey(_es19m20))
|
||||
{
|
||||
SetHoldings(_es20h20, 0.2);
|
||||
SetHoldings(_es19m20, 0.2);
|
||||
|
||||
_invested = true;
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
base.OnEndOfAlgorithm();
|
||||
|
||||
if (!_onDataReached)
|
||||
{
|
||||
throw new Exception("OnData() was never called.");
|
||||
}
|
||||
if (_symbolsReceived.Count != _expectedSymbolsReceived.Count)
|
||||
{
|
||||
throw new AggregateException($"Expected {_expectedSymbolsReceived.Count} option contracts Symbols, found {_symbolsReceived.Count}");
|
||||
}
|
||||
|
||||
var missingSymbols = new List<Symbol>();
|
||||
foreach (var expectedSymbol in _expectedSymbolsReceived)
|
||||
{
|
||||
if (!_symbolsReceived.Contains(expectedSymbol))
|
||||
{
|
||||
missingSymbols.Add(expectedSymbol);
|
||||
}
|
||||
}
|
||||
|
||||
if (missingSymbols.Count > 0)
|
||||
{
|
||||
throw new Exception($"Symbols: \"{string.Join(", ", missingSymbols)}\" were not found in OnData");
|
||||
}
|
||||
|
||||
foreach (var expectedSymbol in _expectedSymbolsReceived)
|
||||
{
|
||||
var data = _dataReceived[expectedSymbol];
|
||||
var nonDupeDataCount = data.Select(x =>
|
||||
{
|
||||
x.EndTime = default(DateTime);
|
||||
return x;
|
||||
}).Distinct().Count();
|
||||
|
||||
if (nonDupeDataCount < 1000)
|
||||
{
|
||||
throw new Exception($"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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 Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "217.585%"},
|
||||
{"Drawdown", "0.600%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.635%"},
|
||||
{"Sharpe 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", "-14.395"},
|
||||
{"Tracking Error", "0.043"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Fitness Score", "1"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "3.199"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1074366800"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Securities.Future;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests that we only receive the option chain for a single future contract
|
||||
/// in the option universe filter.
|
||||
/// </summary>
|
||||
public class AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private bool _invested;
|
||||
private bool _onDataReached;
|
||||
private bool _optionFilterRan;
|
||||
private readonly HashSet<Symbol> _symbolsReceived = new HashSet<Symbol>();
|
||||
private readonly HashSet<Symbol> _expectedSymbolsReceived = new HashSet<Symbol>();
|
||||
private readonly Dictionary<Symbol, List<QuoteBar>> _dataReceived = new Dictionary<Symbol, List<QuoteBar>>();
|
||||
|
||||
private Future _es;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 1, 6);
|
||||
|
||||
_es = AddFuture(Futures.Indices.SP500EMini, Resolution.Minute, Market.CME);
|
||||
_es.SetFilter((futureFilter) =>
|
||||
{
|
||||
return futureFilter.Expiration(0, 365).ExpirationCycle(new[] { 3, 6 });
|
||||
});
|
||||
|
||||
AddFutureOption(_es.Symbol, optionContracts =>
|
||||
{
|
||||
_optionFilterRan = true;
|
||||
|
||||
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>(((IEnumerable<Symbol>)optionContracts).Select(x => x.Underlying)).SingleOrDefault();
|
||||
|
||||
if (expiry == null || symbol == null)
|
||||
{
|
||||
throw new InvalidOperationException("Expected a single Option contract in the chain, found 0 contracts");
|
||||
}
|
||||
|
||||
var enumerator = optionContracts.GetEnumerator();
|
||||
while (enumerator.MoveNext())
|
||||
{
|
||||
_expectedSymbolsReceived.Add(enumerator.Current);
|
||||
}
|
||||
|
||||
return optionContracts;
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!data.HasData)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_onDataReached = true;
|
||||
|
||||
var hasOptionQuoteBars = false;
|
||||
foreach (var qb in data.QuoteBars.Values)
|
||||
{
|
||||
if (qb.Symbol.SecurityType != SecurityType.FutureOption)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
hasOptionQuoteBars = true;
|
||||
|
||||
_symbolsReceived.Add(qb.Symbol);
|
||||
if (!_dataReceived.ContainsKey(qb.Symbol))
|
||||
{
|
||||
_dataReceived[qb.Symbol] = new List<QuoteBar>();
|
||||
}
|
||||
|
||||
_dataReceived[qb.Symbol].Add(qb);
|
||||
}
|
||||
|
||||
if (_invested || !hasOptionQuoteBars)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var chain in data.OptionChains.Values)
|
||||
{
|
||||
var futureInvested = false;
|
||||
var optionInvested = false;
|
||||
|
||||
foreach (var option in chain.Contracts.Keys)
|
||||
{
|
||||
if (futureInvested && optionInvested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var future = option.Underlying;
|
||||
|
||||
if (!optionInvested && data.ContainsKey(option))
|
||||
{
|
||||
MarketOrder(option, 1);
|
||||
_invested = true;
|
||||
optionInvested = true;
|
||||
}
|
||||
if (!futureInvested && data.ContainsKey(future))
|
||||
{
|
||||
MarketOrder(future, 1);
|
||||
_invested = true;
|
||||
futureInvested = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
base.OnEndOfAlgorithm();
|
||||
|
||||
if (!_optionFilterRan)
|
||||
{
|
||||
throw new InvalidOperationException("Option chain filter was never ran");
|
||||
}
|
||||
if (!_onDataReached)
|
||||
{
|
||||
throw new Exception("OnData() was never called.");
|
||||
}
|
||||
if (_symbolsReceived.Count != _expectedSymbolsReceived.Count)
|
||||
{
|
||||
throw new AggregateException($"Expected {_expectedSymbolsReceived.Count} option contracts Symbols, found {_symbolsReceived.Count}");
|
||||
}
|
||||
|
||||
var missingSymbols = new List<Symbol>();
|
||||
foreach (var expectedSymbol in _expectedSymbolsReceived)
|
||||
{
|
||||
if (!_symbolsReceived.Contains(expectedSymbol))
|
||||
{
|
||||
missingSymbols.Add(expectedSymbol);
|
||||
}
|
||||
}
|
||||
|
||||
if (missingSymbols.Count > 0)
|
||||
{
|
||||
throw new Exception($"Symbols: \"{string.Join(", ", missingSymbols)}\" were not found in OnData");
|
||||
}
|
||||
|
||||
foreach (var expectedSymbol in _expectedSymbolsReceived)
|
||||
{
|
||||
var data = _dataReceived[expectedSymbol];
|
||||
var nonDupeDataCount = data.Select(x =>
|
||||
{
|
||||
x.EndTime = default(DateTime);
|
||||
return x;
|
||||
}).Distinct().Count();
|
||||
|
||||
if (nonDupeDataCount < 1000)
|
||||
{
|
||||
throw new Exception($"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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 Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "-15.625%"},
|
||||
{"Drawdown", "0.200%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "-0.093%"},
|
||||
{"Sharpe Ratio", "-11.181"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.002"},
|
||||
{"Beta", "-0.016"},
|
||||
{"Annual Standard Deviation", "0.001"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-14.343"},
|
||||
{"Tracking Error", "0.044"},
|
||||
{"Treynor Ratio", "0.479"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Fitness Score", "0.41"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-185.654"},
|
||||
{"Portfolio Turnover", "0.821"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1532330301"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.Quiver;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp.AltData
|
||||
{
|
||||
/// <summary>
|
||||
/// Quiver Quantitative is a provider of alternative data.
|
||||
/// This algorithm shows how to consume the <see cref="QuiverWallStreetBets"/>
|
||||
/// </summary>
|
||||
public class QuiverWallStreetBetsDataAlgorithm : QCAlgorithm
|
||||
{
|
||||
/// <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(2019, 1, 1);
|
||||
SetEndDate(2020, 6, 1);
|
||||
SetCash(100000);
|
||||
|
||||
var aapl = AddEquity("AAPL", Resolution.Daily).Symbol;
|
||||
var quiverWSBSymbol = AddData<QuiverWallStreetBets>(aapl).Symbol;
|
||||
var history = History<QuiverWallStreetBets>(quiverWSBSymbol, 60, Resolution.Daily);
|
||||
|
||||
Debug($"We got {history.Count()} items from our history request");
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
var points = data.Get<QuiverWallStreetBets>();
|
||||
foreach (var point in points.Values)
|
||||
{
|
||||
// Go long in the stock if it was mentioned more than 5 times in the WallStreetBets daily discussion
|
||||
if (point.Mentions > 5)
|
||||
{
|
||||
SetHoldings(point.Symbol.Underlying, 1);
|
||||
}
|
||||
// Go short in the stock if it was mentioned less than 5 times in the WallStreetBets daily discussion
|
||||
if (point.Mentions < 5)
|
||||
{
|
||||
SetHoldings(point.Symbol.Underlying, -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -107,7 +107,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "498372354"}
|
||||
{"OrderListHash", "-1575550889"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,4 +119,4 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"OrderListHash", "491919591"}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -222,12 +222,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$85.33"},
|
||||
{"Total Fees", "$85.34"},
|
||||
{"Fitness Score", "0.5"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-43.937"},
|
||||
{"Return Over Maximum Drawdown", "-43.943"},
|
||||
{"Portfolio Turnover", "1.028"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -242,7 +242,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "415415696"}
|
||||
{"OrderListHash", "956597072"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,8 +151,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-30.28"},
|
||||
{"Portfolio Turnover", "1.029"},
|
||||
{"Return Over Maximum Drawdown", "-30.158"},
|
||||
{"Portfolio Turnover", "1.033"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -166,7 +166,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "737971736"}
|
||||
{"OrderListHash", "1349023435"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
138
Algorithm.CSharp/CustomBuyingPowerModelAlgorithm.cs
Normal file
138
Algorithm.CSharp/CustomBuyingPowerModelAlgorithm.cs
Normal file
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
* 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.Securities;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Demonstration of using custom buying power model in backtesting.
|
||||
/// QuantConnect allows you to model all orders as deeply and accurately as you need.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="trading and orders" />
|
||||
/// <meta name="tag" content="transaction fees and slippage" />
|
||||
/// <meta name="tag" content="custom buying power models" />
|
||||
public class CustomBuyingPowerModelAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _spy;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 10, 01);
|
||||
SetEndDate(2013, 10, 31);
|
||||
var security = AddEquity("SPY", Resolution.Hour);
|
||||
_spy = security.Symbol;
|
||||
|
||||
// set the buying power model
|
||||
security.SetBuyingPowerModel(new CustomBuyingPowerModel());
|
||||
}
|
||||
|
||||
public void OnData(Slice slice)
|
||||
{
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var quantity = CalculateOrderQuantity(_spy, 1m);
|
||||
if (quantity % 100 != 0)
|
||||
{
|
||||
throw new Exception($"CustomBuyingPowerModel only allow quantity that is multiple of 100 and {quantity} was found");
|
||||
}
|
||||
|
||||
// We normally get insufficient buying power model, but the
|
||||
// CustomBuyingPowerModel always says that there is sufficient buying power for the orders
|
||||
MarketOrder(_spy, quantity * 10);
|
||||
}
|
||||
|
||||
public class CustomBuyingPowerModel : BuyingPowerModel
|
||||
{
|
||||
public override GetMaximumOrderQuantityResult GetMaximumOrderQuantityForTargetBuyingPower(
|
||||
GetMaximumOrderQuantityForTargetBuyingPowerParameters parameters)
|
||||
{
|
||||
var quantity = base.GetMaximumOrderQuantityForTargetBuyingPower(parameters).Quantity;
|
||||
quantity = Math.Floor(quantity / 100) * 100;
|
||||
return new GetMaximumOrderQuantityResult(quantity);
|
||||
}
|
||||
|
||||
public override HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerForOrder(
|
||||
HasSufficientBuyingPowerForOrderParameters parameters)
|
||||
{
|
||||
return new HasSufficientBuyingPowerForOrderResult(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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 Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "5672.520%"},
|
||||
{"Drawdown", "22.500%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "40.601%"},
|
||||
{"Sharpe Ratio", "40.201"},
|
||||
{"Probabilistic Sharpe Ratio", "77.339%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "41.848"},
|
||||
{"Beta", "9.224"},
|
||||
{"Annual Standard Deviation", "1.164"},
|
||||
{"Annual Variance", "1.355"},
|
||||
{"Information Ratio", "44.459"},
|
||||
{"Tracking Error", "1.04"},
|
||||
{"Treynor Ratio", "5.073"},
|
||||
{"Total Fees", "$30.00"},
|
||||
{"Fitness Score", "0.418"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "113.05"},
|
||||
{"Return Over Maximum Drawdown", "442.81"},
|
||||
{"Portfolio Turnover", "0.418"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "639761089"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -26,11 +26,12 @@ using QuantConnect.Securities;
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Demonstration of using custom fee, slippage and fill models for modelling transactions in backtesting.
|
||||
/// Demonstration of using custom fee, slippage, fill, and buying power models for modelling transactions in backtesting.
|
||||
/// QuantConnect allows you to model all orders as deeply and accurately as you need.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="trading and orders" />
|
||||
/// <meta name="tag" content="transaction fees and slippage" />
|
||||
/// <meta name="tag" content="custom buying power models" />
|
||||
/// <meta name="tag" content="custom transaction models" />
|
||||
/// <meta name="tag" content="custom slippage models" />
|
||||
/// <meta name="tag" content="custom fee models" />
|
||||
@@ -50,6 +51,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
_security.SetFeeModel(new CustomFeeModel(this));
|
||||
_security.SetFillModel(new CustomFillModel(this));
|
||||
_security.SetSlippageModel(new CustomSlippageModel(this));
|
||||
_security.SetBuyingPowerModel(new CustomBuyingPowerModel(this));
|
||||
}
|
||||
|
||||
public void OnData(TradeBars data)
|
||||
@@ -60,13 +62,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
if (Time.Day > 10 && _security.Holdings.Quantity <= 0)
|
||||
{
|
||||
var quantity = CalculateOrderQuantity(_spy, .5m);
|
||||
Log("MarketOrder: " + quantity);
|
||||
Log($"MarketOrder: {quantity}");
|
||||
MarketOrder(_spy, quantity, asynchronous: true); // async needed for partial fill market orders
|
||||
}
|
||||
else if (Time.Day > 20 && _security.Holdings.Quantity >= 0)
|
||||
{
|
||||
var quantity = CalculateOrderQuantity(_spy, -.5m);
|
||||
Log("MarketOrder: " + quantity);
|
||||
Log($"MarketOrder: {quantity}");
|
||||
MarketOrder(_spy, quantity, asynchronous: true); // async needed for partial fill market orders
|
||||
}
|
||||
}
|
||||
@@ -109,7 +111,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
fill.Status = OrderStatus.PartiallyFilled;
|
||||
}
|
||||
|
||||
_algorithm.Log("CustomFillModel: " + fill);
|
||||
_algorithm.Log($"CustomFillModel: {fill}");
|
||||
|
||||
return fill;
|
||||
}
|
||||
@@ -131,7 +133,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
1m,
|
||||
parameters.Security.Price*parameters.Order.AbsoluteQuantity*0.00001m);
|
||||
|
||||
_algorithm.Log("CustomFeeModel: " + fee);
|
||||
_algorithm.Log($"CustomFeeModel: {fee}");
|
||||
return new OrderFee(new CashAmount(fee, "USD"));
|
||||
}
|
||||
}
|
||||
@@ -150,11 +152,31 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
// custom slippage math
|
||||
var slippage = asset.Price*0.0001m*(decimal) Math.Log10(2*(double) order.AbsoluteQuantity);
|
||||
|
||||
_algorithm.Log("CustomSlippageModel: " + slippage);
|
||||
_algorithm.Log($"CustomSlippageModel: {slippage}");
|
||||
return slippage;
|
||||
}
|
||||
}
|
||||
|
||||
public class CustomBuyingPowerModel : BuyingPowerModel
|
||||
{
|
||||
private readonly QCAlgorithm _algorithm;
|
||||
|
||||
public CustomBuyingPowerModel(QCAlgorithm algorithm)
|
||||
{
|
||||
_algorithm = algorithm;
|
||||
}
|
||||
|
||||
public override HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerForOrder(
|
||||
HasSufficientBuyingPowerForOrderParameters parameters)
|
||||
{
|
||||
// custom behavior: this model will assume that there is always enough buying power
|
||||
var hasSufficientBuyingPowerForOrderResult = new HasSufficientBuyingPowerForOrderResult(true);
|
||||
_algorithm.Log($"CustomBuyingPowerModel: {hasSufficientBuyingPowerForOrderResult.IsSufficient}");
|
||||
|
||||
return hasSufficientBuyingPowerForOrderResult;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
|
||||
@@ -187,12 +187,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "6441"},
|
||||
{"Average Win", "0.07%"},
|
||||
{"Average Loss", "-0.07%"},
|
||||
{"Compounding Annual Return", "13.284%"},
|
||||
{"Compounding Annual Return", "13.331%"},
|
||||
{"Drawdown", "10.700%"},
|
||||
{"Expectancy", "0.061"},
|
||||
{"Net Profit", "13.284%"},
|
||||
{"Sharpe Ratio", "0.96"},
|
||||
{"Probabilistic Sharpe Ratio", "46.111%"},
|
||||
{"Net Profit", "13.331%"},
|
||||
{"Sharpe Ratio", "0.963"},
|
||||
{"Probabilistic Sharpe Ratio", "46.232%"},
|
||||
{"Loss Rate", "46%"},
|
||||
{"Win Rate", "54%"},
|
||||
{"Profit-Loss Ratio", "0.97"},
|
||||
@@ -200,15 +200,15 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Beta", "-0.066"},
|
||||
{"Annual Standard Deviation", "0.121"},
|
||||
{"Annual Variance", "0.015"},
|
||||
{"Information Ratio", "0.004"},
|
||||
{"Information Ratio", "0.006"},
|
||||
{"Tracking Error", "0.171"},
|
||||
{"Treynor Ratio", "-1.754"},
|
||||
{"Total Fees", "$8669.33"},
|
||||
{"Treynor Ratio", "-1.761"},
|
||||
{"Total Fees", "$8669.41"},
|
||||
{"Fitness Score", "0.675"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "1.124"},
|
||||
{"Return Over Maximum Drawdown", "1.242"},
|
||||
{"Sortino Ratio", "1.127"},
|
||||
{"Return Over Maximum Drawdown", "1.246"},
|
||||
{"Portfolio Turnover", "1.64"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -223,7 +223,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1120327913"}
|
||||
{"OrderListHash", "-75671425"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,12 +160,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "5059"},
|
||||
{"Average Win", "0.08%"},
|
||||
{"Average Loss", "-0.08%"},
|
||||
{"Compounding Annual Return", "14.901%"},
|
||||
{"Compounding Annual Return", "14.950%"},
|
||||
{"Drawdown", "10.600%"},
|
||||
{"Expectancy", "0.075"},
|
||||
{"Net Profit", "14.901%"},
|
||||
{"Sharpe Ratio", "1.068"},
|
||||
{"Probabilistic Sharpe Ratio", "50.201%"},
|
||||
{"Net Profit", "14.950%"},
|
||||
{"Sharpe Ratio", "1.072"},
|
||||
{"Probabilistic Sharpe Ratio", "50.327%"},
|
||||
{"Loss Rate", "45%"},
|
||||
{"Win Rate", "55%"},
|
||||
{"Profit-Loss Ratio", "0.97"},
|
||||
@@ -173,15 +173,15 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Beta", "-0.066"},
|
||||
{"Annual Standard Deviation", "0.121"},
|
||||
{"Annual Variance", "0.015"},
|
||||
{"Information Ratio", "0.08"},
|
||||
{"Information Ratio", "0.083"},
|
||||
{"Tracking Error", "0.171"},
|
||||
{"Treynor Ratio", "-1.963"},
|
||||
{"Total Fees", "$6806.57"},
|
||||
{"Treynor Ratio", "-1.971"},
|
||||
{"Total Fees", "$6806.67"},
|
||||
{"Fitness Score", "0.694"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "1.261"},
|
||||
{"Return Over Maximum Drawdown", "1.404"},
|
||||
{"Sortino Ratio", "1.265"},
|
||||
{"Return Over Maximum Drawdown", "1.409"},
|
||||
{"Portfolio Turnover", "1.296"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -196,7 +196,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "974523768"}
|
||||
{"OrderListHash", "1142077166"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,13 +90,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$14.91"},
|
||||
{"Total Fees", "$14.92"},
|
||||
{"Fitness Score", "0.258"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-27.251"},
|
||||
{"Portfolio Turnover", "0.515"},
|
||||
{"Return Over Maximum Drawdown", "-27.228"},
|
||||
{"Portfolio Turnover", "0.516"},
|
||||
{"Total Insights Generated", "1"},
|
||||
{"Total Insights Closed", "1"},
|
||||
{"Total Insights Analysis Completed", "1"},
|
||||
@@ -110,7 +110,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "221046152"}
|
||||
{"OrderListHash", "1296183675"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-15.574"},
|
||||
{"Portfolio Turnover", "2.056"},
|
||||
{"Portfolio Turnover", "2.057"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -193,7 +193,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1311542155"}
|
||||
{"OrderListHash", "-1116140375"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
private readonly Dictionary<Symbol, int> _dataPointsPerSymbol = new Dictionary<Symbol, int>();
|
||||
private bool _added;
|
||||
private Symbol _eurusd;
|
||||
private DateTime lastDataTime = DateTime.MinValue;
|
||||
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
@@ -51,6 +52,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (lastDataTime == data.Time)
|
||||
{
|
||||
throw new Exception("Duplicate time for current data and last data slice");
|
||||
}
|
||||
|
||||
lastDataTime = data.Time;
|
||||
|
||||
if (_added)
|
||||
{
|
||||
var eurUsdSubscription = SubscriptionManager.SubscriptionDataConfigService
|
||||
@@ -94,7 +102,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
var expectedDataPointsPerSymbol = new Dictionary<string, int>
|
||||
{
|
||||
{ "EURGBP", 3 },
|
||||
{ "EURUSD", 29 }
|
||||
{ "EURUSD", 28 }
|
||||
};
|
||||
|
||||
foreach (var kvp in _dataPointsPerSymbol)
|
||||
|
||||
@@ -30,6 +30,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
private readonly Dictionary<Symbol, int> _dataPointsPerSymbol = new Dictionary<Symbol, int>();
|
||||
private bool _added;
|
||||
private Symbol _eurusd;
|
||||
private DateTime lastDataTime = DateTime.MinValue;
|
||||
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
@@ -51,6 +52,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (lastDataTime == data.Time)
|
||||
{
|
||||
throw new Exception("Duplicate time for current data and last data slice");
|
||||
}
|
||||
|
||||
lastDataTime = data.Time;
|
||||
|
||||
if (_added)
|
||||
{
|
||||
var eurUsdSubscription = SubscriptionManager.SubscriptionDataConfigService
|
||||
@@ -96,7 +104,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
// normal feed
|
||||
{ "EURGBP", 3 },
|
||||
// internal feed on the first day, normal feed on the other two days
|
||||
{ "EURUSD", 3 },
|
||||
{ "EURUSD", 2 },
|
||||
// internal feed only
|
||||
{ "GBPUSD", 0 }
|
||||
};
|
||||
|
||||
@@ -101,7 +101,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "6"},
|
||||
{"Average Win", "6.02%"},
|
||||
{"Average Loss", "-2.40%"},
|
||||
{"Compounding Annual Return", "915.481%"},
|
||||
{"Compounding Annual Return", "915.480%"},
|
||||
{"Drawdown", "5.500%"},
|
||||
{"Expectancy", "1.338"},
|
||||
{"Net Profit", "11.400%"},
|
||||
@@ -117,7 +117,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Information Ratio", "9.507"},
|
||||
{"Tracking Error", "0.507"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$2651.00"},
|
||||
{"Total Fees", "$2651.01"},
|
||||
{"Fitness Score", "0.467"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -137,7 +137,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1241317053"}
|
||||
{"OrderListHash", "-89452746"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests In The Money (ITM) future option calls across different strike prices.
|
||||
/// We expect 6 orders from the algorithm, which are:
|
||||
///
|
||||
/// * (1) Initial entry, buy ES Call Option (ES19M20 expiring ITM)
|
||||
/// * (2) Initial entry, sell ES Call Option at different strike (ES20H20 expiring ITM)
|
||||
/// * [2] Option assignment, opens a position in the underlying (ES20H20, Qty: -1)
|
||||
/// * [2] Future contract liquidation, due to impending expiry
|
||||
/// * [1] Option exercise, receive 1 ES19M20 future contract
|
||||
/// * [1] Liquidate ES19M20 contract, due to expiry
|
||||
///
|
||||
/// Additionally, we test delistings for future options and assert that our
|
||||
/// portfolio holdings reflect the orders the algorithm has submitted.
|
||||
/// </summary>
|
||||
public class FutureOptionBuySellCallIntradayRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 6, 30);
|
||||
|
||||
// We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
// which causes delisting events to never be processed, thus leading to options that might never
|
||||
// be exercised until the next data point arrives.
|
||||
AddEquity("AAPL", Resolution.Daily);
|
||||
|
||||
var es20h20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
new DateTime(2020, 3, 20)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
var es20m20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
new DateTime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
// Select a future option expiring ITM, and adds it to the algorithm.
|
||||
var esOptions = OptionChainProvider.GetOptionContractList(es20m20, Time)
|
||||
.Concat(OptionChainProvider.GetOptionContractList(es20h20, Time))
|
||||
.Where(x => x.ID.StrikePrice == 3200m && x.ID.OptionRight == OptionRight.Call)
|
||||
.Select(x => AddFutureOptionContract(x, Resolution.Minute).Symbol)
|
||||
.ToList();
|
||||
|
||||
var expectedContracts = new[]
|
||||
{
|
||||
QuantConnect.Symbol.CreateOption(es20h20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m,
|
||||
new DateTime(2020, 3, 20)),
|
||||
QuantConnect.Symbol.CreateOption(es20m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m,
|
||||
new DateTime(2020, 6, 19))
|
||||
};
|
||||
|
||||
foreach (var esOption in esOptions)
|
||||
{
|
||||
if (!expectedContracts.Contains(esOption))
|
||||
{
|
||||
throw new Exception($"Contract {esOption} was not found in the chain");
|
||||
}
|
||||
}
|
||||
|
||||
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(es20m20, 1), () =>
|
||||
{
|
||||
MarketOrder(esOptions[0], 1);
|
||||
MarketOrder(esOptions[1], -1);
|
||||
});
|
||||
Schedule.On(DateRules.Tomorrow, TimeRules.Noon, () =>
|
||||
{
|
||||
Liquidate();
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
|
||||
/// </summary>
|
||||
/// <exception cref="Exception">The algorithm has holdings</exception>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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 Trades", "6"},
|
||||
{"Average Win", "2.94%"},
|
||||
{"Average Loss", "-4.15%"},
|
||||
{"Compounding Annual Return", "-5.601%"},
|
||||
{"Drawdown", "5.600%"},
|
||||
{"Expectancy", "-0.146"},
|
||||
{"Net Profit", "-2.771%"},
|
||||
{"Sharpe Ratio", "-0.49"},
|
||||
{"Probabilistic Sharpe Ratio", "10.583%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.71"},
|
||||
{"Alpha", "-0.043"},
|
||||
{"Beta", "-0.001"},
|
||||
{"Annual Standard Deviation", "0.087"},
|
||||
{"Annual Variance", "0.008"},
|
||||
{"Information Ratio", "0.96"},
|
||||
{"Tracking Error", "0.192"},
|
||||
{"Treynor Ratio", "58.394"},
|
||||
{"Total Fees", "$14.80"},
|
||||
{"Fitness Score", "0.018"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.096"},
|
||||
{"Return Over Maximum Drawdown", "-0.993"},
|
||||
{"Portfolio Turnover", "0.043"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-290004562"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
259
Algorithm.CSharp/FutureOptionCallITMExpiryRegressionAlgorithm.cs
Normal file
259
Algorithm.CSharp/FutureOptionCallITMExpiryRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,259 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests In The Money (ITM) future option expiry for calls.
|
||||
/// We expect 3 orders from the algorithm, which are:
|
||||
///
|
||||
/// * Initial entry, buy ES Call Option (expiring ITM)
|
||||
/// * Option exercise, receiving ES future contracts
|
||||
/// * Future contract liquidation, due to impending expiry
|
||||
///
|
||||
/// Additionally, we test delistings for future options and assert that our
|
||||
/// portfolio holdings reflect the orders the algorithm has submitted.
|
||||
/// </summary>
|
||||
public class FutureOptionCallITMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _es19m20;
|
||||
private Symbol _esOption;
|
||||
private Symbol _expectedOptionContract;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 6, 30);
|
||||
|
||||
// We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
// which causes delisting events to never be processed, thus leading to options that might never
|
||||
// be exercised until the next data point arrives.
|
||||
AddEquity("AAPL", Resolution.Daily);
|
||||
|
||||
_es19m20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
new DateTime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
// Select a future option expiring ITM, and adds it to the algorithm.
|
||||
_esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
|
||||
.Where(x => x.ID.StrikePrice <= 3200m && x.ID.OptionRight == OptionRight.Call)
|
||||
.OrderByDescending(x => x.ID.StrikePrice)
|
||||
.Take(1)
|
||||
.Single(), Resolution.Minute).Symbol;
|
||||
|
||||
_expectedOptionContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m, new DateTime(2020, 6, 19));
|
||||
if (_esOption != _expectedOptionContract)
|
||||
{
|
||||
throw new Exception($"Contract {_expectedOptionContract} was not found in the chain");
|
||||
}
|
||||
|
||||
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
|
||||
{
|
||||
MarketOrder(_esOption, 1);
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
// the expected time. These assertions detect bug #4872
|
||||
foreach (var delisting in data.Delistings.Values)
|
||||
{
|
||||
if (delisting.Type == DelistingType.Warning)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 19))
|
||||
{
|
||||
throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
if (delisting.Type == DelistingType.Delisted)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 20))
|
||||
{
|
||||
throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status != OrderStatus.Filled)
|
||||
{
|
||||
// There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Securities.ContainsKey(orderEvent.Symbol))
|
||||
{
|
||||
throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
var security = Securities[orderEvent.Symbol];
|
||||
if (security.Symbol == _es19m20)
|
||||
{
|
||||
AssertFutureOptionOrderExercise(orderEvent, security, Securities[_expectedOptionContract]);
|
||||
}
|
||||
else if (security.Symbol == _expectedOptionContract)
|
||||
{
|
||||
AssertFutureOptionContractOrder(orderEvent, security);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
Log($"{Time:yyyy-MM-dd HH:mm:ss} -- {orderEvent.Symbol} :: Price: {Securities[orderEvent.Symbol].Holdings.Price} Qty: {Securities[orderEvent.Symbol].Holdings.Quantity} Direction: {orderEvent.Direction} Msg: {orderEvent.Message}");
|
||||
}
|
||||
|
||||
private void AssertFutureOptionOrderExercise(OrderEvent orderEvent, Security future, Security optionContract)
|
||||
{
|
||||
// We expect the liquidation to occur on the day of the delisting (while the market is open),
|
||||
// but currently we liquidate at the next market open (AAPL open) which happens to be
|
||||
// at 9:30:00 Eastern Time. For unknown reasons, the delisting happens two minutes after the
|
||||
// market open.
|
||||
// Read more about the issue affecting this test here: https://github.com/QuantConnect/Lean/issues/4980
|
||||
var expectedLiquidationTimeUtc = new DateTime(2020, 6, 22, 13, 32, 0);
|
||||
|
||||
if (orderEvent.Direction == OrderDirection.Sell && future.Holdings.Quantity != 0)
|
||||
{
|
||||
// We expect the contract to have been liquidated immediately
|
||||
throw new Exception($"Did not liquidate existing holdings for Symbol {future.Symbol}");
|
||||
}
|
||||
if (orderEvent.Direction == OrderDirection.Sell && orderEvent.UtcTime != expectedLiquidationTimeUtc)
|
||||
{
|
||||
throw new Exception($"Liquidated future contract, but not at the expected time. Expected: {expectedLiquidationTimeUtc:yyyy-MM-dd HH:mm:ss} - found {orderEvent.UtcTime:yyyy-MM-dd HH:mm:ss}");
|
||||
}
|
||||
|
||||
// No way to detect option exercise orders or any other kind of special orders
|
||||
// other than matching strings, for now.
|
||||
if (orderEvent.Message.Contains("Option Exercise"))
|
||||
{
|
||||
if (orderEvent.FillPrice != 3200m)
|
||||
{
|
||||
throw new Exception("Option did not exercise at expected strike price (3200)");
|
||||
}
|
||||
if (future.Holdings.Quantity != 1)
|
||||
{
|
||||
// Here, we expect to have some holdings in the underlying, but not in the future option anymore.
|
||||
throw new Exception($"Exercised option contract, but we have no holdings for Future {future.Symbol}");
|
||||
}
|
||||
|
||||
if (optionContract.Holdings.Quantity != 0)
|
||||
{
|
||||
throw new Exception($"Exercised option contract, but we have holdings for Option contract {optionContract.Symbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option)
|
||||
{
|
||||
if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 1)
|
||||
{
|
||||
throw new Exception($"No holdings were created for option contract {option.Symbol}");
|
||||
}
|
||||
if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != 0)
|
||||
{
|
||||
throw new Exception($"Holdings were found after a filled option exercise");
|
||||
}
|
||||
if (orderEvent.Message.Contains("Exercise") && option.Holdings.Quantity != 0)
|
||||
{
|
||||
throw new Exception($"Holdings were found after exercising option contract {option.Symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
|
||||
/// </summary>
|
||||
/// <exception cref="Exception">The algorithm has holdings</exception>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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 Trades", "3"},
|
||||
{"Average Win", "1.25%"},
|
||||
{"Average Loss", "-7.42%"},
|
||||
{"Compounding Annual Return", "-12.413%"},
|
||||
{"Drawdown", "6.300%"},
|
||||
{"Expectancy", "-0.416"},
|
||||
{"Net Profit", "-6.257%"},
|
||||
{"Sharpe Ratio", "-1.325"},
|
||||
{"Probabilistic Sharpe Ratio", "0.004%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.17"},
|
||||
{"Alpha", "-0.102"},
|
||||
{"Beta", "-0.003"},
|
||||
{"Annual Standard Deviation", "0.076"},
|
||||
{"Annual Variance", "0.006"},
|
||||
{"Information Ratio", "0.673"},
|
||||
{"Tracking Error", "0.188"},
|
||||
{"Treynor Ratio", "33.559"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Fitness Score", "0.008"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.205"},
|
||||
{"Return Over Maximum Drawdown", "-1.983"},
|
||||
{"Portfolio Turnover", "0.023"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "23301049"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Securities.Option;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests In The Money (ITM) future option expiry for calls.
|
||||
/// We test to make sure that FOPs have greeks enabled, same as equity options.
|
||||
/// </summary>
|
||||
public class FutureOptionCallITMGreeksExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private bool _invested;
|
||||
private int _onDataCalls;
|
||||
private Symbol _es19m20;
|
||||
private Option _esOption;
|
||||
private Symbol _expectedOptionContract;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 6, 30);
|
||||
|
||||
// We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
// which causes delisting events to never be processed, thus leading to options that might never
|
||||
// be exercised until the next data point arrives.
|
||||
AddEquity("AAPL", Resolution.Daily);
|
||||
|
||||
_es19m20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
new DateTime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
// Select a future option expiring ITM, and adds it to the algorithm.
|
||||
_esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, new DateTime(2020, 1, 5))
|
||||
.Where(x => x.ID.StrikePrice <= 3200m && x.ID.OptionRight == OptionRight.Call)
|
||||
.OrderByDescending(x => x.ID.StrikePrice)
|
||||
.Take(1)
|
||||
.Single(), Resolution.Minute);
|
||||
|
||||
_esOption.PriceModel = OptionPriceModels.BjerksundStensland();
|
||||
|
||||
_expectedOptionContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m, new DateTime(2020, 6, 19));
|
||||
if (_esOption.Symbol != _expectedOptionContract)
|
||||
{
|
||||
throw new Exception($"Contract {_expectedOptionContract} was not found in the chain");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// Let the algo warmup, but without using SetWarmup. Otherwise, we get
|
||||
// no contracts in the option chain
|
||||
if (_invested || _onDataCalls++ < 40)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.OptionChains.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (data.OptionChains.Values.All(o => o.Contracts.Values.Any(c => !data.ContainsKey(c.Symbol))))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (data.OptionChains.Values.First().Contracts.Count == 0)
|
||||
{
|
||||
throw new Exception($"No contracts found in the option {data.OptionChains.Keys.First()}");
|
||||
}
|
||||
|
||||
var deltas = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Delta).ToList();
|
||||
var gammas = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Gamma).ToList();
|
||||
var lambda = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Lambda).ToList();
|
||||
var rho = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Rho).ToList();
|
||||
var theta = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Theta).ToList();
|
||||
var vega = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Vega).ToList();
|
||||
|
||||
// The commented out test cases all return zero.
|
||||
// This is because of failure to evaluate the greeks in the option pricing model.
|
||||
// For now, let's skip those.
|
||||
if (deltas.Any(d => d == 0))
|
||||
{
|
||||
throw new AggregateException("Option contract Delta was equal to zero");
|
||||
}
|
||||
if (gammas.Any(g => g == 0))
|
||||
{
|
||||
throw new AggregateException("Option contract Gamma was equal to zero");
|
||||
}
|
||||
//if (lambda.Any(l => l == 0))
|
||||
//{
|
||||
// throw new AggregateException("Option contract Lambda was equal to zero");
|
||||
//}
|
||||
if (rho.Any(r => r == 0))
|
||||
{
|
||||
throw new AggregateException("Option contract Rho was equal to zero");
|
||||
}
|
||||
//if (theta.Any(t => t == 0))
|
||||
//{
|
||||
// throw new AggregateException("Option contract Theta was equal to zero");
|
||||
//}
|
||||
//if (vega.Any(v => v == 0))
|
||||
//{
|
||||
// throw new AggregateException("Option contract Vega was equal to zero");
|
||||
//}
|
||||
|
||||
if (!_invested)
|
||||
{
|
||||
SetHoldings(data.OptionChains.Values.First().Contracts.Values.First().Symbol, 1);
|
||||
_invested = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
|
||||
/// </summary>
|
||||
/// <exception cref="Exception">The algorithm has holdings</exception>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
|
||||
}
|
||||
if (!_invested)
|
||||
{
|
||||
throw new Exception($"Never checked greeks, maybe we have no option data?");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// 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 Trades", "3"},
|
||||
{"Average Win", "28.04%"},
|
||||
{"Average Loss", "-62.81%"},
|
||||
{"Compounding Annual Return", "-78.165%"},
|
||||
{"Drawdown", "52.400%"},
|
||||
{"Expectancy", "-0.277"},
|
||||
{"Net Profit", "-52.379%"},
|
||||
{"Sharpe Ratio", "-0.865"},
|
||||
{"Probabilistic Sharpe Ratio", "0.019%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.45"},
|
||||
{"Alpha", "-0.596"},
|
||||
{"Beta", "-0.031"},
|
||||
{"Annual Standard Deviation", "0.681"},
|
||||
{"Annual Variance", "0.463"},
|
||||
{"Information Ratio", "-0.514"},
|
||||
{"Tracking Error", "0.703"},
|
||||
{"Treynor Ratio", "18.748"},
|
||||
{"Total Fees", "$66.60"},
|
||||
{"Fitness Score", "0.157"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.133"},
|
||||
{"Return Over Maximum Drawdown", "-1.492"},
|
||||
{"Portfolio Turnover", "0.411"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "151392833"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
226
Algorithm.CSharp/FutureOptionCallOTMExpiryRegressionAlgorithm.cs
Normal file
226
Algorithm.CSharp/FutureOptionCallOTMExpiryRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,226 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests Out of The Money (OTM) future option expiry for calls.
|
||||
/// We expect 1 order from the algorithm, which are:
|
||||
///
|
||||
/// * Initial entry, buy ES Call Option (expiring OTM)
|
||||
/// - contract expires worthless, not exercised, so never opened a position in the underlying
|
||||
///
|
||||
/// Additionally, we test delistings for future options and assert that our
|
||||
/// portfolio holdings reflect the orders the algorithm has submitted.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Total Trades in regression algorithm should be 1, but expiration is counted as a trade.
|
||||
/// See related issue: https://github.com/QuantConnect/Lean/issues/4854
|
||||
/// </remarks>
|
||||
public class FutureOptionCallOTMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _es19m20;
|
||||
private Symbol _esOption;
|
||||
private Symbol _expectedContract;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 6, 30);
|
||||
|
||||
// We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
// which causes delisting events to never be processed, thus leading to options that might never
|
||||
// be exercised until the next data point arrives.
|
||||
AddEquity("AAPL", Resolution.Daily);
|
||||
|
||||
_es19m20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
new DateTime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
// Select a future option call expiring OTM, and adds it to the algorithm.
|
||||
_esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
|
||||
.Where(x => x.ID.StrikePrice >= 3300m && x.ID.OptionRight == OptionRight.Call)
|
||||
.OrderBy(x => x.ID.StrikePrice)
|
||||
.Take(1)
|
||||
.Single(), Resolution.Minute).Symbol;
|
||||
|
||||
_expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3300m, new DateTime(2020, 6, 19));
|
||||
if (_esOption != _expectedContract)
|
||||
{
|
||||
throw new Exception($"Contract {_expectedContract} was not found in the chain");
|
||||
}
|
||||
|
||||
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
|
||||
{
|
||||
MarketOrder(_esOption, 1);
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
// the expected time. These assertions detect bug #4872
|
||||
foreach (var delisting in data.Delistings.Values)
|
||||
{
|
||||
if (delisting.Type == DelistingType.Warning)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 19))
|
||||
{
|
||||
throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
if (delisting.Type == DelistingType.Delisted)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 20))
|
||||
{
|
||||
throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status != OrderStatus.Filled)
|
||||
{
|
||||
// There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Securities.ContainsKey(orderEvent.Symbol))
|
||||
{
|
||||
throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
var security = Securities[orderEvent.Symbol];
|
||||
if (security.Symbol == _es19m20)
|
||||
{
|
||||
throw new Exception("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM");
|
||||
}
|
||||
if (security.Symbol == _expectedContract)
|
||||
{
|
||||
AssertFutureOptionContractOrder(orderEvent, security);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
|
||||
private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option)
|
||||
{
|
||||
if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 1)
|
||||
{
|
||||
throw new Exception($"No holdings were created for option contract {option.Symbol}");
|
||||
}
|
||||
if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != 0)
|
||||
{
|
||||
throw new Exception("Holdings were found after a filled option exercise");
|
||||
}
|
||||
if (orderEvent.Direction == OrderDirection.Sell && !orderEvent.Message.Contains("OTM"))
|
||||
{
|
||||
throw new Exception("Contract did not expire OTM");
|
||||
}
|
||||
if (orderEvent.Message.Contains("Exercise"))
|
||||
{
|
||||
throw new Exception("Exercised option, even though it expires OTM");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
|
||||
/// </summary>
|
||||
/// <exception cref="Exception">The algorithm has holdings</exception>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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 Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-4.03%"},
|
||||
{"Compounding Annual Return", "-8.088%"},
|
||||
{"Drawdown", "4.000%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-4.029%"},
|
||||
{"Sharpe Ratio", "-1.274"},
|
||||
{"Probabilistic Sharpe Ratio", "0.015%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.066"},
|
||||
{"Beta", "-0.002"},
|
||||
{"Annual Standard Deviation", "0.052"},
|
||||
{"Annual Variance", "0.003"},
|
||||
{"Information Ratio", "0.9"},
|
||||
{"Tracking Error", "0.179"},
|
||||
{"Treynor Ratio", "28.537"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.183"},
|
||||
{"Return Over Maximum Drawdown", "-2.007"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1116221764"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
259
Algorithm.CSharp/FutureOptionPutITMExpiryRegressionAlgorithm.cs
Normal file
259
Algorithm.CSharp/FutureOptionPutITMExpiryRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,259 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests In The Money (ITM) future option expiry for puts.
|
||||
/// We expect 3 orders from the algorithm, which are:
|
||||
///
|
||||
/// * Initial entry, buy ES Put Option (expiring ITM) (buy, qty 1)
|
||||
/// * Option exercise, receiving short ES future contracts (sell, qty -1)
|
||||
/// * Future contract liquidation, due to impending expiry (buy qty 1)
|
||||
///
|
||||
/// Additionally, we test delistings for future options and assert that our
|
||||
/// portfolio holdings reflect the orders the algorithm has submitted.
|
||||
/// </summary>
|
||||
public class FutureOptionPutITMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _es19m20;
|
||||
private Symbol _esOption;
|
||||
private Symbol _expectedContract;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 6, 30);
|
||||
|
||||
// We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
// which causes delisting events to never be processed, thus leading to options that might never
|
||||
// be exercised until the next data point arrives.
|
||||
AddEquity("AAPL", Resolution.Daily);
|
||||
|
||||
_es19m20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
new DateTime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
// Select a future option expiring ITM, and adds it to the algorithm.
|
||||
_esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
|
||||
.Where(x => x.ID.StrikePrice >= 3300m && x.ID.OptionRight == OptionRight.Put)
|
||||
.OrderBy(x => x.ID.StrikePrice)
|
||||
.Take(1)
|
||||
.Single(), Resolution.Minute).Symbol;
|
||||
|
||||
_expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3300m, new DateTime(2020, 6, 19));
|
||||
if (_esOption != _expectedContract)
|
||||
{
|
||||
throw new Exception($"Contract {_expectedContract} was not found in the chain");
|
||||
}
|
||||
|
||||
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
|
||||
{
|
||||
MarketOrder(_esOption, 1);
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
// the expected time. These assertions detect bug #4872
|
||||
foreach (var delisting in data.Delistings.Values)
|
||||
{
|
||||
if (delisting.Type == DelistingType.Warning)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 19))
|
||||
{
|
||||
throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
if (delisting.Type == DelistingType.Delisted)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 20))
|
||||
{
|
||||
throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status != OrderStatus.Filled)
|
||||
{
|
||||
// There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Securities.ContainsKey(orderEvent.Symbol))
|
||||
{
|
||||
throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
var security = Securities[orderEvent.Symbol];
|
||||
if (security.Symbol == _es19m20)
|
||||
{
|
||||
AssertFutureOptionOrderExercise(orderEvent, security, Securities[_expectedContract]);
|
||||
}
|
||||
else if (security.Symbol == _expectedContract)
|
||||
{
|
||||
AssertFutureOptionContractOrder(orderEvent, security);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
Log($"{Time:yyyy-MM-dd HH:mm:ss} -- {orderEvent.Symbol} :: Price: {Securities[orderEvent.Symbol].Holdings.Price} Qty: {Securities[orderEvent.Symbol].Holdings.Quantity} Direction: {orderEvent.Direction} Msg: {orderEvent.Message}");
|
||||
}
|
||||
|
||||
private void AssertFutureOptionOrderExercise(OrderEvent orderEvent, Security future, Security optionContract)
|
||||
{
|
||||
// We expect the liquidation to occur on the day of the delisting (while the market is open),
|
||||
// but currently we liquidate at the next market open (AAPL open) which happens to be
|
||||
// at 9:30:00 Eastern Time. For unknown reasons, the delisting happens two minutes after the
|
||||
// market open.
|
||||
// Read more about the issue affecting this test here: https://github.com/QuantConnect/Lean/issues/4980
|
||||
var expectedLiquidationTimeUtc = new DateTime(2020, 6, 22, 13, 32, 0);
|
||||
|
||||
if (orderEvent.Direction == OrderDirection.Buy && future.Holdings.Quantity != 0)
|
||||
{
|
||||
// We expect the contract to have been liquidated immediately
|
||||
throw new Exception($"Did not liquidate existing holdings for Symbol {future.Symbol}");
|
||||
}
|
||||
if (orderEvent.Direction == OrderDirection.Buy && orderEvent.UtcTime != expectedLiquidationTimeUtc)
|
||||
{
|
||||
throw new Exception($"Liquidated future contract, but not at the expected time. Expected: {expectedLiquidationTimeUtc:yyyy-MM-dd HH:mm:ss} - found {orderEvent.UtcTime:yyyy-MM-dd HH:mm:ss}");
|
||||
}
|
||||
|
||||
// No way to detect option exercise orders or any other kind of special orders
|
||||
// other than matching strings, for now.
|
||||
if (orderEvent.Message.Contains("Option Exercise"))
|
||||
{
|
||||
if (orderEvent.FillPrice != 3300m)
|
||||
{
|
||||
throw new Exception("Option did not exercise at expected strike price (3300)");
|
||||
}
|
||||
if (future.Holdings.Quantity != -1)
|
||||
{
|
||||
// Here, we expect to have some holdings in the underlying, but not in the future option anymore.
|
||||
throw new Exception($"Exercised option contract, but we have no holdings for Future {future.Symbol}");
|
||||
}
|
||||
|
||||
if (optionContract.Holdings.Quantity != 0)
|
||||
{
|
||||
throw new Exception($"Exercised option contract, but we have holdings for Option contract {optionContract.Symbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option)
|
||||
{
|
||||
if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 1)
|
||||
{
|
||||
throw new Exception($"No holdings were created for option contract {option.Symbol}");
|
||||
}
|
||||
if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != 0)
|
||||
{
|
||||
throw new Exception($"Holdings were found after a filled option exercise");
|
||||
}
|
||||
if (orderEvent.Message.Contains("Exercise") && option.Holdings.Quantity != 0)
|
||||
{
|
||||
throw new Exception($"Holdings were found after exercising option contract {option.Symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
|
||||
/// </summary>
|
||||
/// <exception cref="Exception">The algorithm has holdings</exception>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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 Trades", "3"},
|
||||
{"Average Win", "4.18%"},
|
||||
{"Average Loss", "-8.27%"},
|
||||
{"Compounding Annual Return", "-8.879%"},
|
||||
{"Drawdown", "4.400%"},
|
||||
{"Expectancy", "-0.247"},
|
||||
{"Net Profit", "-4.432%"},
|
||||
{"Sharpe Ratio", "-1.391"},
|
||||
{"Probabilistic Sharpe Ratio", "0.002%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.51"},
|
||||
{"Alpha", "-0.073"},
|
||||
{"Beta", "-0.002"},
|
||||
{"Annual Standard Deviation", "0.052"},
|
||||
{"Annual Variance", "0.003"},
|
||||
{"Information Ratio", "0.863"},
|
||||
{"Tracking Error", "0.179"},
|
||||
{"Treynor Ratio", "38.46"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Fitness Score", "0.008"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.224"},
|
||||
{"Return Over Maximum Drawdown", "-2.003"},
|
||||
{"Portfolio Turnover", "0.023"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-675079082"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
225
Algorithm.CSharp/FutureOptionPutOTMExpiryRegressionAlgorithm.cs
Normal file
225
Algorithm.CSharp/FutureOptionPutOTMExpiryRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,225 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests Out of The Money (OTM) future option expiry for puts.
|
||||
/// We expect 1 order from the algorithm, which are:
|
||||
///
|
||||
/// * Initial entry, buy ES Put Option (expiring OTM)
|
||||
/// - contract expires worthless, not exercised, so never opened a position in the underlying
|
||||
///
|
||||
/// Additionally, we test delistings for future options and assert that our
|
||||
/// portfolio holdings reflect the orders the algorithm has submitted.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Total Trades in regression algorithm should be 1, but expiration is counted as a trade.
|
||||
/// </remarks>
|
||||
public class FutureOptionPutOTMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _es19m20;
|
||||
private Symbol _esOption;
|
||||
private Symbol _expectedContract;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 6, 30);
|
||||
|
||||
// We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
// which causes delisting events to never be processed, thus leading to options that might never
|
||||
// be exercised until the next data point arrives.
|
||||
AddEquity("AAPL", Resolution.Daily);
|
||||
|
||||
_es19m20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
new DateTime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
// Select a future option expiring ITM, and adds it to the algorithm.
|
||||
_esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
|
||||
.Where(x => x.ID.StrikePrice <= 3150m && x.ID.OptionRight == OptionRight.Put)
|
||||
.OrderByDescending(x => x.ID.StrikePrice)
|
||||
.Take(1)
|
||||
.Single(), Resolution.Minute).Symbol;
|
||||
|
||||
_expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3150m, new DateTime(2020, 6, 19));
|
||||
if (_esOption != _expectedContract)
|
||||
{
|
||||
throw new Exception($"Contract {_expectedContract} was not found in the chain");
|
||||
}
|
||||
|
||||
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
|
||||
{
|
||||
MarketOrder(_esOption, 1);
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
// the expected time. These assertions detect bug #4872
|
||||
foreach (var delisting in data.Delistings.Values)
|
||||
{
|
||||
if (delisting.Type == DelistingType.Warning)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 19))
|
||||
{
|
||||
throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
if (delisting.Type == DelistingType.Delisted)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 20))
|
||||
{
|
||||
throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status != OrderStatus.Filled)
|
||||
{
|
||||
// There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Securities.ContainsKey(orderEvent.Symbol))
|
||||
{
|
||||
throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
var security = Securities[orderEvent.Symbol];
|
||||
if (security.Symbol == _es19m20)
|
||||
{
|
||||
throw new Exception("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM");
|
||||
}
|
||||
if (security.Symbol == _expectedContract)
|
||||
{
|
||||
AssertFutureOptionContractOrder(orderEvent, security);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
|
||||
private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option)
|
||||
{
|
||||
if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 1)
|
||||
{
|
||||
throw new Exception($"No holdings were created for option contract {option.Symbol}");
|
||||
}
|
||||
if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != 0)
|
||||
{
|
||||
throw new Exception("Holdings were found after a filled option exercise");
|
||||
}
|
||||
if (orderEvent.Direction == OrderDirection.Sell && !orderEvent.Message.Contains("OTM"))
|
||||
{
|
||||
throw new Exception("Contract did not expire OTM");
|
||||
}
|
||||
if (orderEvent.Message.Contains("Exercise"))
|
||||
{
|
||||
throw new Exception("Exercised option, even though it expires OTM");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
|
||||
/// </summary>
|
||||
/// <exception cref="Exception">The algorithm has holdings</exception>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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 Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-5.12%"},
|
||||
{"Compounding Annual Return", "-10.212%"},
|
||||
{"Drawdown", "5.100%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-5.116%"},
|
||||
{"Sharpe Ratio", "-1.26"},
|
||||
{"Probabilistic Sharpe Ratio", "0.016%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.084"},
|
||||
{"Beta", "-0.003"},
|
||||
{"Annual Standard Deviation", "0.066"},
|
||||
{"Annual Variance", "0.004"},
|
||||
{"Information Ratio", "0.785"},
|
||||
{"Tracking Error", "0.184"},
|
||||
{"Treynor Ratio", "28.158"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.181"},
|
||||
{"Return Over Maximum Drawdown", "-1.995"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "515984318"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests In The Money (ITM) future option expiry for short calls.
|
||||
/// We expect 3 orders from the algorithm, which are:
|
||||
///
|
||||
/// * Initial entry, sell ES Call Option (expiring ITM)
|
||||
/// * Option assignment, sell 1 contract of the underlying (ES)
|
||||
/// * Future contract expiry, liquidation (buy 1 ES future)
|
||||
///
|
||||
/// Additionally, we test delistings for future options and assert that our
|
||||
/// portfolio holdings reflect the orders the algorithm has submitted.
|
||||
/// </summary>
|
||||
public class FutureOptionShortCallITMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _es19m20;
|
||||
private Symbol _esOption;
|
||||
private Symbol _expectedContract;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 6, 30);
|
||||
|
||||
// We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
// which causes delisting events to never be processed, thus leading to options that might never
|
||||
// be exercised until the next data point arrives.
|
||||
AddEquity("AAPL", Resolution.Daily);
|
||||
|
||||
_es19m20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
new DateTime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
// Select a future option expiring ITM, and adds it to the algorithm.
|
||||
_esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
|
||||
.Where(x => x.ID.StrikePrice <= 3100m && x.ID.OptionRight == OptionRight.Call)
|
||||
.OrderByDescending(x => x.ID.StrikePrice)
|
||||
.Take(1)
|
||||
.Single(), Resolution.Minute).Symbol;
|
||||
|
||||
_expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3100m, new DateTime(2020, 6, 19));
|
||||
if (_esOption != _expectedContract)
|
||||
{
|
||||
throw new Exception($"Contract {_expectedContract} was not found in the chain");
|
||||
}
|
||||
|
||||
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
|
||||
{
|
||||
MarketOrder(_esOption, -1);
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
// the expected time. These assertions detect bug #4872
|
||||
foreach (var delisting in data.Delistings.Values)
|
||||
{
|
||||
if (delisting.Type == DelistingType.Warning)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 19))
|
||||
{
|
||||
throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
if (delisting.Type == DelistingType.Delisted)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 20))
|
||||
{
|
||||
throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status != OrderStatus.Filled)
|
||||
{
|
||||
// There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Securities.ContainsKey(orderEvent.Symbol))
|
||||
{
|
||||
throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
var security = Securities[orderEvent.Symbol];
|
||||
if (security.Symbol == _es19m20)
|
||||
{
|
||||
AssertFutureOptionOrderExercise(orderEvent, security, Securities[_expectedContract]);
|
||||
}
|
||||
else if (security.Symbol == _expectedContract)
|
||||
{
|
||||
AssertFutureOptionContractOrder(orderEvent, security);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
|
||||
private void AssertFutureOptionOrderExercise(OrderEvent orderEvent, Security future, Security optionContract)
|
||||
{
|
||||
if (orderEvent.Message.Contains("Assignment"))
|
||||
{
|
||||
if (orderEvent.FillPrice != 3100m)
|
||||
{
|
||||
throw new Exception("Option was not assigned at expected strike price (3100)");
|
||||
}
|
||||
if (orderEvent.Direction != OrderDirection.Sell || future.Holdings.Quantity != -1)
|
||||
{
|
||||
throw new Exception($"Expected Qty: -1 futures holdings for assigned future {future.Symbol}, found {future.Holdings.Quantity}");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (orderEvent.Direction == OrderDirection.Buy && future.Holdings.Quantity != 0)
|
||||
{
|
||||
// We buy back the underlying at expiration, so we expect a neutral position then
|
||||
throw new Exception($"Expected no holdings when liquidating future contract {future.Symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option)
|
||||
{
|
||||
if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != -1)
|
||||
{
|
||||
throw new Exception($"No holdings were created for option contract {option.Symbol}");
|
||||
}
|
||||
if (orderEvent.IsAssignment && option.Holdings.Quantity != 0)
|
||||
{
|
||||
throw new Exception($"Holdings were found after option contract was assigned: {option.Symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
|
||||
/// </summary>
|
||||
/// <exception cref="Exception">The algorithm has holdings</exception>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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 Trades", "3"},
|
||||
{"Average Win", "10.05%"},
|
||||
{"Average Loss", "-5.60%"},
|
||||
{"Compounding Annual Return", "8.121%"},
|
||||
{"Drawdown", "0.500%"},
|
||||
{"Expectancy", "0.396"},
|
||||
{"Net Profit", "3.880%"},
|
||||
{"Sharpe Ratio", "1.192"},
|
||||
{"Probabilistic Sharpe Ratio", "58.203%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "1.79"},
|
||||
{"Alpha", "0.069"},
|
||||
{"Beta", "0.003"},
|
||||
{"Annual Standard Deviation", "0.057"},
|
||||
{"Annual Variance", "0.003"},
|
||||
{"Information Ratio", "1.641"},
|
||||
{"Tracking Error", "0.18"},
|
||||
{"Treynor Ratio", "22.101"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Fitness Score", "0.021"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "17.255"},
|
||||
{"Portfolio Turnover", "0.021"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1118389718"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests Out of The Money (OTM) future option expiry for short calls.
|
||||
/// We expect 1 order from the algorithm, which are:
|
||||
///
|
||||
/// * Initial entry, sell ES Call Option (expiring OTM)
|
||||
/// - Profit the option premium, since the option was not assigned.
|
||||
///
|
||||
/// Additionally, we test delistings for future options and assert that our
|
||||
/// portfolio holdings reflect the orders the algorithm has submitted.
|
||||
/// </summary>
|
||||
public class FutureOptionShortCallOTMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _es19m20;
|
||||
private Symbol _esOption;
|
||||
private Symbol _expectedContract;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 6, 30);
|
||||
|
||||
// We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
// which causes delisting events to never be processed, thus leading to options that might never
|
||||
// be exercised until the next data point arrives.
|
||||
AddEquity("AAPL", Resolution.Daily);
|
||||
|
||||
_es19m20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
new DateTime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
// Select a future option expiring ITM, and adds it to the algorithm.
|
||||
_esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
|
||||
.Where(x => x.ID.StrikePrice >= 3400m && x.ID.OptionRight == OptionRight.Call)
|
||||
.OrderBy(x => x.ID.StrikePrice)
|
||||
.Take(1)
|
||||
.Single(), Resolution.Minute).Symbol;
|
||||
|
||||
_expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3400m, new DateTime(2020, 6, 19));
|
||||
if (_esOption != _expectedContract)
|
||||
{
|
||||
throw new Exception($"Contract {_expectedContract} was not found in the chain");
|
||||
}
|
||||
|
||||
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
|
||||
{
|
||||
MarketOrder(_esOption, -1);
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
// the expected time. These assertions detect bug #4872
|
||||
foreach (var delisting in data.Delistings.Values)
|
||||
{
|
||||
if (delisting.Type == DelistingType.Warning)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 19))
|
||||
{
|
||||
throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
if (delisting.Type == DelistingType.Delisted)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 20))
|
||||
{
|
||||
throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status != OrderStatus.Filled)
|
||||
{
|
||||
// There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Securities.ContainsKey(orderEvent.Symbol))
|
||||
{
|
||||
throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
var security = Securities[orderEvent.Symbol];
|
||||
if (security.Symbol == _es19m20)
|
||||
{
|
||||
throw new Exception($"Expected no order events for underlying Symbol {security.Symbol}");
|
||||
}
|
||||
|
||||
if (security.Symbol == _expectedContract)
|
||||
{
|
||||
AssertFutureOptionContractOrder(orderEvent, security);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
|
||||
private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security optionContract)
|
||||
{
|
||||
if (orderEvent.Direction == OrderDirection.Sell && optionContract.Holdings.Quantity != -1)
|
||||
{
|
||||
throw new Exception($"No holdings were created for option contract {optionContract.Symbol}");
|
||||
}
|
||||
if (orderEvent.Direction == OrderDirection.Buy && optionContract.Holdings.Quantity != 0)
|
||||
{
|
||||
throw new Exception("Expected no options holdings after closing position");
|
||||
}
|
||||
if (orderEvent.IsAssignment)
|
||||
{
|
||||
throw new Exception($"Assignment was not expected for {orderEvent.Symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
|
||||
/// </summary>
|
||||
/// <exception cref="Exception">The algorithm has holdings</exception>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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 Trades", "2"},
|
||||
{"Average Win", "1.81%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "3.745%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.809%"},
|
||||
{"Sharpe Ratio", "1.292"},
|
||||
{"Probabilistic Sharpe Ratio", "65.890%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.031"},
|
||||
{"Beta", "0.001"},
|
||||
{"Annual Standard Deviation", "0.024"},
|
||||
{"Annual Variance", "0.001"},
|
||||
{"Information Ratio", "1.496"},
|
||||
{"Tracking Error", "0.173"},
|
||||
{"Treynor Ratio", "27.281"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "95.176"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1364902860"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests In The Money (ITM) future option expiry for short puts.
|
||||
/// We expect 3 orders from the algorithm, which are:
|
||||
///
|
||||
/// * Initial entry, sell ES Put Option (expiring ITM)
|
||||
/// * Option assignment, buy 1 contract of the underlying (ES)
|
||||
/// * Future contract expiry, liquidation (sell 1 ES future)
|
||||
///
|
||||
/// Additionally, we test delistings for future options and assert that our
|
||||
/// portfolio holdings reflect the orders the algorithm has submitted.
|
||||
/// </summary>
|
||||
public class FutureOptionShortPutITMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _es19m20;
|
||||
private Symbol _esOption;
|
||||
private Symbol _expectedContract;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 6, 30);
|
||||
|
||||
// We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
// which causes delisting events to never be processed, thus leading to options that might never
|
||||
// be exercised until the next data point arrives.
|
||||
AddEquity("AAPL", Resolution.Daily);
|
||||
|
||||
_es19m20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
new DateTime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
// Select a future option expiring ITM, and adds it to the algorithm.
|
||||
_esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
|
||||
.Where(x => x.ID.StrikePrice <= 3400m && x.ID.OptionRight == OptionRight.Put)
|
||||
.OrderByDescending(x => x.ID.StrikePrice)
|
||||
.Take(1)
|
||||
.Single(), Resolution.Minute).Symbol;
|
||||
|
||||
_expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3400m, new DateTime(2020, 6, 19));
|
||||
if (_esOption != _expectedContract)
|
||||
{
|
||||
throw new Exception($"Contract {_expectedContract} was not found in the chain");
|
||||
}
|
||||
|
||||
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
|
||||
{
|
||||
MarketOrder(_esOption, -1);
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
// the expected time. These assertions detect bug #4872
|
||||
foreach (var delisting in data.Delistings.Values)
|
||||
{
|
||||
if (delisting.Type == DelistingType.Warning)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 19))
|
||||
{
|
||||
throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
if (delisting.Type == DelistingType.Delisted)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 20))
|
||||
{
|
||||
throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status != OrderStatus.Filled)
|
||||
{
|
||||
// There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Securities.ContainsKey(orderEvent.Symbol))
|
||||
{
|
||||
throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
var security = Securities[orderEvent.Symbol];
|
||||
if (security.Symbol == _es19m20)
|
||||
{
|
||||
AssertFutureOptionOrderExercise(orderEvent, security, Securities[_expectedContract]);
|
||||
}
|
||||
else if (security.Symbol == _expectedContract)
|
||||
{
|
||||
AssertFutureOptionContractOrder(orderEvent, security);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
|
||||
private void AssertFutureOptionOrderExercise(OrderEvent orderEvent, Security future, Security optionContract)
|
||||
{
|
||||
if (orderEvent.Message.Contains("Assignment"))
|
||||
{
|
||||
if (orderEvent.FillPrice != 3400)
|
||||
{
|
||||
throw new Exception("Option was not assigned at expected strike price (3400)");
|
||||
}
|
||||
if (orderEvent.Direction != OrderDirection.Buy || future.Holdings.Quantity != 1)
|
||||
{
|
||||
throw new Exception($"Expected Qty: 1 futures holdings for assigned future {future.Symbol}, found {future.Holdings.Quantity}");
|
||||
}
|
||||
}
|
||||
if (!orderEvent.Message.Contains("Assignment") && orderEvent.Direction == OrderDirection.Sell && future.Holdings.Quantity != 0)
|
||||
{
|
||||
// We buy back the underlying at expiration, so we expect a neutral position then
|
||||
throw new Exception($"Expected no holdings when liquidating future contract {future.Symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option)
|
||||
{
|
||||
if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != -1)
|
||||
{
|
||||
throw new Exception($"No holdings were created for option contract {option.Symbol}");
|
||||
}
|
||||
if (orderEvent.IsAssignment && option.Holdings.Quantity != 0)
|
||||
{
|
||||
throw new Exception($"Holdings were found after option contract was assigned: {option.Symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
|
||||
/// </summary>
|
||||
/// <exception cref="Exception">The algorithm has holdings</exception>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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 Trades", "3"},
|
||||
{"Average Win", "10.18%"},
|
||||
{"Average Loss", "-8.02%"},
|
||||
{"Compounding Annual Return", "2.773%"},
|
||||
{"Drawdown", "0.500%"},
|
||||
{"Expectancy", "0.135"},
|
||||
{"Net Profit", "1.343%"},
|
||||
{"Sharpe Ratio", "0.939"},
|
||||
{"Probabilistic Sharpe Ratio", "46.842%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "1.27"},
|
||||
{"Alpha", "0.023"},
|
||||
{"Beta", "0.002"},
|
||||
{"Annual Standard Deviation", "0.025"},
|
||||
{"Annual Variance", "0.001"},
|
||||
{"Information Ratio", "1.45"},
|
||||
{"Tracking Error", "0.173"},
|
||||
{"Treynor Ratio", "14.62"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Fitness Score", "0.021"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "5.815"},
|
||||
{"Portfolio Turnover", "0.022"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "980293281"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests Out of The Money (OTM) future option expiry for short puts.
|
||||
/// We expect 1 order from the algorithm, which are:
|
||||
///
|
||||
/// * Initial entry, sell ES Put Option (expiring OTM)
|
||||
/// - Profit the option premium, since the option was not assigned.
|
||||
///
|
||||
/// Additionally, we test delistings for future options and assert that our
|
||||
/// portfolio holdings reflect the orders the algorithm has submitted.
|
||||
/// </summary>
|
||||
public class FutureOptionShortPutOTMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _es19m20;
|
||||
private Symbol _esOption;
|
||||
private Symbol _expectedContract;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 6, 30);
|
||||
|
||||
// We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
// which causes delisting events to never be processed, thus leading to options that might never
|
||||
// be exercised until the next data point arrives.
|
||||
AddEquity("AAPL", Resolution.Daily);
|
||||
|
||||
_es19m20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
new DateTime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
// Select a future option expiring ITM, and adds it to the algorithm.
|
||||
_esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
|
||||
.Where(x => x.ID.StrikePrice <= 3000m && x.ID.OptionRight == OptionRight.Put)
|
||||
.OrderByDescending(x => x.ID.StrikePrice)
|
||||
.Take(1)
|
||||
.Single(), Resolution.Minute).Symbol;
|
||||
|
||||
_expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3000m, new DateTime(2020, 6, 19));
|
||||
if (_esOption != _expectedContract)
|
||||
{
|
||||
throw new Exception($"Contract {_expectedContract} was not found in the chain");
|
||||
}
|
||||
|
||||
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
|
||||
{
|
||||
MarketOrder(_esOption, -1);
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
// the expected time. These assertions detect bug #4872
|
||||
foreach (var delisting in data.Delistings.Values)
|
||||
{
|
||||
if (delisting.Type == DelistingType.Warning)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 19))
|
||||
{
|
||||
throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
if (delisting.Type == DelistingType.Delisted)
|
||||
{
|
||||
if (delisting.Time != new DateTime(2020, 6, 20))
|
||||
{
|
||||
throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status != OrderStatus.Filled)
|
||||
{
|
||||
// There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Securities.ContainsKey(orderEvent.Symbol))
|
||||
{
|
||||
throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
var security = Securities[orderEvent.Symbol];
|
||||
if (security.Symbol == _es19m20)
|
||||
{
|
||||
throw new Exception($"Expected no order events for underlying Symbol {security.Symbol}");
|
||||
}
|
||||
if (security.Symbol == _expectedContract)
|
||||
{
|
||||
AssertFutureOptionContractOrder(orderEvent, security);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
|
||||
}
|
||||
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
|
||||
private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option)
|
||||
{
|
||||
if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != -1)
|
||||
{
|
||||
throw new Exception($"No holdings were created for option contract {option.Symbol}");
|
||||
}
|
||||
if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 0)
|
||||
{
|
||||
throw new Exception("Expected no options holdings after closing position");
|
||||
}
|
||||
if (orderEvent.IsAssignment)
|
||||
{
|
||||
throw new Exception($"Assignment was not expected for {orderEvent.Symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
|
||||
/// </summary>
|
||||
/// <exception cref="Exception">The algorithm has holdings</exception>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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 Trades", "2"},
|
||||
{"Average Win", "3.28%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "6.852%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "3.284%"},
|
||||
{"Sharpe Ratio", "1.319"},
|
||||
{"Probabilistic Sharpe Ratio", "66.574%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.058"},
|
||||
{"Beta", "0.002"},
|
||||
{"Annual Standard Deviation", "0.043"},
|
||||
{"Annual Variance", "0.002"},
|
||||
{"Information Ratio", "1.614"},
|
||||
{"Tracking Error", "0.176"},
|
||||
{"Treynor Ratio", "28.2"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "150.252"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-418839052"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
}
|
||||
|
||||
var firstBar = history.First().Bars.GetValue(symbol);
|
||||
if (firstBar.EndTime != new DateTime(1998, 3, 3) || firstBar.Close != 26.3607004m)
|
||||
if (firstBar.EndTime != new DateTime(1998, 3, 3) || firstBar.Close != 25.11427695m)
|
||||
{
|
||||
throw new Exception("First History bar - unexpected data received");
|
||||
}
|
||||
|
||||
@@ -65,32 +65,32 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Total Trades", "5"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.98%"},
|
||||
{"Compounding Annual Return", "-53.792%"},
|
||||
{"Drawdown", "1.500%"},
|
||||
{"Average Loss", "-0.52%"},
|
||||
{"Compounding Annual Return", "246.602%"},
|
||||
{"Drawdown", "2.300%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.982%"},
|
||||
{"Sharpe Ratio", "-5.949"},
|
||||
{"Probabilistic Sharpe Ratio", "1.216%"},
|
||||
{"Net Profit", "1.602%"},
|
||||
{"Sharpe Ratio", "8.065"},
|
||||
{"Probabilistic Sharpe Ratio", "65.943%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.973"},
|
||||
{"Beta", "0.268"},
|
||||
{"Annual Standard Deviation", "0.077"},
|
||||
{"Annual Variance", "0.006"},
|
||||
{"Information Ratio", "-14.167"},
|
||||
{"Tracking Error", "0.168"},
|
||||
{"Treynor Ratio", "-1.705"},
|
||||
{"Total Fees", "$6.51"},
|
||||
{"Fitness Score", "0.249"},
|
||||
{"Alpha", "-0.157"},
|
||||
{"Beta", "1.015"},
|
||||
{"Annual Standard Deviation", "0.223"},
|
||||
{"Annual Variance", "0.05"},
|
||||
{"Information Ratio", "-27.079"},
|
||||
{"Tracking Error", "0.005"},
|
||||
{"Treynor Ratio", "1.772"},
|
||||
{"Total Fees", "$16.28"},
|
||||
{"Fitness Score", "0.999"},
|
||||
{"Kelly Criterion Estimate", "38.64"},
|
||||
{"Kelly Criterion Probability Value", "0.229"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-55.465"},
|
||||
{"Portfolio Turnover", "0.498"},
|
||||
{"Return Over Maximum Drawdown", "78.607"},
|
||||
{"Portfolio Turnover", "1.246"},
|
||||
{"Total Insights Generated", "100"},
|
||||
{"Total Insights Closed", "99"},
|
||||
{"Total Insights Analysis Completed", "99"},
|
||||
@@ -104,7 +104,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "54.5455%"},
|
||||
{"Rolling Averaged Population Direction", "59.8056%"},
|
||||
{"Rolling Averaged Population Magnitude", "59.8056%"},
|
||||
{"OrderListHash", "160051570"}
|
||||
{"OrderListHash", "-1552239367"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
82
Algorithm.CSharp/OnOrderEventExceptionRegression.cs
Normal file
82
Algorithm.CSharp/OnOrderEventExceptionRegression.cs
Normal file
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* 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.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression Algorithm for testing engine behavior with throwing errors in OnOrderEvent
|
||||
/// Should result in a RunTimeError status.
|
||||
/// Reference GH Issue #4947
|
||||
/// </summary>
|
||||
public class OnOrderEventExceptionRegression : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
|
||||
|
||||
/// <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(2013, 10, 07);
|
||||
SetEndDate(2013, 10, 11);
|
||||
AddEquity("SPY", Resolution.Minute);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
/// </summary>
|
||||
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
SetHoldings(_spy, 1);
|
||||
Debug("Purchased Stock");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OnOrderEvent is called whenever an order is updated
|
||||
/// </summary>
|
||||
/// <param name="orderEvent">Order Event</param>
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
throw new Exception("OnOrderEvent exception");
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// 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>
|
||||
{
|
||||
};
|
||||
}
|
||||
}
|
||||
122
Algorithm.CSharp/OptionAssignmentRegressionAlgorithm.cs
Normal file
122
Algorithm.CSharp/OptionAssignmentRegressionAlgorithm.cs
Normal 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.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm verifies automatic option contract assignment behavior.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="regression test" />
|
||||
/// <meta name="tag" content="options" />
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="filter selection" />
|
||||
public class OptionAssignmentRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Security Stock;
|
||||
|
||||
private Security CallOption;
|
||||
private Symbol CallOptionSymbol;
|
||||
|
||||
private Security PutOption;
|
||||
private Symbol PutOptionSymbol;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2015, 12, 23);
|
||||
SetEndDate(2015, 12, 24);
|
||||
SetCash(100000);
|
||||
Stock = AddEquity("GOOG", Resolution.Minute);
|
||||
|
||||
var contracts = OptionChainProvider.GetOptionContractList(Stock.Symbol, UtcTime).ToList();
|
||||
|
||||
PutOptionSymbol = contracts
|
||||
.Where(c => c.ID.OptionRight == OptionRight.Put)
|
||||
.OrderBy(c => c.ID.Date)
|
||||
.First(c => c.ID.StrikePrice == 800m);
|
||||
|
||||
CallOptionSymbol = contracts
|
||||
.Where(c => c.ID.OptionRight == OptionRight.Call)
|
||||
.OrderBy(c => c.ID.Date)
|
||||
.First(c => c.ID.StrikePrice == 600m);
|
||||
|
||||
PutOption = AddOptionContract(PutOptionSymbol);
|
||||
CallOption = AddOptionContract(CallOptionSymbol);
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!Portfolio.Invested && Stock.Price != 0 && PutOption.Price != 0 && CallOption.Price != 0)
|
||||
{
|
||||
// this gets executed on start and after each auto-assignment, finally ending with expiration assignment
|
||||
MarketOrder(PutOptionSymbol, -1);
|
||||
MarketOrder(CallOptionSymbol, -1);
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanRunLocally { get; } = true;
|
||||
public Language[] Languages { get; } = {Language.CSharp};
|
||||
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "22"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe 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", "$12.00"},
|
||||
{"Fitness Score", "0.5"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-50.218"},
|
||||
{"Portfolio Turnover", "6.713"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1597098916"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <param name="slice">The current slice of data keyed by symbol string</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
foreach (var dividend in slice.Dividends.Values)
|
||||
{
|
||||
if (dividend.ReferencePrice != 32.59m || dividend.Distribution != 3.82m)
|
||||
{
|
||||
throw new Exception($"{Time} - Invalid dividend {dividend}");
|
||||
}
|
||||
}
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
if (Time.Day == 28 && Time.Hour > 9 && Time.Minute > 0)
|
||||
@@ -139,11 +146,11 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "4"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.02%"},
|
||||
{"Compounding Annual Return", "-0.453%"},
|
||||
{"Compounding Annual Return", "-0.492%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.006%"},
|
||||
{"Sharpe Ratio", "-3.554"},
|
||||
{"Sharpe Ratio", "-3.943"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
@@ -152,15 +159,15 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0.002"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-3.554"},
|
||||
{"Information Ratio", "-3.943"},
|
||||
{"Tracking Error", "0.002"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$4.00"},
|
||||
{"Fitness Score", "0.001"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-1.768"},
|
||||
{"Return Over Maximum Drawdown", "-2.808"},
|
||||
{"Portfolio Turnover", "0.001"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
|
||||
@@ -142,7 +142,22 @@
|
||||
<Link>Properties\SharedAssemblyInfo.cs</Link>
|
||||
</Compile>
|
||||
<Compile Include="AddAlphaModelAlgorithm.cs" />
|
||||
<Compile Include="CustomBuyingPowerModelAlgorithm.cs" />
|
||||
<Compile Include="AddFutureOptionContractDataStreamingRegressionAlgorithm.cs" />
|
||||
<Compile Include="AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm.cs" />
|
||||
<Compile Include="AddOptionContractExpiresRegressionAlgorithm.cs" />
|
||||
<Compile Include="AltData\QuiverWallStreetBetsDataAlgorithm.cs" />
|
||||
<Compile Include="FutureOptionCallITMGreeksExpiryRegressionAlgorithm.cs" />
|
||||
<Compile Include="OnOrderEventExceptionRegression.cs" />
|
||||
<Compile Include="FutureOptionCallITMExpiryRegressionAlgorithm.cs" />
|
||||
<Compile Include="FutureOptionCallOTMExpiryRegressionAlgorithm.cs" />
|
||||
<Compile Include="FutureOptionPutITMExpiryRegressionAlgorithm.cs" />
|
||||
<Compile Include="FutureOptionPutOTMExpiryRegressionAlgorithm.cs" />
|
||||
<Compile Include="FutureOptionBuySellCallIntradayRegressionAlgorithm.cs" />
|
||||
<Compile Include="FutureOptionShortCallITMExpiryRegressionAlgorithm.cs" />
|
||||
<Compile Include="FutureOptionShortCallOTMExpiryRegressionAlgorithm.cs" />
|
||||
<Compile Include="FutureOptionShortPutOTMExpiryRegressionAlgorithm.cs" />
|
||||
<Compile Include="FutureOptionShortPutITMExpiryRegressionAlgorithm.cs" />
|
||||
<Compile Include="ScaledFillForwardDataRegressionAlgorithm.cs" />
|
||||
<Compile Include="DailyHistoryForDailyResolutionRegressionAlgorithm.cs" />
|
||||
<Compile Include="DailyHistoryForMinuteResolutionRegressionAlgorithm.cs" />
|
||||
@@ -151,6 +166,7 @@
|
||||
<Compile Include="AddOptionContractFromUniverseRegressionAlgorithm.cs" />
|
||||
<Compile Include="CoarseFineOptionUniverseChainRegressionAlgorithm.cs" />
|
||||
<Compile Include="OptionChainedAndUniverseSelectionRegressionAlgorithm.cs" />
|
||||
<Compile Include="OptionAssignmentRegressionAlgorithm.cs" />
|
||||
<Compile Include="SwitchDataModeRegressionAlgorithm.cs" />
|
||||
<Compile Include="AddRemoveOptionUniverseRegressionAlgorithm.cs" />
|
||||
<Compile Include="AddRemoveSecurityRegressionAlgorithm.cs" />
|
||||
@@ -365,6 +381,7 @@
|
||||
<Compile Include="USEnergyInformationAdministrationAlgorithm.cs" />
|
||||
<Compile Include="UserDefinedUniverseAlgorithm.cs" />
|
||||
<Compile Include="VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm.cs" />
|
||||
<Compile Include="WarmUpAfterIntializeRegression.cs" />
|
||||
<Compile Include="WarmupAlgorithm.cs" />
|
||||
<Compile Include="WarmupConversionRatesRegressionAlgorithm.cs" />
|
||||
<Compile Include="WarmupHistoryAlgorithm.cs" />
|
||||
|
||||
@@ -254,13 +254,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$48.56"},
|
||||
{"Total Fees", "$48.58"},
|
||||
{"Fitness Score", "0.5"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-141.917"},
|
||||
{"Portfolio Turnover", "2.001"},
|
||||
{"Return Over Maximum Drawdown", "-141.877"},
|
||||
{"Portfolio Turnover", "2.002"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -274,7 +274,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-22119963"}
|
||||
{"OrderListHash", "-263077697"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,28 +117,28 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "3528"},
|
||||
{"Average Win", "0.67%"},
|
||||
{"Average Loss", "-0.71%"},
|
||||
{"Compounding Annual Return", "17.318%"},
|
||||
{"Compounding Annual Return", "17.227%"},
|
||||
{"Drawdown", "63.700%"},
|
||||
{"Expectancy", "0.020"},
|
||||
{"Net Profit", "17.318%"},
|
||||
{"Sharpe Ratio", "0.836"},
|
||||
{"Probabilistic Sharpe Ratio", "33.715%"},
|
||||
{"Net Profit", "17.227%"},
|
||||
{"Sharpe Ratio", "0.834"},
|
||||
{"Probabilistic Sharpe Ratio", "33.688%"},
|
||||
{"Loss Rate", "48%"},
|
||||
{"Win Rate", "52%"},
|
||||
{"Profit-Loss Ratio", "0.95"},
|
||||
{"Alpha", "0.826"},
|
||||
{"Alpha", "0.825"},
|
||||
{"Beta", "-0.34"},
|
||||
{"Annual Standard Deviation", "0.945"},
|
||||
{"Annual Variance", "0.893"},
|
||||
{"Information Ratio", "0.714"},
|
||||
{"Information Ratio", "0.713"},
|
||||
{"Tracking Error", "0.957"},
|
||||
{"Treynor Ratio", "-2.325"},
|
||||
{"Total Fees", "$24713.42"},
|
||||
{"Treynor Ratio", "-2.323"},
|
||||
{"Total Fees", "$24760.85"},
|
||||
{"Fitness Score", "0.54"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "0.24"},
|
||||
{"Return Over Maximum Drawdown", "0.272"},
|
||||
{"Sortino Ratio", "0.238"},
|
||||
{"Return Over Maximum Drawdown", "0.27"},
|
||||
{"Portfolio Turnover", "7.204"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -153,7 +153,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1547947497"}
|
||||
{"OrderListHash", "843493486"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
private Symbol _spy;
|
||||
private int _reselectedSpy = -1;
|
||||
private DateTime lastDataTime = DateTime.MinValue;
|
||||
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
@@ -57,6 +58,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (lastDataTime == data.Time)
|
||||
{
|
||||
throw new Exception("Duplicate time for current data and last data slice");
|
||||
}
|
||||
|
||||
lastDataTime = data.Time;
|
||||
|
||||
if (_reselectedSpy == 0)
|
||||
{
|
||||
if (!Securities[_spy].IsTradable)
|
||||
@@ -111,29 +119,29 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "75.079%"},
|
||||
{"Drawdown", "2.200%"},
|
||||
{"Compounding Annual Return", "69.904%"},
|
||||
{"Drawdown", "2.000%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "4.711%"},
|
||||
{"Sharpe Ratio", "5.067"},
|
||||
{"Probabilistic Sharpe Ratio", "84.391%"},
|
||||
{"Net Profit", "4.453%"},
|
||||
{"Sharpe Ratio", "4.805"},
|
||||
{"Probabilistic Sharpe Ratio", "83.459%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.562"},
|
||||
{"Beta", "0.02"},
|
||||
{"Annual Standard Deviation", "0.113"},
|
||||
{"Annual Variance", "0.013"},
|
||||
{"Information Ratio", "0.511"},
|
||||
{"Tracking Error", "0.159"},
|
||||
{"Treynor Ratio", "28.945"},
|
||||
{"Total Fees", "$3.22"},
|
||||
{"Fitness Score", "0.037"},
|
||||
{"Alpha", "0.501"},
|
||||
{"Beta", "0.068"},
|
||||
{"Annual Standard Deviation", "0.111"},
|
||||
{"Annual Variance", "0.012"},
|
||||
{"Information Ratio", "0.284"},
|
||||
{"Tracking Error", "0.153"},
|
||||
{"Treynor Ratio", "7.844"},
|
||||
{"Total Fees", "$3.23"},
|
||||
{"Fitness Score", "0.038"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "17.868"},
|
||||
{"Return Over Maximum Drawdown", "34.832"},
|
||||
{"Portfolio Turnover", "0.037"},
|
||||
{"Sortino Ratio", "16.857"},
|
||||
{"Return Over Maximum Drawdown", "34.897"},
|
||||
{"Portfolio Turnover", "0.038"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -147,7 +155,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "836605283"}
|
||||
{"OrderListHash", "1664042885"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
61
Algorithm.CSharp/WarmUpAfterIntializeRegression.cs
Normal file
61
Algorithm.CSharp/WarmUpAfterIntializeRegression.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* 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.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression algorithm to test warming up after initialize behavior, should throw if used outside of initialize
|
||||
/// Reference GH Issue #4939
|
||||
/// </summary>
|
||||
public class WarmUpAfterIntializeRegression : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 10, 07); //Set Start Date
|
||||
SetEndDate(2013, 10, 11); //Set End Date
|
||||
SetCash(100000);
|
||||
var equity = AddEquity("SPY");
|
||||
}
|
||||
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
// Should throw and set Algorithm status to be runtime error
|
||||
SetWarmUp(TimeSpan.FromDays(2));
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// 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>
|
||||
{
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -105,8 +105,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-315.532"},
|
||||
{"Portfolio Turnover", "0.998"},
|
||||
{"Return Over Maximum Drawdown", "-315.48"},
|
||||
{"Portfolio Turnover", "0.999"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -120,7 +120,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1318619937"}
|
||||
{"OrderListHash", "1703396395"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,9 +67,11 @@ namespace QuantConnect.Algorithm.Framework.Risk
|
||||
}
|
||||
|
||||
var pnl = GetTotalDrawdownPercent(currentValue);
|
||||
if (pnl < _maximumDrawdownPercent)
|
||||
if (pnl < _maximumDrawdownPercent && targets.Length != 0)
|
||||
{
|
||||
foreach(var target in targets)
|
||||
// reset the trailing high value for restart investing on next rebalcing period
|
||||
_initialised = false;
|
||||
foreach (var target in targets)
|
||||
yield return new PortfolioTarget(target.Symbol, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,10 +54,11 @@ class MaximumDrawdownPercentPortfolio(RiskManagementModel):
|
||||
return [] # return if new high reached
|
||||
|
||||
pnl = self.GetTotalDrawdownPercent(currentValue)
|
||||
if pnl < self.maximumDrawdownPercent:
|
||||
if pnl < self.maximumDrawdownPercent and len(targets) != 0:
|
||||
self.initialised = False # reset the trailing high value for restart investing on next rebalcing period
|
||||
return [ PortfolioTarget(target.Symbol, 0) for target in targets ]
|
||||
|
||||
return []
|
||||
|
||||
def GetTotalDrawdownPercent(self, currentValue):
|
||||
return (float(currentValue) / float(self.portfolioHigh)) - 1.0
|
||||
return (float(currentValue) / float(self.portfolioHigh)) - 1.0
|
||||
|
||||
@@ -96,9 +96,9 @@ namespace QuantConnect.Algorithm.Framework.Selection
|
||||
var uniqueUnderlyingSymbols = new HashSet<Symbol>();
|
||||
foreach (var optionSymbol in _optionChainSymbolSelector(algorithm.UtcTime))
|
||||
{
|
||||
if (optionSymbol.SecurityType != SecurityType.Option)
|
||||
if (optionSymbol.SecurityType != SecurityType.Option && optionSymbol.SecurityType != SecurityType.FutureOption)
|
||||
{
|
||||
throw new ArgumentException("optionChainSymbolSelector must return option symbols.");
|
||||
throw new ArgumentException("optionChainSymbolSelector must return option or futures options symbols.");
|
||||
}
|
||||
|
||||
// prevent creating duplicate option chains -- one per underlying
|
||||
@@ -118,4 +118,4 @@ namespace QuantConnect.Algorithm.Framework.Selection
|
||||
return filter;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,8 +58,8 @@ class OptionUniverseSelectionModel(UniverseSelectionModel):
|
||||
|
||||
uniqueUnderlyingSymbols = set()
|
||||
for optionSymbol in self.optionChainSymbolSelector(algorithm.UtcTime):
|
||||
if optionSymbol.SecurityType != SecurityType.Option:
|
||||
raise ValueError("optionChainSymbolSelector must return option symbols.")
|
||||
if optionSymbol.SecurityType != SecurityType.Option and optionSymbol.SecurityType != SecurityType.FutureOption:
|
||||
raise ValueError("optionChainSymbolSelector must return option or futures options symbols.")
|
||||
|
||||
# prevent creating duplicate option chains -- one per underlying
|
||||
if optionSymbol.Underlying not in uniqueUnderlyingSymbols:
|
||||
@@ -73,7 +73,7 @@ class OptionUniverseSelectionModel(UniverseSelectionModel):
|
||||
symbol: Symbol of the option
|
||||
Returns:
|
||||
OptionChainUniverse for the given symbol'''
|
||||
if symbol.SecurityType != SecurityType.Option:
|
||||
if symbol.SecurityType != SecurityType.Option and symbol.SecurityType != SecurityType.FutureOption:
|
||||
raise ValueError("CreateOptionChain requires an option symbol.")
|
||||
|
||||
# rewrite non-canonical symbols to be canonical
|
||||
@@ -122,4 +122,4 @@ class OptionUniverseSelectionModel(UniverseSelectionModel):
|
||||
def Filter(self, filter):
|
||||
'''Defines the option chain universe filter'''
|
||||
# NOP
|
||||
return filter
|
||||
return filter
|
||||
|
||||
10
Algorithm.Python/.idea/Algorithm.Python.iml
generated
10
Algorithm.Python/.idea/Algorithm.Python.iml
generated
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/stubs" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
4
Algorithm.Python/.idea/misc.xml
generated
4
Algorithm.Python/.idea/misc.xml
generated
@@ -1,4 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6" project-jdk-type="Python SDK" />
|
||||
</project>
|
||||
8
Algorithm.Python/.idea/modules.xml
generated
8
Algorithm.Python/.idea/modules.xml
generated
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/Algorithm.Python.iml" filepath="$PROJECT_DIR$/.idea/Algorithm.Python.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
5
Algorithm.Python/.vscode/settings.json
vendored
5
Algorithm.Python/.vscode/settings.json
vendored
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"python.autoComplete.extraPaths": [
|
||||
"stubs"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
# 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.
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Securities import *
|
||||
from QuantConnect.Securities.Future import *
|
||||
from QuantConnect import Market
|
||||
|
||||
### <summary>
|
||||
### This regression algorithm tests that we receive the expected data when
|
||||
### we add future option contracts individually using <see cref="AddFutureOptionContract"/>
|
||||
### </summary>
|
||||
class AddFutureOptionContractDataStreamingRegressionAlgorithm(QCAlgorithm):
|
||||
def Initialize(self):
|
||||
self.onDataReached = False
|
||||
self.invested = False
|
||||
self.symbolsReceived = []
|
||||
self.expectedSymbolsReceived = []
|
||||
self.dataReceived = {}
|
||||
|
||||
self.SetStartDate(2020, 1, 5)
|
||||
self.SetEndDate(2020, 1, 6)
|
||||
|
||||
self.es20h20 = self.AddFutureContract(
|
||||
Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, datetime(2020, 3, 20)),
|
||||
Resolution.Minute).Symbol
|
||||
|
||||
self.es19m20 = self.AddFutureContract(
|
||||
Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, datetime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol
|
||||
|
||||
optionChains = self.OptionChainProvider.GetOptionContractList(self.es20h20, self.Time)
|
||||
optionChains += self.OptionChainProvider.GetOptionContractList(self.es19m20, self.Time)
|
||||
|
||||
for optionContract in optionChains:
|
||||
self.expectedSymbolsReceived.append(self.AddFutureOptionContract(optionContract, Resolution.Minute).Symbol)
|
||||
|
||||
def OnData(self, data: Slice):
|
||||
if not data.HasData:
|
||||
return
|
||||
|
||||
self.onDataReached = True
|
||||
hasOptionQuoteBars = False
|
||||
|
||||
for qb in data.QuoteBars.Values:
|
||||
if qb.Symbol.SecurityType != SecurityType.FutureOption:
|
||||
continue
|
||||
|
||||
hasOptionQuoteBars = True
|
||||
|
||||
self.symbolsReceived.append(qb.Symbol)
|
||||
if qb.Symbol not in self.dataReceived:
|
||||
self.dataReceived[qb.Symbol] = []
|
||||
|
||||
self.dataReceived[qb.Symbol].append(qb)
|
||||
|
||||
if self.invested or not hasOptionQuoteBars:
|
||||
return
|
||||
|
||||
if data.ContainsKey(self.es20h20) and data.ContainsKey(self.es19m20):
|
||||
self.SetHoldings(self.es20h20, 0.2)
|
||||
self.SetHoldings(self.es19m20, 0.2)
|
||||
|
||||
self.invested = True
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
super().OnEndOfAlgorithm()
|
||||
|
||||
self.symbolsReceived = list(set(self.symbolsReceived))
|
||||
self.expectedSymbolsReceived = list(set(self.expectedSymbolsReceived))
|
||||
|
||||
if not self.onDataReached:
|
||||
raise AssertionError("OnData() was never called.")
|
||||
if len(self.symbolsReceived) != len(self.expectedSymbolsReceived):
|
||||
raise AssertionError(f"Expected {len(self.expectedSymbolsReceived)} option contracts Symbols, found {len(self.symbolsReceived)}")
|
||||
|
||||
missingSymbols = [expectedSymbol for expectedSymbol in self.expectedSymbolsReceived if expectedSymbol not in self.symbolsReceived]
|
||||
if any(missingSymbols):
|
||||
raise AssertionError(f'Symbols: "{", ".join(missingSymbols)}" were not found in OnData')
|
||||
|
||||
for expectedSymbol in self.expectedSymbolsReceived:
|
||||
data = self.dataReceived[expectedSymbol]
|
||||
for dataPoint in data:
|
||||
dataPoint.EndTime = datetime(1970, 1, 1)
|
||||
|
||||
nonDupeDataCount = len(set(data))
|
||||
if nonDupeDataCount < 1000:
|
||||
raise AssertionError(f"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}")
|
||||
@@ -0,0 +1,127 @@
|
||||
# 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.
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Securities import *
|
||||
from QuantConnect.Securities.Future import *
|
||||
from QuantConnect import *
|
||||
|
||||
### <summary>
|
||||
### This regression algorithm tests that we only receive the option chain for a single future contract
|
||||
### in the option universe filter.
|
||||
### </summary>
|
||||
class AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm(QCAlgorithm):
|
||||
def Initialize(self):
|
||||
self.invested = False
|
||||
self.onDataReached = False
|
||||
self.optionFilterRan = False
|
||||
self.symbolsReceived = []
|
||||
self.expectedSymbolsReceived = []
|
||||
self.dataReceived = {}
|
||||
|
||||
self.SetStartDate(2020, 1, 5)
|
||||
self.SetEndDate(2020, 1, 6)
|
||||
|
||||
self.es = self.AddFuture(Futures.Indices.SP500EMini, Resolution.Minute, Market.CME)
|
||||
self.es.SetFilter(lambda futureFilter: futureFilter.Expiration(0, 365).ExpirationCycle([3, 6]))
|
||||
|
||||
self.AddFutureOption(self.es.Symbol, self.OptionContractUniverseFilterFunction)
|
||||
|
||||
def OptionContractUniverseFilterFunction(self, optionContracts: OptionFilterUniverse) -> OptionFilterUniverse:
|
||||
self.optionFilterRan = True
|
||||
|
||||
expiry = list(set([x.Underlying.ID.Date for x in optionContracts]))
|
||||
expiry = None if not any(expiry) else expiry[0]
|
||||
|
||||
symbol = [x.Underlying for x in optionContracts]
|
||||
symbol = None if not any(symbol) else symbol[0]
|
||||
|
||||
if expiry is None or symbol is None:
|
||||
raise AssertionError("Expected a single Option contract in the chain, found 0 contracts")
|
||||
|
||||
enumerator = optionContracts.GetEnumerator()
|
||||
while enumerator.MoveNext():
|
||||
self.expectedSymbolsReceived.append(enumerator.Current)
|
||||
|
||||
return optionContracts
|
||||
|
||||
def OnData(self, data: Slice):
|
||||
if not data.HasData:
|
||||
return
|
||||
|
||||
self.onDataReached = True
|
||||
hasOptionQuoteBars = False
|
||||
|
||||
for qb in data.QuoteBars.Values:
|
||||
if qb.Symbol.SecurityType != SecurityType.FutureOption:
|
||||
continue
|
||||
|
||||
hasOptionQuoteBars = True
|
||||
|
||||
self.symbolsReceived.append(qb.Symbol)
|
||||
if qb.Symbol not in self.dataReceived:
|
||||
self.dataReceived[qb.Symbol] = []
|
||||
|
||||
self.dataReceived[qb.Symbol].append(qb)
|
||||
|
||||
if self.invested or not hasOptionQuoteBars:
|
||||
return
|
||||
|
||||
for chain in data.OptionChains.Values:
|
||||
futureInvested = False
|
||||
optionInvested = False
|
||||
|
||||
for option in chain.Contracts.Keys:
|
||||
if futureInvested and optionInvested:
|
||||
return
|
||||
|
||||
future = option.Underlying
|
||||
|
||||
if not optionInvested and data.ContainsKey(option):
|
||||
self.MarketOrder(option, 1)
|
||||
self.invested = True
|
||||
optionInvested = True
|
||||
|
||||
if not futureInvested and data.ContainsKey(future):
|
||||
self.MarketOrder(future, 1)
|
||||
self.invested = True
|
||||
futureInvested = True
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
super().OnEndOfAlgorithm()
|
||||
self.symbolsReceived = list(set(self.symbolsReceived))
|
||||
self.expectedSymbolsReceived = list(set(self.expectedSymbolsReceived))
|
||||
|
||||
if not self.optionFilterRan:
|
||||
raise AssertionError("Option chain filter was never ran")
|
||||
if not self.onDataReached:
|
||||
raise AssertionError("OnData() was never called.")
|
||||
if len(self.symbolsReceived) != len(self.expectedSymbolsReceived):
|
||||
raise AssertionError(f"Expected {len(self.expectedSymbolsReceived)} option contracts Symbols, found {len(self.symbolsReceived)}")
|
||||
|
||||
missingSymbols = [expectedSymbol for expectedSymbol in self.expectedSymbolsReceived if expectedSymbol not in self.symbolsReceived]
|
||||
if any(missingSymbols):
|
||||
raise AssertionError(f'Symbols: "{", ".join(missingSymbols)}" were not found in OnData')
|
||||
|
||||
for expectedSymbol in self.expectedSymbolsReceived:
|
||||
data = self.dataReceived[expectedSymbol]
|
||||
for dataPoint in data:
|
||||
dataPoint.EndTime = datetime(1970, 1, 1)
|
||||
|
||||
nonDupeDataCount = len(set(data))
|
||||
if nonDupeDataCount < 1000:
|
||||
raise AssertionError(f"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}")
|
||||
@@ -0,0 +1,50 @@
|
||||
# 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.
|
||||
|
||||
from clr import AddReference
|
||||
AddReference("System")
|
||||
AddReference("QuantConnect.Algorithm")
|
||||
AddReference("QuantConnect.Common")
|
||||
|
||||
from System import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Custom.Quiver import *
|
||||
|
||||
### <summary>
|
||||
### Quiver Quantitative is a provider of alternative data.
|
||||
### This algorithm shows how to consume the 'QuiverWallStreetBets'
|
||||
### </summary>
|
||||
class QuiverWallStreetBetsDataAlgorithm(QCAlgorithm):
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2019, 1, 1)
|
||||
self.SetEndDate(2020, 6, 1)
|
||||
self.SetCash(100000)
|
||||
|
||||
aapl = self.AddEquity("AAPL", Resolution.Daily).Symbol
|
||||
quiverWSBSymbol = self.AddData(QuiverWallStreetBets, aapl).Symbol
|
||||
history = self.History(QuiverWallStreetBets, quiverWSBSymbol, 60, Resolution.Daily)
|
||||
|
||||
self.Debug(f"We got {len(history)} items from our history request");
|
||||
|
||||
def OnData(self, data):
|
||||
points = data.Get(QuiverWallStreetBets)
|
||||
for point in points.Values:
|
||||
# Go long in the stock if it was mentioned more than 5 times in the WallStreetBets daily discussion
|
||||
if point.Mentions > 5:
|
||||
self.SetHoldings(point.Symbol.Underlying, 1)
|
||||
|
||||
# Go short in the stock if it was mentioned less than 5 times in the WallStreetBets daily discussion
|
||||
if point.Mentions < 5:
|
||||
self.SetHoldings(point.Symbol.Underlying, -1)
|
||||
65
Algorithm.Python/CustomBuyingPowerModelAlgorithm.py
Normal file
65
Algorithm.Python/CustomBuyingPowerModelAlgorithm.py
Normal file
@@ -0,0 +1,65 @@
|
||||
# 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.
|
||||
|
||||
from clr import AddReference
|
||||
AddReference("System")
|
||||
AddReference("QuantConnect.Algorithm")
|
||||
AddReference("QuantConnect.Common")
|
||||
|
||||
from System import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Securities import *
|
||||
import numpy as np
|
||||
|
||||
### <summary>
|
||||
### Demonstration of using custom buying power model in backtesting.
|
||||
### QuantConnect allows you to model all orders as deeply and accurately as you need.
|
||||
### </summary>
|
||||
### <meta name="tag" content="trading and orders" />
|
||||
### <meta name="tag" content="transaction fees and slippage" />
|
||||
### <meta name="tag" content="custom buying power models" />
|
||||
class CustomBuyingPowerModelAlgorithm(QCAlgorithm):
|
||||
'''Demonstration of using custom buying power model in backtesting.
|
||||
QuantConnect allows you to model all orders as deeply and accurately as you need.'''
|
||||
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2013,10,1) # Set Start Date
|
||||
self.SetEndDate(2013,10,31) # Set End Date
|
||||
security = self.AddEquity("SPY", Resolution.Hour)
|
||||
self.spy = security.Symbol
|
||||
|
||||
# set the buying power model
|
||||
security.SetBuyingPowerModel(CustomBuyingPowerModel())
|
||||
|
||||
def OnData(self, slice):
|
||||
if self.Portfolio.Invested:
|
||||
return
|
||||
|
||||
quantity = self.CalculateOrderQuantity(self.spy, 1)
|
||||
if quantity % 100 != 0:
|
||||
raise Exception(f'CustomBuyingPowerModel only allow quantity that is multiple of 100 and {quantity} was found')
|
||||
|
||||
# We normally get insufficient buying power model, but the
|
||||
# CustomBuyingPowerModel always says that there is sufficient buying power for the orders
|
||||
self.MarketOrder(self.spy, quantity * 10)
|
||||
|
||||
|
||||
class CustomBuyingPowerModel(BuyingPowerModel):
|
||||
def GetMaximumOrderQuantityForTargetBuyingPower(self, parameters):
|
||||
quantity = super().GetMaximumOrderQuantityForTargetBuyingPower(parameters).Quantity
|
||||
quantity = np.floor(quantity / 100) * 100
|
||||
return GetMaximumOrderQuantityResult(quantity)
|
||||
|
||||
def HasSufficientBuyingPowerForOrder(self, parameters):
|
||||
return HasSufficientBuyingPowerForOrderResult(True)
|
||||
@@ -27,16 +27,17 @@ import numpy as np
|
||||
import random
|
||||
|
||||
### <summary>
|
||||
### Demonstration of using custom fee, slippage and fill models for modelling transactions in backtesting.
|
||||
### Demonstration of using custom fee, slippage, fill, and buying power models for modelling transactions in backtesting.
|
||||
### QuantConnect allows you to model all orders as deeply and accurately as you need.
|
||||
### </summary>
|
||||
### <meta name="tag" content="trading and orders" />
|
||||
### <meta name="tag" content="transaction fees and slippage" />
|
||||
### <meta name="tag" content="custom buying power models" />
|
||||
### <meta name="tag" content="custom transaction models" />
|
||||
### <meta name="tag" content="custom slippage models" />
|
||||
### <meta name="tag" content="custom fee models" />
|
||||
class CustomModelsAlgorithm(QCAlgorithm):
|
||||
'''Demonstration of using custom fee, slippage and fill models for modelling transactions in backtesting.
|
||||
'''Demonstration of using custom fee, slippage, fill, and buying power models for modelling transactions in backtesting.
|
||||
QuantConnect allows you to model all orders as deeply and accurately as you need.'''
|
||||
|
||||
def Initialize(self):
|
||||
@@ -49,6 +50,7 @@ class CustomModelsAlgorithm(QCAlgorithm):
|
||||
self.security.SetFeeModel(CustomFeeModel(self))
|
||||
self.security.SetFillModel(CustomFillModel(self))
|
||||
self.security.SetSlippageModel(CustomSlippageModel(self))
|
||||
self.security.SetBuyingPowerModel(CustomBuyingPowerModel(self))
|
||||
|
||||
|
||||
def OnData(self, data):
|
||||
@@ -57,12 +59,12 @@ class CustomModelsAlgorithm(QCAlgorithm):
|
||||
|
||||
if self.Time.day > 10 and self.security.Holdings.Quantity <= 0:
|
||||
quantity = self.CalculateOrderQuantity(self.spy, .5)
|
||||
self.Log("MarketOrder: " + str(quantity))
|
||||
self.Log(f"MarketOrder: {quantity}")
|
||||
self.MarketOrder(self.spy, quantity, True) # async needed for partial fill market orders
|
||||
|
||||
elif self.Time.day > 20 and self.security.Holdings.Quantity >= 0:
|
||||
quantity = self.CalculateOrderQuantity(self.spy, -.5)
|
||||
self.Log("MarketOrder: " + str(quantity))
|
||||
self.Log(f"MarketOrder: {quantity}")
|
||||
self.MarketOrder(self.spy, quantity, True) # async needed for partial fill market orders
|
||||
|
||||
# If we want to use methods from other models, you need to inherit from one of them
|
||||
@@ -90,7 +92,7 @@ class CustomFillModel(ImmediateFillModel):
|
||||
absoluteRemaining = absoluteRemaining - absoluteFillQuantity
|
||||
self.absoluteRemainingByOrderId[order.Id] = absoluteRemaining
|
||||
fill.Status = OrderStatus.PartiallyFilled
|
||||
self.algorithm.Log("CustomFillModel: " + str(fill))
|
||||
self.algorithm.Log(f"CustomFillModel: {fill}")
|
||||
return fill
|
||||
|
||||
class CustomFeeModel(FeeModel):
|
||||
@@ -102,7 +104,7 @@ class CustomFeeModel(FeeModel):
|
||||
fee = max(1, parameters.Security.Price
|
||||
* parameters.Order.AbsoluteQuantity
|
||||
* 0.00001)
|
||||
self.algorithm.Log("CustomFeeModel: " + str(fee))
|
||||
self.algorithm.Log(f"CustomFeeModel: {fee}")
|
||||
return OrderFee(CashAmount(fee, "USD"))
|
||||
|
||||
class CustomSlippageModel:
|
||||
@@ -112,5 +114,15 @@ class CustomSlippageModel:
|
||||
def GetSlippageApproximation(self, asset, order):
|
||||
# custom slippage math
|
||||
slippage = asset.Price * 0.0001 * np.log10(2*float(order.AbsoluteQuantity))
|
||||
self.algorithm.Log("CustomSlippageModel: " + str(slippage))
|
||||
return slippage
|
||||
self.algorithm.Log(f"CustomSlippageModel: {slippage}")
|
||||
return slippage
|
||||
|
||||
class CustomBuyingPowerModel(BuyingPowerModel):
|
||||
def __init__(self, algorithm):
|
||||
self.algorithm = algorithm
|
||||
|
||||
def HasSufficientBuyingPowerForOrder(self, parameters):
|
||||
# custom behavior: this model will assume that there is always enough buying power
|
||||
hasSufficientBuyingPowerForOrderResult = HasSufficientBuyingPowerForOrderResult(True)
|
||||
self.algorithm.Log(f"CustomBuyingPowerModel: {hasSufficientBuyingPowerForOrderResult.IsSufficient}")
|
||||
return hasSufficientBuyingPowerForOrderResult
|
||||
@@ -0,0 +1,97 @@
|
||||
# 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
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import clr
|
||||
from System import *
|
||||
from System.Reflection import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Orders import *
|
||||
from QuantConnect.Securities import *
|
||||
from QuantConnect.Securities.Future import *
|
||||
from QuantConnect import Market
|
||||
|
||||
|
||||
### <summary>
|
||||
### This regression algorithm tests In The Money (ITM) future option calls across different strike prices.
|
||||
### We expect 6 orders from the algorithm, which are:
|
||||
###
|
||||
### * (1) Initial entry, buy ES Call Option (ES19M20 expiring ITM)
|
||||
### * (2) Initial entry, sell ES Call Option at different strike (ES20H20 expiring ITM)
|
||||
### * [2] Option assignment, opens a position in the underlying (ES20H20, Qty: -1)
|
||||
### * [2] Future contract liquidation, due to impending expiry
|
||||
### * [1] Option exercise, receive 1 ES19M20 future contract
|
||||
### * [1] Liquidate ES19M20 contract, due to expiry
|
||||
###
|
||||
### Additionally, we test delistings for future options and assert that our
|
||||
### portfolio holdings reflect the orders the algorithm has submitted.
|
||||
### </summary>
|
||||
class FutureOptionBuySellCallIntradayRegressionAlgorithm(QCAlgorithm):
|
||||
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2020, 1, 5)
|
||||
self.SetEndDate(2020, 6, 30)
|
||||
|
||||
# We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
# which causes delisting events to never be processed, thus leading to options that might never
|
||||
# be exercised until the next data point arrives.
|
||||
self.AddEquity("AAPL", Resolution.Daily)
|
||||
|
||||
self.es20h20 = self.AddFutureContract(
|
||||
Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
datetime(2020, 3, 20)
|
||||
),
|
||||
Resolution.Minute).Symbol
|
||||
|
||||
self.es19m20 = self.AddFutureContract(
|
||||
Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
datetime(2020, 6, 19)
|
||||
),
|
||||
Resolution.Minute).Symbol
|
||||
|
||||
# Select a future option expiring ITM, and adds it to the algorithm.
|
||||
self.esOptions = [
|
||||
self.AddFutureOptionContract(i, Resolution.Minute).Symbol for i in (self.OptionChainProvider.GetOptionContractList(self.es19m20, self.Time) + self.OptionChainProvider.GetOptionContractList(self.es20h20, self.Time)) if i.ID.StrikePrice == 3200.0 and i.ID.OptionRight == OptionRight.Call
|
||||
]
|
||||
|
||||
self.expectedContracts = [
|
||||
Symbol.CreateOption(self.es20h20, Market.CME, OptionStyle.American, OptionRight.Call, 3200.0, datetime(2020, 3, 20)),
|
||||
Symbol.CreateOption(self.es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200.0, datetime(2020, 6, 19))
|
||||
]
|
||||
|
||||
for esOption in self.esOptions:
|
||||
if esOption not in self.expectedContracts:
|
||||
raise AssertionError(f"Contract {esOption} was not found in the chain")
|
||||
|
||||
self.Schedule.On(self.DateRules.Tomorrow, self.TimeRules.AfterMarketOpen(self.es19m20, 1), self.ScheduleCallbackBuy)
|
||||
self.Schedule.On(self.DateRules.Tomorrow, self.TimeRules.Noon, self.ScheduleCallbackLiquidate)
|
||||
|
||||
def ScheduleCallbackBuy(self):
|
||||
self.MarketOrder(self.esOptions[0], 1)
|
||||
self.MarketOrder(self.esOptions[1], -1)
|
||||
|
||||
def ScheduleCallbackLiquidate(self):
|
||||
self.Liquidate()
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
if self.Portfolio.Invested:
|
||||
raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.ID) for i in self.Portfolio.Keys])}")
|
||||
|
||||
143
Algorithm.Python/FutureOptionCallITMExpiryRegressionAlgorithm.py
Normal file
143
Algorithm.Python/FutureOptionCallITMExpiryRegressionAlgorithm.py
Normal file
@@ -0,0 +1,143 @@
|
||||
# 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
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import clr
|
||||
from System import *
|
||||
from System.Reflection import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Orders import *
|
||||
from QuantConnect.Securities import *
|
||||
from QuantConnect.Securities.Future import *
|
||||
from QuantConnect import Market
|
||||
|
||||
|
||||
### <summary>
|
||||
### This regression algorithm tests In The Money (ITM) future option expiry for calls.
|
||||
### We expect 3 orders from the algorithm, which are:
|
||||
###
|
||||
### * Initial entry, buy ES Call Option (expiring ITM)
|
||||
### * Option exercise, receiving ES future contracts
|
||||
### * Future contract liquidation, due to impending expiry
|
||||
###
|
||||
### Additionally, we test delistings for future options and assert that our
|
||||
### portfolio holdings reflect the orders the algorithm has submitted.
|
||||
### </summary>
|
||||
class FutureOptionCallITMExpiryRegressionAlgorithm(QCAlgorithm):
|
||||
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2020, 1, 5)
|
||||
self.SetEndDate(2020, 6, 30)
|
||||
|
||||
# We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
# which causes delisting events to never be processed, thus leading to options that might never
|
||||
# be exercised until the next data point arrives.
|
||||
self.AddEquity("AAPL", Resolution.Daily)
|
||||
|
||||
self.es19m20 = self.AddFutureContract(
|
||||
Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
datetime(2020, 6, 19)
|
||||
),
|
||||
Resolution.Minute).Symbol
|
||||
|
||||
# Select a future option expiring ITM, and adds it to the algorithm.
|
||||
self.esOption = self.AddFutureOptionContract(
|
||||
list(
|
||||
sorted([x for x in self.OptionChainProvider.GetOptionContractList(self.es19m20, self.Time) if x.ID.StrikePrice <= 3200.0 and x.ID.OptionRight == OptionRight.Call], key=lambda x: x.ID.StrikePrice, reverse=True)
|
||||
)[0], Resolution.Minute).Symbol
|
||||
|
||||
self.expectedContract = Symbol.CreateOption(self.es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200.0, datetime(2020, 6, 19))
|
||||
if self.esOption != self.expectedContract:
|
||||
raise AssertionError(f"Contract {self.expectedContract} was not found in the chain")
|
||||
|
||||
self.Schedule.On(self.DateRules.Tomorrow, self.TimeRules.AfterMarketOpen(self.es19m20, 1), self.ScheduleCallback)
|
||||
|
||||
def ScheduleCallback(self):
|
||||
self.MarketOrder(self.esOption, 1)
|
||||
|
||||
def OnData(self, data: Slice):
|
||||
# Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
# the expected time. These assertions detect bug #4872
|
||||
for delisting in data.Delistings.Values:
|
||||
if delisting.Type == DelistingType.Warning:
|
||||
if delisting.Time != datetime(2020, 6, 19):
|
||||
raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.Time}")
|
||||
elif delisting.Type == DelistingType.Delisted:
|
||||
if delisting.Time != datetime(2020, 6, 20):
|
||||
raise AssertionError(f"Delisting happened at unexpected date: {delisting.Time}")
|
||||
|
||||
def OnOrderEvent(self, orderEvent: OrderEvent):
|
||||
if orderEvent.Status != OrderStatus.Filled:
|
||||
# There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return
|
||||
|
||||
if not self.Securities.ContainsKey(orderEvent.Symbol):
|
||||
raise AssertionError(f"Order event Symbol not found in Securities collection: {orderEvent.Symbol}")
|
||||
|
||||
security = self.Securities[orderEvent.Symbol]
|
||||
if security.Symbol == self.es19m20:
|
||||
self.AssertFutureOptionOrderExercise(orderEvent, security, self.Securities[self.expectedContract])
|
||||
elif security.Symbol == self.expectedContract:
|
||||
# Expected contract is ES19H21 Call Option expiring ITM @ 3250
|
||||
self.AssertFutureOptionContractOrder(orderEvent, security)
|
||||
else:
|
||||
raise AssertionError(f"Received order event for unknown Symbol: {orderEvent.Symbol}")
|
||||
|
||||
self.Log(f"{self.Time} -- {orderEvent.Symbol} :: Price: {self.Securities[orderEvent.Symbol].Holdings.Price} Qty: {self.Securities[orderEvent.Symbol].Holdings.Quantity} Direction: {orderEvent.Direction} Msg: {orderEvent.Message}")
|
||||
|
||||
def AssertFutureOptionOrderExercise(self, orderEvent: OrderEvent, future: Security, optionContract: Security):
|
||||
# We expect the liquidation to occur on the day of the delisting (while the market is open),
|
||||
# but currently we liquidate at the next market open (AAPL open) which happens to be
|
||||
# at 9:30:00 Eastern Time. For unknown reasons, the delisting happens two minutes after the
|
||||
# market open.
|
||||
# Read more about the issue affecting this test here: https://github.com/QuantConnect/Lean/issues/4980
|
||||
expectedLiquidationTimeUtc = datetime(2020, 6, 22, 13, 32, 0)
|
||||
|
||||
if orderEvent.Direction == OrderDirection.Sell and future.Holdings.Quantity != 0:
|
||||
# We expect the contract to have been liquidated immediately
|
||||
raise AssertionError(f"Did not liquidate existing holdings for Symbol {future.Symbol}")
|
||||
if orderEvent.Direction == OrderDirection.Sell and orderEvent.UtcTime.replace(tzinfo=None) != expectedLiquidationTimeUtc:
|
||||
raise AssertionError(f"Liquidated future contract, but not at the expected time. Expected: {expectedLiquidationTimeUtc} - found {orderEvent.UtcTime.replace(tzinfo=None)}");
|
||||
|
||||
# No way to detect option exercise orders or any other kind of special orders
|
||||
# other than matching strings, for now.
|
||||
if "Option Exercise" in orderEvent.Message:
|
||||
if orderEvent.FillPrice != 3200.0:
|
||||
raise AssertionError("Option did not exercise at expected strike price (3200)")
|
||||
|
||||
if future.Holdings.Quantity != 1:
|
||||
# Here, we expect to have some holdings in the underlying, but not in the future option anymore.
|
||||
raise AssertionError(f"Exercised option contract, but we have no holdings for Future {future.Symbol}")
|
||||
|
||||
if optionContract.Holdings.Quantity != 0:
|
||||
raise AssertionError(f"Exercised option contract, but we have holdings for Option contract {optionContract.Symbol}")
|
||||
|
||||
def AssertFutureOptionContractOrder(self, orderEvent: OrderEvent, option: Security):
|
||||
if orderEvent.Direction == OrderDirection.Buy and option.Holdings.Quantity != 1:
|
||||
raise AssertionError(f"No holdings were created for option contract {option.Symbol}")
|
||||
|
||||
if orderEvent.Direction == OrderDirection.Sell and option.Holdings.Quantity != 0:
|
||||
raise AssertionError(f"Holdings were found after a filled option exercise")
|
||||
|
||||
if "Exercise" in orderEvent.Message and option.Holdings.Quantity != 0:
|
||||
raise AssertionError(f"Holdings were found after exercising option contract {option.Symbol}")
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
if self.Portfolio.Invested:
|
||||
raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.ID) for i in self.Portfolio.Keys])}")
|
||||
127
Algorithm.Python/FutureOptionCallOTMExpiryRegressionAlgorithm.py
Normal file
127
Algorithm.Python/FutureOptionCallOTMExpiryRegressionAlgorithm.py
Normal file
@@ -0,0 +1,127 @@
|
||||
# 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
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import clr
|
||||
from System import *
|
||||
from System.Reflection import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Orders import *
|
||||
from QuantConnect.Securities import *
|
||||
from QuantConnect.Securities.Future import *
|
||||
from QuantConnect import Market
|
||||
|
||||
|
||||
### <summary>
|
||||
### This regression algorithm tests Out of The Money (OTM) future option expiry for calls.
|
||||
### We expect 1 order from the algorithm, which are:
|
||||
###
|
||||
### * Initial entry, buy ES Call Option (expiring OTM)
|
||||
### - contract expires worthless, not exercised, so never opened a position in the underlying
|
||||
###
|
||||
### Additionally, we test delistings for future options and assert that our
|
||||
### portfolio holdings reflect the orders the algorithm has submitted.
|
||||
### </summary>
|
||||
### <remarks>
|
||||
### Total Trades in regression algorithm should be 1, but expiration is counted as a trade.
|
||||
### See related issue: https://github.com/QuantConnect/Lean/issues/4854
|
||||
### </remarks>
|
||||
class FutureOptionCallOTMExpiryRegressionAlgorithm(QCAlgorithm):
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2020, 1, 5)
|
||||
self.SetEndDate(2020, 6, 30)
|
||||
|
||||
# We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
# which causes delisting events to never be processed, thus leading to options that might never
|
||||
# be exercised until the next data point arrives.
|
||||
self.AddEquity("AAPL", Resolution.Daily)
|
||||
|
||||
self.es19m20 = self.AddFutureContract(
|
||||
Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
datetime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol
|
||||
|
||||
# Select a future option expiring ITM, and adds it to the algorithm.
|
||||
self.esOption = self.AddFutureOptionContract(
|
||||
list(
|
||||
sorted(
|
||||
[x for x in self.OptionChainProvider.GetOptionContractList(self.es19m20, self.Time) if x.ID.StrikePrice >= 3300.0 and x.ID.OptionRight == OptionRight.Call],
|
||||
key=lambda x: x.ID.StrikePrice
|
||||
)
|
||||
)[0], Resolution.Minute).Symbol
|
||||
|
||||
self.expectedContract = Symbol.CreateOption(self.es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3300.0, datetime(2020, 6, 19))
|
||||
if self.esOption != self.expectedContract:
|
||||
raise AssertionError(f"Contract {self.expectedContract} was not found in the chain");
|
||||
|
||||
self.Schedule.On(self.DateRules.Tomorrow, self.TimeRules.AfterMarketOpen(self.es19m20, 1), self.ScheduledMarketOrder)
|
||||
|
||||
def ScheduledMarketOrder(self):
|
||||
self.MarketOrder(self.esOption, 1)
|
||||
|
||||
def OnData(self, data: Slice):
|
||||
# Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
# the expected time. These assertions detect bug #4872
|
||||
for delisting in data.Delistings.Values:
|
||||
if delisting.Type == DelistingType.Warning:
|
||||
if delisting.Time != datetime(2020, 6, 19):
|
||||
raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
|
||||
if delisting.Type == DelistingType.Delisted:
|
||||
if delisting.Time != datetime(2020, 6, 20):
|
||||
raise AssertionError(f"Delisting happened at unexpected date: {delisting.Time}");
|
||||
|
||||
|
||||
def OnOrderEvent(self, orderEvent: OrderEvent):
|
||||
if orderEvent.Status != OrderStatus.Filled:
|
||||
# There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return
|
||||
|
||||
if not self.Securities.ContainsKey(orderEvent.Symbol):
|
||||
raise AssertionError(f"Order event Symbol not found in Securities collection: {orderEvent.Symbol}")
|
||||
|
||||
security = self.Securities[orderEvent.Symbol]
|
||||
if security.Symbol == self.es19m20:
|
||||
raise AssertionError("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM")
|
||||
|
||||
# Expected contract is ES19M20 Call Option expiring OTM @ 3300
|
||||
if (security.Symbol == self.expectedContract):
|
||||
self.AssertFutureOptionContractOrder(orderEvent, security)
|
||||
else:
|
||||
raise AssertionError(f"Received order event for unknown Symbol: {orderEvent.Symbol}")
|
||||
|
||||
self.Log(f"{orderEvent}");
|
||||
|
||||
|
||||
def AssertFutureOptionContractOrder(self, orderEvent: OrderEvent, option: Security):
|
||||
if orderEvent.Direction == OrderDirection.Buy and option.Holdings.Quantity != 1:
|
||||
raise AssertionError(f"No holdings were created for option contract {option.Symbol}");
|
||||
|
||||
if orderEvent.Direction == OrderDirection.Sell and option.Holdings.Quantity != 0:
|
||||
raise AssertionError("Holdings were found after a filled option exercise");
|
||||
|
||||
if orderEvent.Direction == OrderDirection.Sell and "OTM" not in orderEvent.Message:
|
||||
raise AssertionError("Contract did not expire OTM");
|
||||
|
||||
if "Exercise" in orderEvent.Message:
|
||||
raise AssertionError("Exercised option, even though it expires OTM");
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
if self.Portfolio.Invested:
|
||||
raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.ID) for i in self.Portfolio.Keys])}")
|
||||
142
Algorithm.Python/FutureOptionPutITMExpiryRegressionAlgorithm.py
Normal file
142
Algorithm.Python/FutureOptionPutITMExpiryRegressionAlgorithm.py
Normal file
@@ -0,0 +1,142 @@
|
||||
# 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
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import clr
|
||||
from System import *
|
||||
from System.Reflection import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Orders import *
|
||||
from QuantConnect.Securities import *
|
||||
from QuantConnect.Securities.Future import *
|
||||
from QuantConnect import Market
|
||||
|
||||
|
||||
### <summary>
|
||||
### This regression algorithm tests In The Money (ITM) future option expiry for puts.
|
||||
### We expect 3 orders from the algorithm, which are:
|
||||
###
|
||||
### * Initial entry, buy ES Put Option (expiring ITM) (buy, qty 1)
|
||||
### * Option exercise, receiving short ES future contracts (sell, qty -1)
|
||||
### * Future contract liquidation, due to impending expiry (buy qty 1)
|
||||
###
|
||||
### Additionally, we test delistings for future options and assert that our
|
||||
### portfolio holdings reflect the orders the algorithm has submitted.
|
||||
### </summary>
|
||||
class FutureOptionPutITMExpiryRegressionAlgorithm(QCAlgorithm):
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2020, 1, 5)
|
||||
self.SetEndDate(2020, 6, 30)
|
||||
|
||||
# We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
# which causes delisting events to never be processed, thus leading to options that might never
|
||||
# be exercised until the next data point arrives.
|
||||
self.AddEquity("AAPL", Resolution.Daily)
|
||||
|
||||
self.es19m20 = self.AddFutureContract(
|
||||
Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
datetime(2020, 6, 19)
|
||||
),
|
||||
Resolution.Minute).Symbol
|
||||
|
||||
# Select a future option expiring ITM, and adds it to the algorithm.
|
||||
self.esOption = self.AddFutureOptionContract(
|
||||
list(
|
||||
sorted([x for x in self.OptionChainProvider.GetOptionContractList(self.es19m20, self.Time) if x.ID.StrikePrice >= 3300.0 and x.ID.OptionRight == OptionRight.Put], key=lambda x: x.ID.StrikePrice)
|
||||
)[0], Resolution.Minute).Symbol
|
||||
|
||||
self.expectedContract = Symbol.CreateOption(self.es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3300.0, datetime(2020, 6, 19))
|
||||
if self.esOption != self.expectedContract:
|
||||
raise AssertionError(f"Contract {self.expectedContract} was not found in the chain")
|
||||
|
||||
self.Schedule.On(self.DateRules.Tomorrow, self.TimeRules.AfterMarketOpen(self.es19m20, 1), self.ScheduleCallback)
|
||||
|
||||
def ScheduleCallback(self):
|
||||
self.MarketOrder(self.esOption, 1)
|
||||
|
||||
def OnData(self, data: Slice):
|
||||
# Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
# the expected time. These assertions detect bug #4872
|
||||
for delisting in data.Delistings.Values:
|
||||
if delisting.Type == DelistingType.Warning:
|
||||
if delisting.Time != datetime(2020, 6, 19):
|
||||
raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.Time}")
|
||||
elif delisting.Type == DelistingType.Delisted:
|
||||
if delisting.Time != datetime(2020, 6, 20):
|
||||
raise AssertionError(f"Delisting happened at unexpected date: {delisting.Time}")
|
||||
|
||||
def OnOrderEvent(self, orderEvent: OrderEvent):
|
||||
if orderEvent.Status != OrderStatus.Filled:
|
||||
# There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return
|
||||
|
||||
if not self.Securities.ContainsKey(orderEvent.Symbol):
|
||||
raise AssertionError(f"Order event Symbol not found in Securities collection: {orderEvent.Symbol}")
|
||||
|
||||
security = self.Securities[orderEvent.Symbol]
|
||||
if security.Symbol == self.es19m20:
|
||||
self.AssertFutureOptionOrderExercise(orderEvent, security, self.Securities[self.expectedContract])
|
||||
elif security.Symbol == self.expectedContract:
|
||||
# Expected contract is ES19M20 Call Option expiring ITM @ 3250
|
||||
self.AssertFutureOptionContractOrder(orderEvent, security)
|
||||
else:
|
||||
raise AssertionError(f"Received order event for unknown Symbol: {orderEvent.Symbol}")
|
||||
|
||||
self.Log(f"{self.Time} -- {orderEvent.Symbol} :: Price: {self.Securities[orderEvent.Symbol].Holdings.Price} Qty: {self.Securities[orderEvent.Symbol].Holdings.Quantity} Direction: {orderEvent.Direction} Msg: {orderEvent.Message}")
|
||||
|
||||
def AssertFutureOptionOrderExercise(self, orderEvent: OrderEvent, future: Security, optionContract: Security):
|
||||
# We expect the liquidation to occur on the day of the delisting (while the market is open),
|
||||
# but currently we liquidate at the next market open (AAPL open) which happens to be
|
||||
# at 9:30:00 Eastern Time. For unknown reasons, the delisting happens two minutes after the
|
||||
# market open.
|
||||
# Read more about the issue affecting this test here: https://github.com/QuantConnect/Lean/issues/4980
|
||||
expectedLiquidationTimeUtc = datetime(2020, 6, 22, 13, 32, 0)
|
||||
|
||||
if orderEvent.Direction == OrderDirection.Buy and future.Holdings.Quantity != 0:
|
||||
# We expect the contract to have been liquidated immediately
|
||||
raise AssertionError(f"Did not liquidate existing holdings for Symbol {future.Symbol}")
|
||||
if orderEvent.Direction == OrderDirection.Buy and orderEvent.UtcTime.replace(tzinfo=None) != expectedLiquidationTimeUtc:
|
||||
raise AssertionError(f"Liquidated future contract, but not at the expected time. Expected: {expectedLiquidationTimeUtc} - found {orderEvent.UtcTime.replace(tzinfo=None)}");
|
||||
|
||||
# No way to detect option exercise orders or any other kind of special orders
|
||||
# other than matching strings, for now.
|
||||
if "Option Exercise" in orderEvent.Message:
|
||||
if orderEvent.FillPrice != 3300.0:
|
||||
raise AssertionError("Option did not exercise at expected strike price (3300)")
|
||||
|
||||
if future.Holdings.Quantity != -1:
|
||||
# Here, we expect to have some holdings in the underlying, but not in the future option anymore.
|
||||
raise AssertionError(f"Exercised option contract, but we have no holdings for Future {future.Symbol}")
|
||||
|
||||
if optionContract.Holdings.Quantity != 0:
|
||||
raise AssertionError(f"Exercised option contract, but we have holdings for Option contract {optionContract.Symbol}")
|
||||
|
||||
def AssertFutureOptionContractOrder(self, orderEvent: OrderEvent, option: Security):
|
||||
if orderEvent.Direction == OrderDirection.Buy and option.Holdings.Quantity != 1:
|
||||
raise AssertionError(f"No holdings were created for option contract {option.Symbol}")
|
||||
|
||||
if orderEvent.Direction == OrderDirection.Sell and option.Holdings.Quantity != 0:
|
||||
raise AssertionError(f"Holdings were found after a filled option exercise")
|
||||
|
||||
if "Exercise" in orderEvent.Message and option.Holdings.Quantity != 0:
|
||||
raise AssertionError(f"Holdings were found after exercising option contract {option.Symbol}")
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
if self.Portfolio.Invested:
|
||||
raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.ID) for i in self.Portfolio.Keys])}")
|
||||
127
Algorithm.Python/FutureOptionPutOTMExpiryRegressionAlgorithm.py
Normal file
127
Algorithm.Python/FutureOptionPutOTMExpiryRegressionAlgorithm.py
Normal file
@@ -0,0 +1,127 @@
|
||||
# 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
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import clr
|
||||
from System import *
|
||||
from System.Reflection import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Orders import *
|
||||
from QuantConnect.Securities import *
|
||||
from QuantConnect.Securities.Future import *
|
||||
from QuantConnect import Market
|
||||
|
||||
|
||||
### <summary>
|
||||
### This regression algorithm tests Out of The Money (OTM) future option expiry for puts.
|
||||
### We expect 1 order from the algorithm, which are:
|
||||
###
|
||||
### * Initial entry, buy ES Put Option (expiring OTM)
|
||||
### - contract expires worthless, not exercised, so never opened a position in the underlying
|
||||
###
|
||||
### Additionally, we test delistings for future options and assert that our
|
||||
### portfolio holdings reflect the orders the algorithm has submitted.
|
||||
### </summary>
|
||||
### <remarks>
|
||||
### Total Trades in regression algorithm should be 1, but expiration is counted as a trade.
|
||||
### </remarks>
|
||||
class FutureOptionPutOTMExpiryRegressionAlgorithm(QCAlgorithm):
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2020, 1, 5)
|
||||
self.SetEndDate(2020, 6, 30)
|
||||
|
||||
# We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
# which causes delisting events to never be processed, thus leading to options that might never
|
||||
# be exercised until the next data point arrives.
|
||||
self.AddEquity("AAPL", Resolution.Daily)
|
||||
|
||||
self.es19m20 = self.AddFutureContract(
|
||||
Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
datetime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol
|
||||
|
||||
# Select a future option expiring ITM, and adds it to the algorithm.
|
||||
self.esOption = self.AddFutureOptionContract(
|
||||
list(
|
||||
sorted(
|
||||
[x for x in self.OptionChainProvider.GetOptionContractList(self.es19m20, self.Time) if x.ID.StrikePrice <= 3150.0 and x.ID.OptionRight == OptionRight.Put],
|
||||
key=lambda x: x.ID.StrikePrice,
|
||||
reverse=True
|
||||
)
|
||||
)[0], Resolution.Minute).Symbol
|
||||
|
||||
self.expectedContract = Symbol.CreateOption(self.es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3150.0, datetime(2020, 6, 19))
|
||||
if self.esOption != self.expectedContract:
|
||||
raise AssertionError(f"Contract {self.expectedContract} was not found in the chain");
|
||||
|
||||
self.Schedule.On(self.DateRules.Tomorrow, self.TimeRules.AfterMarketOpen(self.es19m20, 1), self.ScheduledMarketOrder)
|
||||
|
||||
def ScheduledMarketOrder(self):
|
||||
self.MarketOrder(self.esOption, 1)
|
||||
|
||||
def OnData(self, data: Slice):
|
||||
# Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
# the expected time. These assertions detect bug #4872
|
||||
for delisting in data.Delistings.Values:
|
||||
if delisting.Type == DelistingType.Warning:
|
||||
if delisting.Time != datetime(2020, 6, 19):
|
||||
raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
|
||||
if delisting.Type == DelistingType.Delisted:
|
||||
if delisting.Time != datetime(2020, 6, 20):
|
||||
raise AssertionError(f"Delisting happened at unexpected date: {delisting.Time}");
|
||||
|
||||
|
||||
def OnOrderEvent(self, orderEvent: OrderEvent):
|
||||
if orderEvent.Status != OrderStatus.Filled:
|
||||
# There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return
|
||||
|
||||
if not self.Securities.ContainsKey(orderEvent.Symbol):
|
||||
raise AssertionError(f"Order event Symbol not found in Securities collection: {orderEvent.Symbol}")
|
||||
|
||||
security = self.Securities[orderEvent.Symbol]
|
||||
if security.Symbol == self.es19m20:
|
||||
raise AssertionError("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM")
|
||||
|
||||
# Expected contract is ES19M20 Put Option expiring OTM @ 3200
|
||||
if (security.Symbol == self.expectedContract):
|
||||
self.AssertFutureOptionContractOrder(orderEvent, security)
|
||||
else:
|
||||
raise AssertionError(f"Received order event for unknown Symbol: {orderEvent.Symbol}")
|
||||
|
||||
self.Log(f"{orderEvent}");
|
||||
|
||||
|
||||
def AssertFutureOptionContractOrder(self, orderEvent: OrderEvent, option: Security):
|
||||
if orderEvent.Direction == OrderDirection.Buy and option.Holdings.Quantity != 1:
|
||||
raise AssertionError(f"No holdings were created for option contract {option.Symbol}");
|
||||
|
||||
if orderEvent.Direction == OrderDirection.Sell and option.Holdings.Quantity != 0:
|
||||
raise AssertionError("Holdings were found after a filled option exercise");
|
||||
|
||||
if orderEvent.Direction == OrderDirection.Sell and "OTM" not in orderEvent.Message:
|
||||
raise AssertionError("Contract did not expire OTM");
|
||||
|
||||
if "Exercise" in orderEvent.Message:
|
||||
raise AssertionError("Exercised option, even though it expires OTM");
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
if self.Portfolio.Invested:
|
||||
raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.ID) for i in self.Portfolio.Keys])}")
|
||||
@@ -0,0 +1,132 @@
|
||||
# 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
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import clr
|
||||
from System import *
|
||||
from System.Reflection import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Orders import *
|
||||
from QuantConnect.Securities import *
|
||||
from QuantConnect.Securities.Future import *
|
||||
from QuantConnect import Market
|
||||
|
||||
|
||||
### <summary>
|
||||
### This regression algorithm tests In The Money (ITM) future option expiry for short calls.
|
||||
### We expect 3 orders from the algorithm, which are:
|
||||
###
|
||||
### * Initial entry, sell ES Call Option (expiring ITM)
|
||||
### * Option assignment, sell 1 contract of the underlying (ES)
|
||||
### * Future contract expiry, liquidation (buy 1 ES future)
|
||||
###
|
||||
### Additionally, we test delistings for future options and assert that our
|
||||
### portfolio holdings reflect the orders the algorithm has submitted.
|
||||
### </summary>
|
||||
class FutureOptionShortCallITMExpiryRegressionAlgorithm(QCAlgorithm):
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2020, 1, 5)
|
||||
self.SetEndDate(2020, 6, 30)
|
||||
|
||||
# We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
# which causes delisting events to never be processed, thus leading to options that might never
|
||||
# be exercised until the next data point arrives.
|
||||
self.AddEquity("AAPL", Resolution.Daily)
|
||||
|
||||
self.es19m20 = self.AddFutureContract(
|
||||
Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
datetime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol
|
||||
|
||||
# Select a future option expiring ITM, and adds it to the algorithm.
|
||||
self.esOption = self.AddFutureOptionContract(
|
||||
list(
|
||||
sorted(
|
||||
[x for x in self.OptionChainProvider.GetOptionContractList(self.es19m20, self.Time) if x.ID.StrikePrice <= 3100.0 and x.ID.OptionRight == OptionRight.Call],
|
||||
key=lambda x: x.ID.StrikePrice,
|
||||
reverse=True
|
||||
)
|
||||
)[0], Resolution.Minute).Symbol
|
||||
|
||||
self.expectedContract = Symbol.CreateOption(self.es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3100.0, datetime(2020, 6, 19))
|
||||
if self.esOption != self.expectedContract:
|
||||
raise AssertionError(f"Contract {self.expectedContract} was not found in the chain");
|
||||
|
||||
self.Schedule.On(self.DateRules.Tomorrow, self.TimeRules.AfterMarketOpen(self.es19m20, 1), self.ScheduledMarketOrder)
|
||||
|
||||
def ScheduledMarketOrder(self):
|
||||
self.MarketOrder(self.esOption, -1)
|
||||
|
||||
def OnData(self, data: Slice):
|
||||
# Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
# the expected time. These assertions detect bug #4872
|
||||
for delisting in data.Delistings.Values:
|
||||
if delisting.Type == DelistingType.Warning:
|
||||
if delisting.Time != datetime(2020, 6, 19):
|
||||
raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
|
||||
if delisting.Type == DelistingType.Delisted:
|
||||
if delisting.Time != datetime(2020, 6, 20):
|
||||
raise AssertionError(f"Delisting happened at unexpected date: {delisting.Time}");
|
||||
|
||||
|
||||
def OnOrderEvent(self, orderEvent: OrderEvent):
|
||||
if orderEvent.Status != OrderStatus.Filled:
|
||||
# There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return
|
||||
|
||||
if not self.Securities.ContainsKey(orderEvent.Symbol):
|
||||
raise AssertionError(f"Order event Symbol not found in Securities collection: {orderEvent.Symbol}")
|
||||
|
||||
security = self.Securities[orderEvent.Symbol]
|
||||
if security.Symbol == self.es19m20:
|
||||
self.AssertFutureOptionOrderExercise(orderEvent, security, self.Securities[self.expectedContract])
|
||||
|
||||
elif security.Symbol == self.expectedContract:
|
||||
self.AssertFutureOptionContractOrder(orderEvent, security)
|
||||
|
||||
else:
|
||||
raise AssertionError(f"Received order event for unknown Symbol: {orderEvent.Symbol}")
|
||||
|
||||
self.Log(f"{orderEvent}");
|
||||
|
||||
def AssertFutureOptionOrderExercise(self, orderEvent: OrderEvent, future: Security, optionContract: Security):
|
||||
if "Assignment" in orderEvent.Message:
|
||||
if orderEvent.FillPrice != 3100.0:
|
||||
raise AssertionError("Option was not assigned at expected strike price (3100)")
|
||||
|
||||
if orderEvent.Direction != OrderDirection.Sell or future.Holdings.Quantity != -1:
|
||||
raise AssertionError(f"Expected Qty: -1 futures holdings for assigned future {future.Symbol}, found {future.Holdings.Quantity}")
|
||||
|
||||
return
|
||||
|
||||
if orderEvent.Direction == OrderDirection.Buy and future.Holdings.Quantity != 0:
|
||||
# We buy back the underlying at expiration, so we expect a neutral position then
|
||||
raise AssertionError(f"Expected no holdings when liquidating future contract {future.Symbol}")
|
||||
|
||||
def AssertFutureOptionContractOrder(self, orderEvent: OrderEvent, option: Security):
|
||||
if orderEvent.Direction == OrderDirection.Sell and option.Holdings.Quantity != -1:
|
||||
raise AssertionError(f"No holdings were created for option contract {option.Symbol}");
|
||||
|
||||
if orderEvent.IsAssignment and option.Holdings.Quantity != 0:
|
||||
raise AssertionError(f"Holdings were found after option contract was assigned: {option.Symbol}")
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
if self.Portfolio.Invested:
|
||||
raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.ID) for i in self.Portfolio.Keys])}")
|
||||
@@ -0,0 +1,119 @@
|
||||
# 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
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import clr
|
||||
from System import *
|
||||
from System.Reflection import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Orders import *
|
||||
from QuantConnect.Securities import *
|
||||
from QuantConnect.Securities.Future import *
|
||||
from QuantConnect import Market
|
||||
|
||||
|
||||
### <summary>
|
||||
### This regression algorithm tests Out of The Money (OTM) future option expiry for short calls.
|
||||
### We expect 1 order from the algorithm, which are:
|
||||
###
|
||||
### * Initial entry, sell ES Call Option (expiring OTM)
|
||||
### - Profit the option premium, since the option was not assigned.
|
||||
###
|
||||
### Additionally, we test delistings for future options and assert that our
|
||||
### portfolio holdings reflect the orders the algorithm has submitted.
|
||||
### </summary>
|
||||
class FutureOptionShortCallOTMExpiryRegressionAlgorithm(QCAlgorithm):
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2020, 1, 5)
|
||||
self.SetEndDate(2020, 6, 30)
|
||||
|
||||
# We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
# which causes delisting events to never be processed, thus leading to options that might never
|
||||
# be exercised until the next data point arrives.
|
||||
self.AddEquity("AAPL", Resolution.Daily)
|
||||
|
||||
self.es19m20 = self.AddFutureContract(
|
||||
Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
datetime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol
|
||||
|
||||
# Select a future option expiring ITM, and adds it to the algorithm.
|
||||
self.esOption = self.AddFutureOptionContract(
|
||||
list(
|
||||
sorted(
|
||||
[x for x in self.OptionChainProvider.GetOptionContractList(self.es19m20, self.Time) if x.ID.StrikePrice >= 3400.0 and x.ID.OptionRight == OptionRight.Call],
|
||||
key=lambda x: x.ID.StrikePrice
|
||||
)
|
||||
)[0], Resolution.Minute).Symbol
|
||||
|
||||
self.expectedContract = Symbol.CreateOption(self.es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3400.0, datetime(2020, 6, 19))
|
||||
if self.esOption != self.expectedContract:
|
||||
raise AssertionError(f"Contract {self.expectedContract} was not found in the chain");
|
||||
|
||||
self.Schedule.On(self.DateRules.Tomorrow, self.TimeRules.AfterMarketOpen(self.es19m20, 1), self.ScheduledMarketOrder)
|
||||
|
||||
def ScheduledMarketOrder(self):
|
||||
self.MarketOrder(self.esOption, -1)
|
||||
|
||||
def OnData(self, data: Slice):
|
||||
# Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
# the expected time. These assertions detect bug #4872
|
||||
for delisting in data.Delistings.Values:
|
||||
if delisting.Type == DelistingType.Warning:
|
||||
if delisting.Time != datetime(2020, 6, 19):
|
||||
raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
|
||||
if delisting.Type == DelistingType.Delisted:
|
||||
if delisting.Time != datetime(2020, 6, 20):
|
||||
raise AssertionError(f"Delisting happened at unexpected date: {delisting.Time}");
|
||||
|
||||
|
||||
def OnOrderEvent(self, orderEvent: OrderEvent):
|
||||
if orderEvent.Status != OrderStatus.Filled:
|
||||
# There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return
|
||||
|
||||
if not self.Securities.ContainsKey(orderEvent.Symbol):
|
||||
raise AssertionError(f"Order event Symbol not found in Securities collection: {orderEvent.Symbol}")
|
||||
|
||||
security = self.Securities[orderEvent.Symbol]
|
||||
if security.Symbol == self.es19m20:
|
||||
raise AssertionError(f"Expected no order events for underlying Symbol {security.Symbol}")
|
||||
|
||||
if security.Symbol == self.expectedContract:
|
||||
self.AssertFutureOptionContractOrder(orderEvent, security)
|
||||
|
||||
else:
|
||||
raise AssertionError(f"Received order event for unknown Symbol: {orderEvent.Symbol}")
|
||||
|
||||
self.Log(f"{orderEvent}");
|
||||
|
||||
def AssertFutureOptionContractOrder(self, orderEvent: OrderEvent, optionContract: Security):
|
||||
if orderEvent.Direction == OrderDirection.Sell and optionContract.Holdings.Quantity != -1:
|
||||
raise AssertionError(f"No holdings were created for option contract {optionContract.Symbol}")
|
||||
|
||||
if orderEvent.Direction == OrderDirection.Buy and optionContract.Holdings.Quantity != 0:
|
||||
raise AssertionError("Expected no options holdings after closing position")
|
||||
|
||||
if orderEvent.IsAssignment:
|
||||
raise AssertionError(f"Assignment was not expected for {orderEvent.Symbol}")
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
if self.Portfolio.Invested:
|
||||
raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.ID) for i in self.Portfolio.Keys])}")
|
||||
@@ -0,0 +1,132 @@
|
||||
# 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
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import clr
|
||||
from System import *
|
||||
from System.Reflection import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Orders import *
|
||||
from QuantConnect.Securities import *
|
||||
from QuantConnect.Securities.Future import *
|
||||
from QuantConnect import Market
|
||||
|
||||
|
||||
### <summary>
|
||||
### This regression algorithm tests In The Money (ITM) future option expiry for short puts.
|
||||
### We expect 3 orders from the algorithm, which are:
|
||||
###
|
||||
### * Initial entry, sell ES Put Option (expiring ITM)
|
||||
### * Option assignment, buy 1 contract of the underlying (ES)
|
||||
### * Future contract expiry, liquidation (sell 1 ES future)
|
||||
###
|
||||
### Additionally, we test delistings for future options and assert that our
|
||||
### portfolio holdings reflect the orders the algorithm has submitted.
|
||||
### </summary>
|
||||
class FutureOptionShortPutITMExpiryRegressionAlgorithm(QCAlgorithm):
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2020, 1, 5)
|
||||
self.SetEndDate(2020, 6, 30)
|
||||
|
||||
# We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
# which causes delisting events to never be processed, thus leading to options that might never
|
||||
# be exercised until the next data point arrives.
|
||||
self.AddEquity("AAPL", Resolution.Daily)
|
||||
|
||||
self.es19m20 = self.AddFutureContract(
|
||||
Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
datetime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol
|
||||
|
||||
# Select a future option expiring ITM, and adds it to the algorithm.
|
||||
self.esOption = self.AddFutureOptionContract(
|
||||
list(
|
||||
sorted(
|
||||
[x for x in self.OptionChainProvider.GetOptionContractList(self.es19m20, self.Time) if x.ID.StrikePrice <= 3400.0 and x.ID.OptionRight == OptionRight.Put],
|
||||
key=lambda x: x.ID.StrikePrice,
|
||||
reverse=True
|
||||
)
|
||||
)[0], Resolution.Minute).Symbol
|
||||
|
||||
self.expectedContract = Symbol.CreateOption(self.es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3400.0, datetime(2020, 6, 19))
|
||||
if self.esOption != self.expectedContract:
|
||||
raise AssertionError(f"Contract {self.expectedContract} was not found in the chain");
|
||||
|
||||
self.Schedule.On(self.DateRules.Tomorrow, self.TimeRules.AfterMarketOpen(self.es19m20, 1), self.ScheduledMarketOrder)
|
||||
|
||||
def ScheduledMarketOrder(self):
|
||||
self.MarketOrder(self.esOption, -1)
|
||||
|
||||
def OnData(self, data: Slice):
|
||||
# Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
# the expected time. These assertions detect bug #4872
|
||||
for delisting in data.Delistings.Values:
|
||||
if delisting.Type == DelistingType.Warning:
|
||||
if delisting.Time != datetime(2020, 6, 19):
|
||||
raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
|
||||
if delisting.Type == DelistingType.Delisted:
|
||||
if delisting.Time != datetime(2020, 6, 20):
|
||||
raise AssertionError(f"Delisting happened at unexpected date: {delisting.Time}");
|
||||
|
||||
|
||||
def OnOrderEvent(self, orderEvent: OrderEvent):
|
||||
if orderEvent.Status != OrderStatus.Filled:
|
||||
# There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return
|
||||
|
||||
if not self.Securities.ContainsKey(orderEvent.Symbol):
|
||||
raise AssertionError(f"Order event Symbol not found in Securities collection: {orderEvent.Symbol}")
|
||||
|
||||
security = self.Securities[orderEvent.Symbol]
|
||||
if security.Symbol == self.es19m20:
|
||||
self.AssertFutureOptionOrderExercise(orderEvent, security, self.Securities[self.expectedContract])
|
||||
|
||||
elif security.Symbol == self.expectedContract:
|
||||
self.AssertFutureOptionContractOrder(orderEvent, security)
|
||||
|
||||
else:
|
||||
raise AssertionError(f"Received order event for unknown Symbol: {orderEvent.Symbol}")
|
||||
|
||||
self.Log(f"{orderEvent}");
|
||||
|
||||
def AssertFutureOptionOrderExercise(self, orderEvent: OrderEvent, future: Security, optionContract: Security):
|
||||
if "Assignment" in orderEvent.Message:
|
||||
if orderEvent.FillPrice != 3400.0:
|
||||
raise AssertionError("Option was not assigned at expected strike price (3400)")
|
||||
|
||||
if orderEvent.Direction != OrderDirection.Buy or future.Holdings.Quantity != 1:
|
||||
raise AssertionError(f"Expected Qty: 1 futures holdings for assigned future {future.Symbol}, found {future.Holdings.Quantity}")
|
||||
|
||||
return
|
||||
|
||||
if orderEvent.Direction == OrderDirection.Sell and future.Holdings.Quantity != 0:
|
||||
# We buy back the underlying at expiration, so we expect a neutral position then
|
||||
raise AssertionError(f"Expected no holdings when liquidating future contract {future.Symbol}")
|
||||
|
||||
def AssertFutureOptionContractOrder(self, orderEvent: OrderEvent, option: Security):
|
||||
if orderEvent.Direction == OrderDirection.Sell and option.Holdings.Quantity != -1:
|
||||
raise AssertionError(f"No holdings were created for option contract {option.Symbol}");
|
||||
|
||||
if orderEvent.IsAssignment and option.Holdings.Quantity != 0:
|
||||
raise AssertionError(f"Holdings were found after option contract was assigned: {option.Symbol}")
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
if self.Portfolio.Invested:
|
||||
raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.ID) for i in self.Portfolio.Keys])}")
|
||||
@@ -0,0 +1,120 @@
|
||||
# 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
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import clr
|
||||
from System import *
|
||||
from System.Reflection import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Orders import *
|
||||
from QuantConnect.Securities import *
|
||||
from QuantConnect.Securities.Future import *
|
||||
from QuantConnect import Market
|
||||
|
||||
|
||||
### <summary>
|
||||
### This regression algorithm tests Out of The Money (OTM) future option expiry for short puts.
|
||||
### We expect 1 order from the algorithm, which are:
|
||||
###
|
||||
### * Initial entry, sell ES Put Option (expiring OTM)
|
||||
### - Profit the option premium, since the option was not assigned.
|
||||
###
|
||||
### Additionally, we test delistings for future options and assert that our
|
||||
### portfolio holdings reflect the orders the algorithm has submitted.
|
||||
### </summary>
|
||||
class FutureOptionShortPutOTMExpiryRegressionAlgorithm(QCAlgorithm):
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2020, 1, 5)
|
||||
self.SetEndDate(2020, 6, 30)
|
||||
|
||||
# We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
|
||||
# which causes delisting events to never be processed, thus leading to options that might never
|
||||
# be exercised until the next data point arrives.
|
||||
self.AddEquity("AAPL", Resolution.Daily)
|
||||
|
||||
self.es19m20 = self.AddFutureContract(
|
||||
Symbol.CreateFuture(
|
||||
Futures.Indices.SP500EMini,
|
||||
Market.CME,
|
||||
datetime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol
|
||||
|
||||
# Select a future option expiring ITM, and adds it to the algorithm.
|
||||
self.esOption = self.AddFutureOptionContract(
|
||||
list(
|
||||
sorted(
|
||||
[x for x in self.OptionChainProvider.GetOptionContractList(self.es19m20, self.Time) if x.ID.StrikePrice <= 3000.0 and x.ID.OptionRight == OptionRight.Put],
|
||||
key=lambda x: x.ID.StrikePrice,
|
||||
reverse=True
|
||||
)
|
||||
)[0], Resolution.Minute).Symbol
|
||||
|
||||
self.expectedContract = Symbol.CreateOption(self.es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3000.0, datetime(2020, 6, 19))
|
||||
if self.esOption != self.expectedContract:
|
||||
raise AssertionError(f"Contract {self.expectedContract} was not found in the chain");
|
||||
|
||||
self.Schedule.On(self.DateRules.Tomorrow, self.TimeRules.AfterMarketOpen(self.es19m20, 1), self.ScheduledMarketOrder)
|
||||
|
||||
def ScheduledMarketOrder(self):
|
||||
self.MarketOrder(self.esOption, -1)
|
||||
|
||||
def OnData(self, data: Slice):
|
||||
# Assert delistings, so that we can make sure that we receive the delisting warnings at
|
||||
# the expected time. These assertions detect bug #4872
|
||||
for delisting in data.Delistings.Values:
|
||||
if delisting.Type == DelistingType.Warning:
|
||||
if delisting.Time != datetime(2020, 6, 19):
|
||||
raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.Time}");
|
||||
|
||||
if delisting.Type == DelistingType.Delisted:
|
||||
if delisting.Time != datetime(2020, 6, 20):
|
||||
raise AssertionError(f"Delisting happened at unexpected date: {delisting.Time}");
|
||||
|
||||
|
||||
def OnOrderEvent(self, orderEvent: OrderEvent):
|
||||
if orderEvent.Status != OrderStatus.Filled:
|
||||
# There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
||||
return
|
||||
|
||||
if not self.Securities.ContainsKey(orderEvent.Symbol):
|
||||
raise AssertionError(f"Order event Symbol not found in Securities collection: {orderEvent.Symbol}")
|
||||
|
||||
security = self.Securities[orderEvent.Symbol]
|
||||
if security.Symbol == self.es19m20:
|
||||
raise AssertionError(f"Expected no order events for underlying Symbol {security.Symbol}")
|
||||
|
||||
if security.Symbol == self.expectedContract:
|
||||
self.AssertFutureOptionContractOrder(orderEvent, security)
|
||||
|
||||
else:
|
||||
raise AssertionError(f"Received order event for unknown Symbol: {orderEvent.Symbol}")
|
||||
|
||||
self.Log(f"{orderEvent}");
|
||||
|
||||
def AssertFutureOptionContractOrder(self, orderEvent: OrderEvent, optionContract: Security):
|
||||
if orderEvent.Direction == OrderDirection.Sell and optionContract.Holdings.Quantity != -1:
|
||||
raise AssertionError(f"No holdings were created for option contract {optionContract.Symbol}")
|
||||
|
||||
if orderEvent.Direction == OrderDirection.Buy and optionContract.Holdings.Quantity != 0:
|
||||
raise AssertionError("Expected no options holdings after closing position")
|
||||
|
||||
if orderEvent.IsAssignment:
|
||||
raise AssertionError(f"Assignment was not expected for {orderEvent.Symbol}")
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
if self.Portfolio.Invested:
|
||||
raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.ID) for i in self.Portfolio.Keys])}")
|
||||
@@ -46,6 +46,8 @@
|
||||
<ItemGroup>
|
||||
<Content Include="AccumulativeInsightPortfolioRegressionAlgorithm.py" />
|
||||
<Content Include="AddAlphaModelAlgorithm.py" />
|
||||
<Content Include="AddFutureOptionContractDataStreamingRegressionAlgorithm.py" />
|
||||
<Content Include="AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm.py" />
|
||||
<Content Include="AddOptionContractExpiresRegressionAlgorithm.py" />
|
||||
<Content Include="AddOptionContractFromUniverseRegressionAlgorithm.py" />
|
||||
<Content Include="AddRiskManagementAlgorithm.py" />
|
||||
@@ -65,6 +67,7 @@
|
||||
<Content Include="Alphas\VIXDualThrustAlpha.py" />
|
||||
<Content Include="AltData\CachedAlternativeDataAlgorithm.py" />
|
||||
<Content Include="AltData\BenzingaNewsAlgorithm.py" />
|
||||
<Content Include="AltData\QuiverWallStreetBetsDataAlgorithm.py" />
|
||||
<Content Include="AltData\SECReport8KAlgorithm.py" />
|
||||
<Content Include="AltData\SmartInsiderTransactionAlgorithm.py" />
|
||||
<Content Include="AltData\USTreasuryYieldCurveRateAlgorithm.py" />
|
||||
@@ -91,11 +94,21 @@
|
||||
<Content Include="CustomConsolidatorRegressionAlgorithm.py" />
|
||||
<Content Include="CustomDataAddDataOnSecuritiesChangedRegressionAlgorithm.py" />
|
||||
<Content Include="CustomDataAddDataCoarseSelectionRegressionAlgorithm.py" />
|
||||
<None Include="CustomBuyingPowerModelAlgorithm.py" />
|
||||
<Content Include="DynamicSecurityDataAlgorithm.py" />
|
||||
<Content Include="ConfidenceWeightedFrameworkAlgorithm.py" />
|
||||
<Content Include="ExtendedMarketTradingRegressionAlgorithm.py" />
|
||||
<Content Include="FilterUniverseRegressionAlgorithm.py" />
|
||||
<Content Include="FineFundamentalFilteredUniverseRegressionAlgorithm.py" />
|
||||
<Content Include="FutureOptionBuySellCallIntradayRegressionAlgorithm.py" />
|
||||
<Content Include="FutureOptionCallITMExpiryRegressionAlgorithm.py" />
|
||||
<Content Include="FutureOptionCallOTMExpiryRegressionAlgorithm.py" />
|
||||
<Content Include="FutureOptionPutITMExpiryRegressionAlgorithm.py" />
|
||||
<Content Include="FutureOptionPutOTMExpiryRegressionAlgorithm.py" />
|
||||
<Content Include="FutureOptionShortCallITMExpiryRegressionAlgorithm.py" />
|
||||
<Content Include="FutureOptionShortCallOTMExpiryRegressionAlgorithm.py" />
|
||||
<Content Include="FutureOptionShortPutITMExpiryRegressionAlgorithm.py" />
|
||||
<Content Include="FutureOptionShortPutOTMExpiryRegressionAlgorithm.py" />
|
||||
<Content Include="KerasNeuralNetworkAlgorithm.py" />
|
||||
<Content Include="CustomDataUsingMapFileRegressionAlgorithm.py" />
|
||||
<Content Include="LiquidETFUniverseFrameworkAlgorithm.py" />
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
<ProjectHome>.</ProjectHome>
|
||||
<StartupFile>
|
||||
</StartupFile>
|
||||
<SearchPath>stubs</SearchPath>
|
||||
<SearchPath>
|
||||
</SearchPath>
|
||||
<WorkingDirectory>.</WorkingDirectory>
|
||||
<OutputPath>.</OutputPath>
|
||||
<Name>QuantConnect.Algorithm.PythonTools</Name>
|
||||
@@ -45,6 +46,7 @@
|
||||
<Compile Include="ConstituentsQC500GeneratorAlgorithm.py" />
|
||||
<Compile Include="ConstituentsUniverseRegressionAlgorithm.py" />
|
||||
<Compile Include="ConvertToFrameworkAlgorithm.py" />
|
||||
<Compile Include="CustomBuyingPowerModelAlgorithm.py" />
|
||||
<Compile Include="CustomDataAddDataCoarseSelectionRegressionAlgorithm.py" />
|
||||
<Compile Include="CustomDataAddDataOnSecuritiesChangedRegressionAlgorithm.py" />
|
||||
<Compile Include="CustomDataAddDataRegressionAlgorithm.py" />
|
||||
|
||||
@@ -1,6 +1,24 @@
|
||||
QuantConnect Python Algorithm Project:
|
||||
=============
|
||||
|
||||
## Local Python Autocomplete
|
||||
To enable autocomplete for your local Python IDE, install the `quantconnect-stubs` package from PyPI using the following command:
|
||||
```
|
||||
pip install quantconnect-stubs
|
||||
```
|
||||
|
||||
To update your autocomplete to the latest version, you can run the following command:
|
||||
```
|
||||
pip install --upgrade quantconnect-stubs
|
||||
```
|
||||
|
||||
Copy and paste the imports found [here](#python-autocomplete-imports) to the top of your project file to enable autocomplete.
|
||||
|
||||
In addition, you can use [Skylight](https://www.quantconnect.com/skylight) to automatically sync local changes to the cloud.
|
||||
|
||||
------
|
||||
|
||||
## Running LEAN Locally with Python
|
||||
Before we enable python support, follow the [installation instructions](https://github.com/QuantConnect/Lean#installation-instructions) to get LEAN running C# algorithms in your machine.
|
||||
|
||||
### Install Python 3.6:
|
||||
@@ -15,25 +33,25 @@ Before we enable python support, follow the [installation instructions](https://
|
||||
- Value of the variable: python installation path.
|
||||
4. Install [pandas=0.25.3](https://pandas.pydata.org/) and its [dependencies](https://pandas.pydata.org/pandas-docs/stable/install.html#dependencies).
|
||||
5. Install [wrapt=1.11.2](https://pypi.org/project/wrapt/) module.
|
||||
6. Reboot computer to ensure changes are propogated.
|
||||
6. Install [pyarrow=1.0.1](https://arrow.apache.org/install/) module.
|
||||
7. Reboot computer to ensure changes are propagated.
|
||||
|
||||
#### [macOS](https://github.com/QuantConnect/Lean#macos)
|
||||
|
||||
1. Use the macOS x86-64 package installer from [Anaconda](https://repo.anaconda.com/archive/Anaconda3-5.2.0-MacOSX-x86_64.pkg) and follow "[Installing on macOS](https://docs.anaconda.com/anaconda/install/mac-os)" instructions from Anaconda documentation page.
|
||||
2. Install [pandas=0.25.3](https://pandas.pydata.org/) and its [dependencies](https://pandas.pydata.org/pandas-docs/stable/install.html#dependencies).
|
||||
3. Install [wrapt=1.11.2](https://pypi.org/project/wrapt/) module.
|
||||
4. Install [pyarrow=1.0.1](https://arrow.apache.org/install/) module.
|
||||
|
||||
*Note:* If you encounter the "System.DllNotFoundException: python3.6m" runtime error when running Python algorithms on macOS:
|
||||
1. Find `libpython3.6m.dylib` in your Python installation folder. If you installed Python with Anaconda, it may be find at
|
||||
```
|
||||
/Users/{your_user_name}/anaconda3/lib/libpython3.6m.dylib
|
||||
```
|
||||
2. Open `Lean/Launcher/bin/Debug/Python.Runtime.dll.config`, add the following text and save:
|
||||
```
|
||||
<configuration>
|
||||
<dllmap dll="python3.6m" target="{the path in step 1 including libpython3.6m.dylib}" os="!windows"/>
|
||||
</configuration>
|
||||
```
|
||||
1. Find `libpython3.6m.dylib` in your Python installation folder. If you installed Python with Anaconda, it may be found at
|
||||
```
|
||||
/Users/{your_user_name}/anaconda3/lib/libpython3.6m.dylib
|
||||
```
|
||||
2. Open `Lean/Launcher/bin/Debug/Python.Runtime.dll.config`, add the following text under `<configuration> ... </configuration>` and save:
|
||||
```
|
||||
<dllmap dll="python3.6m" target="{the path in step 1 including libpython3.6m.dylib}" os="osx"/>
|
||||
```
|
||||
Note: Specify the install of v3.6.8 _exactly_, i.e. if with conda `conda install python=3.6.8` as this is a known compatible version and other versions may have issues as of this writing.
|
||||
|
||||
#### [Linux](https://github.com/QuantConnect/Lean#linux-debian-ubuntu)
|
||||
@@ -48,25 +66,41 @@ conda update -y python conda pip
|
||||
conda install -y cython=0.29.11
|
||||
conda install -y pandas=0.25.3
|
||||
conda install -y wrapt=1.11.2
|
||||
pip install pyarrow==1.0.1
|
||||
```
|
||||
|
||||
*Note:* There is a [known issue](https://github.com/pythonnet/pythonnet/issues/609) with python 3.6.5 that prevents pythonnet installation, please upgrade python to version 3.6.8:
|
||||
```
|
||||
conda install -y python=3.6.8
|
||||
```
|
||||
*Note 1:* There is a [known issue](https://github.com/pythonnet/pythonnet/issues/609) with python 3.6.5 that prevents pythonnet installation, please upgrade python to version 3.6.8:
|
||||
```
|
||||
conda install -y python=3.6.8
|
||||
```
|
||||
|
||||
*Note 2:* If you encounter the "System.DllNotFoundException: python3.6m" runtime error when running Python algorithms on Linux:
|
||||
1. Find `libpython3.6m.so` in your Python installation folder. If you installed Python with Miniconda, it may be found at
|
||||
```
|
||||
/home/{your_user_name}/miniconda3/envs/{qc_environment}/lib/libpython3.6m.so
|
||||
```
|
||||
Note that you can create a new virtual environment with all required dependencies by executing:
|
||||
```
|
||||
conda create -n qc_environment python=3.6.8 cython=0.29.11 pandas=0.25.3 wrapt=1.11.2
|
||||
|
||||
```
|
||||
2. Open `Lean/Launcher/bin/Debug/Python.Runtime.dll.config`, add the following text under `<configuration> ... </configuration>` and save:
|
||||
```
|
||||
<dllmap dll="python3.6m" target="{the path in step 1 including libpython3.6m.so}" os="linux"/>
|
||||
```
|
||||
### Run python algorithm
|
||||
1. Update the [config](https://github.com/QuantConnect/Lean/blob/master/Launcher/config.json) to run the python algorithm:
|
||||
```json
|
||||
"algorithm-type-name": "BasicTemplateAlgorithm",
|
||||
"algorithm-language": "Python",
|
||||
"algorithm-location": "../../../Algorithm.Python/BasicTemplateAlgorithm.py",
|
||||
```
|
||||
```json
|
||||
"algorithm-type-name": "BasicTemplateAlgorithm",
|
||||
"algorithm-language": "Python",
|
||||
"algorithm-location": "../../../Algorithm.Python/BasicTemplateAlgorithm.py",
|
||||
```
|
||||
2. Rebuild LEAN.
|
||||
3. Run LEAN. You should see the same result of the C# algorithm you tested earlier.
|
||||
|
||||
___
|
||||
#### Python.Runtime.dll compilation
|
||||
|
||||
### Python.NET development - Python.Runtime.dll compilation
|
||||
LEAN users do **not** need to compile `Python.Runtime.dll`. The information below is targeted to developers who wish to improve it.
|
||||
|
||||
Download [QuantConnect/pythonnet](https://github.com/QuantConnect/pythonnet/) github clone or downloading the zip. If downloading the zip - unzip to a local pathway.
|
||||
@@ -87,3 +121,45 @@ msbuild pythonnet.sln /nologo /v:quiet /t:Clean;Rebuild /p:Platform=x64 /p:Pytho
|
||||
```
|
||||
msbuild pythonnet.sln /nologo /v:quiet /t:Clean;Rebuild /p:Platform=x64 /p:PythonInteropFile="interop36m.cs" /p:Configuration=ReleaseMono /p:DefineConstants="PYTHON36,PYTHON3,UCS4,MONO_LINUX,PYTHON_WITH_PYMALLOC"
|
||||
```
|
||||
|
||||
# Python Autocomplete Imports
|
||||
Copy and paste these imports to the top of your Python file to enable a development experience equal to the cloud (these imports are exactly the same as the ones used in the QuantConnect Terminal).
|
||||
|
||||
```python
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Parameters import *
|
||||
from QuantConnect.Benchmarks import *
|
||||
from QuantConnect.Brokerages import *
|
||||
from QuantConnect.Util import *
|
||||
from QuantConnect.Interfaces import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Algorithm.Framework import *
|
||||
from QuantConnect.Algorithm.Framework.Selection import *
|
||||
from QuantConnect.Algorithm.Framework.Alphas import *
|
||||
from QuantConnect.Algorithm.Framework.Portfolio import *
|
||||
from QuantConnect.Algorithm.Framework.Execution import *
|
||||
from QuantConnect.Algorithm.Framework.Risk import *
|
||||
from QuantConnect.Indicators import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Consolidators import *
|
||||
from QuantConnect.Data.Custom import *
|
||||
from QuantConnect.Data.Fundamental import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Data.UniverseSelection import *
|
||||
from QuantConnect.Notifications import *
|
||||
from QuantConnect.Orders import *
|
||||
from QuantConnect.Orders.Fees import *
|
||||
from QuantConnect.Orders.Fills import *
|
||||
from QuantConnect.Orders.Slippage import *
|
||||
from QuantConnect.Scheduling import *
|
||||
from QuantConnect.Securities import *
|
||||
from QuantConnect.Securities.Equity import *
|
||||
from QuantConnect.Securities.Forex import *
|
||||
from QuantConnect.Securities.Interfaces import *
|
||||
from datetime import date, datetime, timedelta
|
||||
from QuantConnect.Python import *
|
||||
from QuantConnect.Storage import *
|
||||
QCAlgorithmFramework = QCAlgorithm
|
||||
QCAlgorithmFrameworkBridge = QCAlgorithm
|
||||
```
|
||||
|
||||
|
||||
@@ -1,402 +0,0 @@
|
||||
# encoding: utf-8
|
||||
# module QuantConnect.API calls itself API
|
||||
# from QuantConnect.Common, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null
|
||||
# by generator 1.145
|
||||
# no doc
|
||||
|
||||
# imports
|
||||
import datetime
|
||||
import Newtonsoft.Json
|
||||
import Newtonsoft.Json.Linq
|
||||
import QuantConnect
|
||||
import QuantConnect.API
|
||||
import QuantConnect.Packets
|
||||
import System
|
||||
import typing
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class BaseLiveAlgorithmSettings(System.object):
|
||||
"""
|
||||
Base class for settings that must be configured per Brokerage to create new algorithms via the API.
|
||||
|
||||
BaseLiveAlgorithmSettings(user: str, password: str, environment: BrokerageEnvironment, account: str)
|
||||
BaseLiveAlgorithmSettings(user: str, password: str)
|
||||
BaseLiveAlgorithmSettings(environment: BrokerageEnvironment, account: str)
|
||||
BaseLiveAlgorithmSettings(account: str)
|
||||
"""
|
||||
@typing.overload
|
||||
def __init__(self, user: str, password: str, environment: QuantConnect.BrokerageEnvironment, account: str) -> QuantConnect.API.BaseLiveAlgorithmSettings:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, user: str, password: str) -> QuantConnect.API.BaseLiveAlgorithmSettings:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, environment: QuantConnect.BrokerageEnvironment, account: str) -> QuantConnect.API.BaseLiveAlgorithmSettings:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, account: str) -> QuantConnect.API.BaseLiveAlgorithmSettings:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.API.BaseLiveAlgorithmSettings:
|
||||
pass
|
||||
|
||||
Account: str
|
||||
|
||||
Environment: QuantConnect.BrokerageEnvironment
|
||||
|
||||
Id: str
|
||||
|
||||
Password: str
|
||||
|
||||
User: str
|
||||
|
||||
|
||||
|
||||
class CreatedNode(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Rest api response wrapper for node/create, reads in the nodes information into a
|
||||
node object
|
||||
|
||||
CreatedNode()
|
||||
"""
|
||||
Node: QuantConnect.API.Node
|
||||
|
||||
|
||||
|
||||
class DefaultLiveAlgorithmSettings(QuantConnect.API.BaseLiveAlgorithmSettings):
|
||||
"""
|
||||
Default live algorithm settings
|
||||
|
||||
DefaultLiveAlgorithmSettings(user: str, password: str, environment: BrokerageEnvironment, account: str)
|
||||
"""
|
||||
def __init__(self, user: str, password: str, environment: QuantConnect.BrokerageEnvironment, account: str) -> QuantConnect.API.DefaultLiveAlgorithmSettings:
|
||||
pass
|
||||
|
||||
|
||||
class Dividend(System.object):
|
||||
"""
|
||||
Dividend returned from the api
|
||||
|
||||
Dividend()
|
||||
"""
|
||||
Date: datetime.datetime
|
||||
|
||||
DividendPerShare: float
|
||||
|
||||
ReferencePrice: float
|
||||
|
||||
Symbol: QuantConnect.Symbol
|
||||
|
||||
SymbolID: str
|
||||
|
||||
|
||||
|
||||
class DividendList(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Collection container for a list of dividend objects
|
||||
|
||||
DividendList()
|
||||
"""
|
||||
Dividends: typing.List[QuantConnect.API.Dividend]
|
||||
|
||||
|
||||
|
||||
class FXCMLiveAlgorithmSettings(QuantConnect.API.BaseLiveAlgorithmSettings):
|
||||
"""
|
||||
Algorithm setting for trading with FXCM
|
||||
|
||||
FXCMLiveAlgorithmSettings(user: str, password: str, environment: BrokerageEnvironment, account: str)
|
||||
"""
|
||||
def __init__(self, user: str, password: str, environment: QuantConnect.BrokerageEnvironment, account: str) -> QuantConnect.API.FXCMLiveAlgorithmSettings:
|
||||
pass
|
||||
|
||||
|
||||
class InteractiveBrokersLiveAlgorithmSettings(QuantConnect.API.BaseLiveAlgorithmSettings):
|
||||
"""
|
||||
Live algorithm settings for trading with Interactive Brokers
|
||||
|
||||
InteractiveBrokersLiveAlgorithmSettings(user: str, password: str, account: str)
|
||||
"""
|
||||
def __init__(self, user: str, password: str, account: str) -> QuantConnect.API.InteractiveBrokersLiveAlgorithmSettings:
|
||||
pass
|
||||
|
||||
|
||||
class LiveAlgorithm(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Live algorithm instance result from the QuantConnect Rest API.
|
||||
|
||||
LiveAlgorithm()
|
||||
"""
|
||||
Brokerage: str
|
||||
DeployId: str
|
||||
Error: str
|
||||
Launched: datetime.datetime
|
||||
ProjectId: int
|
||||
Status: QuantConnect.AlgorithmStatus
|
||||
Stopped: typing.Optional[datetime.datetime]
|
||||
Subscription: str
|
||||
|
||||
class LiveAlgorithmApiSettingsWrapper(System.object):
|
||||
"""
|
||||
Helper class to put BaseLiveAlgorithmSettings in proper format.
|
||||
|
||||
LiveAlgorithmApiSettingsWrapper(projectId: int, compileId: str, serverType: str, settings: BaseLiveAlgorithmSettings, version: str)
|
||||
"""
|
||||
def __init__(self, projectId: int, compileId: str, serverType: str, settings: QuantConnect.API.BaseLiveAlgorithmSettings, version: str) -> QuantConnect.API.LiveAlgorithmApiSettingsWrapper:
|
||||
pass
|
||||
|
||||
Brokerage: QuantConnect.API.BaseLiveAlgorithmSettings
|
||||
|
||||
CompileId: str
|
||||
|
||||
ProjectId: int
|
||||
|
||||
ServerType: str
|
||||
|
||||
VersionId: str
|
||||
|
||||
|
||||
|
||||
class LiveAlgorithmResults(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Details a live algorithm from the "live/read" Api endpoint
|
||||
|
||||
LiveAlgorithmResults()
|
||||
"""
|
||||
LiveResults: QuantConnect.API.LiveResultsData
|
||||
|
||||
|
||||
|
||||
class LiveAlgorithmResultsJsonConverter(Newtonsoft.Json.JsonConverter):
|
||||
"""
|
||||
Custom JsonConverter for LiveResults data for live algorithms
|
||||
|
||||
LiveAlgorithmResultsJsonConverter()
|
||||
"""
|
||||
def CanConvert(self, objectType: type) -> bool:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def CreateLiveResultsFromJObject(jObject: Newtonsoft.Json.Linq.JObject) -> QuantConnect.API.LiveAlgorithmResults:
|
||||
pass
|
||||
|
||||
def ReadJson(self, reader: Newtonsoft.Json.JsonReader, objectType: type, existingValue: object, serializer: Newtonsoft.Json.JsonSerializer) -> object:
|
||||
pass
|
||||
|
||||
def WriteJson(self, writer: Newtonsoft.Json.JsonWriter, value: object, serializer: Newtonsoft.Json.JsonSerializer) -> None:
|
||||
pass
|
||||
|
||||
CanWrite: bool
|
||||
|
||||
|
||||
|
||||
class LiveList(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
List of the live algorithms running which match the requested status
|
||||
|
||||
LiveList()
|
||||
"""
|
||||
Algorithms: typing.List[QuantConnect.API.LiveAlgorithm]
|
||||
|
||||
class LiveLog(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Logs from a live algorithm
|
||||
|
||||
LiveLog()
|
||||
"""
|
||||
Logs: typing.List[str]
|
||||
|
||||
|
||||
|
||||
class LiveResultsData(System.object):
|
||||
"""
|
||||
Holds information about the state and operation of the live running algorithm
|
||||
|
||||
LiveResultsData()
|
||||
"""
|
||||
Resolution: QuantConnect.Resolution
|
||||
|
||||
Results: QuantConnect.Packets.LiveResult
|
||||
|
||||
Version: int
|
||||
|
||||
|
||||
|
||||
class Node(System.object):
|
||||
"""
|
||||
Node class built for API endpoints nodes/read and nodes/create.
|
||||
Converts JSON properties from API response into data members for the class.
|
||||
Contains all relevant information on a Node to interact through API endpoints.
|
||||
|
||||
Node()
|
||||
"""
|
||||
Busy: bool
|
||||
|
||||
CpuCount: int
|
||||
|
||||
Description: str
|
||||
|
||||
Id: str
|
||||
|
||||
Name: str
|
||||
|
||||
Prices: QuantConnect.API.NodePrices
|
||||
|
||||
ProjectName: str
|
||||
|
||||
Ram: float
|
||||
|
||||
SKU: str
|
||||
|
||||
Speed: float
|
||||
|
||||
UsedBy: str
|
||||
|
||||
|
||||
|
||||
class NodeList(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Rest api response wrapper for node/read, contains sets of node lists for each
|
||||
target environment. List are composed of QuantConnect.API.Node objects.
|
||||
|
||||
NodeList()
|
||||
"""
|
||||
BacktestNodes: typing.List[QuantConnect.API.Node]
|
||||
LiveNodes: typing.List[QuantConnect.API.Node]
|
||||
ResearchNodes: typing.List[QuantConnect.API.Node]
|
||||
|
||||
class NodePrices(System.object):
|
||||
"""
|
||||
Class for deserializing node prices from node object
|
||||
|
||||
NodePrices()
|
||||
"""
|
||||
Monthly: int
|
||||
|
||||
Yearly: int
|
||||
|
||||
|
||||
|
||||
class NodeType(System.Enum, System.IConvertible, System.IFormattable, System.IComparable):
|
||||
"""
|
||||
NodeTypes enum for all possible options of target environments
|
||||
Used in conjuction with SKU class as a NodeType is a required parameter for SKU
|
||||
|
||||
enum NodeType, values: Backtest (0), Live (2), Research (1)
|
||||
"""
|
||||
value__: int
|
||||
Backtest: 'NodeType'
|
||||
Live: 'NodeType'
|
||||
Research: 'NodeType'
|
||||
|
||||
|
||||
class OandaLiveAlgorithmSettings(QuantConnect.API.BaseLiveAlgorithmSettings):
|
||||
"""
|
||||
Live algorithm settings for trading with Oanda
|
||||
|
||||
OandaLiveAlgorithmSettings(accessToken: str, environment: BrokerageEnvironment, account: str)
|
||||
"""
|
||||
def __init__(self, accessToken: str, environment: QuantConnect.BrokerageEnvironment, account: str) -> QuantConnect.API.OandaLiveAlgorithmSettings:
|
||||
pass
|
||||
|
||||
AccessToken: str
|
||||
|
||||
DateIssued: str
|
||||
|
||||
|
||||
|
||||
class Prices(System.object):
|
||||
"""
|
||||
Prices rest response wrapper
|
||||
|
||||
Prices()
|
||||
"""
|
||||
Price: float
|
||||
|
||||
Symbol: QuantConnect.Symbol
|
||||
|
||||
SymbolID: str
|
||||
|
||||
Updated: datetime.datetime
|
||||
|
||||
|
||||
class PricesList(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Collection container for a list of prices objects
|
||||
|
||||
PricesList()
|
||||
"""
|
||||
Prices: typing.List[QuantConnect.API.Prices]
|
||||
|
||||
class SKU(System.object):
|
||||
"""
|
||||
Class for generating a SKU for a node with a given configuration
|
||||
Every SKU is made up of 3 variables:
|
||||
- Target environment (L for live, B for Backtest, R for Research)
|
||||
- CPU core count
|
||||
- Dedicated RAM (GB)
|
||||
|
||||
SKU(cores: int, memory: int, target: NodeType)
|
||||
"""
|
||||
def ToString(self) -> str:
|
||||
pass
|
||||
|
||||
def __init__(self, cores: int, memory: int, target: QuantConnect.API.NodeType) -> QuantConnect.API.SKU:
|
||||
pass
|
||||
|
||||
Cores: int
|
||||
Memory: int
|
||||
Target: QuantConnect.API.NodeType
|
||||
|
||||
class Split(System.object):
|
||||
"""
|
||||
Split returned from the api
|
||||
|
||||
Split()
|
||||
"""
|
||||
Date: datetime.datetime
|
||||
|
||||
ReferencePrice: float
|
||||
|
||||
SplitFactor: float
|
||||
|
||||
Symbol: QuantConnect.Symbol
|
||||
|
||||
SymbolID: str
|
||||
|
||||
|
||||
|
||||
class SplitList(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Collection container for a list of split objects
|
||||
|
||||
SplitList()
|
||||
"""
|
||||
Splits: typing.List[QuantConnect.API.Split]
|
||||
|
||||
|
||||
|
||||
class TradierLiveAlgorithmSettings(QuantConnect.API.BaseLiveAlgorithmSettings):
|
||||
"""
|
||||
Live algorithm settings for trading with Tradier
|
||||
|
||||
TradierLiveAlgorithmSettings(accessToken: str, dateIssued: str, refreshToken: str, account: str)
|
||||
"""
|
||||
def __init__(self, accessToken: str, dateIssued: str, refreshToken: str, account: str) -> QuantConnect.API.TradierLiveAlgorithmSettings:
|
||||
pass
|
||||
|
||||
AccessToken: str
|
||||
|
||||
DateIssued: str
|
||||
|
||||
Lifetime: str
|
||||
|
||||
RefreshToken: str
|
||||
|
||||
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
# encoding: utf-8
|
||||
# module QuantConnect.Algorithm.Framework.Alphas.Analysis.Functions calls itself Functions
|
||||
# from QuantConnect.Common, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null
|
||||
# by generator 1.145
|
||||
# no doc
|
||||
|
||||
# imports
|
||||
import datetime
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm.Framework.Alphas.Analysis
|
||||
import typing
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class BinaryInsightScoreFunction(System.object, QuantConnect.Algorithm.Framework.Alphas.Analysis.IInsightScoreFunction):
|
||||
"""
|
||||
Defines a scoring function that always returns 1 or 0.
|
||||
You're either right or you're wrong with this one :)
|
||||
|
||||
BinaryInsightScoreFunction()
|
||||
"""
|
||||
def Evaluate(self, context: QuantConnect.Algorithm.Framework.Alphas.Analysis.InsightAnalysisContext, scoreType: QuantConnect.Algorithm.Framework.Alphas.InsightScoreType) -> float:
|
||||
pass
|
||||
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
# encoding: utf-8
|
||||
# module QuantConnect.Algorithm.Framework.Alphas.Analysis.Providers calls itself Providers
|
||||
# from QuantConnect.Common, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null
|
||||
# by generator 1.145
|
||||
# no doc
|
||||
|
||||
# imports
|
||||
import datetime
|
||||
import QuantConnect
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm.Framework.Alphas.Analysis
|
||||
import QuantConnect.Algorithm.Framework.Alphas.Analysis.Providers
|
||||
import QuantConnect.Interfaces
|
||||
import typing
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class AlgorithmSecurityValuesProvider(System.object, QuantConnect.Algorithm.Framework.Alphas.Analysis.ISecurityValuesProvider):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Securities.ISecurityProvider that uses the QuantConnect.Securities.SecurityManager
|
||||
to get the price for the specified symbols
|
||||
|
||||
AlgorithmSecurityValuesProvider(algorithm: IAlgorithm)
|
||||
"""
|
||||
def GetAllValues(self) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.ReadOnlySecurityValuesCollection:
|
||||
pass
|
||||
|
||||
def GetValues(self, symbol: QuantConnect.Symbol) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.SecurityValues:
|
||||
pass
|
||||
|
||||
def __init__(self, algorithm: QuantConnect.Interfaces.IAlgorithm) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.Providers.AlgorithmSecurityValuesProvider:
|
||||
pass
|
||||
|
||||
|
||||
class DefaultInsightScoreFunctionProvider(System.object, QuantConnect.Algorithm.Framework.Alphas.Analysis.IInsightScoreFunctionProvider):
|
||||
"""
|
||||
Default implementation of QuantConnect.Algorithm.Framework.Alphas.Analysis.IInsightScoreFunctionProvider always returns the QuantConnect.Algorithm.Framework.Alphas.Analysis.Functions.BinaryInsightScoreFunction
|
||||
|
||||
DefaultInsightScoreFunctionProvider()
|
||||
"""
|
||||
def GetScoreFunction(self, insightType: QuantConnect.Algorithm.Framework.Alphas.InsightType, scoreType: QuantConnect.Algorithm.Framework.Alphas.InsightScoreType) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.IInsightScoreFunction:
|
||||
pass
|
||||
|
||||
|
||||
@@ -1,210 +0,0 @@
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Algorithm.Framework.Alphas.Analysis
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect
|
||||
import datetime
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class IInsightManager(System.IDisposable):
|
||||
""" Encapsulates the storage and on-line scoring of insights. """
|
||||
def AddExtension(self, extension: QuantConnect.Algorithm.Framework.Alphas.IInsightManagerExtension) -> None:
|
||||
pass
|
||||
|
||||
def InitializeExtensionsForRange(self, start: datetime.datetime, end: datetime.datetime, current: datetime.datetime) -> None:
|
||||
pass
|
||||
|
||||
def RemoveInsights(self, insightIds: typing.List[System.Guid]) -> None:
|
||||
pass
|
||||
|
||||
def Step(self, frontierTimeUtc: datetime.datetime, securityValuesCollection: QuantConnect.Algorithm.Framework.Alphas.Analysis.ReadOnlySecurityValuesCollection, generatedInsights: QuantConnect.Algorithm.Framework.Alphas.GeneratedInsightsCollection) -> None:
|
||||
pass
|
||||
|
||||
AllInsights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]
|
||||
|
||||
ClosedInsights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]
|
||||
|
||||
OpenInsights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]
|
||||
|
||||
|
||||
|
||||
class IInsightScoreFunction:
|
||||
"""
|
||||
Defines a function used to determine how correct a particular insight is.
|
||||
The result of calling QuantConnect.Algorithm.Framework.Alphas.Analysis.IInsightScoreFunction.Evaluate(QuantConnect.Algorithm.Framework.Alphas.Analysis.InsightAnalysisContext,QuantConnect.Algorithm.Framework.Alphas.InsightScoreType) is expected to be within the range [0, 1]
|
||||
where 0 is completely wrong and 1 is completely right
|
||||
"""
|
||||
def Evaluate(self, context: QuantConnect.Algorithm.Framework.Alphas.Analysis.InsightAnalysisContext, scoreType: QuantConnect.Algorithm.Framework.Alphas.InsightScoreType) -> float:
|
||||
pass
|
||||
|
||||
|
||||
class IInsightScoreFunctionProvider:
|
||||
""" Retrieves the registered scoring function for the specified insight/score type """
|
||||
def GetScoreFunction(self, insightType: QuantConnect.Algorithm.Framework.Alphas.InsightType, scoreType: QuantConnect.Algorithm.Framework.Alphas.InsightScoreType) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.IInsightScoreFunction:
|
||||
pass
|
||||
|
||||
|
||||
class InsightAnalysisContext(System.object):
|
||||
"""
|
||||
Defines a context for performing analysis on a single insight
|
||||
|
||||
InsightAnalysisContext(insight: Insight, initialValues: SecurityValues, analysisPeriod: TimeSpan)
|
||||
"""
|
||||
def Equals(self, obj: object) -> bool:
|
||||
pass
|
||||
|
||||
def Get(self, key: str) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.T:
|
||||
pass
|
||||
|
||||
def GetHashCode(self) -> int:
|
||||
pass
|
||||
|
||||
def Set(self, key: str, value: object) -> None:
|
||||
pass
|
||||
|
||||
def ShouldAnalyze(self, scoreType: QuantConnect.Algorithm.Framework.Alphas.InsightScoreType) -> bool:
|
||||
pass
|
||||
|
||||
def ToString(self) -> str:
|
||||
pass
|
||||
|
||||
def __init__(self, insight: QuantConnect.Algorithm.Framework.Alphas.Insight, initialValues: QuantConnect.Algorithm.Framework.Alphas.Analysis.SecurityValues, analysisPeriod: datetime.timedelta) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.InsightAnalysisContext:
|
||||
pass
|
||||
|
||||
AnalysisEndTimeUtc: datetime.datetime
|
||||
|
||||
CurrentValues: QuantConnect.Algorithm.Framework.Alphas.Analysis.SecurityValues
|
||||
|
||||
Id: System.Guid
|
||||
|
||||
InitialValues: QuantConnect.Algorithm.Framework.Alphas.Analysis.SecurityValues
|
||||
|
||||
Insight: QuantConnect.Algorithm.Framework.Alphas.Insight
|
||||
|
||||
InsightPeriodClosed: bool
|
||||
|
||||
NormalizedTime: float
|
||||
|
||||
NormalizedTimeStep: float
|
||||
|
||||
Score: QuantConnect.Algorithm.Framework.Alphas.InsightScore
|
||||
|
||||
Symbol: QuantConnect.Symbol
|
||||
|
||||
|
||||
|
||||
class InsightManager(System.object, System.IDisposable, QuantConnect.Algorithm.Framework.Alphas.Analysis.IInsightManager):
|
||||
"""
|
||||
Encapsulates the storage and on-line scoring of insights.
|
||||
|
||||
InsightManager(scoreFunctionProvider: IInsightScoreFunctionProvider, extraAnalysisPeriodRatio: float, *extensions: Array[IInsightManagerExtension])
|
||||
"""
|
||||
def AddExtension(self, extension: QuantConnect.Algorithm.Framework.Alphas.IInsightManagerExtension) -> None:
|
||||
pass
|
||||
|
||||
def ContextsOpenAt(self, frontierTimeUtc: datetime.datetime) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Analysis.InsightAnalysisContext]:
|
||||
pass
|
||||
|
||||
def Dispose(self) -> None:
|
||||
pass
|
||||
|
||||
def GetUpdatedContexts(self) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Analysis.InsightAnalysisContext]:
|
||||
pass
|
||||
|
||||
def InitializeExtensionsForRange(self, start: datetime.datetime, end: datetime.datetime, current: datetime.datetime) -> None:
|
||||
pass
|
||||
|
||||
def RemoveInsights(self, insightIds: typing.List[System.Guid]) -> None:
|
||||
pass
|
||||
|
||||
def Step(self, frontierTimeUtc: datetime.datetime, securityValuesCollection: QuantConnect.Algorithm.Framework.Alphas.Analysis.ReadOnlySecurityValuesCollection, generatedInsights: QuantConnect.Algorithm.Framework.Alphas.GeneratedInsightsCollection) -> None:
|
||||
pass
|
||||
|
||||
def __init__(self, scoreFunctionProvider: QuantConnect.Algorithm.Framework.Alphas.Analysis.IInsightScoreFunctionProvider, extraAnalysisPeriodRatio: float, extensions: typing.List[QuantConnect.Algorithm.Framework.Alphas.IInsightManagerExtension]) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.InsightManager:
|
||||
pass
|
||||
|
||||
AllInsights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]
|
||||
|
||||
ClosedInsights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]
|
||||
|
||||
OpenInsights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]
|
||||
|
||||
|
||||
ScoreTypes: Array[InsightScoreType]
|
||||
|
||||
|
||||
class ISecurityValuesProvider:
|
||||
"""
|
||||
Provides a simple abstraction that returns a security's current price and volatility.
|
||||
This facilitates testing by removing the dependency of IAlgorithm on the analysis components
|
||||
"""
|
||||
def GetAllValues(self) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.ReadOnlySecurityValuesCollection:
|
||||
pass
|
||||
|
||||
def GetValues(self, symbol: QuantConnect.Symbol) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.SecurityValues:
|
||||
pass
|
||||
|
||||
|
||||
class ReadOnlySecurityValuesCollection(System.object):
|
||||
"""
|
||||
Defines the security values at a given instant. This is analagous
|
||||
to TimeSlice/Slice, but decoupled from the algorithm thread and is
|
||||
intended to contain all of the information necessary to score all
|
||||
insight at this particular time step
|
||||
|
||||
ReadOnlySecurityValuesCollection(securityValuesBySymbol: Dictionary[Symbol, SecurityValues])
|
||||
ReadOnlySecurityValuesCollection(securityValuesBySymbolFunc: Func[Symbol, SecurityValues])
|
||||
"""
|
||||
@typing.overload
|
||||
def __init__(self, securityValuesBySymbol: System.Collections.Generic.Dictionary[QuantConnect.Symbol, QuantConnect.Algorithm.Framework.Alphas.Analysis.SecurityValues]) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.ReadOnlySecurityValuesCollection:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, securityValuesBySymbolFunc: typing.Callable[[QuantConnect.Symbol], QuantConnect.Algorithm.Framework.Alphas.Analysis.SecurityValues]) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.ReadOnlySecurityValuesCollection:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.ReadOnlySecurityValuesCollection:
|
||||
pass
|
||||
|
||||
Item: indexer#
|
||||
|
||||
|
||||
class SecurityValues(System.object):
|
||||
"""
|
||||
Contains security values required by insight analysis components
|
||||
|
||||
SecurityValues(symbol: Symbol, timeUtc: DateTime, exchangeHours: SecurityExchangeHours, price: Decimal, volatility: Decimal, volume: Decimal, quoteCurrencyConversionRate: Decimal)
|
||||
"""
|
||||
def Get(self, type: QuantConnect.Algorithm.Framework.Alphas.InsightType) -> float:
|
||||
pass
|
||||
|
||||
def __init__(self, symbol: QuantConnect.Symbol, timeUtc: datetime.datetime, exchangeHours: QuantConnect.Securities.SecurityExchangeHours, price: float, volatility: float, volume: float, quoteCurrencyConversionRate: float) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.SecurityValues:
|
||||
pass
|
||||
|
||||
ExchangeHours: QuantConnect.Securities.SecurityExchangeHours
|
||||
|
||||
Price: float
|
||||
|
||||
QuoteCurrencyConversionRate: float
|
||||
|
||||
Symbol: QuantConnect.Symbol
|
||||
|
||||
TimeUtc: datetime.datetime
|
||||
|
||||
Volatility: float
|
||||
|
||||
Volume: float
|
||||
|
||||
|
||||
|
||||
class SecurityValuesProviderExtensions(System.object):
|
||||
""" Provides extension methods for QuantConnect.Algorithm.Framework.Alphas.Analysis.ISecurityValuesProvider """
|
||||
@staticmethod
|
||||
def GetValues(securityValuesProvider: QuantConnect.Algorithm.Framework.Alphas.Analysis.ISecurityValuesProvider, symbols: typing.List[QuantConnect.Symbol]) -> QuantConnect.Algorithm.Framework.Alphas.Analysis.ReadOnlySecurityValuesCollection:
|
||||
pass
|
||||
|
||||
__all__: list
|
||||
@@ -1,85 +0,0 @@
|
||||
# encoding: utf-8
|
||||
# module QuantConnect.Algorithm.Framework.Alphas.Serialization calls itself Serialization
|
||||
# from QuantConnect.Common, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null
|
||||
# by generator 1.145
|
||||
# no doc
|
||||
|
||||
# imports
|
||||
import datetime
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm.Framework.Alphas.Serialization
|
||||
import typing
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class InsightJsonConverter(QuantConnect.Util.TypeChangeJsonConverter[Insight, SerializedInsight]):
|
||||
"""
|
||||
Defines how insights should be serialized to json
|
||||
|
||||
InsightJsonConverter()
|
||||
"""
|
||||
|
||||
|
||||
class SerializedInsight(System.object):
|
||||
"""
|
||||
DTO used for serializing an insight that was just generated by an algorithm.
|
||||
This type does not contain any of the analysis dependent fields, such as scores
|
||||
and estimated value
|
||||
|
||||
SerializedInsight()
|
||||
SerializedInsight(insight: Insight)
|
||||
"""
|
||||
@typing.overload
|
||||
def __init__(self) -> QuantConnect.Algorithm.Framework.Alphas.Serialization.SerializedInsight:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, insight: QuantConnect.Algorithm.Framework.Alphas.Insight) -> QuantConnect.Algorithm.Framework.Alphas.Serialization.SerializedInsight:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Alphas.Serialization.SerializedInsight:
|
||||
pass
|
||||
|
||||
CloseTime: float
|
||||
|
||||
Confidence: typing.Optional[float]
|
||||
|
||||
CreatedTime: float
|
||||
|
||||
Direction: QuantConnect.Algorithm.Framework.Alphas.InsightDirection
|
||||
|
||||
EstimatedValue: float
|
||||
|
||||
GeneratedTime: float
|
||||
|
||||
GroupId: str
|
||||
|
||||
Id: str
|
||||
|
||||
Magnitude: typing.Optional[float]
|
||||
|
||||
Period: float
|
||||
|
||||
ReferenceValue: float
|
||||
|
||||
ReferenceValueFinal: float
|
||||
|
||||
ScoreDirection: float
|
||||
|
||||
ScoreIsFinal: bool
|
||||
|
||||
ScoreMagnitude: float
|
||||
|
||||
SourceModel: str
|
||||
|
||||
Symbol: str
|
||||
|
||||
Ticker: str
|
||||
|
||||
Type: QuantConnect.Algorithm.Framework.Alphas.InsightType
|
||||
|
||||
Weight: typing.Optional[float]
|
||||
|
||||
|
||||
|
||||
@@ -1,272 +0,0 @@
|
||||
from .____init___2 import *
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Indicators
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Data
|
||||
import QuantConnect.Algorithm.Framework.Alphas.Serialization
|
||||
import QuantConnect.Algorithm.Framework.Alphas.Analysis
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import datetime
|
||||
|
||||
|
||||
class INamedModel:
|
||||
"""
|
||||
Provides a marker interface allowing models to define their own names.
|
||||
If not specified, the framework will use the model's type name.
|
||||
Implementation of this is not required unless you plan on running multiple models
|
||||
of the same type w/ different parameters.
|
||||
"""
|
||||
Name: str
|
||||
|
||||
|
||||
|
||||
class Insight(System.object):
|
||||
"""
|
||||
Defines a alpha prediction for a single symbol generated by the algorithm
|
||||
|
||||
Insight(symbol: Symbol, period: TimeSpan, type: InsightType, direction: InsightDirection)
|
||||
Insight(symbol: Symbol, period: TimeSpan, type: InsightType, direction: InsightDirection, magnitude: Nullable[float], confidence: Nullable[float], sourceModel: str, weight: Nullable[float])
|
||||
Insight(symbol: Symbol, expiryFunc: Func[DateTime, DateTime], type: InsightType, direction: InsightDirection)
|
||||
Insight(symbol: Symbol, expiryFunc: Func[DateTime, DateTime], type: InsightType, direction: InsightDirection, magnitude: Nullable[float], confidence: Nullable[float], sourceModel: str, weight: Nullable[float])
|
||||
Insight(generatedTimeUtc: DateTime, symbol: Symbol, period: TimeSpan, type: InsightType, direction: InsightDirection, magnitude: Nullable[float], confidence: Nullable[float], sourceModel: str, weight: Nullable[float])
|
||||
"""
|
||||
def Clone(self) -> QuantConnect.Algorithm.Framework.Alphas.Insight:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def ComputeCloseTime(exchangeHours: QuantConnect.Securities.SecurityExchangeHours, generatedTimeUtc: datetime.datetime, resolution: QuantConnect.Resolution, barCount: int) -> datetime.datetime:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def ComputeCloseTime(exchangeHours: QuantConnect.Securities.SecurityExchangeHours, generatedTimeUtc: datetime.datetime, period: datetime.timedelta) -> datetime.datetime:
|
||||
pass
|
||||
|
||||
def ComputeCloseTime(self, *args) -> datetime.datetime:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def ComputePeriod(exchangeHours: QuantConnect.Securities.SecurityExchangeHours, generatedTimeUtc: datetime.datetime, closeTimeUtc: datetime.datetime) -> datetime.timedelta:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def FromSerializedInsight(serializedInsight: QuantConnect.Algorithm.Framework.Alphas.Serialization.SerializedInsight) -> QuantConnect.Algorithm.Framework.Alphas.Insight:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def Group(insights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def Group(insight: QuantConnect.Algorithm.Framework.Alphas.Insight) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
def Group(self, *args) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
def IsActive(self, utcTime: datetime.datetime) -> bool:
|
||||
pass
|
||||
|
||||
def IsExpired(self, utcTime: datetime.datetime) -> bool:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def Price(symbol: QuantConnect.Symbol, resolution: QuantConnect.Resolution, barCount: int, direction: QuantConnect.Algorithm.Framework.Alphas.InsightDirection, magnitude: typing.Optional[float], confidence: typing.Optional[float], sourceModel: str, weight: typing.Optional[float]) -> QuantConnect.Algorithm.Framework.Alphas.Insight:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def Price(symbol: QuantConnect.Symbol, closeTimeLocal: datetime.datetime, direction: QuantConnect.Algorithm.Framework.Alphas.InsightDirection, magnitude: typing.Optional[float], confidence: typing.Optional[float], sourceModel: str, weight: typing.Optional[float]) -> QuantConnect.Algorithm.Framework.Alphas.Insight:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def Price(symbol: QuantConnect.Symbol, period: datetime.timedelta, direction: QuantConnect.Algorithm.Framework.Alphas.InsightDirection, magnitude: typing.Optional[float], confidence: typing.Optional[float], sourceModel: str, weight: typing.Optional[float]) -> QuantConnect.Algorithm.Framework.Alphas.Insight:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def Price(symbol: QuantConnect.Symbol, expiryFunc: typing.Callable[[datetime.datetime], datetime.datetime], direction: QuantConnect.Algorithm.Framework.Alphas.InsightDirection, magnitude: typing.Optional[float], confidence: typing.Optional[float], sourceModel: str, weight: typing.Optional[float]) -> QuantConnect.Algorithm.Framework.Alphas.Insight:
|
||||
pass
|
||||
|
||||
def Price(self, *args) -> QuantConnect.Algorithm.Framework.Alphas.Insight:
|
||||
pass
|
||||
|
||||
def SetPeriodAndCloseTime(self, exchangeHours: QuantConnect.Securities.SecurityExchangeHours) -> None:
|
||||
pass
|
||||
|
||||
def ToString(self) -> str:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, symbol: QuantConnect.Symbol, period: datetime.timedelta, type: QuantConnect.Algorithm.Framework.Alphas.InsightType, direction: QuantConnect.Algorithm.Framework.Alphas.InsightDirection) -> QuantConnect.Algorithm.Framework.Alphas.Insight:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, symbol: QuantConnect.Symbol, period: datetime.timedelta, type: QuantConnect.Algorithm.Framework.Alphas.InsightType, direction: QuantConnect.Algorithm.Framework.Alphas.InsightDirection, magnitude: typing.Optional[float], confidence: typing.Optional[float], sourceModel: str, weight: typing.Optional[float]) -> QuantConnect.Algorithm.Framework.Alphas.Insight:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, symbol: QuantConnect.Symbol, expiryFunc: typing.Callable[[datetime.datetime], datetime.datetime], type: QuantConnect.Algorithm.Framework.Alphas.InsightType, direction: QuantConnect.Algorithm.Framework.Alphas.InsightDirection) -> QuantConnect.Algorithm.Framework.Alphas.Insight:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, symbol: QuantConnect.Symbol, expiryFunc: typing.Callable[[datetime.datetime], datetime.datetime], type: QuantConnect.Algorithm.Framework.Alphas.InsightType, direction: QuantConnect.Algorithm.Framework.Alphas.InsightDirection, magnitude: typing.Optional[float], confidence: typing.Optional[float], sourceModel: str, weight: typing.Optional[float]) -> QuantConnect.Algorithm.Framework.Alphas.Insight:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, generatedTimeUtc: datetime.datetime, symbol: QuantConnect.Symbol, period: datetime.timedelta, type: QuantConnect.Algorithm.Framework.Alphas.InsightType, direction: QuantConnect.Algorithm.Framework.Alphas.InsightDirection, magnitude: typing.Optional[float], confidence: typing.Optional[float], sourceModel: str, weight: typing.Optional[float]) -> QuantConnect.Algorithm.Framework.Alphas.Insight:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Alphas.Insight:
|
||||
pass
|
||||
|
||||
CloseTimeUtc: datetime.datetime
|
||||
|
||||
Confidence: typing.Optional[float]
|
||||
|
||||
Direction: QuantConnect.Algorithm.Framework.Alphas.InsightDirection
|
||||
|
||||
EstimatedValue: float
|
||||
|
||||
GeneratedTimeUtc: datetime.datetime
|
||||
|
||||
GroupId: typing.Optional[System.Guid]
|
||||
|
||||
Id: System.Guid
|
||||
|
||||
Magnitude: typing.Optional[float]
|
||||
|
||||
Period: datetime.timedelta
|
||||
|
||||
ReferenceValue: float
|
||||
|
||||
ReferenceValueFinal: float
|
||||
|
||||
Score: QuantConnect.Algorithm.Framework.Alphas.InsightScore
|
||||
|
||||
SourceModel: str
|
||||
|
||||
Symbol: QuantConnect.Symbol
|
||||
|
||||
Type: QuantConnect.Algorithm.Framework.Alphas.InsightType
|
||||
|
||||
Weight: typing.Optional[float]
|
||||
|
||||
|
||||
|
||||
class InsightCollection(System.object, System.Collections.IEnumerable, System.Collections.Generic.ICollection[Insight], System.Collections.Generic.IEnumerable[Insight]):
|
||||
"""
|
||||
Provides a collection for managing insights. This type provides collection access semantics
|
||||
as well as dictionary access semantics through TryGetValue, ContainsKey, and this[symbol]
|
||||
|
||||
InsightCollection()
|
||||
"""
|
||||
def Add(self, item: QuantConnect.Algorithm.Framework.Alphas.Insight) -> None:
|
||||
pass
|
||||
|
||||
def AddRange(self, insights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Clear(self) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Clear(self, symbols: typing.List[QuantConnect.Symbol]) -> None:
|
||||
pass
|
||||
|
||||
def Clear(self, *args) -> None:
|
||||
pass
|
||||
|
||||
def Contains(self, item: QuantConnect.Algorithm.Framework.Alphas.Insight) -> bool:
|
||||
pass
|
||||
|
||||
def ContainsKey(self, symbol: QuantConnect.Symbol) -> bool:
|
||||
pass
|
||||
|
||||
def CopyTo(self, array: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight], arrayIndex: int) -> None:
|
||||
pass
|
||||
|
||||
def GetActiveInsights(self, utcTime: datetime.datetime) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
def GetEnumerator(self) -> System.Collections.Generic.IEnumerator[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
def GetNextExpiryTime(self) -> typing.Optional[datetime.datetime]:
|
||||
pass
|
||||
|
||||
def HasActiveInsights(self, symbol: QuantConnect.Symbol, utcTime: datetime.datetime) -> bool:
|
||||
pass
|
||||
|
||||
def Remove(self, item: QuantConnect.Algorithm.Framework.Alphas.Insight) -> bool:
|
||||
pass
|
||||
|
||||
def RemoveExpiredInsights(self, utcTime: datetime.datetime) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
def TryGetValue(self, symbol: QuantConnect.Symbol, insights: typing.List) -> bool:
|
||||
pass
|
||||
|
||||
Count: int
|
||||
|
||||
IsReadOnly: bool
|
||||
|
||||
|
||||
Item: indexer#
|
||||
|
||||
|
||||
class InsightDirection(System.Enum, System.IConvertible, System.IFormattable, System.IComparable):
|
||||
"""
|
||||
Specifies the predicted direction for a insight (price/volatility)
|
||||
|
||||
enum InsightDirection, values: Down (-1), Flat (0), Up (1)
|
||||
"""
|
||||
value__: int
|
||||
Down: 'InsightDirection'
|
||||
Flat: 'InsightDirection'
|
||||
Up: 'InsightDirection'
|
||||
|
||||
|
||||
class InsightScore(System.object):
|
||||
"""
|
||||
Defines the scores given to a particular insight
|
||||
|
||||
InsightScore()
|
||||
InsightScore(direction: float, magnitude: float, updatedTimeUtc: DateTime)
|
||||
"""
|
||||
def GetScore(self, type: QuantConnect.Algorithm.Framework.Alphas.InsightScoreType) -> float:
|
||||
pass
|
||||
|
||||
def ToString(self) -> str:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self) -> QuantConnect.Algorithm.Framework.Alphas.InsightScore:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, direction: float, magnitude: float, updatedTimeUtc: datetime.datetime) -> QuantConnect.Algorithm.Framework.Alphas.InsightScore:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Alphas.InsightScore:
|
||||
pass
|
||||
|
||||
Direction: float
|
||||
|
||||
IsFinalScore: bool
|
||||
|
||||
Magnitude: float
|
||||
|
||||
UpdatedTimeUtc: datetime.datetime
|
||||
@@ -1,100 +0,0 @@
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Indicators
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Data
|
||||
import QuantConnect.Algorithm.Framework.Alphas.Serialization
|
||||
import QuantConnect.Algorithm.Framework.Alphas.Analysis
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import datetime
|
||||
|
||||
|
||||
|
||||
class InsightScoreType(System.Enum, System.IConvertible, System.IFormattable, System.IComparable):
|
||||
"""
|
||||
Defines a specific type of score for a insight
|
||||
|
||||
enum InsightScoreType, values: Direction (0), Magnitude (1)
|
||||
"""
|
||||
value__: int
|
||||
Direction: 'InsightScoreType'
|
||||
Magnitude: 'InsightScoreType'
|
||||
|
||||
|
||||
class InsightType(System.Enum, System.IConvertible, System.IFormattable, System.IComparable):
|
||||
"""
|
||||
Specifies the type of insight
|
||||
|
||||
enum InsightType, values: Price (0), Volatility (1)
|
||||
"""
|
||||
value__: int
|
||||
Price: 'InsightType'
|
||||
Volatility: 'InsightType'
|
||||
|
||||
|
||||
class MacdAlphaModel(QuantConnect.Algorithm.Framework.Alphas.AlphaModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Alphas.IAlphaModel, QuantConnect.Algorithm.Framework.Alphas.INamedModel):
|
||||
"""
|
||||
Defines a custom alpha model that uses MACD crossovers. The MACD signal line is
|
||||
used to generate up/down insights if it's stronger than the bounce threshold.
|
||||
If the MACD signal is within the bounce threshold then a flat price insight is returned.
|
||||
|
||||
MacdAlphaModel(fastPeriod: int, slowPeriod: int, signalPeriod: int, movingAverageType: MovingAverageType, resolution: Resolution)
|
||||
"""
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, data: QuantConnect.Data.Slice) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
def __init__(self, fastPeriod: int, slowPeriod: int, signalPeriod: int, movingAverageType: QuantConnect.Indicators.MovingAverageType, resolution: QuantConnect.Resolution) -> QuantConnect.Algorithm.Framework.Alphas.MacdAlphaModel:
|
||||
pass
|
||||
|
||||
|
||||
class NullAlphaModel(QuantConnect.Algorithm.Framework.Alphas.AlphaModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Alphas.IAlphaModel, QuantConnect.Algorithm.Framework.Alphas.INamedModel):
|
||||
"""
|
||||
Provides a null implementation of an alpha model
|
||||
|
||||
NullAlphaModel()
|
||||
"""
|
||||
def Update(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, data: QuantConnect.Data.Slice) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
|
||||
class PearsonCorrelationPairsTradingAlphaModel(QuantConnect.Algorithm.Framework.Alphas.BasePairsTradingAlphaModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Alphas.IAlphaModel, QuantConnect.Algorithm.Framework.Alphas.INamedModel):
|
||||
"""
|
||||
This alpha model is designed to rank every pair combination by its pearson correlation
|
||||
and trade the pair with the hightest correlation
|
||||
This model generates alternating long ratio/short ratio insights emitted as a group
|
||||
|
||||
PearsonCorrelationPairsTradingAlphaModel(lookback: int, resolution: Resolution, threshold: Decimal, minimumCorrelation: float)
|
||||
"""
|
||||
def HasPassedTest(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, asset1: QuantConnect.Symbol, asset2: QuantConnect.Symbol) -> bool:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def __init__(self, lookback: int, resolution: QuantConnect.Resolution, threshold: float, minimumCorrelation: float) -> QuantConnect.Algorithm.Framework.Alphas.PearsonCorrelationPairsTradingAlphaModel:
|
||||
pass
|
||||
|
||||
|
||||
class RsiAlphaModel(QuantConnect.Algorithm.Framework.Alphas.AlphaModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Alphas.IAlphaModel, QuantConnect.Algorithm.Framework.Alphas.INamedModel):
|
||||
"""
|
||||
Uses Wilder's RSI to create insights. Using default settings, a cross over below 30 or above 70 will
|
||||
trigger a new insight.
|
||||
|
||||
RsiAlphaModel(period: int, resolution: Resolution)
|
||||
"""
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, data: QuantConnect.Data.Slice) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
def __init__(self, period: int, resolution: QuantConnect.Resolution) -> QuantConnect.Algorithm.Framework.Alphas.RsiAlphaModel:
|
||||
pass
|
||||
@@ -1,226 +0,0 @@
|
||||
from .____init___1 import *
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Indicators
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Data
|
||||
import QuantConnect.Algorithm.Framework.Alphas.Serialization
|
||||
import QuantConnect.Algorithm.Framework.Alphas.Analysis
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import datetime
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class AlphaModel(System.object, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Alphas.IAlphaModel, QuantConnect.Algorithm.Framework.Alphas.INamedModel):
|
||||
"""
|
||||
Provides a base class for alpha models.
|
||||
|
||||
AlphaModel()
|
||||
"""
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, data: QuantConnect.Data.Slice) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
Name: str
|
||||
|
||||
|
||||
|
||||
class AlphaModelExtensions(System.object):
|
||||
""" Provides extension methods for alpha models """
|
||||
@staticmethod
|
||||
def GetModelName(model: QuantConnect.Algorithm.Framework.Alphas.IAlphaModel) -> str:
|
||||
pass
|
||||
|
||||
__all__: list
|
||||
|
||||
|
||||
class AlphaModelPythonWrapper(QuantConnect.Algorithm.Framework.Alphas.AlphaModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Alphas.IAlphaModel, QuantConnect.Algorithm.Framework.Alphas.INamedModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Alphas.IAlphaModel that wraps a Python.Runtime.PyObject object
|
||||
|
||||
AlphaModelPythonWrapper(model: PyObject)
|
||||
"""
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, data: QuantConnect.Data.Slice) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
def __init__(self, model: Python.Runtime.PyObject) -> QuantConnect.Algorithm.Framework.Alphas.AlphaModelPythonWrapper:
|
||||
pass
|
||||
|
||||
Name: str
|
||||
|
||||
|
||||
|
||||
class BasePairsTradingAlphaModel(QuantConnect.Algorithm.Framework.Alphas.AlphaModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Alphas.IAlphaModel, QuantConnect.Algorithm.Framework.Alphas.INamedModel):
|
||||
"""
|
||||
This alpha model is designed to accept every possible pair combination
|
||||
from securities selected by the universe selection model
|
||||
This model generates alternating long ratio/short ratio insights emitted as a group
|
||||
|
||||
BasePairsTradingAlphaModel(lookback: int, resolution: Resolution, threshold: Decimal)
|
||||
"""
|
||||
def HasPassedTest(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, asset1: QuantConnect.Symbol, asset2: QuantConnect.Symbol) -> bool:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, data: QuantConnect.Data.Slice) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
def __init__(self, lookback: int, resolution: QuantConnect.Resolution, threshold: float) -> QuantConnect.Algorithm.Framework.Alphas.BasePairsTradingAlphaModel:
|
||||
pass
|
||||
|
||||
Securities: System.Collections.Generic.HashSet[QuantConnect.Securities.Security]
|
||||
|
||||
|
||||
|
||||
class CompositeAlphaModel(QuantConnect.Algorithm.Framework.Alphas.AlphaModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Alphas.IAlphaModel, QuantConnect.Algorithm.Framework.Alphas.INamedModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Alphas.IAlphaModel that combines multiple alpha
|
||||
models into a single alpha model and properly sets each insights 'SourceModel' property.
|
||||
|
||||
CompositeAlphaModel(*alphaModels: Array[IAlphaModel])
|
||||
CompositeAlphaModel(*alphaModels: Array[PyObject])
|
||||
CompositeAlphaModel(alphaModel: PyObject)
|
||||
"""
|
||||
@typing.overload
|
||||
def AddAlpha(self, alphaModel: QuantConnect.Algorithm.Framework.Alphas.IAlphaModel) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def AddAlpha(self, pyAlphaModel: Python.Runtime.PyObject) -> None:
|
||||
pass
|
||||
|
||||
def AddAlpha(self, *args) -> None:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, data: QuantConnect.Data.Slice) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, alphaModels: typing.List[QuantConnect.Algorithm.Framework.Alphas.IAlphaModel]) -> QuantConnect.Algorithm.Framework.Alphas.CompositeAlphaModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, alphaModels: typing.List[Python.Runtime.PyObject]) -> QuantConnect.Algorithm.Framework.Alphas.CompositeAlphaModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, alphaModel: Python.Runtime.PyObject) -> QuantConnect.Algorithm.Framework.Alphas.CompositeAlphaModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Alphas.CompositeAlphaModel:
|
||||
pass
|
||||
|
||||
|
||||
class ConstantAlphaModel(QuantConnect.Algorithm.Framework.Alphas.AlphaModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Alphas.IAlphaModel, QuantConnect.Algorithm.Framework.Alphas.INamedModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Alphas.IAlphaModel that always returns the same insight for each security
|
||||
|
||||
ConstantAlphaModel(type: InsightType, direction: InsightDirection, period: TimeSpan)
|
||||
ConstantAlphaModel(type: InsightType, direction: InsightDirection, period: TimeSpan, magnitude: Nullable[float], confidence: Nullable[float], weight: Nullable[float])
|
||||
"""
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, data: QuantConnect.Data.Slice) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, type: QuantConnect.Algorithm.Framework.Alphas.InsightType, direction: QuantConnect.Algorithm.Framework.Alphas.InsightDirection, period: datetime.timedelta) -> QuantConnect.Algorithm.Framework.Alphas.ConstantAlphaModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, type: QuantConnect.Algorithm.Framework.Alphas.InsightType, direction: QuantConnect.Algorithm.Framework.Alphas.InsightDirection, period: datetime.timedelta, magnitude: typing.Optional[float], confidence: typing.Optional[float], weight: typing.Optional[float]) -> QuantConnect.Algorithm.Framework.Alphas.ConstantAlphaModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Alphas.ConstantAlphaModel:
|
||||
pass
|
||||
|
||||
|
||||
class EmaCrossAlphaModel(QuantConnect.Algorithm.Framework.Alphas.AlphaModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Alphas.IAlphaModel, QuantConnect.Algorithm.Framework.Alphas.INamedModel):
|
||||
"""
|
||||
Alpha model that uses an EMA cross to create insights
|
||||
|
||||
EmaCrossAlphaModel(fastPeriod: int, slowPeriod: int, resolution: Resolution)
|
||||
"""
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, data: QuantConnect.Data.Slice) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
def __init__(self, fastPeriod: int, slowPeriod: int, resolution: QuantConnect.Resolution) -> QuantConnect.Algorithm.Framework.Alphas.EmaCrossAlphaModel:
|
||||
pass
|
||||
|
||||
|
||||
class GeneratedInsightsCollection(System.object):
|
||||
"""
|
||||
Defines a collection of insights that were generated at the same time step
|
||||
|
||||
GeneratedInsightsCollection(dateTimeUtc: DateTime, insights: IEnumerable[Insight], clone: bool)
|
||||
"""
|
||||
def __init__(self, dateTimeUtc: datetime.datetime, insights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight], clone: bool) -> QuantConnect.Algorithm.Framework.Alphas.GeneratedInsightsCollection:
|
||||
pass
|
||||
|
||||
DateTimeUtc: datetime.datetime
|
||||
|
||||
Insights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]
|
||||
|
||||
|
||||
|
||||
class HistoricalReturnsAlphaModel(QuantConnect.Algorithm.Framework.Alphas.AlphaModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Alphas.IAlphaModel, QuantConnect.Algorithm.Framework.Alphas.INamedModel):
|
||||
"""
|
||||
Alpha model that uses historical returns to create insights
|
||||
|
||||
HistoricalReturnsAlphaModel(lookback: int, resolution: Resolution)
|
||||
"""
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, data: QuantConnect.Data.Slice) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
def __init__(self, lookback: int, resolution: QuantConnect.Resolution) -> QuantConnect.Algorithm.Framework.Alphas.HistoricalReturnsAlphaModel:
|
||||
pass
|
||||
|
||||
|
||||
class IAlphaModel(QuantConnect.Algorithm.Framework.INotifiedSecurityChanges):
|
||||
""" Algorithm framework model that produces insights """
|
||||
def Update(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, data: QuantConnect.Data.Slice) -> typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]:
|
||||
pass
|
||||
|
||||
|
||||
class IInsightManagerExtension:
|
||||
"""
|
||||
Abstraction point to handle the various concerns from a common api.
|
||||
At the time of writing, these concerns are charting, scoring, perisistence and messaging.
|
||||
"""
|
||||
def InitializeForRange(self, algorithmStartDate: datetime.datetime, algorithmEndDate: datetime.datetime, algorithmUtcTime: datetime.datetime) -> None:
|
||||
pass
|
||||
|
||||
def OnInsightAnalysisCompleted(self, context: QuantConnect.Algorithm.Framework.Alphas.Analysis.InsightAnalysisContext) -> None:
|
||||
pass
|
||||
|
||||
def OnInsightClosed(self, context: QuantConnect.Algorithm.Framework.Alphas.Analysis.InsightAnalysisContext) -> None:
|
||||
pass
|
||||
|
||||
def OnInsightGenerated(self, context: QuantConnect.Algorithm.Framework.Alphas.Analysis.InsightAnalysisContext) -> None:
|
||||
pass
|
||||
|
||||
def Step(self, frontierTimeUtc: datetime.datetime) -> None:
|
||||
pass
|
||||
@@ -1,109 +0,0 @@
|
||||
import typing
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Algorithm.Framework.Portfolio
|
||||
import QuantConnect.Algorithm.Framework.Execution
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import datetime
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class ExecutionModel(System.object, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Execution.IExecutionModel):
|
||||
"""
|
||||
Provides a base class for execution models
|
||||
|
||||
ExecutionModel()
|
||||
"""
|
||||
def Execute(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> None:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class ExecutionModelPythonWrapper(QuantConnect.Algorithm.Framework.Execution.ExecutionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Execution.IExecutionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Execution.IExecutionModel that wraps a Python.Runtime.PyObject object
|
||||
|
||||
ExecutionModelPythonWrapper(model: PyObject)
|
||||
"""
|
||||
def Execute(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> None:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def __init__(self, model: Python.Runtime.PyObject) -> QuantConnect.Algorithm.Framework.Execution.ExecutionModelPythonWrapper:
|
||||
pass
|
||||
|
||||
|
||||
class IExecutionModel(QuantConnect.Algorithm.Framework.INotifiedSecurityChanges):
|
||||
""" Algorithm framework model that executes portfolio targets """
|
||||
def Execute(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class ImmediateExecutionModel(QuantConnect.Algorithm.Framework.Execution.ExecutionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Execution.IExecutionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Execution.IExecutionModel that immediately submits
|
||||
market orders to achieve the desired portfolio targets
|
||||
|
||||
ImmediateExecutionModel()
|
||||
"""
|
||||
def Execute(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> None:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class NullExecutionModel(QuantConnect.Algorithm.Framework.Execution.ExecutionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Execution.IExecutionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Execution.IExecutionModel that does nothing
|
||||
|
||||
NullExecutionModel()
|
||||
"""
|
||||
def Execute(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class StandardDeviationExecutionModel(QuantConnect.Algorithm.Framework.Execution.ExecutionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Execution.IExecutionModel):
|
||||
"""
|
||||
Execution model that submits orders while the current market prices is at least the configured number of standard
|
||||
deviations away from the mean in the favorable direction (below/above for buy/sell respectively)
|
||||
|
||||
StandardDeviationExecutionModel(period: int, deviations: Decimal, resolution: Resolution)
|
||||
"""
|
||||
def Execute(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> None:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def __init__(self, period: int, deviations: float, resolution: QuantConnect.Resolution) -> QuantConnect.Algorithm.Framework.Execution.StandardDeviationExecutionModel:
|
||||
pass
|
||||
|
||||
MaximumOrderValue: float
|
||||
|
||||
|
||||
SymbolData: type
|
||||
|
||||
|
||||
class VolumeWeightedAveragePriceExecutionModel(QuantConnect.Algorithm.Framework.Execution.ExecutionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Execution.IExecutionModel):
|
||||
"""
|
||||
Execution model that submits orders while the current market price is more favorable that the current volume weighted average price.
|
||||
|
||||
VolumeWeightedAveragePriceExecutionModel()
|
||||
"""
|
||||
def Execute(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> None:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
MaximumOrderQuantityPercentVolume: float
|
||||
|
||||
|
||||
SymbolData: type
|
||||
@@ -1,149 +0,0 @@
|
||||
from .__Portfolio_1 import *
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Scheduling
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Algorithm.Framework.Portfolio
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import datetime
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class PortfolioConstructionModel(System.object, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel):
|
||||
"""
|
||||
Provides a base class for portfolio construction models
|
||||
|
||||
PortfolioConstructionModel(rebalancingFunc: Func[DateTime, Nullable[DateTime]])
|
||||
PortfolioConstructionModel(rebalancingFunc: Func[DateTime, DateTime])
|
||||
"""
|
||||
def CreateTargets(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, insights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], typing.Optional[datetime.datetime]]) -> QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], datetime.datetime]) -> QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
RebalanceOnInsightChanges: bool
|
||||
|
||||
RebalanceOnSecurityChanges: bool
|
||||
|
||||
PythonWrapper: QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModelPythonWrapper
|
||||
|
||||
|
||||
class AccumulativeInsightPortfolioConstructionModel(QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel that allocates percent of account
|
||||
to each insight, defaulting to 3%.
|
||||
For insights of direction QuantConnect.Algorithm.Framework.Alphas.InsightDirection.Up, long targets are returned and
|
||||
for insights of direction QuantConnect.Algorithm.Framework.Alphas.InsightDirection.Down, short targets are returned.
|
||||
By default, no rebalancing shall be done.
|
||||
Rules:
|
||||
1. On active Up insight, increase position size by percent
|
||||
2. On active Down insight, decrease position size by percent
|
||||
3. On active Flat insight, move by percent towards 0
|
||||
4. On expired insight, and no other active insight, emits a 0 target'''
|
||||
|
||||
AccumulativeInsightPortfolioConstructionModel(rebalancingDateRules: IDateRule, portfolioBias: PortfolioBias, percent: float)
|
||||
AccumulativeInsightPortfolioConstructionModel(rebalancingFunc: Func[DateTime, Nullable[DateTime]], portfolioBias: PortfolioBias, percent: float)
|
||||
AccumulativeInsightPortfolioConstructionModel(rebalancingFunc: Func[DateTime, DateTime], portfolioBias: PortfolioBias, percent: float)
|
||||
AccumulativeInsightPortfolioConstructionModel(rebalance: PyObject, portfolioBias: PortfolioBias, percent: float)
|
||||
AccumulativeInsightPortfolioConstructionModel(timeSpan: TimeSpan, portfolioBias: PortfolioBias, percent: float)
|
||||
AccumulativeInsightPortfolioConstructionModel(resolution: Resolution, portfolioBias: PortfolioBias, percent: float)
|
||||
"""
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingDateRules: QuantConnect.Scheduling.IDateRule, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, percent: float) -> QuantConnect.Algorithm.Framework.Portfolio.AccumulativeInsightPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], typing.Optional[datetime.datetime]], portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, percent: float) -> QuantConnect.Algorithm.Framework.Portfolio.AccumulativeInsightPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], datetime.datetime], portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, percent: float) -> QuantConnect.Algorithm.Framework.Portfolio.AccumulativeInsightPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalance: Python.Runtime.PyObject, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, percent: float) -> QuantConnect.Algorithm.Framework.Portfolio.AccumulativeInsightPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, timeSpan: datetime.timedelta, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, percent: float) -> QuantConnect.Algorithm.Framework.Portfolio.AccumulativeInsightPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, resolution: QuantConnect.Resolution, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, percent: float) -> QuantConnect.Algorithm.Framework.Portfolio.AccumulativeInsightPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Portfolio.AccumulativeInsightPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
PythonWrapper: QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModelPythonWrapper
|
||||
|
||||
|
||||
class BlackLittermanOptimizationPortfolioConstructionModel(QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel):
|
||||
"""
|
||||
Provides an implementation of Black-Litterman portfolio optimization. The model adjusts equilibrium market
|
||||
returns by incorporating views from multiple alpha models and therefore to get the optimal risky portfolio
|
||||
reflecting those views. If insights of all alpha models have None magnitude or there are linearly dependent
|
||||
vectors in link matrix of views, the expected return would be the implied excess equilibrium return.
|
||||
The interval of weights in optimization method can be changed based on the long-short algorithm.
|
||||
The default model uses the 0.0025 as weight-on-views scalar parameter tau. The optimization method
|
||||
maximizes the Sharpe ratio with the weight range from -1 to 1.
|
||||
|
||||
BlackLittermanOptimizationPortfolioConstructionModel(timeSpan: TimeSpan, portfolioBias: PortfolioBias, lookback: int, period: int, resolution: Resolution, riskFreeRate: float, delta: float, tau: float, optimizer: IPortfolioOptimizer)
|
||||
BlackLittermanOptimizationPortfolioConstructionModel(rebalanceResolution: Resolution, portfolioBias: PortfolioBias, lookback: int, period: int, resolution: Resolution, riskFreeRate: float, delta: float, tau: float, optimizer: IPortfolioOptimizer)
|
||||
BlackLittermanOptimizationPortfolioConstructionModel(rebalancingFunc: Func[DateTime, DateTime], portfolioBias: PortfolioBias, lookback: int, period: int, resolution: Resolution, riskFreeRate: float, delta: float, tau: float, optimizer: IPortfolioOptimizer)
|
||||
BlackLittermanOptimizationPortfolioConstructionModel(rebalancingDateRules: IDateRule, portfolioBias: PortfolioBias, lookback: int, period: int, resolution: Resolution, riskFreeRate: float, delta: float, tau: float, optimizer: IPortfolioOptimizer)
|
||||
BlackLittermanOptimizationPortfolioConstructionModel(rebalance: PyObject, portfolioBias: PortfolioBias, lookback: int, period: int, resolution: Resolution, riskFreeRate: float, delta: float, tau: float, optimizer: IPortfolioOptimizer)
|
||||
BlackLittermanOptimizationPortfolioConstructionModel(rebalancingFunc: Func[DateTime, Nullable[DateTime]], portfolioBias: PortfolioBias, lookback: int, period: int, resolution: Resolution, riskFreeRate: float, delta: float, tau: float, optimizer: IPortfolioOptimizer)
|
||||
"""
|
||||
def GetEquilibriumReturns(self, returns: typing.List[typing.List[float]], Σ: typing.List[typing.List[float]]) -> typing.List[float]:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, timeSpan: datetime.timedelta, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, lookback: int, period: int, resolution: QuantConnect.Resolution, riskFreeRate: float, delta: float, tau: float, optimizer: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer) -> QuantConnect.Algorithm.Framework.Portfolio.BlackLittermanOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalanceResolution: QuantConnect.Resolution, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, lookback: int, period: int, resolution: QuantConnect.Resolution, riskFreeRate: float, delta: float, tau: float, optimizer: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer) -> QuantConnect.Algorithm.Framework.Portfolio.BlackLittermanOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], datetime.datetime], portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, lookback: int, period: int, resolution: QuantConnect.Resolution, riskFreeRate: float, delta: float, tau: float, optimizer: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer) -> QuantConnect.Algorithm.Framework.Portfolio.BlackLittermanOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingDateRules: QuantConnect.Scheduling.IDateRule, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, lookback: int, period: int, resolution: QuantConnect.Resolution, riskFreeRate: float, delta: float, tau: float, optimizer: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer) -> QuantConnect.Algorithm.Framework.Portfolio.BlackLittermanOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalance: Python.Runtime.PyObject, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, lookback: int, period: int, resolution: QuantConnect.Resolution, riskFreeRate: float, delta: float, tau: float, optimizer: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer) -> QuantConnect.Algorithm.Framework.Portfolio.BlackLittermanOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], typing.Optional[datetime.datetime]], portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, lookback: int, period: int, resolution: QuantConnect.Resolution, riskFreeRate: float, delta: float, tau: float, optimizer: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer) -> QuantConnect.Algorithm.Framework.Portfolio.BlackLittermanOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Portfolio.BlackLittermanOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
PythonWrapper: QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModelPythonWrapper
|
||||
@@ -1,174 +0,0 @@
|
||||
import typing
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Algorithm.Framework.Risk
|
||||
import QuantConnect.Algorithm.Framework.Portfolio
|
||||
import QuantConnect.Algorithm
|
||||
import Python.Runtime
|
||||
import datetime
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class RiskManagementModel(System.object, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel):
|
||||
"""
|
||||
Provides a base class for risk management models
|
||||
|
||||
RiskManagementModel()
|
||||
"""
|
||||
def ManageRisk(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class CompositeRiskManagementModel(QuantConnect.Algorithm.Framework.Risk.RiskManagementModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel that combines multiple risk
|
||||
models into a single risk management model and properly sets each insights 'SourceModel' property.
|
||||
|
||||
CompositeRiskManagementModel(*riskManagementModels: Array[IRiskManagementModel])
|
||||
CompositeRiskManagementModel(riskManagementModels: IEnumerable[IRiskManagementModel])
|
||||
CompositeRiskManagementModel(*riskManagementModels: Array[PyObject])
|
||||
CompositeRiskManagementModel(riskManagementModel: PyObject)
|
||||
"""
|
||||
@typing.overload
|
||||
def AddRiskManagement(self, riskManagementModel: QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def AddRiskManagement(self, pyRiskManagementModel: Python.Runtime.PyObject) -> None:
|
||||
pass
|
||||
|
||||
def AddRiskManagement(self, *args) -> None:
|
||||
pass
|
||||
|
||||
def ManageRisk(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, riskManagementModels: typing.List[QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel]) -> QuantConnect.Algorithm.Framework.Risk.CompositeRiskManagementModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, riskManagementModels: typing.List[QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel]) -> QuantConnect.Algorithm.Framework.Risk.CompositeRiskManagementModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, riskManagementModels: typing.List[Python.Runtime.PyObject]) -> QuantConnect.Algorithm.Framework.Risk.CompositeRiskManagementModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, riskManagementModel: Python.Runtime.PyObject) -> QuantConnect.Algorithm.Framework.Risk.CompositeRiskManagementModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Risk.CompositeRiskManagementModel:
|
||||
pass
|
||||
|
||||
|
||||
class IRiskManagementModel(QuantConnect.Algorithm.Framework.INotifiedSecurityChanges):
|
||||
""" Algorithm framework model that manages an algorithm's risk/downside """
|
||||
def ManageRisk(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
|
||||
class MaximumDrawdownPercentPerSecurity(QuantConnect.Algorithm.Framework.Risk.RiskManagementModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel that limits the drawdown
|
||||
per holding to the specified percentage
|
||||
|
||||
MaximumDrawdownPercentPerSecurity(maximumDrawdownPercent: Decimal)
|
||||
"""
|
||||
def ManageRisk(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
def __init__(self, maximumDrawdownPercent: float) -> QuantConnect.Algorithm.Framework.Risk.MaximumDrawdownPercentPerSecurity:
|
||||
pass
|
||||
|
||||
|
||||
class MaximumDrawdownPercentPortfolio(QuantConnect.Algorithm.Framework.Risk.RiskManagementModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel that limits the drawdown of the portfolio
|
||||
to the specified percentage. Once this is triggered the algorithm will need to be manually restarted.
|
||||
|
||||
MaximumDrawdownPercentPortfolio(maximumDrawdownPercent: Decimal, isTrailing: bool)
|
||||
"""
|
||||
def ManageRisk(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
def __init__(self, maximumDrawdownPercent: float, isTrailing: bool) -> QuantConnect.Algorithm.Framework.Risk.MaximumDrawdownPercentPortfolio:
|
||||
pass
|
||||
|
||||
|
||||
class MaximumSectorExposureRiskManagementModel(QuantConnect.Algorithm.Framework.Risk.RiskManagementModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel that limits
|
||||
the sector exposure to the specified percentage
|
||||
|
||||
MaximumSectorExposureRiskManagementModel(maximumSectorExposure: Decimal)
|
||||
"""
|
||||
def ManageRisk(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def __init__(self, maximumSectorExposure: float) -> QuantConnect.Algorithm.Framework.Risk.MaximumSectorExposureRiskManagementModel:
|
||||
pass
|
||||
|
||||
|
||||
class MaximumUnrealizedProfitPercentPerSecurity(QuantConnect.Algorithm.Framework.Risk.RiskManagementModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel that limits the unrealized profit
|
||||
per holding to the specified percentage
|
||||
|
||||
MaximumUnrealizedProfitPercentPerSecurity(maximumUnrealizedProfitPercent: Decimal)
|
||||
"""
|
||||
def ManageRisk(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
def __init__(self, maximumUnrealizedProfitPercent: float) -> QuantConnect.Algorithm.Framework.Risk.MaximumUnrealizedProfitPercentPerSecurity:
|
||||
pass
|
||||
|
||||
|
||||
class NullRiskManagementModel(QuantConnect.Algorithm.Framework.Risk.RiskManagementModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel that does nothing
|
||||
|
||||
NullRiskManagementModel()
|
||||
"""
|
||||
def ManageRisk(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
|
||||
class RiskManagementModelPythonWrapper(QuantConnect.Algorithm.Framework.Risk.RiskManagementModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel that wraps a Python.Runtime.PyObject object
|
||||
|
||||
RiskManagementModelPythonWrapper(model: PyObject)
|
||||
"""
|
||||
def ManageRisk(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def __init__(self, model: Python.Runtime.PyObject) -> QuantConnect.Algorithm.Framework.Risk.RiskManagementModelPythonWrapper:
|
||||
pass
|
||||
|
||||
|
||||
class TrailingStopRiskManagementModel(QuantConnect.Algorithm.Framework.Risk.RiskManagementModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Risk.IRiskManagementModel that limits the maximum possible loss
|
||||
measured from the highest unrealized profit
|
||||
|
||||
TrailingStopRiskManagementModel(maximumDrawdownPercent: Decimal)
|
||||
"""
|
||||
def ManageRisk(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
def __init__(self, maximumDrawdownPercent: float) -> QuantConnect.Algorithm.Framework.Risk.TrailingStopRiskManagementModel:
|
||||
pass
|
||||
@@ -1,195 +0,0 @@
|
||||
from .__Selection_1 import *
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Scheduling
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Data.Fundamental
|
||||
import QuantConnect.Data
|
||||
import QuantConnect.Algorithm.Framework.Selection
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import NodaTime
|
||||
import datetime
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class UniverseSelectionModel(System.object, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Provides a base class for universe selection models.
|
||||
|
||||
UniverseSelectionModel()
|
||||
"""
|
||||
def CreateUniverses(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> typing.List[QuantConnect.Data.UniverseSelection.Universe]:
|
||||
pass
|
||||
|
||||
def GetNextRefreshTimeUtc(self) -> datetime.datetime:
|
||||
pass
|
||||
|
||||
|
||||
class FundamentalUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.UniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
""" Provides a base class for defining equity coarse/fine fundamental selection models """
|
||||
@staticmethod
|
||||
def Coarse(coarseSelector: typing.Callable[[typing.List[QuantConnect.Data.UniverseSelection.CoarseFundamental]], typing.List[QuantConnect.Symbol]]) -> QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
def CreateCoarseFundamentalUniverse(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def CreateUniverses(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> typing.List[QuantConnect.Data.UniverseSelection.Universe]:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def Fine(coarseSelector: typing.Callable[[typing.List[QuantConnect.Data.UniverseSelection.CoarseFundamental]], typing.List[QuantConnect.Symbol]], fineSelector: typing.Callable[[typing.List[QuantConnect.Data.Fundamental.FineFundamental]], typing.List[QuantConnect.Symbol]]) -> QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
def SelectCoarse(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, coarse: typing.List[QuantConnect.Data.UniverseSelection.CoarseFundamental]) -> typing.List[QuantConnect.Symbol]:
|
||||
pass
|
||||
|
||||
def SelectFine(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, fine: typing.List[QuantConnect.Data.Fundamental.FineFundamental]) -> typing.List[QuantConnect.Symbol]:
|
||||
pass
|
||||
|
||||
def __init__(self, *args): #cannot find CLR constructor
|
||||
pass
|
||||
|
||||
|
||||
class CoarseFundamentalUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.FundamentalUniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Portfolio selection model that uses coarse selectors. For US equities only.
|
||||
|
||||
CoarseFundamentalUniverseSelectionModel(coarseSelector: Func[IEnumerable[CoarseFundamental], IEnumerable[Symbol]], universeSettings: UniverseSettings, securityInitializer: ISecurityInitializer)
|
||||
CoarseFundamentalUniverseSelectionModel(coarseSelector: PyObject, universeSettings: UniverseSettings, securityInitializer: ISecurityInitializer)
|
||||
"""
|
||||
def SelectCoarse(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, coarse: typing.List[QuantConnect.Data.UniverseSelection.CoarseFundamental]) -> typing.List[QuantConnect.Symbol]:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, coarseSelector: typing.Callable[[typing.List[QuantConnect.Data.UniverseSelection.CoarseFundamental]], typing.List[QuantConnect.Symbol]], universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, securityInitializer: QuantConnect.Securities.ISecurityInitializer) -> QuantConnect.Algorithm.Framework.Selection.CoarseFundamentalUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, coarseSelector: Python.Runtime.PyObject, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, securityInitializer: QuantConnect.Securities.ISecurityInitializer) -> QuantConnect.Algorithm.Framework.Selection.CoarseFundamentalUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Selection.CoarseFundamentalUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
|
||||
class CompositeUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.UniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel that combines multiple universe
|
||||
selection models into a single model.
|
||||
|
||||
CompositeUniverseSelectionModel(*universeSelectionModels: Array[IUniverseSelectionModel])
|
||||
CompositeUniverseSelectionModel(*universeSelectionModels: Array[PyObject])
|
||||
CompositeUniverseSelectionModel(universeSelectionModel: PyObject)
|
||||
"""
|
||||
@typing.overload
|
||||
def AddUniverseSelection(self, universeSelectionModel: QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def AddUniverseSelection(self, pyUniverseSelectionModel: Python.Runtime.PyObject) -> None:
|
||||
pass
|
||||
|
||||
def AddUniverseSelection(self, *args) -> None:
|
||||
pass
|
||||
|
||||
def CreateUniverses(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> typing.List[QuantConnect.Data.UniverseSelection.Universe]:
|
||||
pass
|
||||
|
||||
def GetNextRefreshTimeUtc(self) -> datetime.datetime:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, universeSelectionModels: typing.List[QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel]) -> QuantConnect.Algorithm.Framework.Selection.CompositeUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, universeSelectionModels: typing.List[Python.Runtime.PyObject]) -> QuantConnect.Algorithm.Framework.Selection.CompositeUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, universeSelectionModel: Python.Runtime.PyObject) -> QuantConnect.Algorithm.Framework.Selection.CompositeUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Selection.CompositeUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
|
||||
class CustomUniverse(QuantConnect.Data.UniverseSelection.UserDefinedUniverse, System.IDisposable, QuantConnect.Data.UniverseSelection.ITimeTriggeredUniverse, System.Collections.Specialized.INotifyCollectionChanged):
|
||||
"""
|
||||
Defines a universe as a set of dynamically set symbols.
|
||||
|
||||
CustomUniverse(configuration: SubscriptionDataConfig, universeSettings: UniverseSettings, interval: TimeSpan, selector: Func[DateTime, IEnumerable[str]])
|
||||
"""
|
||||
@typing.overload
|
||||
def GetSubscriptionRequests(self, security: QuantConnect.Securities.Security, currentTimeUtc: datetime.datetime, maximumEndTimeUtc: datetime.datetime, subscriptionService: QuantConnect.Interfaces.ISubscriptionDataConfigService) -> typing.List[QuantConnect.Data.UniverseSelection.SubscriptionRequest]:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def GetSubscriptionRequests(self, security: QuantConnect.Securities.Security, currentTimeUtc: datetime.datetime, maximumEndTimeUtc: datetime.datetime) -> typing.List[QuantConnect.Data.UniverseSelection.SubscriptionRequest]:
|
||||
pass
|
||||
|
||||
def GetSubscriptionRequests(self, *args) -> typing.List[QuantConnect.Data.UniverseSelection.SubscriptionRequest]:
|
||||
pass
|
||||
|
||||
def __init__(self, configuration: QuantConnect.Data.SubscriptionDataConfig, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, interval: datetime.timedelta, selector: typing.Callable[[datetime.datetime], typing.List[str]]) -> QuantConnect.Algorithm.Framework.Selection.CustomUniverse:
|
||||
pass
|
||||
|
||||
|
||||
class CustomUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.UniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel that simply
|
||||
subscribes to the specified set of symbols
|
||||
|
||||
CustomUniverseSelectionModel(name: str, selector: Func[DateTime, IEnumerable[str]])
|
||||
CustomUniverseSelectionModel(name: str, selector: PyObject)
|
||||
CustomUniverseSelectionModel(securityType: SecurityType, name: str, market: str, selector: Func[DateTime, IEnumerable[str]], universeSettings: UniverseSettings, interval: TimeSpan)
|
||||
CustomUniverseSelectionModel(securityType: SecurityType, name: str, market: str, selector: PyObject, universeSettings: UniverseSettings, interval: TimeSpan)
|
||||
"""
|
||||
def CreateUniverses(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> typing.List[QuantConnect.Data.UniverseSelection.Universe]:
|
||||
pass
|
||||
|
||||
def Select(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, date: datetime.datetime) -> typing.List[str]:
|
||||
pass
|
||||
|
||||
def ToString(self) -> str:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, name: str, selector: typing.Callable[[datetime.datetime], typing.List[str]]) -> QuantConnect.Algorithm.Framework.Selection.CustomUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, name: str, selector: Python.Runtime.PyObject) -> QuantConnect.Algorithm.Framework.Selection.CustomUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, securityType: QuantConnect.SecurityType, name: str, market: str, selector: typing.Callable[[datetime.datetime], typing.List[str]], universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, interval: datetime.timedelta) -> QuantConnect.Algorithm.Framework.Selection.CustomUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, securityType: QuantConnect.SecurityType, name: str, market: str, selector: Python.Runtime.PyObject, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, interval: datetime.timedelta) -> QuantConnect.Algorithm.Framework.Selection.CustomUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Selection.CustomUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
|
||||
class EmaCrossUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.FundamentalUniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Selection.FundamentalUniverseSelectionModel that subscribes
|
||||
to symbols with the larger delta by percentage between the two exponential moving average
|
||||
|
||||
EmaCrossUniverseSelectionModel(fastPeriod: int, slowPeriod: int, universeCount: int, universeSettings: UniverseSettings, securityInitializer: ISecurityInitializer)
|
||||
"""
|
||||
def SelectCoarse(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, coarse: typing.List[QuantConnect.Data.UniverseSelection.CoarseFundamental]) -> typing.List[QuantConnect.Symbol]:
|
||||
pass
|
||||
|
||||
def __init__(self, fastPeriod: int, slowPeriod: int, universeCount: int, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, securityInitializer: QuantConnect.Securities.ISecurityInitializer) -> QuantConnect.Algorithm.Framework.Selection.EmaCrossUniverseSelectionModel:
|
||||
pass
|
||||
@@ -1,153 +0,0 @@
|
||||
from .__Portfolio_2 import *
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Scheduling
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Algorithm.Framework.Portfolio
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import datetime
|
||||
|
||||
|
||||
class EqualWeightingPortfolioConstructionModel(QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel that gives equal weighting to all
|
||||
securities. The target percent holdings of each security is 1/N where N is the number of securities. For
|
||||
insights of direction QuantConnect.Algorithm.Framework.Alphas.InsightDirection.Up, long targets are returned and for insights of direction
|
||||
QuantConnect.Algorithm.Framework.Alphas.InsightDirection.Down, short targets are returned.
|
||||
|
||||
EqualWeightingPortfolioConstructionModel(rebalancingDateRules: IDateRule, portfolioBias: PortfolioBias)
|
||||
EqualWeightingPortfolioConstructionModel(rebalancingFunc: Func[DateTime, Nullable[DateTime]], portfolioBias: PortfolioBias)
|
||||
EqualWeightingPortfolioConstructionModel(rebalancingFunc: Func[DateTime, DateTime], portfolioBias: PortfolioBias)
|
||||
EqualWeightingPortfolioConstructionModel(rebalance: PyObject, portfolioBias: PortfolioBias)
|
||||
EqualWeightingPortfolioConstructionModel(timeSpan: TimeSpan, portfolioBias: PortfolioBias)
|
||||
EqualWeightingPortfolioConstructionModel(resolution: Resolution, portfolioBias: PortfolioBias)
|
||||
"""
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingDateRules: QuantConnect.Scheduling.IDateRule, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.EqualWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], typing.Optional[datetime.datetime]], portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.EqualWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], datetime.datetime], portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.EqualWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalance: Python.Runtime.PyObject, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.EqualWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, timeSpan: datetime.timedelta, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.EqualWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, resolution: QuantConnect.Resolution, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.EqualWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Portfolio.EqualWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
PythonWrapper: QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModelPythonWrapper
|
||||
|
||||
|
||||
class InsightWeightingPortfolioConstructionModel(QuantConnect.Algorithm.Framework.Portfolio.EqualWeightingPortfolioConstructionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel that generates percent targets based on the
|
||||
QuantConnect.Algorithm.Framework.Alphas.Insight.Weight. The target percent holdings of each Symbol is given by the QuantConnect.Algorithm.Framework.Alphas.Insight.Weight
|
||||
from the last active QuantConnect.Algorithm.Framework.Alphas.Insight for that symbol.
|
||||
For insights of direction QuantConnect.Algorithm.Framework.Alphas.InsightDirection.Up, long targets are returned and for insights of direction
|
||||
QuantConnect.Algorithm.Framework.Alphas.InsightDirection.Down, short targets are returned.
|
||||
If the sum of all the last active QuantConnect.Algorithm.Framework.Alphas.Insight per symbol is bigger than 1, it will factor down each target
|
||||
percent holdings proportionally so the sum is 1.
|
||||
It will ignore QuantConnect.Algorithm.Framework.Alphas.Insight that have no QuantConnect.Algorithm.Framework.Alphas.Insight.Weight value.
|
||||
|
||||
InsightWeightingPortfolioConstructionModel(rebalancingDateRules: IDateRule, portfolioBias: PortfolioBias)
|
||||
InsightWeightingPortfolioConstructionModel(rebalance: PyObject, portfolioBias: PortfolioBias)
|
||||
InsightWeightingPortfolioConstructionModel(rebalancingFunc: Func[DateTime, Nullable[DateTime]], portfolioBias: PortfolioBias)
|
||||
InsightWeightingPortfolioConstructionModel(rebalancingFunc: Func[DateTime, DateTime], portfolioBias: PortfolioBias)
|
||||
InsightWeightingPortfolioConstructionModel(timeSpan: TimeSpan, portfolioBias: PortfolioBias)
|
||||
InsightWeightingPortfolioConstructionModel(resolution: Resolution, portfolioBias: PortfolioBias)
|
||||
"""
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingDateRules: QuantConnect.Scheduling.IDateRule, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.InsightWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalance: Python.Runtime.PyObject, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.InsightWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], typing.Optional[datetime.datetime]], portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.InsightWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], datetime.datetime], portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.InsightWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, timeSpan: datetime.timedelta, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.InsightWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, resolution: QuantConnect.Resolution, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.InsightWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Portfolio.InsightWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
PythonWrapper: QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModelPythonWrapper
|
||||
|
||||
|
||||
class ConfidenceWeightedPortfolioConstructionModel(QuantConnect.Algorithm.Framework.Portfolio.InsightWeightingPortfolioConstructionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel that generates percent targets based on the
|
||||
QuantConnect.Algorithm.Framework.Alphas.Insight.Confidence. The target percent holdings of each Symbol is given by the QuantConnect.Algorithm.Framework.Alphas.Insight.Confidence
|
||||
from the last active QuantConnect.Algorithm.Framework.Alphas.Insight for that symbol.
|
||||
For insights of direction QuantConnect.Algorithm.Framework.Alphas.InsightDirection.Up, long targets are returned and for insights of direction
|
||||
QuantConnect.Algorithm.Framework.Alphas.InsightDirection.Down, short targets are returned.
|
||||
If the sum of all the last active QuantConnect.Algorithm.Framework.Alphas.Insight per symbol is bigger than 1, it will factor down each target
|
||||
percent holdings proportionally so the sum is 1.
|
||||
It will ignore QuantConnect.Algorithm.Framework.Alphas.Insight that have no QuantConnect.Algorithm.Framework.Alphas.Insight.Confidence value.
|
||||
|
||||
ConfidenceWeightedPortfolioConstructionModel(rebalancingDateRules: IDateRule, portfolioBias: PortfolioBias)
|
||||
ConfidenceWeightedPortfolioConstructionModel(rebalance: PyObject, portfolioBias: PortfolioBias)
|
||||
ConfidenceWeightedPortfolioConstructionModel(rebalancingFunc: Func[DateTime, Nullable[DateTime]], portfolioBias: PortfolioBias)
|
||||
ConfidenceWeightedPortfolioConstructionModel(rebalancingFunc: Func[DateTime, DateTime], portfolioBias: PortfolioBias)
|
||||
ConfidenceWeightedPortfolioConstructionModel(timeSpan: TimeSpan, portfolioBias: PortfolioBias)
|
||||
ConfidenceWeightedPortfolioConstructionModel(resolution: Resolution, portfolioBias: PortfolioBias)
|
||||
"""
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingDateRules: QuantConnect.Scheduling.IDateRule, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.ConfidenceWeightedPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalance: Python.Runtime.PyObject, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.ConfidenceWeightedPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], typing.Optional[datetime.datetime]], portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.ConfidenceWeightedPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], datetime.datetime], portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.ConfidenceWeightedPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, timeSpan: datetime.timedelta, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.ConfidenceWeightedPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, resolution: QuantConnect.Resolution, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias) -> QuantConnect.Algorithm.Framework.Portfolio.ConfidenceWeightedPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Portfolio.ConfidenceWeightedPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
PythonWrapper: QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModelPythonWrapper
|
||||
@@ -1,158 +0,0 @@
|
||||
from .__Portfolio_3 import *
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Scheduling
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Algorithm.Framework.Portfolio
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import datetime
|
||||
|
||||
|
||||
class IPortfolioConstructionModel(QuantConnect.Algorithm.Framework.INotifiedSecurityChanges):
|
||||
""" Algorithm framework model that """
|
||||
def CreateTargets(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, insights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
|
||||
class IPortfolioOptimizer:
|
||||
""" Interface for portfolio optimization algorithms """
|
||||
def Optimize(self, historicalReturns: typing.List[typing.List[float]], expectedReturns: typing.List[float], covariance: typing.List[typing.List[float]]) -> typing.List[float]:
|
||||
pass
|
||||
|
||||
|
||||
class IPortfolioTarget:
|
||||
"""
|
||||
Represents a portfolio target. This may be a percentage of total portfolio value
|
||||
or it may be a fixed number of shares.
|
||||
"""
|
||||
Quantity: float
|
||||
|
||||
Symbol: QuantConnect.Symbol
|
||||
|
||||
|
||||
|
||||
class MaximumSharpeRatioPortfolioOptimizer(System.object, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer):
|
||||
"""
|
||||
Provides an implementation of a portfolio optimizer that maximizes the portfolio Sharpe Ratio.
|
||||
The interval of weights in optimization method can be changed based on the long-short algorithm.
|
||||
The default model uses flat risk free rate and weight for an individual security range from -1 to 1.
|
||||
|
||||
MaximumSharpeRatioPortfolioOptimizer(lower: float, upper: float, riskFreeRate: float)
|
||||
"""
|
||||
def Optimize(self, historicalReturns: typing.List[typing.List[float]], expectedReturns: typing.List[float], covariance: typing.List[typing.List[float]]) -> typing.List[float]:
|
||||
pass
|
||||
|
||||
def __init__(self, lower: float, upper: float, riskFreeRate: float) -> QuantConnect.Algorithm.Framework.Portfolio.MaximumSharpeRatioPortfolioOptimizer:
|
||||
pass
|
||||
|
||||
|
||||
class MeanVarianceOptimizationPortfolioConstructionModel(QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel):
|
||||
"""
|
||||
Provides an implementation of Mean-Variance portfolio optimization based on modern portfolio theory.
|
||||
The interval of weights in optimization method can be changed based on the long-short algorithm.
|
||||
The default model uses the last three months daily price to calculate the optimal weight
|
||||
with the weight range from -1 to 1 and minimize the portfolio variance with a target return of 2%
|
||||
|
||||
MeanVarianceOptimizationPortfolioConstructionModel(rebalancingDateRules: IDateRule, portfolioBias: PortfolioBias, lookback: int, period: int, resolution: Resolution, targetReturn: float, optimizer: IPortfolioOptimizer)
|
||||
MeanVarianceOptimizationPortfolioConstructionModel(rebalanceResolution: Resolution, portfolioBias: PortfolioBias, lookback: int, period: int, resolution: Resolution, targetReturn: float, optimizer: IPortfolioOptimizer)
|
||||
MeanVarianceOptimizationPortfolioConstructionModel(timeSpan: TimeSpan, portfolioBias: PortfolioBias, lookback: int, period: int, resolution: Resolution, targetReturn: float, optimizer: IPortfolioOptimizer)
|
||||
MeanVarianceOptimizationPortfolioConstructionModel(rebalance: PyObject, portfolioBias: PortfolioBias, lookback: int, period: int, resolution: Resolution, targetReturn: float, optimizer: IPortfolioOptimizer)
|
||||
MeanVarianceOptimizationPortfolioConstructionModel(rebalancingFunc: Func[DateTime, DateTime], portfolioBias: PortfolioBias, lookback: int, period: int, resolution: Resolution, targetReturn: float, optimizer: IPortfolioOptimizer)
|
||||
MeanVarianceOptimizationPortfolioConstructionModel(rebalancingFunc: Func[DateTime, Nullable[DateTime]], portfolioBias: PortfolioBias, lookback: int, period: int, resolution: Resolution, targetReturn: float, optimizer: IPortfolioOptimizer)
|
||||
"""
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingDateRules: QuantConnect.Scheduling.IDateRule, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, lookback: int, period: int, resolution: QuantConnect.Resolution, targetReturn: float, optimizer: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer) -> QuantConnect.Algorithm.Framework.Portfolio.MeanVarianceOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalanceResolution: QuantConnect.Resolution, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, lookback: int, period: int, resolution: QuantConnect.Resolution, targetReturn: float, optimizer: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer) -> QuantConnect.Algorithm.Framework.Portfolio.MeanVarianceOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, timeSpan: datetime.timedelta, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, lookback: int, period: int, resolution: QuantConnect.Resolution, targetReturn: float, optimizer: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer) -> QuantConnect.Algorithm.Framework.Portfolio.MeanVarianceOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalance: Python.Runtime.PyObject, portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, lookback: int, period: int, resolution: QuantConnect.Resolution, targetReturn: float, optimizer: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer) -> QuantConnect.Algorithm.Framework.Portfolio.MeanVarianceOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], datetime.datetime], portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, lookback: int, period: int, resolution: QuantConnect.Resolution, targetReturn: float, optimizer: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer) -> QuantConnect.Algorithm.Framework.Portfolio.MeanVarianceOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], typing.Optional[datetime.datetime]], portfolioBias: QuantConnect.Algorithm.Framework.Portfolio.PortfolioBias, lookback: int, period: int, resolution: QuantConnect.Resolution, targetReturn: float, optimizer: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer) -> QuantConnect.Algorithm.Framework.Portfolio.MeanVarianceOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Portfolio.MeanVarianceOptimizationPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
PythonWrapper: QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModelPythonWrapper
|
||||
|
||||
|
||||
class MinimumVariancePortfolioOptimizer(System.object, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer):
|
||||
"""
|
||||
Provides an implementation of a minimum variance portfolio optimizer that calculate the optimal weights
|
||||
with the weight range from -1 to 1 and minimize the portfolio variance with a target return of 2%
|
||||
|
||||
MinimumVariancePortfolioOptimizer(lower: float, upper: float, targetReturn: float)
|
||||
"""
|
||||
def Optimize(self, historicalReturns: typing.List[typing.List[float]], expectedReturns: typing.List[float], covariance: typing.List[typing.List[float]]) -> typing.List[float]:
|
||||
pass
|
||||
|
||||
def __init__(self, lower: float, upper: float, targetReturn: float) -> QuantConnect.Algorithm.Framework.Portfolio.MinimumVariancePortfolioOptimizer:
|
||||
pass
|
||||
|
||||
|
||||
class NullPortfolioConstructionModel(QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel that does nothing
|
||||
|
||||
NullPortfolioConstructionModel()
|
||||
"""
|
||||
def CreateTargets(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, insights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
PythonWrapper: QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModelPythonWrapper
|
||||
|
||||
|
||||
class PortfolioBias(System.Enum, System.IConvertible, System.IFormattable, System.IComparable):
|
||||
"""
|
||||
Specifies the bias of the portfolio (Short, Long/Short, Long)
|
||||
|
||||
enum PortfolioBias, values: Long (1), LongShort (0), Short (-1)
|
||||
"""
|
||||
value__: int
|
||||
Long: 'PortfolioBias'
|
||||
LongShort: 'PortfolioBias'
|
||||
Short: 'PortfolioBias'
|
||||
|
||||
|
||||
class PortfolioConstructionModelPythonWrapper(QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel that wraps a Python.Runtime.PyObject object
|
||||
|
||||
PortfolioConstructionModelPythonWrapper(model: PyObject)
|
||||
"""
|
||||
def CreateTargets(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, insights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
def __init__(self, model: Python.Runtime.PyObject) -> QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModelPythonWrapper:
|
||||
pass
|
||||
|
||||
RebalanceOnInsightChanges: bool
|
||||
|
||||
RebalanceOnSecurityChanges: bool
|
||||
|
||||
PythonWrapper: QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModelPythonWrapper
|
||||
@@ -1,243 +0,0 @@
|
||||
from .__Portfolio_4 import *
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Scheduling
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Algorithm.Framework.Portfolio
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import datetime
|
||||
|
||||
|
||||
class PortfolioTarget(System.object, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget that specifies a
|
||||
specified quantity of a security to be held by the algorithm
|
||||
|
||||
PortfolioTarget(symbol: Symbol, quantity: Decimal)
|
||||
"""
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def Percent(algorithm: QuantConnect.Interfaces.IAlgorithm, symbol: QuantConnect.Symbol, percent: float) -> QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def Percent(algorithm: QuantConnect.Interfaces.IAlgorithm, symbol: QuantConnect.Symbol, percent: float, returnDeltaQuantity: bool) -> QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget:
|
||||
pass
|
||||
|
||||
def Percent(self, *args) -> QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget:
|
||||
pass
|
||||
|
||||
def ToString(self) -> str:
|
||||
pass
|
||||
|
||||
def __init__(self, symbol: QuantConnect.Symbol, quantity: float) -> QuantConnect.Algorithm.Framework.Portfolio.PortfolioTarget:
|
||||
pass
|
||||
|
||||
Quantity: float
|
||||
|
||||
Symbol: QuantConnect.Symbol
|
||||
|
||||
|
||||
|
||||
class PortfolioTargetCollection(System.object, System.Collections.IEnumerable, System.Collections.Generic.ICollection[KeyValuePair[Symbol, IPortfolioTarget]], System.Collections.Generic.ICollection[IPortfolioTarget], System.Collections.Generic.IDictionary[Symbol, IPortfolioTarget], System.Collections.Generic.IEnumerable[KeyValuePair[Symbol, IPortfolioTarget]], System.Collections.Generic.IEnumerable[IPortfolioTarget]):
|
||||
"""
|
||||
Provides a collection for managing QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTargets for each symbol
|
||||
|
||||
PortfolioTargetCollection()
|
||||
"""
|
||||
@typing.overload
|
||||
def Add(self, target: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Add(self, target: System.Collections.Generic.KeyValuePair[QuantConnect.Symbol, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Add(self, symbol: QuantConnect.Symbol, target: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget) -> None:
|
||||
pass
|
||||
|
||||
def Add(self, *args) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def AddRange(self, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def AddRange(self, targets: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> None:
|
||||
pass
|
||||
|
||||
def AddRange(self, *args) -> None:
|
||||
pass
|
||||
|
||||
def Clear(self) -> None:
|
||||
pass
|
||||
|
||||
def ClearFulfilled(self, algorithm: QuantConnect.Interfaces.IAlgorithm) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Contains(self, target: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget) -> bool:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Contains(self, target: System.Collections.Generic.KeyValuePair[QuantConnect.Symbol, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> bool:
|
||||
pass
|
||||
|
||||
def Contains(self, *args) -> bool:
|
||||
pass
|
||||
|
||||
def ContainsKey(self, symbol: QuantConnect.Symbol) -> bool:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def CopyTo(self, array: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget], arrayIndex: int) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def CopyTo(self, array: typing.List[System.Collections.Generic.KeyValuePair], arrayIndex: int) -> None:
|
||||
pass
|
||||
|
||||
def CopyTo(self, *args) -> None:
|
||||
pass
|
||||
|
||||
def GetEnumerator(self) -> System.Collections.Generic.IEnumerator[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
def OrderByMarginImpact(self, algorithm: QuantConnect.Interfaces.IAlgorithm) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Remove(self, symbol: QuantConnect.Symbol) -> bool:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Remove(self, target: System.Collections.Generic.KeyValuePair[QuantConnect.Symbol, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]) -> bool:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Remove(self, target: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget) -> bool:
|
||||
pass
|
||||
|
||||
def Remove(self, *args) -> bool:
|
||||
pass
|
||||
|
||||
def TryGetValue(self, symbol: QuantConnect.Symbol, target: QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget) -> bool:
|
||||
pass
|
||||
|
||||
Count: int
|
||||
|
||||
IsReadOnly: bool
|
||||
|
||||
Keys: typing.List[QuantConnect.Symbol]
|
||||
|
||||
Values: typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]
|
||||
|
||||
|
||||
Item: indexer#
|
||||
|
||||
|
||||
class ReturnsSymbolData(System.object):
|
||||
"""
|
||||
Contains returns specific to a symbol required for optimization model
|
||||
|
||||
ReturnsSymbolData(symbol: Symbol, lookback: int, period: int)
|
||||
"""
|
||||
def Add(self, time: datetime.datetime, value: float) -> None:
|
||||
pass
|
||||
|
||||
def Reset(self) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, time: datetime.datetime, value: float) -> bool:
|
||||
pass
|
||||
|
||||
def __init__(self, symbol: QuantConnect.Symbol, lookback: int, period: int) -> QuantConnect.Algorithm.Framework.Portfolio.ReturnsSymbolData:
|
||||
pass
|
||||
|
||||
Returns: System.Collections.Generic.Dictionary[datetime.datetime, float]
|
||||
|
||||
|
||||
|
||||
class ReturnsSymbolDataExtensions(System.object):
|
||||
""" Extension methods for QuantConnect.Algorithm.Framework.Portfolio.ReturnsSymbolData """
|
||||
@staticmethod
|
||||
def FormReturnsMatrix(symbolData: System.Collections.Generic.Dictionary[QuantConnect.Symbol, QuantConnect.Algorithm.Framework.Portfolio.ReturnsSymbolData], symbols: typing.List[QuantConnect.Symbol]) -> typing.List[typing.List[float]]:
|
||||
pass
|
||||
|
||||
__all__: list
|
||||
|
||||
|
||||
class SectorWeightingPortfolioConstructionModel(QuantConnect.Algorithm.Framework.Portfolio.EqualWeightingPortfolioConstructionModel, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel that generates percent targets based on the
|
||||
QuantConnect.Data.Fundamental.CompanyReference.IndustryTemplateCode.
|
||||
The target percent holdings of each sector is 1/S where S is the number of sectors and
|
||||
the target percent holdings of each security is 1/N where N is the number of securities of each sector.
|
||||
For insights of direction QuantConnect.Algorithm.Framework.Alphas.InsightDirection.Up, long targets are returned and for insights of direction
|
||||
QuantConnect.Algorithm.Framework.Alphas.InsightDirection.Down, short targets are returned.
|
||||
It will ignore QuantConnect.Algorithm.Framework.Alphas.Insight for symbols that have no QuantConnect.Data.Fundamental.CompanyReference.IndustryTemplateCode value.
|
||||
|
||||
SectorWeightingPortfolioConstructionModel(rebalancingDateRules: IDateRule)
|
||||
SectorWeightingPortfolioConstructionModel(rebalancingFunc: Func[DateTime, Nullable[DateTime]])
|
||||
SectorWeightingPortfolioConstructionModel(rebalancingFunc: Func[DateTime, DateTime])
|
||||
SectorWeightingPortfolioConstructionModel(rebalance: PyObject)
|
||||
SectorWeightingPortfolioConstructionModel(timeSpan: TimeSpan)
|
||||
SectorWeightingPortfolioConstructionModel(resolution: Resolution)
|
||||
"""
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingDateRules: QuantConnect.Scheduling.IDateRule) -> QuantConnect.Algorithm.Framework.Portfolio.SectorWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], typing.Optional[datetime.datetime]]) -> QuantConnect.Algorithm.Framework.Portfolio.SectorWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], datetime.datetime]) -> QuantConnect.Algorithm.Framework.Portfolio.SectorWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalance: Python.Runtime.PyObject) -> QuantConnect.Algorithm.Framework.Portfolio.SectorWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, timeSpan: datetime.timedelta) -> QuantConnect.Algorithm.Framework.Portfolio.SectorWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, resolution: QuantConnect.Resolution) -> QuantConnect.Algorithm.Framework.Portfolio.SectorWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Portfolio.SectorWeightingPortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
PythonWrapper: QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModelPythonWrapper
|
||||
|
||||
|
||||
class UnconstrainedMeanVariancePortfolioOptimizer(System.object, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer):
|
||||
"""
|
||||
Provides an implementation of a portfolio optimizer with unconstrained mean variance.
|
||||
|
||||
UnconstrainedMeanVariancePortfolioOptimizer()
|
||||
"""
|
||||
def Optimize(self, historicalReturns: typing.List[typing.List[float]], expectedReturns: typing.List[float], covariance: typing.List[typing.List[float]]) -> typing.List[float]:
|
||||
pass
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class IPortfolioConstructionModel(QuantConnect.Algorithm.Framework.INotifiedSecurityChanges):
|
||||
""" Algorithm framework model that """
|
||||
def CreateTargets(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, insights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
@@ -1,58 +0,0 @@
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Scheduling
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Algorithm.Framework.Portfolio
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import datetime
|
||||
|
||||
|
||||
class PortfolioConstructionModel(System.object, QuantConnect.Algorithm.Framework.INotifiedSecurityChanges, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioConstructionModel):
|
||||
"""
|
||||
Provides a base class for portfolio construction models
|
||||
|
||||
PortfolioConstructionModel(rebalancingFunc: Func[DateTime, Nullable[DateTime]])
|
||||
PortfolioConstructionModel(rebalancingFunc: Func[DateTime, DateTime])
|
||||
"""
|
||||
def CreateTargets(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, insights: typing.List[QuantConnect.Algorithm.Framework.Alphas.Insight]) -> typing.List[QuantConnect.Algorithm.Framework.Portfolio.IPortfolioTarget]:
|
||||
pass
|
||||
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], typing.Optional[datetime.datetime]]) -> QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, rebalancingFunc: typing.Callable[[datetime.datetime], datetime.datetime]) -> QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModel:
|
||||
pass
|
||||
|
||||
RebalanceOnInsightChanges: bool
|
||||
|
||||
RebalanceOnSecurityChanges: bool
|
||||
|
||||
PythonWrapper: QuantConnect.Algorithm.Framework.Portfolio.PortfolioConstructionModelPythonWrapper
|
||||
|
||||
|
||||
class MaximumSharpeRatioPortfolioOptimizer(System.object, QuantConnect.Algorithm.Framework.Portfolio.IPortfolioOptimizer):
|
||||
"""
|
||||
Provides an implementation of a portfolio optimizer that maximizes the portfolio Sharpe Ratio.
|
||||
The interval of weights in optimization method can be changed based on the long-short algorithm.
|
||||
The default model uses flat risk free rate and weight for an individual security range from -1 to 1.
|
||||
|
||||
MaximumSharpeRatioPortfolioOptimizer(lower: float, upper: float, riskFreeRate: float)
|
||||
"""
|
||||
def Optimize(self, historicalReturns: typing.List[typing.List[float]], expectedReturns: typing.List[float], covariance: typing.List[typing.List[float]]) -> typing.List[float]:
|
||||
pass
|
||||
|
||||
def __init__(self, lower: float, upper: float, riskFreeRate: float) -> QuantConnect.Algorithm.Framework.Portfolio.MaximumSharpeRatioPortfolioOptimizer:
|
||||
pass
|
||||
@@ -1,184 +0,0 @@
|
||||
from .__Selection_2 import *
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Scheduling
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Data.Fundamental
|
||||
import QuantConnect.Data
|
||||
import QuantConnect.Algorithm.Framework.Selection
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import NodaTime
|
||||
import datetime
|
||||
|
||||
|
||||
class InceptionDateUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.CustomUniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Inception Date Universe that accepts a Dictionary of DateTime keyed by String that represent
|
||||
the Inception date for each ticker
|
||||
|
||||
InceptionDateUniverseSelectionModel(name: str, tickersByDate: Dictionary[str, DateTime])
|
||||
InceptionDateUniverseSelectionModel(name: str, tickersByDate: PyObject)
|
||||
"""
|
||||
def Select(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, date: datetime.datetime) -> typing.List[str]:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, name: str, tickersByDate: System.Collections.Generic.Dictionary[str, datetime.datetime]) -> QuantConnect.Algorithm.Framework.Selection.InceptionDateUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, name: str, tickersByDate: Python.Runtime.PyObject) -> QuantConnect.Algorithm.Framework.Selection.InceptionDateUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Selection.InceptionDateUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
|
||||
class EnergyETFUniverse(QuantConnect.Algorithm.Framework.Selection.InceptionDateUniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
""" EnergyETFUniverse() """
|
||||
|
||||
class FineFundamentalUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.FundamentalUniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Portfolio selection model that uses coarse/fine selectors. For US equities only.
|
||||
|
||||
FineFundamentalUniverseSelectionModel(coarseSelector: Func[IEnumerable[CoarseFundamental], IEnumerable[Symbol]], fineSelector: Func[IEnumerable[FineFundamental], IEnumerable[Symbol]], universeSettings: UniverseSettings, securityInitializer: ISecurityInitializer)
|
||||
FineFundamentalUniverseSelectionModel(coarseSelector: PyObject, fineSelector: PyObject, universeSettings: UniverseSettings, securityInitializer: ISecurityInitializer)
|
||||
"""
|
||||
def SelectCoarse(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, coarse: typing.List[QuantConnect.Data.UniverseSelection.CoarseFundamental]) -> typing.List[QuantConnect.Symbol]:
|
||||
pass
|
||||
|
||||
def SelectFine(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, fine: typing.List[QuantConnect.Data.Fundamental.FineFundamental]) -> typing.List[QuantConnect.Symbol]:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, coarseSelector: typing.Callable[[typing.List[QuantConnect.Data.UniverseSelection.CoarseFundamental]], typing.List[QuantConnect.Symbol]], fineSelector: typing.Callable[[typing.List[QuantConnect.Data.Fundamental.FineFundamental]], typing.List[QuantConnect.Symbol]], universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, securityInitializer: QuantConnect.Securities.ISecurityInitializer) -> QuantConnect.Algorithm.Framework.Selection.FineFundamentalUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, coarseSelector: Python.Runtime.PyObject, fineSelector: Python.Runtime.PyObject, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, securityInitializer: QuantConnect.Securities.ISecurityInitializer) -> QuantConnect.Algorithm.Framework.Selection.FineFundamentalUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Selection.FineFundamentalUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
|
||||
class FutureUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.UniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel that subscribes to future chains
|
||||
|
||||
FutureUniverseSelectionModel(refreshInterval: TimeSpan, futureChainSymbolSelector: Func[DateTime, IEnumerable[Symbol]])
|
||||
FutureUniverseSelectionModel(refreshInterval: TimeSpan, futureChainSymbolSelector: Func[DateTime, IEnumerable[Symbol]], universeSettings: UniverseSettings, securityInitializer: ISecurityInitializer)
|
||||
FutureUniverseSelectionModel(refreshInterval: TimeSpan, futureChainSymbolSelector: Func[DateTime, IEnumerable[Symbol]], universeSettings: UniverseSettings)
|
||||
"""
|
||||
def CreateUniverses(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> typing.List[QuantConnect.Data.UniverseSelection.Universe]:
|
||||
pass
|
||||
|
||||
def GetNextRefreshTimeUtc(self) -> datetime.datetime:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, refreshInterval: datetime.timedelta, futureChainSymbolSelector: typing.Callable[[datetime.datetime], typing.List[QuantConnect.Symbol]]) -> QuantConnect.Algorithm.Framework.Selection.FutureUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, refreshInterval: datetime.timedelta, futureChainSymbolSelector: typing.Callable[[datetime.datetime], typing.List[QuantConnect.Symbol]], universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, securityInitializer: QuantConnect.Securities.ISecurityInitializer) -> QuantConnect.Algorithm.Framework.Selection.FutureUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, refreshInterval: datetime.timedelta, futureChainSymbolSelector: typing.Callable[[datetime.datetime], typing.List[QuantConnect.Symbol]], universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Algorithm.Framework.Selection.FutureUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Selection.FutureUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
|
||||
class IUniverseSelectionModel:
|
||||
""" Algorithm framework model that defines the universes to be used by an algorithm """
|
||||
def CreateUniverses(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> typing.List[QuantConnect.Data.UniverseSelection.Universe]:
|
||||
pass
|
||||
|
||||
def GetNextRefreshTimeUtc(self) -> datetime.datetime:
|
||||
pass
|
||||
|
||||
|
||||
class LiquidETFUniverse(QuantConnect.Algorithm.Framework.Selection.InceptionDateUniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Universe Selection Model that adds the following ETFs at their inception date
|
||||
|
||||
LiquidETFUniverse()
|
||||
"""
|
||||
Grouping: type
|
||||
|
||||
|
||||
class ManualUniverse(QuantConnect.Data.UniverseSelection.UserDefinedUniverse, System.IDisposable, QuantConnect.Data.UniverseSelection.ITimeTriggeredUniverse, System.Collections.Specialized.INotifyCollectionChanged):
|
||||
"""
|
||||
Defines a universe as a set of manually set symbols. This differs from QuantConnect.Data.UniverseSelection.UserDefinedUniverse
|
||||
in that these securities were not added via AddSecurity.
|
||||
|
||||
ManualUniverse(configuration: SubscriptionDataConfig, universeSettings: UniverseSettings, securityInitializer: ISecurityInitializer, symbols: IEnumerable[Symbol])
|
||||
ManualUniverse(configuration: SubscriptionDataConfig, universeSettings: UniverseSettings, symbols: IEnumerable[Symbol])
|
||||
ManualUniverse(configuration: SubscriptionDataConfig, universeSettings: UniverseSettings, symbols: Array[Symbol])
|
||||
"""
|
||||
@typing.overload
|
||||
def GetSubscriptionRequests(self, security: QuantConnect.Securities.Security, currentTimeUtc: datetime.datetime, maximumEndTimeUtc: datetime.datetime, subscriptionService: QuantConnect.Interfaces.ISubscriptionDataConfigService) -> typing.List[QuantConnect.Data.UniverseSelection.SubscriptionRequest]:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def GetSubscriptionRequests(self, security: QuantConnect.Securities.Security, currentTimeUtc: datetime.datetime, maximumEndTimeUtc: datetime.datetime) -> typing.List[QuantConnect.Data.UniverseSelection.SubscriptionRequest]:
|
||||
pass
|
||||
|
||||
def GetSubscriptionRequests(self, *args) -> typing.List[QuantConnect.Data.UniverseSelection.SubscriptionRequest]:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, configuration: QuantConnect.Data.SubscriptionDataConfig, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, securityInitializer: QuantConnect.Securities.ISecurityInitializer, symbols: typing.List[QuantConnect.Symbol]) -> QuantConnect.Algorithm.Framework.Selection.ManualUniverse:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, configuration: QuantConnect.Data.SubscriptionDataConfig, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, symbols: typing.List[QuantConnect.Symbol]) -> QuantConnect.Algorithm.Framework.Selection.ManualUniverse:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, configuration: QuantConnect.Data.SubscriptionDataConfig, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, symbols: typing.List[QuantConnect.Symbol]) -> QuantConnect.Algorithm.Framework.Selection.ManualUniverse:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Selection.ManualUniverse:
|
||||
pass
|
||||
|
||||
|
||||
class ManualUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.UniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel that simply
|
||||
subscribes to the specified set of symbols
|
||||
|
||||
ManualUniverseSelectionModel()
|
||||
ManualUniverseSelectionModel(symbols: IEnumerable[Symbol])
|
||||
ManualUniverseSelectionModel(*symbols: Array[Symbol])
|
||||
ManualUniverseSelectionModel(symbols: IEnumerable[Symbol], universeSettings: UniverseSettings, securityInitializer: ISecurityInitializer)
|
||||
"""
|
||||
def CreateUniverses(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> typing.List[QuantConnect.Data.UniverseSelection.Universe]:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self) -> QuantConnect.Algorithm.Framework.Selection.ManualUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, symbols: typing.List[QuantConnect.Symbol]) -> QuantConnect.Algorithm.Framework.Selection.ManualUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, symbols: typing.List[QuantConnect.Symbol]) -> QuantConnect.Algorithm.Framework.Selection.ManualUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, symbols: typing.List[QuantConnect.Symbol], universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, securityInitializer: QuantConnect.Securities.ISecurityInitializer) -> QuantConnect.Algorithm.Framework.Selection.ManualUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Selection.ManualUniverseSelectionModel:
|
||||
pass
|
||||
@@ -1,165 +0,0 @@
|
||||
from .__Selection_3 import *
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Scheduling
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Data.Fundamental
|
||||
import QuantConnect.Data
|
||||
import QuantConnect.Algorithm.Framework.Selection
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import NodaTime
|
||||
import datetime
|
||||
|
||||
|
||||
class MetalsETFUniverse(QuantConnect.Algorithm.Framework.Selection.InceptionDateUniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Universe Selection Model that adds the following Metals ETFs at their inception date
|
||||
2004-11-18 GLD SPDR Gold Trust
|
||||
2005-01-28 IAU iShares Gold Trust
|
||||
2006-04-28 SLV iShares Silver Trust
|
||||
2006-05-22 GDX VanEck Vectors Gold Miners ETF
|
||||
2008-12-04 AGQ ProShares Ultra Silver
|
||||
2009-11-11 GDXJ VanEck Vectors Junior Gold Miners ETF
|
||||
2010-01-08 PPLT Aberdeen Standard Platinum Shares ETF
|
||||
2010-12-08 NUGT Direxion Daily Gold Miners Bull 3X Shares
|
||||
2010-12-08 DUST Direxion Daily Gold Miners Bear 3X Shares
|
||||
2011-10-17 USLV VelocityShares 3x Long Silver ETN
|
||||
2011-10-17 UGLD VelocityShares 3x Long Gold ETN
|
||||
2013-10-03 JNUG Direxion Daily Junior Gold Miners Index Bull 3x Shares
|
||||
2013-10-03 JDST Direxion Daily Junior Gold Miners Index Bear 3X Shares
|
||||
|
||||
MetalsETFUniverse()
|
||||
"""
|
||||
|
||||
class NullUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.UniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Provides a null implementation of QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel
|
||||
|
||||
NullUniverseSelectionModel()
|
||||
"""
|
||||
def CreateUniverses(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> typing.List[QuantConnect.Data.UniverseSelection.Universe]:
|
||||
pass
|
||||
|
||||
|
||||
class OpenInterestFutureUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.FutureUniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Selects contracts in a futures universe, sorted by open interest. This allows the selection to identifiy current
|
||||
active contract.
|
||||
|
||||
OpenInterestFutureUniverseSelectionModel(algorithm: IAlgorithm, futureChainSymbolSelector: Func[DateTime, IEnumerable[Symbol]], chainContractsLookupLimit: Nullable[int], resultsLimit: Nullable[int])
|
||||
"""
|
||||
def FilterByOpenInterest(self, contracts: System.Collections.Generic.IReadOnlyDictionary[QuantConnect.Symbol, QuantConnect.Securities.SecurityExchangeHours]) -> typing.List[QuantConnect.Symbol]:
|
||||
pass
|
||||
|
||||
def __init__(self, algorithm: QuantConnect.Interfaces.IAlgorithm, futureChainSymbolSelector: typing.Callable[[datetime.datetime], typing.List[QuantConnect.Symbol]], chainContractsLookupLimit: typing.Optional[int], resultsLimit: typing.Optional[int]) -> QuantConnect.Algorithm.Framework.Selection.OpenInterestFutureUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
|
||||
class OptionUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.UniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel that subscribes to option chains
|
||||
|
||||
OptionUniverseSelectionModel(refreshInterval: TimeSpan, optionChainSymbolSelector: Func[DateTime, IEnumerable[Symbol]])
|
||||
OptionUniverseSelectionModel(refreshInterval: TimeSpan, optionChainSymbolSelector: Func[DateTime, IEnumerable[Symbol]], universeSettings: UniverseSettings, securityInitializer: ISecurityInitializer)
|
||||
OptionUniverseSelectionModel(refreshInterval: TimeSpan, optionChainSymbolSelector: Func[DateTime, IEnumerable[Symbol]], universeSettings: UniverseSettings)
|
||||
"""
|
||||
def CreateUniverses(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> typing.List[QuantConnect.Data.UniverseSelection.Universe]:
|
||||
pass
|
||||
|
||||
def GetNextRefreshTimeUtc(self) -> datetime.datetime:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, refreshInterval: datetime.timedelta, optionChainSymbolSelector: typing.Callable[[datetime.datetime], typing.List[QuantConnect.Symbol]]) -> QuantConnect.Algorithm.Framework.Selection.OptionUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, refreshInterval: datetime.timedelta, optionChainSymbolSelector: typing.Callable[[datetime.datetime], typing.List[QuantConnect.Symbol]], universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, securityInitializer: QuantConnect.Securities.ISecurityInitializer) -> QuantConnect.Algorithm.Framework.Selection.OptionUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, refreshInterval: datetime.timedelta, optionChainSymbolSelector: typing.Callable[[datetime.datetime], typing.List[QuantConnect.Symbol]], universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Algorithm.Framework.Selection.OptionUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Selection.OptionUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
|
||||
class QC500UniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.FundamentalUniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Defines the QC500 universe as a universe selection model for framework algorithm
|
||||
For details: https://github.com/QuantConnect/Lean/pull/1663
|
||||
|
||||
QC500UniverseSelectionModel()
|
||||
QC500UniverseSelectionModel(universeSettings: UniverseSettings, securityInitializer: ISecurityInitializer)
|
||||
"""
|
||||
def SelectCoarse(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, coarse: typing.List[QuantConnect.Data.UniverseSelection.CoarseFundamental]) -> typing.List[QuantConnect.Symbol]:
|
||||
pass
|
||||
|
||||
def SelectFine(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, fine: typing.List[QuantConnect.Data.Fundamental.FineFundamental]) -> typing.List[QuantConnect.Symbol]:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self) -> QuantConnect.Algorithm.Framework.Selection.QC500UniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings, securityInitializer: QuantConnect.Securities.ISecurityInitializer) -> QuantConnect.Algorithm.Framework.Selection.QC500UniverseSelectionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Selection.QC500UniverseSelectionModel:
|
||||
pass
|
||||
|
||||
|
||||
class ScheduledUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.UniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Defines a universe selection model that invokes a selector function on a specific scheduled given by an QuantConnect.Scheduling.IDateRule and an QuantConnect.Scheduling.ITimeRule
|
||||
|
||||
ScheduledUniverseSelectionModel(dateRule: IDateRule, timeRule: ITimeRule, selector: Func[DateTime, IEnumerable[Symbol]], settings: UniverseSettings, initializer: ISecurityInitializer)
|
||||
ScheduledUniverseSelectionModel(timeZone: DateTimeZone, dateRule: IDateRule, timeRule: ITimeRule, selector: Func[DateTime, IEnumerable[Symbol]], settings: UniverseSettings, initializer: ISecurityInitializer)
|
||||
ScheduledUniverseSelectionModel(dateRule: IDateRule, timeRule: ITimeRule, selector: PyObject, settings: UniverseSettings, initializer: ISecurityInitializer)
|
||||
ScheduledUniverseSelectionModel(timeZone: DateTimeZone, dateRule: IDateRule, timeRule: ITimeRule, selector: PyObject, settings: UniverseSettings, initializer: ISecurityInitializer)
|
||||
"""
|
||||
def CreateUniverses(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> typing.List[QuantConnect.Data.UniverseSelection.Universe]:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, dateRule: QuantConnect.Scheduling.IDateRule, timeRule: QuantConnect.Scheduling.ITimeRule, selector: typing.Callable[[datetime.datetime], typing.List[QuantConnect.Symbol]], settings: QuantConnect.Data.UniverseSelection.UniverseSettings, initializer: QuantConnect.Securities.ISecurityInitializer) -> QuantConnect.Algorithm.Framework.Selection.ScheduledUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, timeZone: NodaTime.DateTimeZone, dateRule: QuantConnect.Scheduling.IDateRule, timeRule: QuantConnect.Scheduling.ITimeRule, selector: typing.Callable[[datetime.datetime], typing.List[QuantConnect.Symbol]], settings: QuantConnect.Data.UniverseSelection.UniverseSettings, initializer: QuantConnect.Securities.ISecurityInitializer) -> QuantConnect.Algorithm.Framework.Selection.ScheduledUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, dateRule: QuantConnect.Scheduling.IDateRule, timeRule: QuantConnect.Scheduling.ITimeRule, selector: Python.Runtime.PyObject, settings: QuantConnect.Data.UniverseSelection.UniverseSettings, initializer: QuantConnect.Securities.ISecurityInitializer) -> QuantConnect.Algorithm.Framework.Selection.ScheduledUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, timeZone: NodaTime.DateTimeZone, dateRule: QuantConnect.Scheduling.IDateRule, timeRule: QuantConnect.Scheduling.ITimeRule, selector: Python.Runtime.PyObject, settings: QuantConnect.Data.UniverseSelection.UniverseSettings, initializer: QuantConnect.Securities.ISecurityInitializer) -> QuantConnect.Algorithm.Framework.Selection.ScheduledUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Algorithm.Framework.Selection.ScheduledUniverseSelectionModel:
|
||||
pass
|
||||
|
||||
|
||||
class SP500SectorsETFUniverse(QuantConnect.Algorithm.Framework.Selection.InceptionDateUniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Universe Selection Model that adds the following SP500 Sectors ETFs at their inception date
|
||||
1998-12-22 XLB Materials Select Sector SPDR ETF
|
||||
1998-12-22 XLE Energy Select Sector SPDR Fund
|
||||
1998-12-22 XLF Financial Select Sector SPDR Fund
|
||||
1998-12-22 XLI Industrial Select Sector SPDR Fund
|
||||
1998-12-22 XLK Technology Select Sector SPDR Fund
|
||||
1998-12-22 XLP Consumer Staples Select Sector SPDR Fund
|
||||
1998-12-22 XLU Utilities Select Sector SPDR Fund
|
||||
1998-12-22 XLV Health Care Select Sector SPDR Fund
|
||||
1998-12-22 XLY Consumer Discretionary Select Sector SPDR Fund
|
||||
|
||||
SP500SectorsETFUniverse()
|
||||
"""
|
||||
@@ -1,110 +0,0 @@
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Scheduling
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Data.Fundamental
|
||||
import QuantConnect.Data
|
||||
import QuantConnect.Algorithm.Framework.Selection
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import NodaTime
|
||||
import datetime
|
||||
|
||||
class TechnologyETFUniverse(QuantConnect.Algorithm.Framework.Selection.InceptionDateUniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Universe Selection Model that adds the following Technology ETFs at their inception date
|
||||
1998-12-22 XLK Technology Select Sector SPDR Fund
|
||||
1999-03-10 QQQ Invesco QQQ
|
||||
2001-07-13 SOXX iShares PHLX Semiconductor ETF
|
||||
2001-07-13 IGV iShares Expanded Tech-Software Sector ETF
|
||||
2004-01-30 VGT Vanguard Information Technology ETF
|
||||
2006-04-25 QTEC First Trust NASDAQ 100 Technology
|
||||
2006-06-23 FDN First Trust Dow Jones Internet Index
|
||||
2007-05-10 FXL First Trust Technology AlphaDEX Fund
|
||||
2008-12-17 TECL Direxion Daily Technology Bull 3X Shares
|
||||
2008-12-17 TECS Direxion Daily Technology Bear 3X Shares
|
||||
2010-03-11 SOXL Direxion Daily Semiconductor Bull 3x Shares
|
||||
2010-03-11 SOXS Direxion Daily Semiconductor Bear 3x Shares
|
||||
2011-07-06 SKYY First Trust ISE Cloud Computing Index Fund
|
||||
2011-12-21 SMH VanEck Vectors Semiconductor ETF
|
||||
2013-08-01 KWEB KraneShares CSI China Internet ETF
|
||||
2013-10-24 FTEC Fidelity MSCI Information Technology Index ETF
|
||||
|
||||
TechnologyETFUniverse()
|
||||
"""
|
||||
|
||||
class UniverseSelectionModelPythonWrapper(QuantConnect.Algorithm.Framework.Selection.UniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel that wraps a Python.Runtime.PyObject object
|
||||
|
||||
UniverseSelectionModelPythonWrapper(model: PyObject)
|
||||
"""
|
||||
def CreateUniverses(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> typing.List[QuantConnect.Data.UniverseSelection.Universe]:
|
||||
pass
|
||||
|
||||
def GetNextRefreshTimeUtc(self) -> datetime.datetime:
|
||||
pass
|
||||
|
||||
def __init__(self, model: Python.Runtime.PyObject) -> QuantConnect.Algorithm.Framework.Selection.UniverseSelectionModelPythonWrapper:
|
||||
pass
|
||||
|
||||
|
||||
class USTreasuriesETFUniverse(QuantConnect.Algorithm.Framework.Selection.InceptionDateUniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Universe Selection Model that adds the following US Treasuries ETFs at their inception date
|
||||
2002-07-26 IEF iShares 7-10 Year Treasury Bond ETF
|
||||
2002-07-26 SHY iShares 1-3 Year Treasury Bond ETF
|
||||
2002-07-26 TLT iShares 20+ Year Treasury Bond ETF
|
||||
2007-01-11 SHV iShares Short Treasury Bond ETF
|
||||
2007-01-11 IEI iShares 3-7 Year Treasury Bond ETF
|
||||
2007-01-11 TLH iShares 10-20 Year Treasury Bond ETF
|
||||
2007-12-10 EDV Vanguard Ext Duration Treasury ETF
|
||||
2007-05-30 BIL SPDR Barclays 1-3 Month T-Bill ETF
|
||||
2007-05-30 SPTL SPDR Portfolio Long Term Treasury ETF
|
||||
2008-05-01 TBT UltraShort Barclays 20+ Year Treasury
|
||||
2009-04-16 TMF Direxion Daily 20-Year Treasury Bull 3X
|
||||
2009-04-16 TMV Direxion Daily 20-Year Treasury Bear 3X
|
||||
2009-08-20 TBF ProShares Short 20+ Year Treasury
|
||||
2009-11-23 VGSH Vanguard Short-Term Treasury ETF
|
||||
2009-11-23 VGIT Vanguard Intermediate-Term Treasury ETF
|
||||
2009-11-24 VGLT Vanguard Long-Term Treasury ETF
|
||||
2010-08-06 SCHO Schwab Short-Term U.S. Treasury ETF
|
||||
2010-08-06 SCHR Schwab Intermediate-Term U.S. Treasury ETF
|
||||
2011-12-01 SPTS SPDR Portfolio Short Term Treasury ETF
|
||||
2012-02-24 GOVT iShares U.S. Treasury Bond ETF
|
||||
|
||||
USTreasuriesETFUniverse()
|
||||
"""
|
||||
|
||||
class VolatilityETFUniverse(QuantConnect.Algorithm.Framework.Selection.InceptionDateUniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
""" VolatilityETFUniverse() """
|
||||
|
||||
|
||||
class NullUniverseSelectionModel(QuantConnect.Algorithm.Framework.Selection.UniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Provides a null implementation of QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel
|
||||
|
||||
NullUniverseSelectionModel()
|
||||
"""
|
||||
def CreateUniverses(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> typing.List[QuantConnect.Data.UniverseSelection.Universe]:
|
||||
pass
|
||||
|
||||
|
||||
class UniverseSelectionModelPythonWrapper(QuantConnect.Algorithm.Framework.Selection.UniverseSelectionModel, QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Algorithm.Framework.Selection.IUniverseSelectionModel that wraps a Python.Runtime.PyObject object
|
||||
|
||||
UniverseSelectionModelPythonWrapper(model: PyObject)
|
||||
"""
|
||||
def CreateUniverses(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> typing.List[QuantConnect.Data.UniverseSelection.Universe]:
|
||||
pass
|
||||
|
||||
def GetNextRefreshTimeUtc(self) -> datetime.datetime:
|
||||
pass
|
||||
|
||||
def __init__(self, model: Python.Runtime.PyObject) -> QuantConnect.Algorithm.Framework.Selection.UniverseSelectionModelPythonWrapper:
|
||||
pass
|
||||
@@ -1,56 +0,0 @@
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Algorithm.Framework
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import datetime
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class INotifiedSecurityChanges:
|
||||
""" Types implementing this interface will be called when the algorithm's set of securities changes """
|
||||
def OnSecuritiesChanged(self, algorithm: QuantConnect.Algorithm.QCAlgorithm, changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class NotifiedSecurityChanges(System.object):
|
||||
""" Provides convenience methods for updating collections in responses to securities changed events """
|
||||
@staticmethod
|
||||
def Update(changes: QuantConnect.Data.UniverseSelection.SecurityChanges, add: typing.Callable[[QuantConnect.Securities.Security], None], remove: typing.Callable[[QuantConnect.Securities.Security], None]) -> None:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def UpdateCollection(securities: typing.List[QuantConnect.Securities.Security], changes: QuantConnect.Data.UniverseSelection.SecurityChanges) -> None:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def UpdateCollection(securities: typing.List[QuantConnect.Algorithm.Framework.TValue], changes: QuantConnect.Data.UniverseSelection.SecurityChanges, valueFactory: typing.Callable[[QuantConnect.Securities.Security], QuantConnect.Algorithm.Framework.TValue]) -> None:
|
||||
pass
|
||||
|
||||
def UpdateCollection(self, *args) -> None:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def UpdateDictionary(dictionary: System.Collections.Generic.IDictionary[QuantConnect.Securities.Security, QuantConnect.Algorithm.Framework.TValue], changes: QuantConnect.Data.UniverseSelection.SecurityChanges, valueFactory: typing.Callable[[QuantConnect.Securities.Security], QuantConnect.Algorithm.Framework.TValue]) -> None:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def UpdateDictionary(dictionary: System.Collections.Generic.IDictionary[QuantConnect.Symbol, QuantConnect.Algorithm.Framework.TValue], changes: QuantConnect.Data.UniverseSelection.SecurityChanges, valueFactory: typing.Callable[[QuantConnect.Securities.Security], QuantConnect.Algorithm.Framework.TValue]) -> None:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def UpdateDictionary(dictionary: System.Collections.Generic.IDictionary[QuantConnect.Algorithm.Framework.TKey, QuantConnect.Algorithm.Framework.TValue], changes: QuantConnect.Data.UniverseSelection.SecurityChanges, keyFactory: typing.Callable[[QuantConnect.Securities.Security], QuantConnect.Algorithm.Framework.TKey], valueFactory: typing.Callable[[QuantConnect.Securities.Security], QuantConnect.Algorithm.Framework.TValue]) -> None:
|
||||
pass
|
||||
|
||||
def UpdateDictionary(self, *args) -> None:
|
||||
pass
|
||||
|
||||
__all__: list
|
||||
@@ -1,265 +0,0 @@
|
||||
from .____init___2 import *
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System.Collections.Concurrent
|
||||
import System
|
||||
import QuantConnect.Storage
|
||||
import QuantConnect.Securities.Option
|
||||
import QuantConnect.Securities.Future
|
||||
import QuantConnect.Securities.Forex
|
||||
import QuantConnect.Securities.Equity
|
||||
import QuantConnect.Securities.Crypto
|
||||
import QuantConnect.Securities.Cfd
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Scheduling
|
||||
import QuantConnect.Python
|
||||
import QuantConnect.Orders
|
||||
import QuantConnect.Notifications
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Indicators.CandlestickPatterns
|
||||
import QuantConnect.Indicators
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Data.Market
|
||||
import QuantConnect.Data.Fundamental
|
||||
import QuantConnect.Data.Consolidators
|
||||
import QuantConnect.Data
|
||||
import QuantConnect.Brokerages
|
||||
import QuantConnect.Benchmarks
|
||||
import QuantConnect.Algorithm.Framework.Selection
|
||||
import QuantConnect.Algorithm.Framework.Risk
|
||||
import QuantConnect.Algorithm.Framework.Portfolio
|
||||
import QuantConnect.Algorithm.Framework.Execution
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import pandas
|
||||
import NodaTime
|
||||
import datetime
|
||||
|
||||
|
||||
class ConstituentUniverseDefinitions(System.object):
|
||||
"""
|
||||
Provides helpers for defining constituent universes based on the Morningstar
|
||||
asset classification QuantConnect.Data.Fundamental.AssetClassification https://www.morningstar.com/
|
||||
|
||||
ConstituentUniverseDefinitions(algorithm: IAlgorithm)
|
||||
"""
|
||||
def AerospaceAndDefense(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def AggressiveGrowth(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Agriculture(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def AssetManagement(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Banks(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def BeveragesAlcoholic(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def BeveragesNonAlcoholic(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Biotechnology(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def BuildingMaterials(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def BusinessServices(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def CapitalMarkets(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Chemicals(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def ClassicGrowth(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Conglomerates(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Construction(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def ConsumerPackagedGoods(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def CreditServices(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Cyclicals(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Distressed(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def DiversifiedFinancialServices(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def DrugManufacturers(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Education(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def FarmAndHeavyConstructionMachinery(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def FixturesAndAppliances(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def ForestProducts(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def HardAsset(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Hardware(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def HealthcarePlans(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def HealthcareProvidersAndServices(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def HighYield(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def HomebuildingAndConstruction(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def IndustrialDistribution(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def IndustrialProducts(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Insurance(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def InteractiveMedia(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def LargeCore(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def LargeGrowth(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def LargeValue(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def ManufacturingApparelAndAccessories(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def MediaDiversified(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def MedicalDevicesAndInstruments(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def MedicalDiagnosticsAndResearch(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def MedicalDistribution(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def MetalsAndMining(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def MidCore(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def MidGrowth(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def MidValue(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def OilAndGas(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def OtherEnergySources(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def PackagingAndContainers(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def PersonalServices(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def RealEstate(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def REITs(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Restaurants(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def RetailCyclical(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def RetailDefensive(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Semiconductors(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def SlowGrowth(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def SmallCore(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def SmallGrowth(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def SmallValue(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Software(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def SpeculativeGrowth(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Steel(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def TelecommunicationServices(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def TobaccoProducts(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def Transportation(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def TravelAndLeisure(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def UtilitiesIndependentPowerProducers(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def UtilitiesRegulated(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def VehiclesAndParts(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def WasteManagement(self, universeSettings: QuantConnect.Data.UniverseSelection.UniverseSettings) -> QuantConnect.Data.UniverseSelection.Universe:
|
||||
pass
|
||||
|
||||
def __init__(self, algorithm: QuantConnect.Interfaces.IAlgorithm) -> QuantConnect.Algorithm.ConstituentUniverseDefinitions:
|
||||
pass
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,55 +0,0 @@
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System.Collections.Concurrent
|
||||
import System
|
||||
import QuantConnect.Storage
|
||||
import QuantConnect.Securities.Option
|
||||
import QuantConnect.Securities.Future
|
||||
import QuantConnect.Securities.Forex
|
||||
import QuantConnect.Securities.Equity
|
||||
import QuantConnect.Securities.Crypto
|
||||
import QuantConnect.Securities.Cfd
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Scheduling
|
||||
import QuantConnect.Python
|
||||
import QuantConnect.Orders
|
||||
import QuantConnect.Notifications
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Indicators.CandlestickPatterns
|
||||
import QuantConnect.Indicators
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Data.Market
|
||||
import QuantConnect.Data.Fundamental
|
||||
import QuantConnect.Data.Consolidators
|
||||
import QuantConnect.Data
|
||||
import QuantConnect.Brokerages
|
||||
import QuantConnect.Benchmarks
|
||||
import QuantConnect.Algorithm.Framework.Selection
|
||||
import QuantConnect.Algorithm.Framework.Risk
|
||||
import QuantConnect.Algorithm.Framework.Portfolio
|
||||
import QuantConnect.Algorithm.Framework.Execution
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import pandas
|
||||
import NodaTime
|
||||
import datetime
|
||||
|
||||
|
||||
class UniverseDefinitions(System.object):
|
||||
"""
|
||||
Provides helpers for defining universes in algorithms
|
||||
|
||||
UniverseDefinitions(algorithm: QCAlgorithm)
|
||||
"""
|
||||
def __init__(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> QuantConnect.Algorithm.UniverseDefinitions:
|
||||
pass
|
||||
|
||||
Constituent: QuantConnect.Algorithm.ConstituentUniverseDefinitions
|
||||
|
||||
DollarVolume: QuantConnect.Algorithm.DollarVolumeUniverseDefinitions
|
||||
|
||||
Index: QuantConnect.Algorithm.IndexUniverseDefinitions
|
||||
|
||||
Unchanged: QuantConnect.Data.UniverseSelection.UnchangedUniverse
|
||||
@@ -1,233 +0,0 @@
|
||||
from .____init___1 import *
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System.Collections.Concurrent
|
||||
import System
|
||||
import QuantConnect.Storage
|
||||
import QuantConnect.Securities.Option
|
||||
import QuantConnect.Securities.Future
|
||||
import QuantConnect.Securities.Forex
|
||||
import QuantConnect.Securities.Equity
|
||||
import QuantConnect.Securities.Crypto
|
||||
import QuantConnect.Securities.Cfd
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Scheduling
|
||||
import QuantConnect.Python
|
||||
import QuantConnect.Orders
|
||||
import QuantConnect.Notifications
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Indicators.CandlestickPatterns
|
||||
import QuantConnect.Indicators
|
||||
import QuantConnect.Data.UniverseSelection
|
||||
import QuantConnect.Data.Market
|
||||
import QuantConnect.Data.Fundamental
|
||||
import QuantConnect.Data.Consolidators
|
||||
import QuantConnect.Data
|
||||
import QuantConnect.Brokerages
|
||||
import QuantConnect.Benchmarks
|
||||
import QuantConnect.Algorithm.Framework.Selection
|
||||
import QuantConnect.Algorithm.Framework.Risk
|
||||
import QuantConnect.Algorithm.Framework.Portfolio
|
||||
import QuantConnect.Algorithm.Framework.Execution
|
||||
import QuantConnect.Algorithm.Framework.Alphas
|
||||
import QuantConnect.Algorithm
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import pandas
|
||||
import NodaTime
|
||||
import datetime
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class CandlestickPatterns(System.object):
|
||||
"""
|
||||
Provides helpers for using candlestick patterns
|
||||
|
||||
CandlestickPatterns(algorithm: QCAlgorithm)
|
||||
"""
|
||||
def AbandonedBaby(self, symbol: QuantConnect.Symbol, penetration: float, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.AbandonedBaby:
|
||||
pass
|
||||
|
||||
def AdvanceBlock(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.AdvanceBlock:
|
||||
pass
|
||||
|
||||
def BeltHold(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.BeltHold:
|
||||
pass
|
||||
|
||||
def Breakaway(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.Breakaway:
|
||||
pass
|
||||
|
||||
def ClosingMarubozu(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.ClosingMarubozu:
|
||||
pass
|
||||
|
||||
def ConcealedBabySwallow(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.ConcealedBabySwallow:
|
||||
pass
|
||||
|
||||
def Counterattack(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.Counterattack:
|
||||
pass
|
||||
|
||||
def DarkCloudCover(self, symbol: QuantConnect.Symbol, penetration: float, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.DarkCloudCover:
|
||||
pass
|
||||
|
||||
def Doji(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.Doji:
|
||||
pass
|
||||
|
||||
def DojiStar(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.DojiStar:
|
||||
pass
|
||||
|
||||
def DragonflyDoji(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.DragonflyDoji:
|
||||
pass
|
||||
|
||||
def Engulfing(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.Engulfing:
|
||||
pass
|
||||
|
||||
def EveningDojiStar(self, symbol: QuantConnect.Symbol, penetration: float, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.EveningDojiStar:
|
||||
pass
|
||||
|
||||
def EveningStar(self, symbol: QuantConnect.Symbol, penetration: float, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.EveningStar:
|
||||
pass
|
||||
|
||||
def GapSideBySideWhite(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.GapSideBySideWhite:
|
||||
pass
|
||||
|
||||
def GravestoneDoji(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.GravestoneDoji:
|
||||
pass
|
||||
|
||||
def Hammer(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.Hammer:
|
||||
pass
|
||||
|
||||
def HangingMan(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.HangingMan:
|
||||
pass
|
||||
|
||||
def Harami(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.Harami:
|
||||
pass
|
||||
|
||||
def HaramiCross(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.HaramiCross:
|
||||
pass
|
||||
|
||||
def HighWaveCandle(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.HighWaveCandle:
|
||||
pass
|
||||
|
||||
def Hikkake(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.Hikkake:
|
||||
pass
|
||||
|
||||
def HikkakeModified(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.HikkakeModified:
|
||||
pass
|
||||
|
||||
def HomingPigeon(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.HomingPigeon:
|
||||
pass
|
||||
|
||||
def IdenticalThreeCrows(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.IdenticalThreeCrows:
|
||||
pass
|
||||
|
||||
def InNeck(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.InNeck:
|
||||
pass
|
||||
|
||||
def InvertedHammer(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.InvertedHammer:
|
||||
pass
|
||||
|
||||
def Kicking(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.Kicking:
|
||||
pass
|
||||
|
||||
def KickingByLength(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.KickingByLength:
|
||||
pass
|
||||
|
||||
def LadderBottom(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.LadderBottom:
|
||||
pass
|
||||
|
||||
def LongLeggedDoji(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.LongLeggedDoji:
|
||||
pass
|
||||
|
||||
def LongLineCandle(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.LongLineCandle:
|
||||
pass
|
||||
|
||||
def Marubozu(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.Marubozu:
|
||||
pass
|
||||
|
||||
def MatchingLow(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.MatchingLow:
|
||||
pass
|
||||
|
||||
def MatHold(self, symbol: QuantConnect.Symbol, penetration: float, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.MatHold:
|
||||
pass
|
||||
|
||||
def MorningDojiStar(self, symbol: QuantConnect.Symbol, penetration: float, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.MorningDojiStar:
|
||||
pass
|
||||
|
||||
def MorningStar(self, symbol: QuantConnect.Symbol, penetration: float, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.MorningStar:
|
||||
pass
|
||||
|
||||
def OnNeck(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.OnNeck:
|
||||
pass
|
||||
|
||||
def Piercing(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.Piercing:
|
||||
pass
|
||||
|
||||
def RickshawMan(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.RickshawMan:
|
||||
pass
|
||||
|
||||
def RiseFallThreeMethods(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.RiseFallThreeMethods:
|
||||
pass
|
||||
|
||||
def SeparatingLines(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.SeparatingLines:
|
||||
pass
|
||||
|
||||
def ShootingStar(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.ShootingStar:
|
||||
pass
|
||||
|
||||
def ShortLineCandle(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.ShortLineCandle:
|
||||
pass
|
||||
|
||||
def SpinningTop(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.SpinningTop:
|
||||
pass
|
||||
|
||||
def StalledPattern(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.StalledPattern:
|
||||
pass
|
||||
|
||||
def StickSandwich(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.StickSandwich:
|
||||
pass
|
||||
|
||||
def Takuri(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.Takuri:
|
||||
pass
|
||||
|
||||
def TasukiGap(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.TasukiGap:
|
||||
pass
|
||||
|
||||
def ThreeBlackCrows(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.ThreeBlackCrows:
|
||||
pass
|
||||
|
||||
def ThreeInside(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.ThreeInside:
|
||||
pass
|
||||
|
||||
def ThreeLineStrike(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.ThreeLineStrike:
|
||||
pass
|
||||
|
||||
def ThreeOutside(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.ThreeOutside:
|
||||
pass
|
||||
|
||||
def ThreeStarsInSouth(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.ThreeStarsInSouth:
|
||||
pass
|
||||
|
||||
def ThreeWhiteSoldiers(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.ThreeWhiteSoldiers:
|
||||
pass
|
||||
|
||||
def Thrusting(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.Thrusting:
|
||||
pass
|
||||
|
||||
def Tristar(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.Tristar:
|
||||
pass
|
||||
|
||||
def TwoCrows(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.TwoCrows:
|
||||
pass
|
||||
|
||||
def UniqueThreeRiver(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.UniqueThreeRiver:
|
||||
pass
|
||||
|
||||
def UpDownGapThreeMethods(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.UpDownGapThreeMethods:
|
||||
pass
|
||||
|
||||
def UpsideGapTwoCrows(self, symbol: QuantConnect.Symbol, resolution: typing.Optional[QuantConnect.Resolution], selector: typing.Callable[[QuantConnect.Data.IBaseData], QuantConnect.Data.Market.IBaseDataBar]) -> QuantConnect.Indicators.CandlestickPatterns.UpsideGapTwoCrows:
|
||||
pass
|
||||
|
||||
def __init__(self, algorithm: QuantConnect.Algorithm.QCAlgorithm) -> QuantConnect.Algorithm.CandlestickPatterns:
|
||||
pass
|
||||
@@ -1,139 +0,0 @@
|
||||
# encoding: utf-8
|
||||
# module QuantConnect.Api calls itself Api
|
||||
# from QuantConnect.Common, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null
|
||||
# by generator 1.145
|
||||
# no doc
|
||||
|
||||
# imports
|
||||
import datetime
|
||||
import QuantConnect
|
||||
import QuantConnect.Api
|
||||
import QuantConnect.Packets
|
||||
import System
|
||||
import typing
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class RestResponse(System.object):
|
||||
"""
|
||||
Base API response class for the QuantConnect API.
|
||||
|
||||
RestResponse()
|
||||
"""
|
||||
Errors: typing.List[str]
|
||||
Success: bool
|
||||
|
||||
class AuthenticationResponse(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Verify if the credentials are OK.
|
||||
|
||||
AuthenticationResponse()
|
||||
"""
|
||||
|
||||
class Backtest(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Backtest response packet from the QuantConnect.com API.
|
||||
|
||||
Backtest()
|
||||
"""
|
||||
BacktestId: str
|
||||
Completed: bool
|
||||
Created: datetime.datetime
|
||||
Error: str
|
||||
Name: str
|
||||
Note: str
|
||||
Progress: float
|
||||
Result: QuantConnect.Packets.BacktestResult
|
||||
StackTrace: str
|
||||
|
||||
class BacktestList(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Collection container for a list of backtests for a project
|
||||
|
||||
BacktestList()
|
||||
"""
|
||||
Backtests: typing.List[QuantConnect.Api.Backtest]
|
||||
|
||||
class BacktestReport(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Backtest Report Response wrapper
|
||||
|
||||
BacktestReport()
|
||||
"""
|
||||
Report: str
|
||||
|
||||
|
||||
|
||||
class Compile(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Response from the compiler on a build event
|
||||
|
||||
Compile()
|
||||
"""
|
||||
CompileId: str
|
||||
Logs: typing.List[str]
|
||||
State: QuantConnect.Api.CompileState
|
||||
|
||||
class CompileState(System.Enum, System.IConvertible, System.IFormattable, System.IComparable):
|
||||
"""
|
||||
State of the compilation request
|
||||
|
||||
enum CompileState, values: BuildError (2), BuildSuccess (1), InQueue (0)
|
||||
"""
|
||||
value__: int
|
||||
BuildError: 'CompileState'
|
||||
BuildSuccess: 'CompileState'
|
||||
InQueue: 'CompileState'
|
||||
|
||||
|
||||
class Link(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Response from reading purchased data
|
||||
|
||||
Link()
|
||||
"""
|
||||
DataLink: str
|
||||
|
||||
|
||||
|
||||
class Project(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Response from reading a project by id.
|
||||
|
||||
Project()
|
||||
"""
|
||||
Created: datetime.datetime
|
||||
Language: QuantConnect.Language
|
||||
Modified: datetime.datetime
|
||||
Name: str
|
||||
ProjectId: int
|
||||
|
||||
class ProjectFile(System.object):
|
||||
"""
|
||||
File for a project
|
||||
|
||||
ProjectFile()
|
||||
"""
|
||||
DateModified: datetime.datetime
|
||||
|
||||
Code: str
|
||||
Name: str
|
||||
|
||||
|
||||
class ProjectFilesResponse(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Response received when reading all files of a project
|
||||
|
||||
ProjectFilesResponse()
|
||||
"""
|
||||
Files: typing.List[QuantConnect.Api.ProjectFile]
|
||||
|
||||
class ProjectResponse(QuantConnect.Api.RestResponse):
|
||||
"""
|
||||
Project list response
|
||||
|
||||
ProjectResponse()
|
||||
"""
|
||||
Projects: typing.List[QuantConnect.Api.Project]
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
# encoding: utf-8
|
||||
# module QuantConnect.Benchmarks calls itself Benchmarks
|
||||
# from QuantConnect.Common, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null
|
||||
# by generator 1.145
|
||||
# no doc
|
||||
|
||||
# imports
|
||||
import datetime
|
||||
import QuantConnect.Benchmarks
|
||||
import QuantConnect.Securities
|
||||
import System
|
||||
import typing
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class FuncBenchmark(System.object, QuantConnect.Benchmarks.IBenchmark):
|
||||
"""
|
||||
Creates a benchmark defined by a function
|
||||
|
||||
FuncBenchmark(benchmark: Func[DateTime, Decimal])
|
||||
"""
|
||||
def Evaluate(self, time: datetime.datetime) -> float:
|
||||
pass
|
||||
|
||||
def __init__(self, benchmark: typing.Callable[[datetime.datetime], float]) -> QuantConnect.Benchmarks.FuncBenchmark:
|
||||
pass
|
||||
|
||||
|
||||
class IBenchmark:
|
||||
""" Specifies how to compute a benchmark for an algorithm """
|
||||
def Evaluate(self, time: datetime.datetime) -> float:
|
||||
pass
|
||||
|
||||
|
||||
class SecurityBenchmark(System.object, QuantConnect.Benchmarks.IBenchmark):
|
||||
"""
|
||||
Creates a benchmark defined by the closing price of a QuantConnect.Benchmarks.SecurityBenchmark.Security instance
|
||||
|
||||
SecurityBenchmark(security: Security)
|
||||
"""
|
||||
def Evaluate(self, time: datetime.datetime) -> float:
|
||||
pass
|
||||
|
||||
def __init__(self, security: QuantConnect.Securities.Security) -> QuantConnect.Benchmarks.SecurityBenchmark:
|
||||
pass
|
||||
|
||||
Security: QuantConnect.Securities.Security
|
||||
|
||||
|
||||
|
||||
@@ -1,279 +0,0 @@
|
||||
from .__Brokerages_1 import *
|
||||
import typing
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Packets
|
||||
import QuantConnect.Orders.Slippage
|
||||
import QuantConnect.Orders.Fills
|
||||
import QuantConnect.Orders.Fees
|
||||
import QuantConnect.Orders
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Data.Market
|
||||
import QuantConnect.Brokerages
|
||||
import QuantConnect
|
||||
import datetime
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class DefaultBrokerageModel(System.object, QuantConnect.Brokerages.IBrokerageModel):
|
||||
"""
|
||||
Provides a default implementation of QuantConnect.Brokerages.IBrokerageModel that allows all orders and uses
|
||||
the default transaction models
|
||||
|
||||
DefaultBrokerageModel(accountType: AccountType)
|
||||
"""
|
||||
def ApplySplit(self, tickets: typing.List[QuantConnect.Orders.OrderTicket], split: QuantConnect.Data.Market.Split) -> None:
|
||||
pass
|
||||
|
||||
def CanExecuteOrder(self, security: QuantConnect.Securities.Security, order: QuantConnect.Orders.Order) -> bool:
|
||||
pass
|
||||
|
||||
def CanSubmitOrder(self, security: QuantConnect.Securities.Security, order: QuantConnect.Orders.Order, message: QuantConnect.Brokerages.BrokerageMessageEvent) -> bool:
|
||||
pass
|
||||
|
||||
def CanUpdateOrder(self, security: QuantConnect.Securities.Security, order: QuantConnect.Orders.Order, request: QuantConnect.Orders.UpdateOrderRequest, message: QuantConnect.Brokerages.BrokerageMessageEvent) -> bool:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def GetBuyingPowerModel(self, security: QuantConnect.Securities.Security) -> QuantConnect.Securities.IBuyingPowerModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def GetBuyingPowerModel(self, security: QuantConnect.Securities.Security, accountType: QuantConnect.AccountType) -> QuantConnect.Securities.IBuyingPowerModel:
|
||||
pass
|
||||
|
||||
def GetBuyingPowerModel(self, *args) -> QuantConnect.Securities.IBuyingPowerModel:
|
||||
pass
|
||||
|
||||
def GetFeeModel(self, security: QuantConnect.Securities.Security) -> QuantConnect.Orders.Fees.IFeeModel:
|
||||
pass
|
||||
|
||||
def GetFillModel(self, security: QuantConnect.Securities.Security) -> QuantConnect.Orders.Fills.IFillModel:
|
||||
pass
|
||||
|
||||
def GetLeverage(self, security: QuantConnect.Securities.Security) -> float:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def GetSettlementModel(self, security: QuantConnect.Securities.Security) -> QuantConnect.Securities.ISettlementModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def GetSettlementModel(self, security: QuantConnect.Securities.Security, accountType: QuantConnect.AccountType) -> QuantConnect.Securities.ISettlementModel:
|
||||
pass
|
||||
|
||||
def GetSettlementModel(self, *args) -> QuantConnect.Securities.ISettlementModel:
|
||||
pass
|
||||
|
||||
def GetSlippageModel(self, security: QuantConnect.Securities.Security) -> QuantConnect.Orders.Slippage.ISlippageModel:
|
||||
pass
|
||||
|
||||
def __init__(self, accountType: QuantConnect.AccountType) -> QuantConnect.Brokerages.DefaultBrokerageModel:
|
||||
pass
|
||||
|
||||
AccountType: QuantConnect.AccountType
|
||||
|
||||
DefaultMarkets: System.Collections.Generic.IReadOnlyDictionary[QuantConnect.SecurityType, str]
|
||||
|
||||
RequiredFreeBuyingPowerPercent: float
|
||||
|
||||
|
||||
DefaultMarketMap: ReadOnlyDictionary[SecurityType, str]
|
||||
|
||||
|
||||
class AlpacaBrokerageModel(QuantConnect.Brokerages.DefaultBrokerageModel, QuantConnect.Brokerages.IBrokerageModel):
|
||||
"""
|
||||
Alpaca Brokerage Model Implementation for Back Testing.
|
||||
|
||||
AlpacaBrokerageModel(orderProvider: IOrderProvider, accountType: AccountType)
|
||||
"""
|
||||
def CanSubmitOrder(self, security: QuantConnect.Securities.Security, order: QuantConnect.Orders.Order, message: QuantConnect.Brokerages.BrokerageMessageEvent) -> bool:
|
||||
pass
|
||||
|
||||
def GetFeeModel(self, security: QuantConnect.Securities.Security) -> QuantConnect.Orders.Fees.IFeeModel:
|
||||
pass
|
||||
|
||||
def GetFillModel(self, security: QuantConnect.Securities.Security) -> QuantConnect.Orders.Fills.IFillModel:
|
||||
pass
|
||||
|
||||
def GetSlippageModel(self, security: QuantConnect.Securities.Security) -> QuantConnect.Orders.Slippage.ISlippageModel:
|
||||
pass
|
||||
|
||||
def __init__(self, orderProvider: QuantConnect.Securities.IOrderProvider, accountType: QuantConnect.AccountType) -> QuantConnect.Brokerages.AlpacaBrokerageModel:
|
||||
pass
|
||||
|
||||
DefaultMarkets: System.Collections.Generic.IReadOnlyDictionary[QuantConnect.SecurityType, str]
|
||||
|
||||
|
||||
DefaultMarketMap: ReadOnlyDictionary[SecurityType, str]
|
||||
|
||||
|
||||
class AlphaStreamsBrokerageModel(QuantConnect.Brokerages.DefaultBrokerageModel, QuantConnect.Brokerages.IBrokerageModel):
|
||||
"""
|
||||
Provides properties specific to Alpha Streams
|
||||
|
||||
AlphaStreamsBrokerageModel(accountType: AccountType)
|
||||
"""
|
||||
def GetFeeModel(self, security: QuantConnect.Securities.Security) -> QuantConnect.Orders.Fees.IFeeModel:
|
||||
pass
|
||||
|
||||
def GetLeverage(self, security: QuantConnect.Securities.Security) -> float:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def GetSettlementModel(self, security: QuantConnect.Securities.Security) -> QuantConnect.Securities.ISettlementModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def GetSettlementModel(self, security: QuantConnect.Securities.Security, accountType: QuantConnect.AccountType) -> QuantConnect.Securities.ISettlementModel:
|
||||
pass
|
||||
|
||||
def GetSettlementModel(self, *args) -> QuantConnect.Securities.ISettlementModel:
|
||||
pass
|
||||
|
||||
def GetSlippageModel(self, security: QuantConnect.Securities.Security) -> QuantConnect.Orders.Slippage.ISlippageModel:
|
||||
pass
|
||||
|
||||
def __init__(self, accountType: QuantConnect.AccountType) -> QuantConnect.Brokerages.AlphaStreamsBrokerageModel:
|
||||
pass
|
||||
|
||||
|
||||
class BitfinexBrokerageModel(QuantConnect.Brokerages.DefaultBrokerageModel, QuantConnect.Brokerages.IBrokerageModel):
|
||||
"""
|
||||
Provides Bitfinex specific properties
|
||||
|
||||
BitfinexBrokerageModel(accountType: AccountType)
|
||||
"""
|
||||
@typing.overload
|
||||
def GetBuyingPowerModel(self, security: QuantConnect.Securities.Security) -> QuantConnect.Securities.IBuyingPowerModel:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def GetBuyingPowerModel(self, security: QuantConnect.Securities.Security, accountType: QuantConnect.AccountType) -> QuantConnect.Securities.IBuyingPowerModel:
|
||||
pass
|
||||
|
||||
def GetBuyingPowerModel(self, *args) -> QuantConnect.Securities.IBuyingPowerModel:
|
||||
pass
|
||||
|
||||
def GetFeeModel(self, security: QuantConnect.Securities.Security) -> QuantConnect.Orders.Fees.IFeeModel:
|
||||
pass
|
||||
|
||||
def GetLeverage(self, security: QuantConnect.Securities.Security) -> float:
|
||||
pass
|
||||
|
||||
def __init__(self, accountType: QuantConnect.AccountType) -> QuantConnect.Brokerages.BitfinexBrokerageModel:
|
||||
pass
|
||||
|
||||
DefaultMarkets: System.Collections.Generic.IReadOnlyDictionary[QuantConnect.SecurityType, str]
|
||||
|
||||
|
||||
|
||||
class BrokerageFactoryAttribute(System.Attribute, System.Runtime.InteropServices._Attribute):
|
||||
"""
|
||||
Represents the brokerage factory type required to load a data queue handler
|
||||
|
||||
BrokerageFactoryAttribute(type: Type)
|
||||
"""
|
||||
def __init__(self, type: type) -> QuantConnect.Brokerages.BrokerageFactoryAttribute:
|
||||
pass
|
||||
|
||||
Type: type
|
||||
|
||||
|
||||
|
||||
class BrokerageMessageEvent(System.object):
|
||||
"""
|
||||
Represents a message received from a brokerage
|
||||
|
||||
BrokerageMessageEvent(type: BrokerageMessageType, code: int, message: str)
|
||||
BrokerageMessageEvent(type: BrokerageMessageType, code: str, message: str)
|
||||
"""
|
||||
@staticmethod
|
||||
def Disconnected(message: str) -> QuantConnect.Brokerages.BrokerageMessageEvent:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def Reconnected(message: str) -> QuantConnect.Brokerages.BrokerageMessageEvent:
|
||||
pass
|
||||
|
||||
def ToString(self) -> str:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, type: QuantConnect.Brokerages.BrokerageMessageType, code: int, message: str) -> QuantConnect.Brokerages.BrokerageMessageEvent:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, type: QuantConnect.Brokerages.BrokerageMessageType, code: str, message: str) -> QuantConnect.Brokerages.BrokerageMessageEvent:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Brokerages.BrokerageMessageEvent:
|
||||
pass
|
||||
|
||||
Code: str
|
||||
|
||||
Message: str
|
||||
|
||||
Type: QuantConnect.Brokerages.BrokerageMessageType
|
||||
|
||||
|
||||
|
||||
class BrokerageMessageType(System.Enum, System.IConvertible, System.IFormattable, System.IComparable):
|
||||
"""
|
||||
Specifies the type of message received from an IBrokerage implementation
|
||||
|
||||
enum BrokerageMessageType, values: Disconnect (4), Error (2), Information (0), Reconnect (3), Warning (1)
|
||||
"""
|
||||
value__: int
|
||||
Disconnect: 'BrokerageMessageType'
|
||||
Error: 'BrokerageMessageType'
|
||||
Information: 'BrokerageMessageType'
|
||||
Reconnect: 'BrokerageMessageType'
|
||||
Warning: 'BrokerageMessageType'
|
||||
|
||||
|
||||
class BrokerageModel(System.object):
|
||||
""" Provides factory method for creating an QuantConnect.Brokerages.IBrokerageModel from the QuantConnect.Brokerages.BrokerageName enum """
|
||||
@staticmethod
|
||||
def Create(orderProvider: QuantConnect.Securities.IOrderProvider, brokerage: QuantConnect.Brokerages.BrokerageName, accountType: QuantConnect.AccountType) -> QuantConnect.Brokerages.IBrokerageModel:
|
||||
pass
|
||||
|
||||
__all__: list
|
||||
|
||||
|
||||
class BrokerageName(System.Enum, System.IConvertible, System.IFormattable, System.IComparable):
|
||||
"""
|
||||
Specifices what transaction model and submit/execution rules to use
|
||||
|
||||
enum BrokerageName, values: Alpaca (13), AlphaStreams (14), Bitfinex (5), Default (0), FxcmBrokerage (4), GDAX (12), InteractiveBrokersBrokerage (1), OandaBrokerage (3), QuantConnectBrokerage (0), TradierBrokerage (2)
|
||||
"""
|
||||
value__: int
|
||||
Alpaca: 'BrokerageName'
|
||||
AlphaStreams: 'BrokerageName'
|
||||
Bitfinex: 'BrokerageName'
|
||||
Default: 'BrokerageName'
|
||||
FxcmBrokerage: 'BrokerageName'
|
||||
GDAX: 'BrokerageName'
|
||||
InteractiveBrokersBrokerage: 'BrokerageName'
|
||||
OandaBrokerage: 'BrokerageName'
|
||||
QuantConnectBrokerage: 'BrokerageName'
|
||||
TradierBrokerage: 'BrokerageName'
|
||||
|
||||
|
||||
class DefaultBrokerageMessageHandler(System.object, QuantConnect.Brokerages.IBrokerageMessageHandler):
|
||||
"""
|
||||
Provides a default implementation o QuantConnect.Brokerages.IBrokerageMessageHandler that will forward
|
||||
messages as follows:
|
||||
Information -> IResultHandler.Debug
|
||||
Warning -> IResultHandler.Error && IApi.SendUserEmail
|
||||
Error -> IResultHandler.Error && IAlgorithm.RunTimeError
|
||||
|
||||
DefaultBrokerageMessageHandler(algorithm: IAlgorithm, job: AlgorithmNodePacket, api: IApi, initialDelay: Nullable[TimeSpan], openThreshold: Nullable[TimeSpan])
|
||||
"""
|
||||
def Handle(self, message: QuantConnect.Brokerages.BrokerageMessageEvent) -> None:
|
||||
pass
|
||||
|
||||
def __init__(self, algorithm: QuantConnect.Interfaces.IAlgorithm, job: QuantConnect.Packets.AlgorithmNodePacket, api: QuantConnect.Interfaces.IApi, initialDelay: typing.Optional[datetime.timedelta], openThreshold: typing.Optional[datetime.timedelta]) -> QuantConnect.Brokerages.DefaultBrokerageMessageHandler:
|
||||
pass
|
||||
@@ -1,335 +0,0 @@
|
||||
from .__Auxiliary_1 import *
|
||||
import typing
|
||||
import System.IO
|
||||
import System.Collections.Generic
|
||||
import System
|
||||
import QuantConnect.Securities
|
||||
import QuantConnect.Interfaces
|
||||
import QuantConnect.Data.Market
|
||||
import QuantConnect.Data.Auxiliary
|
||||
import QuantConnect.Data
|
||||
import QuantConnect
|
||||
import datetime
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class FactorFile(System.object, System.Collections.IEnumerable, System.Collections.Generic.IEnumerable[FactorFileRow]):
|
||||
"""
|
||||
Represents an entire factor file for a specified symbol
|
||||
|
||||
FactorFile(permtick: str, data: IEnumerable[FactorFileRow], factorFileMinimumDate: Nullable[DateTime])
|
||||
"""
|
||||
def Apply(self, data: typing.List[QuantConnect.Data.BaseData], exchangeHours: QuantConnect.Securities.SecurityExchangeHours) -> QuantConnect.Data.Auxiliary.FactorFile:
|
||||
pass
|
||||
|
||||
def GetEnumerator(self) -> System.Collections.Generic.IEnumerator[QuantConnect.Data.Auxiliary.FactorFileRow]:
|
||||
pass
|
||||
|
||||
def GetPriceScaleFactor(self, searchDate: datetime.datetime) -> float:
|
||||
pass
|
||||
|
||||
def GetScalingFactors(self, searchDate: datetime.datetime) -> QuantConnect.Data.Auxiliary.FactorFileRow:
|
||||
pass
|
||||
|
||||
def GetSplitFactor(self, searchDate: datetime.datetime) -> float:
|
||||
pass
|
||||
|
||||
def GetSplitsAndDividends(self, symbol: QuantConnect.Symbol, exchangeHours: QuantConnect.Securities.SecurityExchangeHours) -> typing.List[QuantConnect.Data.BaseData]:
|
||||
pass
|
||||
|
||||
def HasDividendEventOnNextTradingDay(self, date: datetime.datetime, priceFactorRatio: float) -> bool:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def HasScalingFactors(permtick: str, market: str) -> bool:
|
||||
pass
|
||||
|
||||
def HasSplitEventOnNextTradingDay(self, date: datetime.datetime, splitFactor: float) -> bool:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def Parse(permtick: str, lines: typing.List[str]) -> QuantConnect.Data.Auxiliary.FactorFile:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def Read(permtick: str, market: str) -> QuantConnect.Data.Auxiliary.FactorFile:
|
||||
pass
|
||||
|
||||
def ToCsvLines(self) -> typing.List[str]:
|
||||
pass
|
||||
|
||||
def WriteToCsv(self, symbol: QuantConnect.Symbol) -> None:
|
||||
pass
|
||||
|
||||
def __init__(self, permtick: str, data: typing.List[QuantConnect.Data.Auxiliary.FactorFileRow], factorFileMinimumDate: typing.Optional[datetime.datetime]) -> QuantConnect.Data.Auxiliary.FactorFile:
|
||||
pass
|
||||
|
||||
FactorFileMinimumDate: typing.Optional[datetime.datetime]
|
||||
|
||||
MostRecentFactorChange: datetime.datetime
|
||||
|
||||
Permtick: str
|
||||
|
||||
SortedFactorFileData: System.Collections.Generic.SortedList[datetime.datetime, QuantConnect.Data.Auxiliary.FactorFileRow]
|
||||
|
||||
|
||||
|
||||
class FactorFileRow(System.object):
|
||||
"""
|
||||
Defines a single row in a factor_factor file. This is a csv file ordered as {date, price factor, split factor, reference price}
|
||||
|
||||
FactorFileRow(date: DateTime, priceFactor: Decimal, splitFactor: Decimal, referencePrice: Decimal)
|
||||
"""
|
||||
@typing.overload
|
||||
def Apply(self, dividend: QuantConnect.Data.Market.Dividend, exchangeHours: QuantConnect.Securities.SecurityExchangeHours) -> QuantConnect.Data.Auxiliary.FactorFileRow:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Apply(self, split: QuantConnect.Data.Market.Split, exchangeHours: QuantConnect.Securities.SecurityExchangeHours) -> QuantConnect.Data.Auxiliary.FactorFileRow:
|
||||
pass
|
||||
|
||||
def Apply(self, *args) -> QuantConnect.Data.Auxiliary.FactorFileRow:
|
||||
pass
|
||||
|
||||
def GetDividend(self, futureFactorFileRow: QuantConnect.Data.Auxiliary.FactorFileRow, symbol: QuantConnect.Symbol, exchangeHours: QuantConnect.Securities.SecurityExchangeHours) -> QuantConnect.Data.Market.Dividend:
|
||||
pass
|
||||
|
||||
def GetSplit(self, futureFactorFileRow: QuantConnect.Data.Auxiliary.FactorFileRow, symbol: QuantConnect.Symbol, exchangeHours: QuantConnect.Securities.SecurityExchangeHours) -> QuantConnect.Data.Market.Split:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def Parse(lines: typing.List[str], factorFileMinimumDate: typing.Optional) -> typing.List[QuantConnect.Data.Auxiliary.FactorFileRow]:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def Read(permtick: str, market: str, factorFileMinimumDate: typing.Optional) -> typing.List[QuantConnect.Data.Auxiliary.FactorFileRow]:
|
||||
pass
|
||||
|
||||
def ToCsv(self, source: str) -> str:
|
||||
pass
|
||||
|
||||
def ToString(self) -> str:
|
||||
pass
|
||||
|
||||
def __init__(self, date: datetime.datetime, priceFactor: float, splitFactor: float, referencePrice: float) -> QuantConnect.Data.Auxiliary.FactorFileRow:
|
||||
pass
|
||||
|
||||
Date: datetime.datetime
|
||||
|
||||
PriceFactor: float
|
||||
|
||||
PriceScaleFactor: float
|
||||
|
||||
ReferencePrice: float
|
||||
|
||||
SplitFactor: float
|
||||
|
||||
|
||||
|
||||
class LocalDiskFactorFileProvider(System.object, QuantConnect.Interfaces.IFactorFileProvider):
|
||||
"""
|
||||
Provides an implementation of QuantConnect.Interfaces.IFactorFileProvider that searches the local disk
|
||||
|
||||
LocalDiskFactorFileProvider()
|
||||
LocalDiskFactorFileProvider(mapFileProvider: IMapFileProvider)
|
||||
"""
|
||||
def Get(self, symbol: QuantConnect.Symbol) -> QuantConnect.Data.Auxiliary.FactorFile:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self) -> QuantConnect.Data.Auxiliary.LocalDiskFactorFileProvider:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, mapFileProvider: QuantConnect.Interfaces.IMapFileProvider) -> QuantConnect.Data.Auxiliary.LocalDiskFactorFileProvider:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Data.Auxiliary.LocalDiskFactorFileProvider:
|
||||
pass
|
||||
|
||||
|
||||
class LocalDiskMapFileProvider(System.object, QuantConnect.Interfaces.IMapFileProvider):
|
||||
"""
|
||||
Provides a default implementation of QuantConnect.Interfaces.IMapFileProvider that reads from
|
||||
the local disk
|
||||
|
||||
LocalDiskMapFileProvider()
|
||||
"""
|
||||
def Get(self, market: str) -> QuantConnect.Data.Auxiliary.MapFileResolver:
|
||||
pass
|
||||
|
||||
|
||||
class MapFile(System.object, System.Collections.IEnumerable, System.Collections.Generic.IEnumerable[MapFileRow]):
|
||||
"""
|
||||
Represents an entire map file for a specified symbol
|
||||
|
||||
MapFile(permtick: str, data: IEnumerable[MapFileRow])
|
||||
"""
|
||||
def GetEnumerator(self) -> System.Collections.Generic.IEnumerator[QuantConnect.Data.Auxiliary.MapFileRow]:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def GetMapFilePath(permtick: str, market: str) -> str:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def GetMapFiles(mapFileDirectory: str) -> typing.List[QuantConnect.Data.Auxiliary.MapFile]:
|
||||
pass
|
||||
|
||||
def GetMappedSymbol(self, searchDate: datetime.datetime, defaultReturnValue: str) -> str:
|
||||
pass
|
||||
|
||||
def HasData(self, date: datetime.datetime) -> bool:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def Read(permtick: str, market: str) -> QuantConnect.Data.Auxiliary.MapFile:
|
||||
pass
|
||||
|
||||
def ToCsvLines(self) -> typing.List[str]:
|
||||
pass
|
||||
|
||||
def WriteToCsv(self, market: str) -> None:
|
||||
pass
|
||||
|
||||
def __init__(self, permtick: str, data: typing.List[QuantConnect.Data.Auxiliary.MapFileRow]) -> QuantConnect.Data.Auxiliary.MapFile:
|
||||
pass
|
||||
|
||||
DelistingDate: datetime.datetime
|
||||
|
||||
FirstDate: datetime.datetime
|
||||
|
||||
FirstTicker: str
|
||||
|
||||
Permtick: str
|
||||
|
||||
|
||||
|
||||
class MapFileResolver(System.object, System.Collections.IEnumerable, System.Collections.Generic.IEnumerable[MapFile]):
|
||||
"""
|
||||
Provides a means of mapping a symbol at a point in time to the map file
|
||||
containing that share class's mapping information
|
||||
|
||||
MapFileResolver(mapFiles: IEnumerable[MapFile])
|
||||
"""
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def Create(dataDirectory: str, market: str) -> QuantConnect.Data.Auxiliary.MapFileResolver:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def Create(mapFileDirectory: str) -> QuantConnect.Data.Auxiliary.MapFileResolver:
|
||||
pass
|
||||
|
||||
def Create(self, *args) -> QuantConnect.Data.Auxiliary.MapFileResolver:
|
||||
pass
|
||||
|
||||
def GetByPermtick(self, permtick: str) -> QuantConnect.Data.Auxiliary.MapFile:
|
||||
pass
|
||||
|
||||
def GetEnumerator(self) -> System.Collections.Generic.IEnumerator[QuantConnect.Data.Auxiliary.MapFile]:
|
||||
pass
|
||||
|
||||
def ResolveMapFile(self, symbol: str, date: datetime.datetime) -> QuantConnect.Data.Auxiliary.MapFile:
|
||||
pass
|
||||
|
||||
def __init__(self, mapFiles: typing.List[QuantConnect.Data.Auxiliary.MapFile]) -> QuantConnect.Data.Auxiliary.MapFileResolver:
|
||||
pass
|
||||
|
||||
Empty: 'MapFileResolver'
|
||||
|
||||
|
||||
class MapFileRow(System.object, System.IEquatable[MapFileRow]):
|
||||
"""
|
||||
Represents a single row in a map_file. This is a csv file ordered as {date, mapped symbol}
|
||||
|
||||
MapFileRow(date: DateTime, mappedSymbol: str)
|
||||
"""
|
||||
@typing.overload
|
||||
def Equals(self, other: QuantConnect.Data.Auxiliary.MapFileRow) -> bool:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Equals(self, obj: object) -> bool:
|
||||
pass
|
||||
|
||||
def Equals(self, *args) -> bool:
|
||||
pass
|
||||
|
||||
def GetHashCode(self) -> int:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def Parse(line: str) -> QuantConnect.Data.Auxiliary.MapFileRow:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def Read(permtick: str, market: str) -> typing.List[QuantConnect.Data.Auxiliary.MapFileRow]:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@typing.overload
|
||||
def Read(path: str) -> typing.List[QuantConnect.Data.Auxiliary.MapFileRow]:
|
||||
pass
|
||||
|
||||
def Read(self, *args) -> typing.List[QuantConnect.Data.Auxiliary.MapFileRow]:
|
||||
pass
|
||||
|
||||
def ToCsv(self) -> str:
|
||||
pass
|
||||
|
||||
def ToString(self) -> str:
|
||||
pass
|
||||
|
||||
def __init__(self, date: datetime.datetime, mappedSymbol: str) -> QuantConnect.Data.Auxiliary.MapFileRow:
|
||||
pass
|
||||
|
||||
Date: datetime.datetime
|
||||
|
||||
MappedSymbol: str
|
||||
|
||||
|
||||
|
||||
class MappingExtensions(System.object):
|
||||
""" Mapping extensions helper methods """
|
||||
@staticmethod
|
||||
def ResolveMapFile(mapFileResolver: QuantConnect.Data.Auxiliary.MapFileResolver, symbol: QuantConnect.Symbol, dataType: type) -> QuantConnect.Data.Auxiliary.MapFile:
|
||||
pass
|
||||
|
||||
__all__: list
|
||||
|
||||
|
||||
class ZipEntryName(QuantConnect.Data.BaseData, QuantConnect.Data.IBaseData):
|
||||
"""
|
||||
Defines a data type that just produces data points from the zip entry names in a zip file
|
||||
|
||||
ZipEntryName()
|
||||
"""
|
||||
@typing.overload
|
||||
def GetSource(self, config: QuantConnect.Data.SubscriptionDataConfig, date: datetime.datetime, isLiveMode: bool) -> QuantConnect.Data.SubscriptionDataSource:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def GetSource(self, config: QuantConnect.Data.SubscriptionDataConfig, date: datetime.datetime, datafeed: QuantConnect.DataFeedEndpoint) -> str:
|
||||
pass
|
||||
|
||||
def GetSource(self, *args) -> str:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Reader(self, config: QuantConnect.Data.SubscriptionDataConfig, line: str, date: datetime.datetime, isLiveMode: bool) -> QuantConnect.Data.BaseData:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Reader(self, config: QuantConnect.Data.SubscriptionDataConfig, stream: System.IO.StreamReader, date: datetime.datetime, isLiveMode: bool) -> QuantConnect.Data.BaseData:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Reader(self, config: QuantConnect.Data.SubscriptionDataConfig, line: str, date: datetime.datetime, datafeed: QuantConnect.DataFeedEndpoint) -> QuantConnect.Data.BaseData:
|
||||
pass
|
||||
|
||||
def Reader(self, *args) -> QuantConnect.Data.BaseData:
|
||||
pass
|
||||
@@ -1,312 +0,0 @@
|
||||
from .__Consolidators_1 import *
|
||||
import typing
|
||||
import System
|
||||
import QuantConnect.Data.Market
|
||||
import QuantConnect.Data.Consolidators
|
||||
import QuantConnect.Data
|
||||
import QuantConnect
|
||||
import Python.Runtime
|
||||
import datetime
|
||||
|
||||
# functions
|
||||
|
||||
def FilteredIdentityDataConsolidator(*args, **kwargs): # real signature unknown
|
||||
""" Provides factory methods for creating instances of QuantConnect.Data.Consolidators.FilteredIdentityDataConsolidator """
|
||||
pass
|
||||
|
||||
def RenkoConsolidator(barSize, type): # real signature unknown; restored from __doc__
|
||||
"""
|
||||
This consolidator can transform a stream of QuantConnect.Data.BaseData instances into a stream of QuantConnect.Data.Market.RenkoBar
|
||||
|
||||
RenkoConsolidator(barSize: Decimal, type: RenkoType)
|
||||
RenkoConsolidator(barSize: Decimal, evenBars: bool)
|
||||
RenkoConsolidator(barSize: Decimal, selector: Func[IBaseData, Decimal], volumeSelector: Func[IBaseData, Decimal], evenBars: bool)
|
||||
RenkoConsolidator(barSize: Decimal, selector: PyObject, volumeSelector: PyObject, evenBars: bool)
|
||||
"""
|
||||
pass
|
||||
|
||||
# classes
|
||||
|
||||
class BaseDataConsolidator(QuantConnect.Data.Consolidators.TradeBarConsolidatorBase[BaseData], System.IDisposable, QuantConnect.Data.Consolidators.IDataConsolidator):
|
||||
"""
|
||||
Type capable of consolidating trade bars from any base data instance
|
||||
|
||||
BaseDataConsolidator(period: TimeSpan)
|
||||
BaseDataConsolidator(maxCount: int)
|
||||
BaseDataConsolidator(maxCount: int, period: TimeSpan)
|
||||
BaseDataConsolidator(func: Func[DateTime, CalendarInfo])
|
||||
BaseDataConsolidator(pyfuncobj: PyObject)
|
||||
"""
|
||||
@staticmethod
|
||||
def FromResolution(resolution: QuantConnect.Resolution) -> QuantConnect.Data.Consolidators.BaseDataConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, period: datetime.timedelta) -> QuantConnect.Data.Consolidators.BaseDataConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, maxCount: int) -> QuantConnect.Data.Consolidators.BaseDataConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, maxCount: int, period: datetime.timedelta) -> QuantConnect.Data.Consolidators.BaseDataConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, func: typing.Callable[[datetime.datetime], QuantConnect.Data.Consolidators.CalendarInfo]) -> QuantConnect.Data.Consolidators.BaseDataConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, pyfuncobj: Python.Runtime.PyObject) -> QuantConnect.Data.Consolidators.BaseDataConsolidator:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Data.Consolidators.BaseDataConsolidator:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
class Calendar(System.object):
|
||||
""" Helper class that provides System.Func used to define consolidation calendar """
|
||||
__all__: list
|
||||
|
||||
|
||||
class CalendarInfo(System.object):
|
||||
""" CalendarInfo(start: DateTime, period: TimeSpan) """
|
||||
def __init__(self, start: datetime.datetime, period: datetime.timedelta) -> QuantConnect.Data.Consolidators.CalendarInfo:
|
||||
pass
|
||||
|
||||
Period: datetime.timedelta
|
||||
Start: datetime.datetime
|
||||
|
||||
class CalendarType(System.object):
|
||||
# no doc
|
||||
__all__: list
|
||||
|
||||
|
||||
class DataConsolidatedHandler(System.MulticastDelegate, System.Runtime.Serialization.ISerializable, System.ICloneable):
|
||||
"""
|
||||
Event handler type for the IDataConsolidator.DataConsolidated event
|
||||
|
||||
DataConsolidatedHandler(object: object, method: IntPtr)
|
||||
"""
|
||||
def BeginInvoke(self, sender: object, consolidated: QuantConnect.Data.IBaseData, callback: System.AsyncCallback, object: object) -> System.IAsyncResult:
|
||||
pass
|
||||
|
||||
def EndInvoke(self, result: System.IAsyncResult) -> None:
|
||||
pass
|
||||
|
||||
def Invoke(self, sender: object, consolidated: QuantConnect.Data.IBaseData) -> None:
|
||||
pass
|
||||
|
||||
def __init__(self, object: object, method: System.IntPtr) -> QuantConnect.Data.Consolidators.DataConsolidatedHandler:
|
||||
pass
|
||||
|
||||
|
||||
class DataConsolidator(System.object, System.IDisposable, QuantConnect.Data.Consolidators.IDataConsolidator):
|
||||
# no doc
|
||||
def Dispose(self) -> None:
|
||||
pass
|
||||
|
||||
def Scan(self, currentLocalTime: datetime.datetime) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Update(self, data: QuantConnect.Data.IBaseData) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Update(self, data: QuantConnect.Data.Consolidators.TInput) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, *args) -> None:
|
||||
pass
|
||||
|
||||
Consolidated: QuantConnect.Data.IBaseData
|
||||
|
||||
InputType: type
|
||||
|
||||
OutputType: type
|
||||
|
||||
WorkingData: QuantConnect.Data.IBaseData
|
||||
|
||||
|
||||
DataConsolidated: BoundEvent
|
||||
|
||||
|
||||
class DynamicDataConsolidator(QuantConnect.Data.Consolidators.TradeBarConsolidatorBase[DynamicData], System.IDisposable, QuantConnect.Data.Consolidators.IDataConsolidator):
|
||||
"""
|
||||
A data csolidator that can make trade bars from DynamicData derived types. This is useful for
|
||||
aggregating Quandl and other highly flexible dynamic custom data types.
|
||||
|
||||
DynamicDataConsolidator(period: TimeSpan)
|
||||
DynamicDataConsolidator(maxCount: int)
|
||||
DynamicDataConsolidator(maxCount: int, period: TimeSpan)
|
||||
DynamicDataConsolidator(func: Func[DateTime, CalendarInfo])
|
||||
"""
|
||||
@typing.overload
|
||||
def __init__(self, period: datetime.timedelta) -> QuantConnect.Data.Consolidators.DynamicDataConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, maxCount: int) -> QuantConnect.Data.Consolidators.DynamicDataConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, maxCount: int, period: datetime.timedelta) -> QuantConnect.Data.Consolidators.DynamicDataConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, func: typing.Callable[[datetime.datetime], QuantConnect.Data.Consolidators.CalendarInfo]) -> QuantConnect.Data.Consolidators.DynamicDataConsolidator:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Data.Consolidators.DynamicDataConsolidator:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
class IDataConsolidator(System.IDisposable):
|
||||
"""
|
||||
Represents a type capable of taking BaseData updates and firing events containing new
|
||||
'consolidated' data. These types can be used to produce larger bars, or even be used to
|
||||
transform the data before being sent to another component. The most common usage of these
|
||||
types is with indicators.
|
||||
"""
|
||||
def Scan(self, currentLocalTime: datetime.datetime) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, data: QuantConnect.Data.IBaseData) -> None:
|
||||
pass
|
||||
|
||||
Consolidated: QuantConnect.Data.IBaseData
|
||||
|
||||
InputType: type
|
||||
|
||||
OutputType: type
|
||||
|
||||
WorkingData: QuantConnect.Data.IBaseData
|
||||
|
||||
|
||||
DataConsolidated: BoundEvent
|
||||
|
||||
|
||||
class IdentityDataConsolidator(QuantConnect.Data.Consolidators.DataConsolidator[T], System.IDisposable, QuantConnect.Data.Consolidators.IDataConsolidator):
|
||||
""" IdentityDataConsolidator[T]() """
|
||||
def Scan(self, currentLocalTime: datetime.datetime) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Update(self, data: QuantConnect.Data.Consolidators.T) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Update(self, data: QuantConnect.Data.IBaseData) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, *args) -> None:
|
||||
pass
|
||||
|
||||
OutputType: type
|
||||
|
||||
WorkingData: QuantConnect.Data.IBaseData
|
||||
|
||||
|
||||
|
||||
class OpenInterestConsolidator(QuantConnect.Data.Consolidators.PeriodCountConsolidatorBase[Tick, OpenInterest], System.IDisposable, QuantConnect.Data.Consolidators.IDataConsolidator):
|
||||
"""
|
||||
Type capable of consolidating open interest
|
||||
|
||||
OpenInterestConsolidator(period: TimeSpan)
|
||||
OpenInterestConsolidator(maxCount: int)
|
||||
OpenInterestConsolidator(maxCount: int, period: TimeSpan)
|
||||
OpenInterestConsolidator(func: Func[DateTime, CalendarInfo])
|
||||
OpenInterestConsolidator(pyfuncobj: PyObject)
|
||||
"""
|
||||
@staticmethod
|
||||
def FromResolution(resolution: QuantConnect.Resolution) -> QuantConnect.Data.Consolidators.OpenInterestConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, period: datetime.timedelta) -> QuantConnect.Data.Consolidators.OpenInterestConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, maxCount: int) -> QuantConnect.Data.Consolidators.OpenInterestConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, maxCount: int, period: datetime.timedelta) -> QuantConnect.Data.Consolidators.OpenInterestConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, func: typing.Callable[[datetime.datetime], QuantConnect.Data.Consolidators.CalendarInfo]) -> QuantConnect.Data.Consolidators.OpenInterestConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, pyfuncobj: Python.Runtime.PyObject) -> QuantConnect.Data.Consolidators.OpenInterestConsolidator:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Data.Consolidators.OpenInterestConsolidator:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
class PeriodCountConsolidatorBase(QuantConnect.Data.Consolidators.DataConsolidator[T], System.IDisposable, QuantConnect.Data.Consolidators.IDataConsolidator):
|
||||
# no doc
|
||||
def Scan(self, currentLocalTime: datetime.datetime) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Update(self, data: QuantConnect.Data.Consolidators.T) -> None:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Update(self, data: QuantConnect.Data.IBaseData) -> None:
|
||||
pass
|
||||
|
||||
def Update(self, *args) -> None:
|
||||
pass
|
||||
|
||||
def __init__(self, *args): #cannot find CLR constructor
|
||||
pass
|
||||
|
||||
OutputType: type
|
||||
|
||||
WorkingData: QuantConnect.Data.IBaseData
|
||||
|
||||
|
||||
DataConsolidated: BoundEvent
|
||||
|
||||
|
||||
class QuoteBarConsolidator(QuantConnect.Data.Consolidators.PeriodCountConsolidatorBase[QuoteBar, QuoteBar], System.IDisposable, QuantConnect.Data.Consolidators.IDataConsolidator):
|
||||
"""
|
||||
Consolidates QuoteBars into larger QuoteBars
|
||||
|
||||
QuoteBarConsolidator(period: TimeSpan)
|
||||
QuoteBarConsolidator(maxCount: int)
|
||||
QuoteBarConsolidator(maxCount: int, period: TimeSpan)
|
||||
QuoteBarConsolidator(func: Func[DateTime, CalendarInfo])
|
||||
QuoteBarConsolidator(pyfuncobj: PyObject)
|
||||
"""
|
||||
@typing.overload
|
||||
def __init__(self, period: datetime.timedelta) -> QuantConnect.Data.Consolidators.QuoteBarConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, maxCount: int) -> QuantConnect.Data.Consolidators.QuoteBarConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, maxCount: int, period: datetime.timedelta) -> QuantConnect.Data.Consolidators.QuoteBarConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, func: typing.Callable[[datetime.datetime], QuantConnect.Data.Consolidators.CalendarInfo]) -> QuantConnect.Data.Consolidators.QuoteBarConsolidator:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def __init__(self, pyfuncobj: Python.Runtime.PyObject) -> QuantConnect.Data.Consolidators.QuoteBarConsolidator:
|
||||
pass
|
||||
|
||||
def __init__(self, *args) -> QuantConnect.Data.Consolidators.QuoteBarConsolidator:
|
||||
pass
|
||||
@@ -1,138 +0,0 @@
|
||||
# encoding: utf-8
|
||||
# module QuantConnect.Data.Custom.Benzinga calls itself Benzinga
|
||||
# from QuantConnect.Common, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null
|
||||
# by generator 1.145
|
||||
# no doc
|
||||
|
||||
# imports
|
||||
import datetime
|
||||
import Newtonsoft.Json
|
||||
import Newtonsoft.Json.Linq
|
||||
import NodaTime
|
||||
import QuantConnect
|
||||
import QuantConnect.Data
|
||||
import QuantConnect.Data.Custom.Benzinga
|
||||
import System
|
||||
import System.IO
|
||||
import typing
|
||||
|
||||
# no functions
|
||||
# classes
|
||||
|
||||
class BenzingaNews(QuantConnect.Data.IndexedBaseData, QuantConnect.Data.IBaseData):
|
||||
"""
|
||||
News data powered by Benzinga - https://docs.benzinga.io/benzinga/newsfeed-v2.html
|
||||
|
||||
BenzingaNews()
|
||||
"""
|
||||
@typing.overload
|
||||
def Clone(self) -> QuantConnect.Data.BaseData:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Clone(self, fillForward: bool) -> QuantConnect.Data.BaseData:
|
||||
pass
|
||||
|
||||
def Clone(self, *args) -> QuantConnect.Data.BaseData:
|
||||
pass
|
||||
|
||||
def DataTimeZone(self) -> NodaTime.DateTimeZone:
|
||||
pass
|
||||
|
||||
def DefaultResolution(self) -> QuantConnect.Resolution:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def GetSource(self, config: QuantConnect.Data.SubscriptionDataConfig, date: datetime.datetime, isLiveMode: bool) -> QuantConnect.Data.SubscriptionDataSource:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def GetSource(self, config: QuantConnect.Data.SubscriptionDataConfig, date: datetime.datetime, datafeed: QuantConnect.DataFeedEndpoint) -> str:
|
||||
pass
|
||||
|
||||
def GetSource(self, *args) -> str:
|
||||
pass
|
||||
|
||||
def GetSourceForAnIndex(self, config: QuantConnect.Data.SubscriptionDataConfig, date: datetime.datetime, index: str, isLiveMode: bool) -> QuantConnect.Data.SubscriptionDataSource:
|
||||
pass
|
||||
|
||||
def IsSparseData(self) -> bool:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Reader(self, config: QuantConnect.Data.SubscriptionDataConfig, line: str, date: datetime.datetime, isLiveMode: bool) -> QuantConnect.Data.BaseData:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Reader(self, config: QuantConnect.Data.SubscriptionDataConfig, stream: System.IO.StreamReader, date: datetime.datetime, isLiveMode: bool) -> QuantConnect.Data.BaseData:
|
||||
pass
|
||||
|
||||
@typing.overload
|
||||
def Reader(self, config: QuantConnect.Data.SubscriptionDataConfig, line: str, date: datetime.datetime, datafeed: QuantConnect.DataFeedEndpoint) -> QuantConnect.Data.BaseData:
|
||||
pass
|
||||
|
||||
def Reader(self, *args) -> QuantConnect.Data.BaseData:
|
||||
pass
|
||||
|
||||
def RequiresMapping(self) -> bool:
|
||||
pass
|
||||
|
||||
def SupportedResolutions(self) -> typing.List[QuantConnect.Resolution]:
|
||||
pass
|
||||
|
||||
def ToString(self) -> str:
|
||||
pass
|
||||
|
||||
Author: str
|
||||
|
||||
Categories: typing.List[str]
|
||||
|
||||
Contents: str
|
||||
|
||||
CreatedAt: datetime.datetime
|
||||
|
||||
EndTime: datetime.datetime
|
||||
|
||||
Id: int
|
||||
|
||||
Symbols: typing.List[QuantConnect.Symbol]
|
||||
|
||||
Tags: typing.List[str]
|
||||
|
||||
Teaser: str
|
||||
|
||||
Title: str
|
||||
|
||||
UpdatedAt: datetime.datetime
|
||||
|
||||
|
||||
|
||||
class BenzingaNewsJsonConverter(Newtonsoft.Json.JsonConverter):
|
||||
"""
|
||||
Helper json converter class used to convert Benzinga news data
|
||||
into QuantConnect.Data.Custom.Benzinga.BenzingaNews
|
||||
|
||||
An example schema of the data in a serialized format is provided
|
||||
to help you better understand this converter.
|
||||
|
||||
BenzingaNewsJsonConverter(symbol: Symbol, liveMode: bool)
|
||||
"""
|
||||
def CanConvert(self, objectType: type) -> bool:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def DeserializeNews(item: Newtonsoft.Json.Linq.JToken, enableLogging: bool) -> QuantConnect.Data.Custom.Benzinga.BenzingaNews:
|
||||
pass
|
||||
|
||||
def ReadJson(self, reader: Newtonsoft.Json.JsonReader, objectType: type, existingValue: object, serializer: Newtonsoft.Json.JsonSerializer) -> object:
|
||||
pass
|
||||
|
||||
def WriteJson(self, writer: Newtonsoft.Json.JsonWriter, value: object, serializer: Newtonsoft.Json.JsonSerializer) -> None:
|
||||
pass
|
||||
|
||||
def __init__(self, symbol: QuantConnect.Symbol, liveMode: bool) -> QuantConnect.Data.Custom.Benzinga.BenzingaNewsJsonConverter:
|
||||
pass
|
||||
|
||||
ShareClassMappedTickers: Dictionary[str, HashSet[str]]
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user