Compare commits
279 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
854b987cd0 | ||
|
|
a26414d273 | ||
|
|
84264ca7ef | ||
|
|
b2ed398687 | ||
|
|
e8c316cbcf | ||
|
|
724e52c0b3 | ||
|
|
4252c79e45 | ||
|
|
cbb40dfa43 | ||
|
|
8792fa2600 | ||
|
|
20e9fd7899 | ||
|
|
e05a6bffd0 | ||
|
|
c2f0fdc47a | ||
|
|
b1b8da1e17 | ||
|
|
01a0454c57 | ||
|
|
90e2c48404 | ||
|
|
888c443264 | ||
|
|
03efc1b735 | ||
|
|
6ef2ead929 | ||
|
|
bfd319c91e | ||
|
|
5f61456df8 | ||
|
|
a46a551c03 | ||
|
|
cf9b547e2e | ||
|
|
faa4e91e04 | ||
|
|
cc83f19528 | ||
|
|
54af12b06a | ||
|
|
1d1c8f5f82 | ||
|
|
3966c0e91f | ||
|
|
28160e1301 | ||
|
|
f4679785a5 | ||
|
|
79b9009452 | ||
|
|
e5b5f80d9d | ||
|
|
027fde8f09 | ||
|
|
c7ccd60bf2 | ||
|
|
b30bb3fcf5 | ||
|
|
40a87eb056 | ||
|
|
035b29fdf5 | ||
|
|
f2fc1aae9e | ||
|
|
ff5fc5db5d | ||
|
|
40c3062348 | ||
|
|
371f2cd469 | ||
|
|
090ceb131e | ||
|
|
6885fd130b | ||
|
|
a450cea8d0 | ||
|
|
934128cfa0 | ||
|
|
c7a74306fb | ||
|
|
cfacc755fa | ||
|
|
194ed59cbe | ||
|
|
776caea1d3 | ||
|
|
460fd626a6 | ||
|
|
1e3a1e3c43 | ||
|
|
e20725b969 | ||
|
|
151901bbd1 | ||
|
|
fb2f846159 | ||
|
|
d03ac0fd90 | ||
|
|
56db26d16d | ||
|
|
dd8dc473b3 | ||
|
|
b8033c496c | ||
|
|
166fee311a | ||
|
|
be8e381fba | ||
|
|
75eac27795 | ||
|
|
12b481f1ce | ||
|
|
9cb2452025 | ||
|
|
d8dc03fadc | ||
|
|
124e76cfe8 | ||
|
|
4a0fb30df5 | ||
|
|
60b8cf76ba | ||
|
|
9916a9069c | ||
|
|
f135fb8060 | ||
|
|
7bb143b215 | ||
|
|
d7e543736f | ||
|
|
8785af7ad6 | ||
|
|
808fa327e2 | ||
|
|
778e3015c8 | ||
|
|
616b2b8d52 | ||
|
|
98d3a98656 | ||
|
|
20791d6a9e | ||
|
|
3609340281 | ||
|
|
8edc89a4ff | ||
|
|
718dc02173 | ||
|
|
ec5ff53566 | ||
|
|
400a0d42d9 | ||
|
|
ae11e9ce43 | ||
|
|
d3ccc14fcd | ||
|
|
90e911f22c | ||
|
|
34676f0c46 | ||
|
|
d4ca27f93f | ||
|
|
f4ed48fce2 | ||
|
|
ce29a68f85 | ||
|
|
375f192f07 | ||
|
|
ef9ca98bd9 | ||
|
|
aded66ec5b | ||
|
|
59ce008725 | ||
|
|
46e10c0a27 | ||
|
|
2431cfabe7 | ||
|
|
b8674731a5 | ||
|
|
a14f8f1f47 | ||
|
|
fc6ccdbc11 | ||
|
|
ccd31bdfab | ||
|
|
14dd52ba00 | ||
|
|
2d46674fb7 | ||
|
|
554b7345bb | ||
|
|
4348e830ba | ||
|
|
c85f608444 | ||
|
|
9cdb4a91c5 | ||
|
|
a128f8bb2e | ||
|
|
3ef6a761ad | ||
|
|
b866c8b893 | ||
|
|
64a99d1194 | ||
|
|
57cbfa2f26 | ||
|
|
bc44e23322 | ||
|
|
6c051cd816 | ||
|
|
4c04efc237 | ||
|
|
a83388ab1a | ||
|
|
1c9b817960 | ||
|
|
c5c57a33c1 | ||
|
|
47ec1ba8be | ||
|
|
e37c9dbb1a | ||
|
|
c2cac7fbee | ||
|
|
df9c1973da | ||
|
|
bfb13e46c8 | ||
|
|
59286bb750 | ||
|
|
939b334478 | ||
|
|
22155bf3ce | ||
|
|
33bb1e8984 | ||
|
|
fb483365ae | ||
|
|
b0fcf9f7ac | ||
|
|
a044cd6416 | ||
|
|
3f556d70ec | ||
|
|
220ccbae7c | ||
|
|
a6d1908aa9 | ||
|
|
99aa1eadd7 | ||
|
|
d53f79b271 | ||
|
|
78d30b23cb | ||
|
|
a8d6857407 | ||
|
|
fad38f8ed4 | ||
|
|
c7091dbf6b | ||
|
|
ea9007601d | ||
|
|
5278a3dd02 | ||
|
|
ebf4d21bd9 | ||
|
|
c83627a89c | ||
|
|
27e0ce7a57 | ||
|
|
457418e7bc | ||
|
|
db1bf686b9 | ||
|
|
bc41b4461e | ||
|
|
036d8684c0 | ||
|
|
d1e38b33a6 | ||
|
|
a28cde3633 | ||
|
|
2360e4c961 | ||
|
|
839b38d904 | ||
|
|
443ec46c89 | ||
|
|
38ce10c723 | ||
|
|
ab8d95f627 | ||
|
|
f44eb64c97 | ||
|
|
b0c21b605c | ||
|
|
103a8e8a0a | ||
|
|
c4140d3644 | ||
|
|
211f1144b5 | ||
|
|
e7682cbd37 | ||
|
|
68455fe19c | ||
|
|
920e4cba85 | ||
|
|
1eb40d0b6b | ||
|
|
07d51a16aa | ||
|
|
2484a85eda | ||
|
|
69e2a0eef0 | ||
|
|
798b92eef1 | ||
|
|
493cad42ad | ||
|
|
6283266da1 | ||
|
|
a3db5d8710 | ||
|
|
835658ec3e | ||
|
|
b70173de22 | ||
|
|
2f7fa4cbc5 | ||
|
|
f031f6a1c0 | ||
|
|
c171431e3f | ||
|
|
c611e65f1e | ||
|
|
2a82cd87f5 | ||
|
|
48db57d224 | ||
|
|
c7f0f6f769 | ||
|
|
dc82c15c18 | ||
|
|
7133e62745 | ||
|
|
0cd0a77034 | ||
|
|
8903942e3d | ||
|
|
460bf9301d | ||
|
|
815d4bf0a1 | ||
|
|
5faf7a0b55 | ||
|
|
8b91283fff | ||
|
|
935db4ed3e | ||
|
|
5188d0cb7f | ||
|
|
d1624ab899 | ||
|
|
3efb39e313 | ||
|
|
6c09a17d13 | ||
|
|
df7bc89d9b | ||
|
|
3c6d3e7d88 | ||
|
|
0f8e4122cd | ||
|
|
117825ba55 | ||
|
|
bab635856d | ||
|
|
aa0dfc7b3b | ||
|
|
e217caef47 | ||
|
|
2ff1b7d12f | ||
|
|
be7730c186 | ||
|
|
75a5f267f1 | ||
|
|
76e16c1163 | ||
|
|
709b6f53dc | ||
|
|
b897f12e66 | ||
|
|
1af01b8b26 | ||
|
|
3b92a1c6e6 | ||
|
|
50b7f434bb | ||
|
|
bb147042df | ||
|
|
23c3d48e8a | ||
|
|
495cf7171f | ||
|
|
c6157a79ac | ||
|
|
af59e57f66 | ||
|
|
290342e910 | ||
|
|
5f7b58bc09 | ||
|
|
44a82b82cf | ||
|
|
ec6abfacc8 | ||
|
|
5131b948dd | ||
|
|
3ae3244318 | ||
|
|
d9902231db | ||
|
|
cf888028af | ||
|
|
be5ab2c0f4 | ||
|
|
d80dc2b49b | ||
|
|
828b2424c6 | ||
|
|
7058254cc7 | ||
|
|
086432c3c6 | ||
|
|
9cfeb36d4f | ||
|
|
a72e3f0598 | ||
|
|
a4a504ce6b | ||
|
|
676f335ee8 | ||
|
|
74485c32ba | ||
|
|
4f393e8dbf | ||
|
|
831e1c0b78 | ||
|
|
053925829c | ||
|
|
4263afab9f | ||
|
|
341067986c | ||
|
|
da89f6f3d1 | ||
|
|
d0fdae71b4 | ||
|
|
c548bd7085 | ||
|
|
efb2667285 | ||
|
|
c3062e4c0e | ||
|
|
b28ed7c9f2 | ||
|
|
a29bdc7f0a | ||
|
|
8924d203e5 | ||
|
|
d7bb8a2018 | ||
|
|
bf3f71ca6c | ||
|
|
917db3c89a | ||
|
|
b7ba768371 | ||
|
|
a9a37c1647 | ||
|
|
172f086d07 | ||
|
|
353961a088 | ||
|
|
0249f51a89 | ||
|
|
62aac8e516 | ||
|
|
c18b1af5ce | ||
|
|
febc4b50ea | ||
|
|
79a05ebd27 | ||
|
|
98cde3479a | ||
|
|
36c59d41bc | ||
|
|
768764030e | ||
|
|
dbf3248f53 | ||
|
|
615bdff3dd | ||
|
|
e6ea8525f6 | ||
|
|
87095577e3 | ||
|
|
06e165fd3b | ||
|
|
cc20f8be66 | ||
|
|
71ab27384b | ||
|
|
b117090ba7 | ||
|
|
65a4bb6a83 | ||
|
|
e9d69eba74 | ||
|
|
8d0d27253a | ||
|
|
17b03a7d28 | ||
|
|
2d022fadff | ||
|
|
3737049dde | ||
|
|
4c7cbd42ca | ||
|
|
b606c3dbaa | ||
|
|
3baf8c3959 | ||
|
|
89015db955 | ||
|
|
81f2c43d0a | ||
|
|
b638c450cb | ||
|
|
b0f787abd8 | ||
|
|
a3356904b0 |
6
.gitignore
vendored
6
.gitignore
vendored
@@ -34,8 +34,9 @@
|
||||
|
||||
# QC Cloud Setup Bash Files
|
||||
*.sh
|
||||
# Include docker build scripts for Mac/Linux
|
||||
# Include docker launch scripts for Mac/Linux
|
||||
!run_docker.sh
|
||||
!research/run_docker_notebook.sh
|
||||
|
||||
# QC Config Files:
|
||||
# config.json
|
||||
@@ -267,3 +268,6 @@ Launcher/Plugins/*
|
||||
/ApiPython/quantconnect.egg-info/*
|
||||
|
||||
QuantConnect.Lean.sln.DotSettings*
|
||||
|
||||
#User notebook files
|
||||
Research/Notebooks
|
||||
|
||||
18
.idea/Lean.iml
generated
Normal file
18
.idea/Lean.iml
generated
Normal file
@@ -0,0 +1,18 @@
|
||||
<?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>
|
||||
144
.idea/readme.md
generated
Normal file
144
.idea/readme.md
generated
Normal file
@@ -0,0 +1,144 @@
|
||||
<h1>Local Development & Docker Integration with Pycharm</h1>
|
||||
|
||||
This document contains information regarding ways to use Lean’s Docker image in conjunction with local development in Pycharm.
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
<h1>Getting Setup</h1>
|
||||
|
||||
|
||||
Before anything we need to ensure a few things have been done:
|
||||
|
||||
|
||||
1. Get [Pycharm Professional](https://www.jetbrains.com/pycharm/)**
|
||||
|
||||
2. Get [Docker](https://docs.docker.com/get-docker/):
|
||||
* Follow the instructions for your Operating System
|
||||
* New to Docker? Try docker getting-started
|
||||
|
||||
|
||||
3. Pull Lean’s latest image from a terminal
|
||||
* _docker pull quantconnect/lean_
|
||||
|
||||
4. Get Lean into Pycharm
|
||||
* Download the repo or clone it using: _git clone[ https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)_
|
||||
* Open the folder using Pycharm
|
||||
|
||||
|
||||
_**PyCharm’s remote debugger requires PyCharm Professional._
|
||||
|
||||
<br />
|
||||
|
||||
<h1>Develop Algorithms Locally, Run in Container</h1>
|
||||
|
||||
|
||||
We have set up a relatively easy way to develop algorithms in your local IDE and push them into the container to be run and debugged.
|
||||
|
||||
Before we can use this method with Windows or Mac OS we need to share the Lean directory with Docker.
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Activate File Sharing for Docker:</h2>
|
||||
|
||||
* Windows:
|
||||
* [Guide to sharing](https://docs.docker.com/docker-for-windows/#file-sharing)
|
||||
* Share the LEAN root directory with docker
|
||||
|
||||
* Mac:
|
||||
* [Guide to sharing](https://docs.docker.com/docker-for-mac/#file-sharing)
|
||||
* Share the LEAN root directory with docker
|
||||
|
||||
* Linux:
|
||||
* (No setup required)
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Lean Configuration</h2>
|
||||
|
||||
Next we need to be sure that our Lean configuration at **.\Launcher\config.json** is properly set. Just like running lean locally the config must reflect what we want Lean to run.
|
||||
|
||||
You configuration file should look something like this:
|
||||
|
||||
<h3>Python:</h3>
|
||||
|
||||
"algorithm-type-name": "**AlgorithmName**",
|
||||
|
||||
"algorithm-language": "Python",
|
||||
|
||||
"algorithm-location": "../../../Algorithm.Python/**AlgorithmName**.py",
|
||||
|
||||
<h4>Note About Python Algorithm Location</h4>
|
||||
|
||||
|
||||
Our specific configuration binds the Algorithm.Python directory to the container by default so any algorithm you would like to run should be in that directory. Please ensure your algorithm location looks just the same as the example above. If you want to use a different location refer to the section bellow on setting that argument for the container and make sure your config.json also reflects this.
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Running Lean in the Container</h2>
|
||||
|
||||
This section will cover how to actually launch Lean in the container with your desired configuration.
|
||||
|
||||
From a terminal; Pycharm has a built in terminal on the bottom taskbar labeled **Terminal**; launch the run_docker.bat/.sh script; there are a few choices on how to launch this:
|
||||
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_\]:
|
||||
* 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=
|
||||
|
||||
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 />
|
||||
|
||||
<h1>Debugging Python</h1>
|
||||
|
||||
Debugging your Python algorithms requires an extra step within your configuration and inside of PyCharm. Thankfully we were able to configure the PyCharm launch configurations to take care of most of the work for you!
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Modifying the Configuration</h2>
|
||||
|
||||
First in order to debug a Python algorithm in Pycharm we must make the following change to our configuration (Launcher\config.json) under the comment debugging configuration:
|
||||
|
||||
"debugging": true,
|
||||
"debugging-method": "PyCharm",
|
||||
|
||||
|
||||
In setting this we are telling Lean to reach out and create a debugger connection using PyCharm’s PyDevd debugger server. Once this is set Lean will **always** attempt to connect to a debugger server on launch. **If you are no longer debugging set “debugging” to false.**
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Using PyCharm Launch Options</h2>
|
||||
|
||||
|
||||
Now that Lean is configured for the debugger we can make use of the programmed launch options to connect.
|
||||
|
||||
|
||||
|
||||
**<h3>Container (Recommended)</h3>**
|
||||
|
||||
|
||||
To debug inside of the container we must first start the debugger server in Pycharm, to do this use the drop down configuration “Debug in Container” and launch the debugger. Be sure to set some breakpoints in your algorithms!
|
||||
|
||||
Then we will need to launch the container, follow the steps described in the section “[Running Lean in the Container](#Running-Lean-in-the-Container)”. After launching the container the debugging configuration will take effect and it will connect to the debug server where you can begin debugging your algorithm.
|
||||
|
||||
|
||||
**<h3>Local</h3>**
|
||||
|
||||
|
||||
To debug locally we must run the program locally. First, just as the container setup, start the PyCharm debugger server by running the “Debug Local” configuration.
|
||||
|
||||
Then start the program locally by whatever means you typically use, such as Mono, directly running the program at **QuantConnect.Lean.Launcher.exe**, etc. Once the program is running it will make the connection to your PyCharm debugger server where you can begin debugging your algorithm.
|
||||
37
.idea/workspace.xml
generated
Normal file
37
.idea/workspace.xml
generated
Normal file
@@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="RunManager" selected="Python Debug Server.Debug in Container">
|
||||
<configuration name="Debug Local" type="PyRemoteDebugConfigurationType" factoryName="Python Remote Debug">
|
||||
<module name="LEAN" />
|
||||
<option name="PORT" value="5678" />
|
||||
<option name="HOST" value="localhost" />
|
||||
<PathMappingSettings>
|
||||
<option name="pathMappings">
|
||||
<list />
|
||||
</option>
|
||||
</PathMappingSettings>
|
||||
<option name="REDIRECT_OUTPUT" value="true" />
|
||||
<option name="SUSPEND_AFTER_CONNECT" value="true" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration name="Debug in Container" type="PyRemoteDebugConfigurationType" factoryName="Python Remote Debug">
|
||||
<module name="LEAN" />
|
||||
<option name="PORT" value="5678" />
|
||||
<option name="HOST" value="localhost" />
|
||||
<PathMappingSettings>
|
||||
<option name="pathMappings">
|
||||
<list>
|
||||
<mapping local-root="$PROJECT_DIR$" remote-root="/Lean" />
|
||||
</list>
|
||||
</option>
|
||||
</PathMappingSettings>
|
||||
<option name="REDIRECT_OUTPUT" value="true" />
|
||||
<option name="SUSPEND_AFTER_CONNECT" value="true" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<list>
|
||||
<item itemvalue="Python Debug Server.Debug Local" />
|
||||
<item itemvalue="Python Debug Server.Debug in Container" />
|
||||
</list>
|
||||
</component>
|
||||
</project>
|
||||
@@ -22,3 +22,5 @@ install:
|
||||
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
|
||||
|
||||
136
.vs/readme.md
Normal file
136
.vs/readme.md
Normal file
@@ -0,0 +1,136 @@
|
||||
<h1>Local Development & Docker Integration with Visual Studio</h1>
|
||||
|
||||
|
||||
This document contains information regarding ways to use Visual Studio to work with the Lean's Docker image.
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
<h1>Getting Setup</h1>
|
||||
|
||||
|
||||
Before anything we need to ensure a few things have been done:
|
||||
|
||||
|
||||
1. Get [Visual Studio](https://code.visualstudio.com/download)
|
||||
* Get the Extension [VSMonoDebugger](https://marketplace.visualstudio.com/items?itemName=GordianDotNet.VSMonoDebugger0d62) for C# Debugging
|
||||
|
||||
2. Get [Docker](https://docs.docker.com/get-docker/):
|
||||
* Follow the instructions for your Operating System
|
||||
* New to Docker? Try docker getting-started
|
||||
|
||||
|
||||
3. Pull Lean’s latest image from a terminal
|
||||
* _docker pull quantconnect/lean_
|
||||
|
||||
4. Get Lean into Visual Studio
|
||||
* Download the repo or clone it using: _git clone[ https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)_
|
||||
* Open the solution **QuantConnect.Lean.sln** using Visual Studio
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
<h1>Develop Algorithms Locally, Run in Container</h1>
|
||||
|
||||
|
||||
We have set up a relatively easy way to develop algorithms in your local IDE and push them into the container to be run and debugged.
|
||||
|
||||
Before we can use this method with Windows or Mac OS we need to share the Lean directory with Docker.
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Activate File Sharing for Docker:</h2>
|
||||
|
||||
* Windows:
|
||||
* [Guide to sharing](https://docs.docker.com/docker-for-windows/#file-sharing)
|
||||
* Share the LEAN root directory with docker
|
||||
|
||||
* Mac:
|
||||
* [Guide to sharing](https://docs.docker.com/docker-for-mac/#file-sharing)
|
||||
* Share the LEAN root directory with docker
|
||||
|
||||
* Linux:
|
||||
* (No setup required)
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Lean Configuration</h2>
|
||||
|
||||
Next we need to be sure that our Lean configuration at **.\Launcher\config.json** is properly set. Just like running lean locally the config must reflect what we want Lean to run.
|
||||
|
||||
You configuration file should look something like this for the following languages:
|
||||
|
||||
<h3>Python:</h3>
|
||||
|
||||
"algorithm-type-name": "**AlgorithmName**",
|
||||
|
||||
"algorithm-language": "Python",
|
||||
|
||||
"algorithm-location": "../../../Algorithm.Python/**AlgorithmName**.py",
|
||||
|
||||
<h3>C#:</h3>
|
||||
|
||||
"algorithm-type-name": "**AlgorithmName**",
|
||||
|
||||
"algorithm-language": "CSharp",
|
||||
|
||||
"algorithm-location": "QuantConnect.Algorithm.CSharp.dll",
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Important Note About C#</h2>
|
||||
|
||||
In order to use a custom C# algorithm, the C# file must be compiled before running in the docker, as it is compiled into the file **"QuantConnect.Algorithm.CSharp.dll"**. Any new C# files will need to be added to the csproj compile list before it will compile, check **Algorithm.CSharp/QuantConnect.Algorithm.CSharp.csproj** for all algorithms that are compiled. Once there is an entry for your algorithm the project can be compiled by using **Build > Build Solution**.
|
||||
|
||||
If you would like to debug this file in the docker container one small change to the solutions target build is required.
|
||||
1. Right click on the solution **QuantConnect.Lean** in the _Solution Explorer_
|
||||
2. Select **Properties**
|
||||
3. For project entry **QuantConnect.Algorithm.CSharp** change the configuration to **DebugDocker**
|
||||
4. Select **Apply** and close out of the window.
|
||||
5. Build the project at least once before running the docker.
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Running Lean in the Container</h2>
|
||||
|
||||
This section will cover how to actually launch Lean in the container with your desired configuration.
|
||||
|
||||
From a terminal launch the run_docker.bat/.sh script; there are a few choices on how to launch this:
|
||||
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_\]:
|
||||
* 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=
|
||||
|
||||
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 />
|
||||
|
||||
<h1>Connecting to Mono Debugger</h1>
|
||||
|
||||
If you launch the script with debugging set to **yes** (y), then you will need to connect to the debugging server with the mono extension that you installed in the setup stage.
|
||||
|
||||
To setup the extension do the following:
|
||||
* Go to **Extensions > Mono > Settings...**
|
||||
* Enter the following for the settings:
|
||||
* Remote Host IP: 127.0.0.1
|
||||
* Remote Host Port: 55555
|
||||
* Mono Debug Port: 55555
|
||||
* Click **Save** and then close the extension settings
|
||||
|
||||
Now that the extension is setup use it to connect to the Docker container by using:
|
||||
* **Extensions > Mono > Attach to mono debugger**
|
||||
|
||||
The program should then launch and trigger any breakpoints you have set in your C# Algorithm.
|
||||
82
.vscode/launch.json
vendored
Normal file
82
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,82 @@
|
||||
{
|
||||
/*
|
||||
VS Code Launch configurations for the LEAN engine
|
||||
|
||||
Launch w/ Mono (Local):
|
||||
Builds the project with MSBuild and then launches the program using mono locally;
|
||||
supports debugging. In order to use this you need msbuild and mono on your system path.
|
||||
As well as the Mono Debug extension from the marketplace.
|
||||
|
||||
Debug in Container:
|
||||
Launches our run_docker script to start the container and attaches to the debugger.
|
||||
Requires that you have built the project at least once as it will transfer the compiled
|
||||
csharp files.
|
||||
Requires Mono Debug extension from the marketplace.
|
||||
|
||||
Attach to Python (Container):
|
||||
Will attempt to attach to LEAN in the container using PTVSD. Requires that the container is
|
||||
actively running and config is set: "debugging": true, "debugging-method": "PTVSD",
|
||||
Requires Python extension from the marketplace.
|
||||
|
||||
Attach to Python (Local):
|
||||
Will attempt to attach to LEAN running locally using PTVSD. Requires that the process is
|
||||
actively running and config is set: "debugging": true, "debugging-method": "PTVSD",
|
||||
Requires Python extension from the marketplace.
|
||||
|
||||
*/
|
||||
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Launch w/ Mono (Local)",
|
||||
"type": "mono",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build",
|
||||
"cwd": "${workspaceFolder}/Launcher/bin/Debug/",
|
||||
"program": "${workspaceFolder}/Launcher/bin/Debug/QuantConnect.Lean.Launcher.exe",
|
||||
"args": [
|
||||
"--data-folder",
|
||||
"${workspaceFolder}/Data",
|
||||
"--config",
|
||||
"${workspaceFolder}/Launcher/config.json"],
|
||||
"console": "externalTerminal"
|
||||
},
|
||||
{
|
||||
"name": "Debug in Container",
|
||||
"type": "mono",
|
||||
"preLaunchTask": "run-docker",
|
||||
"postDebugTask": "close-docker",
|
||||
"request": "attach",
|
||||
"address": "localhost",
|
||||
"port": 55555
|
||||
},
|
||||
{
|
||||
"name": "Attach to Mono",
|
||||
"type": "mono",
|
||||
"request": "attach",
|
||||
"address": "localhost",
|
||||
"postDebugTask": "close-docker",
|
||||
"port": 55555
|
||||
},
|
||||
{
|
||||
"name": "Attach to Python (Container)",
|
||||
"type": "python",
|
||||
"request": "attach",
|
||||
"port": 5678,
|
||||
"pathMappings":[{
|
||||
"localRoot": "${workspaceFolder}",
|
||||
"remoteRoot": "/Lean/"
|
||||
}]
|
||||
},
|
||||
{
|
||||
"name": "Attach to Python (Local)",
|
||||
"type": "python",
|
||||
"request": "attach",
|
||||
"port": 5678,
|
||||
"pathMappings":[{
|
||||
"localRoot": "${workspaceFolder}",
|
||||
"remoteRoot": "${workspaceFolder}"
|
||||
}]
|
||||
}
|
||||
]
|
||||
}
|
||||
197
.vscode/readme.md
vendored
Normal file
197
.vscode/readme.md
vendored
Normal file
@@ -0,0 +1,197 @@
|
||||
<h1>Local Development & Docker Integration with Visual Studio Code</h1>
|
||||
|
||||
|
||||
This document contains information regarding ways to use Visual Studio Code to work with the Lean engine, this includes using Lean’s Docker image in conjunction with local development as well as running Lean locally.
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
<h1>Getting Setup</h1>
|
||||
|
||||
|
||||
Before anything we need to ensure a few things have been done:
|
||||
|
||||
|
||||
1. Get [Visual Studio Code](https://code.visualstudio.com/download)
|
||||
* Get the Extension [Mono Debug](https://marketplace.visualstudio.com/items?itemName=ms-vscode.mono-debug) for C# Debugging
|
||||
* Get the Extension [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) for Python Debugging
|
||||
|
||||
2. Get [Docker](https://docs.docker.com/get-docker/):
|
||||
* Follow the instructions for your Operating System
|
||||
* New to Docker? Try docker getting-started
|
||||
|
||||
3. Install a compiler for the project **(Only needed for C# Debugging or Running Locally)**
|
||||
* On Linux or Mac:
|
||||
* Install [mono-complete](https://www.mono-project.com/docs/getting-started/install/linux/)
|
||||
* Test msbuild with command: _msbuild -version_
|
||||
* On Windows:
|
||||
* Visual Studio comes packed with msbuild or download without VS [here](https://visualstudio.microsoft.com/downloads/?q=build+tools)
|
||||
* Put msbuild on your system path and test with command: _msbuild -version_
|
||||
|
||||
4. Pull Lean’s latest image from a terminal
|
||||
* _docker pull quantconnect/lean_
|
||||
|
||||
5. Get Lean into VS Code
|
||||
* Download the repo or clone it using: _git clone[ https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)_
|
||||
* Open the folder using VS Code
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
<h1>Develop Algorithms Locally, Run in Container</h1>
|
||||
|
||||
|
||||
We have set up a relatively easy way to develop algorithms in your local IDE and push them into the container to be run and debugged.
|
||||
|
||||
Before we can use this method with Windows or Mac OS we need to share the Lean directory with Docker.
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Activate File Sharing for Docker:</h2>
|
||||
|
||||
* Windows:
|
||||
* [Guide to sharing](https://docs.docker.com/docker-for-windows/#file-sharing)
|
||||
* Share the LEAN root directory with docker
|
||||
|
||||
* Mac:
|
||||
* [Guide to sharing](https://docs.docker.com/docker-for-mac/#file-sharing)
|
||||
* Share the LEAN root directory with docker
|
||||
|
||||
* Linux:
|
||||
* (No setup required)
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Lean Configuration</h2>
|
||||
|
||||
Next we need to be sure that our Lean configuration at **.\Launcher\config.json** is properly set. Just like running lean locally the config must reflect what we want Lean to run.
|
||||
|
||||
You configuration file should look something like this for the following languages:
|
||||
|
||||
<h3>Python:</h3>
|
||||
|
||||
"algorithm-type-name": "**AlgorithmName**",
|
||||
|
||||
"algorithm-language": "Python",
|
||||
|
||||
"algorithm-location": "../../../Algorithm.Python/**AlgorithmName**.py",
|
||||
|
||||
<h3>C#:</h3>
|
||||
|
||||
"algorithm-type-name": "**AlgorithmName**",
|
||||
|
||||
"algorithm-language": "CSharp",
|
||||
|
||||
"algorithm-location": "QuantConnect.Algorithm.CSharp.dll",
|
||||
|
||||
|
||||
<h3>Important Note About C#</h3>
|
||||
|
||||
In order to use a custom C# algorithm, the C# file must be compiled before running in the docker, as it is compiled into the file "QuantConnect.Algorithm.CSharp.dll". Any new C# files will need to be added to the csproj compile list before it will compile, check Algorithm.CSharp/QuantConnect.Algorithm.CSharp.csproj for all algorithms that are compiled. Once there is an entry for your algorithm the project can be compiled by using the “build” task under _“Terminal” > “Run Build Task”._
|
||||
|
||||
Python **does not** have this requirement as the engine will compile it on the fly.
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Running Lean in the Container</h2>
|
||||
|
||||
This section will cover how to actually launch Lean in the container with your desired configuration.
|
||||
|
||||
<br />
|
||||
|
||||
<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:
|
||||
|
||||
"image=quantconnect/lean:latest",
|
||||
"config_file=${workspaceFolder}/Launcher/config.json",
|
||||
"data_dir=${workspaceFolder}/Data",
|
||||
"results_dir=${workspaceFolder}/",
|
||||
"debugging=Y",
|
||||
"python_location=${workspaceFolder}/Algorithm.Python"
|
||||
|
||||
As defaults these are all great! Feel free to change them as needed for your setup.
|
||||
|
||||
<br />
|
||||
|
||||
<h3>Option 2</h3>
|
||||
|
||||
From a terminal launch the run_docker.bat/.sh script; there are a few choices on how to launch this:
|
||||
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_\]:
|
||||
* 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=
|
||||
|
||||
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 />
|
||||
|
||||
<h1>Debugging Python</h1>
|
||||
|
||||
Python algorithms require a little extra work in order to be able to debug them locally or in the container. Thankfully we were able to configure VS code tasks to take care of the work for you! Follow the steps below to get Python debugging working.
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Modifying the Configuration</h2>
|
||||
|
||||
First in order to debug a Python algorithm in VS Code we must make the following change to our configuration (Launcher\config.json) under the comment debugging configuration:
|
||||
|
||||
"debugging": true,
|
||||
"debugging-method": "PTVSD",
|
||||
|
||||
In setting this we are telling Lean to expect a debugger connection using ‘Python Tools for Visual Studio Debugger’. Once this is set Lean will stop upon initialization and await a connection to the debugger via port 5678.
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Using VS Code Launch Options to Connect</h2>
|
||||
|
||||
Now that Lean is configured for the python debugger we can make use of the programmed launch options to connect.
|
||||
|
||||
<br />
|
||||
|
||||
<h3>Container</h3>
|
||||
|
||||
|
||||
To debug inside of the container we must first start the container, follow the steps described in the section “[Running Lean in the Container](#Running-Lean-in-the-Container)”. Once the container is started you should see the messages in Figure 2.
|
||||
|
||||
If the message is displayed, use the same drop down for “Debug in Container” and select “Attach to Python (Container)”. Then press run, VS Code will now enter and debug any breakpoints you have set in your Python algorithm.
|
||||
|
||||
<br />
|
||||
|
||||
<h3>Local</h3>
|
||||
|
||||
|
||||
To debug locally we must run the program locally using the programmed task found under Terminal > Run Task > “Run Application”. Once Lean is started you should see the messages in Figure 2.
|
||||
|
||||
If the message is displayed, use the launch option “Attach to Python (Local)”. Then press run, VS Code will now enter and debug any breakpoints you have set in your python algorithm.
|
||||
|
||||
<br />
|
||||
|
||||
_Figure 2: Python Debugger Messages_
|
||||
|
||||
```
|
||||
20200715 17:12:06.546 Trace:: PythonInitializer.Initialize(): ended
|
||||
20200715 17:12:06.547 Trace:: DebuggerHelper.Initialize(): python initialization done
|
||||
20200715 17:12:06.547 Trace:: DebuggerHelper.Initialize(): starting...
|
||||
20200715 17:12:06.548 Trace:: DebuggerHelper.Initialize(): waiting for debugger to attach at localhost:5678...
|
||||
```
|
||||
|
||||
<br />
|
||||
|
||||
<h1>Common Issues</h1>
|
||||
Here we will cover some common issues with setting this up. This section will expand as we get user feedback!
|
||||
|
||||
* Error messages about build in VSCode points to comments in JSON. Either select **ignore** or follow steps described [here](https://stackoverflow.com/questions/47834825/in-vs-code-disable-error-comments-are-not-permitted-in-json) to remove the errors entirely.
|
||||
5
.vscode/settings.json
vendored
Normal file
5
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"python.autoComplete.extraPaths": [
|
||||
"Algorithm.Python/stubs"
|
||||
]
|
||||
}
|
||||
111
.vscode/tasks.json
vendored
Normal file
111
.vscode/tasks.json
vendored
Normal file
@@ -0,0 +1,111 @@
|
||||
{
|
||||
/*
|
||||
VS Code Tasks for the LEAN engine
|
||||
In order to use the build tasks you need msbuild on your system path.
|
||||
*/
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "build",
|
||||
"type": "shell",
|
||||
"command": "msbuild",
|
||||
"args": [
|
||||
"/p:Configuration=Debug",
|
||||
"/p:DebugType=portable",
|
||||
"/t:build",
|
||||
],
|
||||
"group": "build",
|
||||
"presentation": {
|
||||
"reveal": "silent"
|
||||
},
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "force build linux",
|
||||
"type": "shell",
|
||||
"command": "msbuild",
|
||||
"args": [
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/p:Configuration=Debug",
|
||||
"/p:DebugType=portable",
|
||||
"/t:build",
|
||||
"/p:ForceLinuxBuild=true"
|
||||
],
|
||||
"group": "build",
|
||||
"presentation": {
|
||||
"reveal": "silent"
|
||||
},
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "run-docker",
|
||||
"type": "shell",
|
||||
"isBackground": true,
|
||||
"windows": {
|
||||
"command": "${workspaceFolder}/run_docker.bat",
|
||||
},
|
||||
"linux": {
|
||||
"command": "${workspaceFolder}/run_docker.sh"
|
||||
},
|
||||
"osx": {
|
||||
"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"
|
||||
],
|
||||
"problemMatcher": [
|
||||
{
|
||||
"pattern": [
|
||||
{
|
||||
"regexp": ".",
|
||||
"file": 1,
|
||||
"location": 2,
|
||||
"message": 3
|
||||
}
|
||||
],
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": ".",
|
||||
"endsPattern": ".",
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "close-docker",
|
||||
"type": "shell",
|
||||
"command": "docker stop LeanEngine",
|
||||
"presentation": {
|
||||
"echo": false,
|
||||
"reveal": "never",
|
||||
"focus": false,
|
||||
"panel": "shared",
|
||||
"showReuseMessage": false,
|
||||
"clear": true,
|
||||
},
|
||||
"linux":{
|
||||
"command": "sudo docker stop LeanEngine"
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "Run Application",
|
||||
"type": "process",
|
||||
"command": "QuantConnect.Lean.Launcher.exe",
|
||||
"args" : [
|
||||
"--data-folder",
|
||||
"${workspaceFolder}/Data",
|
||||
"--config",
|
||||
"${workspaceFolder}/Launcher/config.json"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}/Launcher/bin/Debug/"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
164
Algorithm.CSharp/AddOptionContractExpiresRegressionAlgorithm.cs
Normal file
164
Algorithm.CSharp/AddOptionContractExpiresRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// We add an option contract using <see cref="QCAlgorithm.AddOptionContract"/> and place a trade and wait till it expires
|
||||
/// later will liquidate the resulting equity position and assert both option and underlying get removed
|
||||
/// </summary>
|
||||
public class AddOptionContractExpiresRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private DateTime _expiration = new DateTime(2014, 06, 21);
|
||||
private Symbol _option;
|
||||
private Symbol _twx;
|
||||
private bool _traded;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 06, 05);
|
||||
SetEndDate(2014, 06, 30);
|
||||
|
||||
_twx = QuantConnect.Symbol.Create("TWX", SecurityType.Equity, Market.USA);
|
||||
|
||||
AddUniverse("my-daily-universe-name", time => new List<string> { "AAPL" });
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (_option == null)
|
||||
{
|
||||
var option = OptionChainProvider.GetOptionContractList(_twx, Time)
|
||||
.OrderBy(symbol => symbol.ID.Symbol)
|
||||
.FirstOrDefault(optionContract => optionContract.ID.Date == _expiration
|
||||
&& optionContract.ID.OptionRight == OptionRight.Call
|
||||
&& optionContract.ID.OptionStyle == OptionStyle.American);
|
||||
if (option != null)
|
||||
{
|
||||
_option = AddOptionContract(option).Symbol;
|
||||
}
|
||||
}
|
||||
|
||||
if (_option != null && Securities[_option].Price != 0 && !_traded)
|
||||
{
|
||||
_traded = true;
|
||||
Buy(_option, 1);
|
||||
|
||||
foreach (var symbol in new [] { _option, _option.Underlying })
|
||||
{
|
||||
var config = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol).ToList();
|
||||
|
||||
if (!config.Any())
|
||||
{
|
||||
throw new Exception($"Was expecting configurations for {symbol}");
|
||||
}
|
||||
if (config.Any(dataConfig => dataConfig.DataNormalizationMode != DataNormalizationMode.Raw))
|
||||
{
|
||||
throw new Exception($"Was expecting DataNormalizationMode.Raw configurations for {symbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Time.Date > _expiration)
|
||||
{
|
||||
if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_option).Any())
|
||||
{
|
||||
throw new Exception($"Unexpected configurations for {_option} after it has been delisted");
|
||||
}
|
||||
|
||||
if (Securities[_twx].Invested)
|
||||
{
|
||||
if (!SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_twx).Any())
|
||||
{
|
||||
throw new Exception($"Was expecting configurations for {_twx}");
|
||||
}
|
||||
|
||||
// first we liquidate the option exercised position
|
||||
Liquidate(_twx);
|
||||
}
|
||||
}
|
||||
else if (Time.Date > _expiration && !Securities[_twx].Invested)
|
||||
{
|
||||
if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_twx).Any())
|
||||
{
|
||||
throw new Exception($"Unexpected configurations for {_twx} after it has been liquidated");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "2.73%"},
|
||||
{"Average Loss", "-2.98%"},
|
||||
{"Compounding Annual Return", "-4.619%"},
|
||||
{"Drawdown", "0.300%"},
|
||||
{"Expectancy", "-0.042"},
|
||||
{"Net Profit", "-0.332%"},
|
||||
{"Sharpe Ratio", "-3.7"},
|
||||
{"Probabilistic Sharpe Ratio", "0.563%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.92"},
|
||||
{"Alpha", "-0.023"},
|
||||
{"Beta", "0.005"},
|
||||
{"Annual Standard Deviation", "0.006"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-3.424"},
|
||||
{"Tracking Error", "0.057"},
|
||||
{"Treynor Ratio", "-4.775"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-43.418"},
|
||||
{"Return Over Maximum Drawdown", "-14.274"},
|
||||
{"Portfolio Turnover", "0.007"},
|
||||
{"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", "-1185639451"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// We add an option contract using <see cref="QCAlgorithm.AddOptionContract"/> and place a trade, the underlying
|
||||
/// gets deselected from the universe selection but should still be present since we manually added the option contract.
|
||||
/// Later we call <see cref="QCAlgorithm.RemoveOptionContract"/> and expect both option and underlying to be removed.
|
||||
/// </summary>
|
||||
public class AddOptionContractFromUniverseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private DateTime _expiration = new DateTime(2014, 06, 21);
|
||||
private SecurityChanges _securityChanges = SecurityChanges.None;
|
||||
private Symbol _option;
|
||||
private Symbol _aapl;
|
||||
private Symbol _twx;
|
||||
private bool _traded;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
_twx = QuantConnect.Symbol.Create("TWX", SecurityType.Equity, Market.USA);
|
||||
_aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
|
||||
UniverseSettings.Resolution = Resolution.Minute;
|
||||
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
|
||||
|
||||
SetStartDate(2014, 06, 05);
|
||||
SetEndDate(2014, 06, 09);
|
||||
|
||||
AddUniverse(enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl },
|
||||
enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl });
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (_option != null && Securities[_option].Price != 0 && !_traded)
|
||||
{
|
||||
_traded = true;
|
||||
Buy(_option, 1);
|
||||
}
|
||||
|
||||
if (Time.Date > new DateTime(2014, 6, 5))
|
||||
{
|
||||
if (Time < new DateTime(2014, 6, 6, 14, 0, 0))
|
||||
{
|
||||
var configs = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_twx);
|
||||
// assert underlying still there after the universe selection removed it, still used by the manually added option contract
|
||||
if (!configs.Any())
|
||||
{
|
||||
throw new Exception($"Was expecting configurations for {_twx}" +
|
||||
$" even after it has been deselected from coarse universe because we still have the option contract.");
|
||||
}
|
||||
}
|
||||
else if (Time == new DateTime(2014, 6, 6, 14, 0, 0))
|
||||
{
|
||||
// liquidate & remove the option
|
||||
RemoveOptionContract(_option);
|
||||
}
|
||||
// assert underlying was finally removed
|
||||
else if(Time > new DateTime(2014, 6, 6, 14, 0, 0))
|
||||
{
|
||||
foreach (var symbol in new[] { _option, _option.Underlying })
|
||||
{
|
||||
var configs = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol);
|
||||
if (configs.Any())
|
||||
{
|
||||
throw new Exception($"Unexpected configuration for {symbol} after it has been deselected from coarse universe and option contract is removed.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
if (_securityChanges.RemovedSecurities.Intersect(changes.RemovedSecurities).Any())
|
||||
{
|
||||
throw new Exception($"SecurityChanges.RemovedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!");
|
||||
}
|
||||
if (_securityChanges.AddedSecurities.Intersect(changes.AddedSecurities).Any())
|
||||
{
|
||||
throw new Exception($"SecurityChanges.AddedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!");
|
||||
}
|
||||
// keep track of all removed and added securities
|
||||
_securityChanges += changes;
|
||||
|
||||
if (changes.AddedSecurities.Any(security => security.Symbol.SecurityType == SecurityType.Option))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var addedSecurity in changes.AddedSecurities)
|
||||
{
|
||||
var option = OptionChainProvider.GetOptionContractList(addedSecurity.Symbol, Time)
|
||||
.OrderBy(symbol => symbol.ID.Symbol)
|
||||
.First(optionContract => optionContract.ID.Date == _expiration
|
||||
&& optionContract.ID.OptionRight == OptionRight.Call
|
||||
&& optionContract.ID.OptionStyle == OptionStyle.American);
|
||||
AddOptionContract(option);
|
||||
|
||||
foreach (var symbol in new[] { option, option.Underlying })
|
||||
{
|
||||
var config = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol).ToList();
|
||||
|
||||
if (!config.Any())
|
||||
{
|
||||
throw new Exception($"Was expecting configurations for {symbol}");
|
||||
}
|
||||
if (config.Any(dataConfig => dataConfig.DataNormalizationMode != DataNormalizationMode.Raw))
|
||||
{
|
||||
throw new Exception($"Was expecting DataNormalizationMode.Raw configurations for {symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
// just keep the first we got
|
||||
if (_option == null)
|
||||
{
|
||||
_option = option;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (SubscriptionManager.Subscriptions.Any(dataConfig => dataConfig.Symbol == _twx || dataConfig.Symbol.Underlying == _twx))
|
||||
{
|
||||
throw new Exception($"Was NOT expecting any configurations for {_twx} or it's options, since we removed the contract");
|
||||
}
|
||||
|
||||
if (SubscriptionManager.Subscriptions.All(dataConfig => dataConfig.Symbol != _aapl))
|
||||
{
|
||||
throw new Exception($"Was expecting configurations for {_aapl}");
|
||||
}
|
||||
if (SubscriptionManager.Subscriptions.All(dataConfig => dataConfig.Symbol.Underlying != _aapl))
|
||||
{
|
||||
throw new Exception($"Was expecting options configurations for {_aapl}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public 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.23%"},
|
||||
{"Compounding Annual Return", "-15.596%"},
|
||||
{"Drawdown", "0.200%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.232%"},
|
||||
{"Sharpe Ratio", "-7.739"},
|
||||
{"Probabilistic Sharpe Ratio", "1.216%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.027"},
|
||||
{"Beta", "-0.174"},
|
||||
{"Annual Standard Deviation", "0.006"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-11.586"},
|
||||
{"Tracking Error", "0.042"},
|
||||
{"Treynor Ratio", "0.286"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-19.883"},
|
||||
{"Return Over Maximum Drawdown", "-67.224"},
|
||||
{"Portfolio Turnover", "0.014"},
|
||||
{"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", "721476625"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.Robintrack;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp.AltData
|
||||
{
|
||||
/// <summary>
|
||||
/// Looks at users holding the stock AAPL at a given point in time
|
||||
/// and keeps track of changes in retail investor sentiment.
|
||||
///
|
||||
/// We go long if the sentiment increases by 0.5%, and short if it decreases by -0.5%
|
||||
/// </summary>
|
||||
public class RobintrackHoldingsAlgorithm : QCAlgorithm
|
||||
{
|
||||
private Symbol _aapl;
|
||||
private Symbol _aaplHoldings;
|
||||
private decimal _lastValue;
|
||||
private bool _isLong;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2018, 5, 1);
|
||||
SetEndDate(2020, 5, 5);
|
||||
SetCash(100000);
|
||||
|
||||
_aapl = AddEquity("AAPL", Resolution.Daily).Symbol;
|
||||
_aaplHoldings = AddData<RobintrackHoldings>(_aapl).Symbol;
|
||||
_isLong = false;
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
foreach (var kvp in data.Get<RobintrackHoldings>())
|
||||
{
|
||||
var holdings = kvp.Value;
|
||||
|
||||
if (_lastValue != 0)
|
||||
{
|
||||
var percentChange = (holdings.UsersHolding - _lastValue) / _lastValue;
|
||||
var holdingInfo = $"There are {holdings.UsersHolding} unique users holding {kvp.Key.Underlying} - users holding % of U.S. equities universe: {holdings.UniverseHoldingPercent * 100m}%";
|
||||
|
||||
if (percentChange >= 0.005m && !_isLong)
|
||||
{
|
||||
Log($"{UtcTime} - Buying AAPL - {holdingInfo}");
|
||||
SetHoldings(_aapl, 0.5);
|
||||
_isLong = true;
|
||||
}
|
||||
else if (percentChange <= -0.005m && _isLong)
|
||||
{
|
||||
Log($"{UtcTime} - Shorting AAPL - {holdingInfo}");
|
||||
SetHoldings(_aapl, -0.5);
|
||||
_isLong = false;
|
||||
}
|
||||
}
|
||||
|
||||
_lastValue = holdings.UsersHolding;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
323
Algorithm.CSharp/BacktestingBrokerageRegressionAlgorithm.cs
Normal file
323
Algorithm.CSharp/BacktestingBrokerageRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,323 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Orders.Fees;
|
||||
using QuantConnect.Orders.Fills;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Securities.Option;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests the order processing of the backtesting brokerage.
|
||||
/// We open an equity position that should fill in two parts, on two different bars.
|
||||
/// We open a long option position and let it expire so we can exercise the position.
|
||||
/// To check the orders we use OnOrderEvent and throw exceptions if verification fails.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="backtesting brokerage" />
|
||||
/// <meta name="tag" content="regression test" />
|
||||
/// <meta name="tag" content="options" />
|
||||
class BacktestingBrokerageRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Security _security;
|
||||
private Symbol _spy;
|
||||
private OrderTicket _equityBuy;
|
||||
private Option _option;
|
||||
private Symbol _optionSymbol;
|
||||
private OrderTicket _optionBuy;
|
||||
private bool _optionBought = false;
|
||||
private bool _equityBought = false;
|
||||
private decimal _optionStrikePrice;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize the algorithm
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetCash(100000);
|
||||
SetStartDate(2015, 12, 24);
|
||||
SetEndDate(2015, 12, 28);
|
||||
|
||||
// Get our equity
|
||||
_security = AddEquity("SPY", Resolution.Hour);
|
||||
_security.SetFillModel(new PartialMarketFillModel(2));
|
||||
_spy = _security.Symbol;
|
||||
|
||||
// Get our option
|
||||
_option = AddOption("GOOG");
|
||||
_option.SetFilter(u => u.IncludeWeeklys()
|
||||
.Strikes(-2, +2)
|
||||
.Expiration(TimeSpan.Zero, TimeSpan.FromDays(10)));
|
||||
_optionSymbol = _option.Symbol;
|
||||
}
|
||||
|
||||
/// <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 (!_equityBought && data.ContainsKey(_spy)) {
|
||||
//Buy our Equity
|
||||
var quantity = CalculateOrderQuantity(_spy, .1m);
|
||||
_equityBuy = MarketOrder(_spy, quantity, asynchronous: true);
|
||||
_equityBought = true;
|
||||
}
|
||||
|
||||
if (!_optionBought)
|
||||
{
|
||||
// Buy our option
|
||||
OptionChain chain;
|
||||
if (data.OptionChains.TryGetValue(_optionSymbol, out chain))
|
||||
{
|
||||
// Find the second call strike under market price expiring today
|
||||
var contracts = (
|
||||
from optionContract in chain.OrderByDescending(x => x.Strike)
|
||||
where optionContract.Right == OptionRight.Call
|
||||
where optionContract.Expiry == Time.Date
|
||||
where optionContract.Strike < chain.Underlying.Price
|
||||
select optionContract
|
||||
).Take(2);
|
||||
|
||||
if (contracts.Any())
|
||||
{
|
||||
var optionToBuy = contracts.FirstOrDefault();
|
||||
_optionStrikePrice = optionToBuy.Strike;
|
||||
_optionBuy = MarketOrder(optionToBuy.Symbol, 1);
|
||||
_optionBought = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// All order events get pushed through this function
|
||||
/// </summary>
|
||||
/// <param name="orderEvent">OrderEvent object that contains all the information about the event</param>
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
// Get the order from our transactions
|
||||
var order = Transactions.GetOrderById(orderEvent.OrderId);
|
||||
|
||||
// Based on the type verify the order
|
||||
switch(order.Type)
|
||||
{
|
||||
case OrderType.Market:
|
||||
VerifyMarketOrder(order, orderEvent);
|
||||
break;
|
||||
|
||||
case OrderType.OptionExercise:
|
||||
VerifyOptionExercise(order, orderEvent);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// To verify Market orders is process correctly
|
||||
/// </summary>
|
||||
/// <param name="order">Order object to analyze</param>
|
||||
public void VerifyMarketOrder(Order order, OrderEvent orderEvent)
|
||||
{
|
||||
switch(order.Status)
|
||||
{
|
||||
case OrderStatus.Submitted:
|
||||
break;
|
||||
|
||||
// All PartiallyFilled orders should have a LastFillTime
|
||||
case OrderStatus.PartiallyFilled:
|
||||
if (order.LastFillTime == null)
|
||||
{
|
||||
throw new Exception("LastFillTime should not be null");
|
||||
}
|
||||
|
||||
if (order.Quantity/2 != orderEvent.FillQuantity)
|
||||
{
|
||||
throw new Exception("Order size should be half");
|
||||
}
|
||||
break;
|
||||
|
||||
// All filled equity orders should have filled after creation because of our fill model!
|
||||
case OrderStatus.Filled:
|
||||
if (order.SecurityType == SecurityType.Equity && order.CreatedTime == order.LastFillTime)
|
||||
{
|
||||
throw new Exception("Order should not finish during the CreatedTime bar");
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// To verify OptionExercise orders is process correctly
|
||||
/// </summary>
|
||||
/// <param name="order">Order object to analyze</param>
|
||||
public void VerifyOptionExercise(Order order, OrderEvent orderEvent)
|
||||
{
|
||||
// If the option price isn't the same as the strike price, its incorrect
|
||||
if (order.Price != _optionStrikePrice)
|
||||
{
|
||||
throw new Exception("OptionExercise order price should be strike price!!");
|
||||
}
|
||||
|
||||
if (orderEvent.Quantity != -1)
|
||||
{
|
||||
throw new Exception("OrderEvent Quantity should be -1");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs after algorithm, used to check our portfolio and orders
|
||||
/// </summary>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (!Portfolio.ContainsKey(_optionBuy.Symbol) || !Portfolio.ContainsKey(_optionBuy.Symbol.Underlying) || !Portfolio.ContainsKey(_equityBuy.Symbol))
|
||||
{
|
||||
throw new Exception("Portfolio does not contain the Symbols we purchased");
|
||||
}
|
||||
|
||||
//Check option holding, should not be invested since it expired, profit should be -400
|
||||
var optionHolding = Portfolio[_optionBuy.Symbol];
|
||||
if (optionHolding.Invested || optionHolding.Profit != -400)
|
||||
{
|
||||
throw new Exception("Options holding does not match expected outcome");
|
||||
}
|
||||
|
||||
//Check the option underlying symbol since we should have bought it at exercise
|
||||
//Quantity should be 100, AveragePrice should be option strike price
|
||||
var optionExerciseHolding = Portfolio[_optionBuy.Symbol.Underlying];
|
||||
if (!optionExerciseHolding.Invested || optionExerciseHolding.Quantity != 100 || optionExerciseHolding.AveragePrice != _optionBuy.Symbol.ID.StrikePrice)
|
||||
{
|
||||
throw new Exception("Equity holding for exercised option does not match expected outcome");
|
||||
}
|
||||
|
||||
//Check equity holding, should be invested, profit should be
|
||||
//Quantity should be 50, AveragePrice should be ticket AverageFillPrice
|
||||
var equityHolding = Portfolio[_equityBuy.Symbol];
|
||||
if (!equityHolding.Invested || equityHolding.Quantity != 50 || equityHolding.AveragePrice != _equityBuy.AverageFillPrice)
|
||||
{
|
||||
throw new Exception("Equity holding does not match expected outcome");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PartialMarketFillModel that allows the user to set the number of fills and restricts
|
||||
/// the fill to only one per bar.
|
||||
/// </summary>
|
||||
private class PartialMarketFillModel : ImmediateFillModel
|
||||
{
|
||||
private readonly decimal _percent;
|
||||
private readonly Dictionary<long, decimal> _absoluteRemainingByOrderId = new Dictionary<long, decimal>();
|
||||
|
||||
/// <param name="numberOfFills"></param>
|
||||
public PartialMarketFillModel(int numberOfFills = 1)
|
||||
{
|
||||
_percent = 1m / numberOfFills;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs partial market fills once per time step
|
||||
/// </summary>
|
||||
/// <param name="asset">The security being ordered</param>
|
||||
/// <param name="order">The order</param>
|
||||
/// <returns>The order fill</returns>
|
||||
public override OrderEvent MarketFill(Security asset, MarketOrder order)
|
||||
{
|
||||
var currentUtcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
|
||||
|
||||
// Only fill once a time slice
|
||||
if (order.LastFillTime != null && currentUtcTime <= order.LastFillTime)
|
||||
{
|
||||
return new OrderEvent(order, currentUtcTime, OrderFee.Zero);
|
||||
}
|
||||
|
||||
decimal absoluteRemaining;
|
||||
if (!_absoluteRemainingByOrderId.TryGetValue(order.Id, out absoluteRemaining))
|
||||
{
|
||||
absoluteRemaining = order.AbsoluteQuantity;
|
||||
_absoluteRemainingByOrderId.Add(order.Id, order.AbsoluteQuantity);
|
||||
}
|
||||
|
||||
var fill = base.MarketFill(asset, order);
|
||||
var absoluteFillQuantity = (int)(Math.Min(absoluteRemaining, (int)(_percent * order.Quantity)));
|
||||
fill.FillQuantity = Math.Sign(order.Quantity) * absoluteFillQuantity;
|
||||
|
||||
if (absoluteRemaining == absoluteFillQuantity)
|
||||
{
|
||||
fill.Status = OrderStatus.Filled;
|
||||
_absoluteRemainingByOrderId.Remove(order.Id);
|
||||
}
|
||||
else
|
||||
{
|
||||
absoluteRemaining = absoluteRemaining - absoluteFillQuantity;
|
||||
_absoluteRemainingByOrderId[order.Id] = absoluteRemaining;
|
||||
fill.Status = OrderStatus.PartiallyFilled;
|
||||
}
|
||||
|
||||
return fill;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "0%"},
|
||||
{"Average Loss", "-0.40%"},
|
||||
{"Compounding Annual Return", "-22.335%"},
|
||||
{"Drawdown", "0.400%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.323%"},
|
||||
{"Sharpe Ratio", "-0.888"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.035"},
|
||||
{"Beta", "0.183"},
|
||||
{"Annual Standard Deviation", "0.004"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "12.058"},
|
||||
{"Tracking Error", "0.017"},
|
||||
{"Treynor Ratio", "-0.018"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Fitness Score", "0.213"},
|
||||
{"OrderListHash", "904167951"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -119,4 +119,4 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"OrderListHash", "491919591"}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -227,7 +227,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-43.917"},
|
||||
{"Return Over Maximum Drawdown", "-43.937"},
|
||||
{"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", "1073240275"}
|
||||
{"OrderListHash", "415415696"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,9 +15,11 @@
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
@@ -31,7 +33,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="options" />
|
||||
/// <meta name="tag" content="filter selection" />
|
||||
public class BasicTemplateOptionsFilterUniverseAlgorithm : QCAlgorithm
|
||||
public class BasicTemplateOptionsFilterUniverseAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private const string UnderlyingTicker = "GOOG";
|
||||
public Symbol OptionSymbol;
|
||||
@@ -40,20 +42,17 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
SetStartDate(2015, 12, 24);
|
||||
SetEndDate(2015, 12, 24);
|
||||
SetCash(10000);
|
||||
SetCash(100000);
|
||||
|
||||
var equity = AddEquity(UnderlyingTicker);
|
||||
var option = AddOption(UnderlyingTicker);
|
||||
OptionSymbol = option.Symbol;
|
||||
|
||||
// set our custom filter for this option chain
|
||||
option.SetFilter(universe => from symbol in universe
|
||||
.WeeklysOnly()
|
||||
// Expiration method accepts TimeSpan objects or integer for days.
|
||||
// The following statements yield the same filtering criteria
|
||||
.Expiration(0, 10)
|
||||
// .Expiration(TimeSpan.Zero, TimeSpan.FromDays(10))
|
||||
// Set our custom universe filter, Expires today, is a call, and is within 10 dollars of the current price
|
||||
option.SetFilter(universe => from symbol in universe.WeeklysOnly().Expiration(0, 1)
|
||||
where symbol.ID.OptionRight != OptionRight.Put &&
|
||||
universe.Underlying.Price - symbol.ID.StrikePrice < 60
|
||||
-10 < universe.Underlying.Price - symbol.ID.StrikePrice &&
|
||||
universe.Underlying.Price - symbol.ID.StrikePrice < 10
|
||||
select symbol);
|
||||
|
||||
// use the underlying equity as the benchmark
|
||||
@@ -67,14 +66,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
OptionChain chain;
|
||||
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
|
||||
{
|
||||
// find the second call strike under market price expiring today
|
||||
// Get the first ITM call expiring today
|
||||
var contract = (
|
||||
from optionContract in chain.OrderByDescending(x => x.Strike)
|
||||
where optionContract.Right == OptionRight.Call
|
||||
where optionContract.Expiry == Time.Date
|
||||
where optionContract.Strike < chain.Underlying.Price
|
||||
select optionContract
|
||||
).Skip(2).FirstOrDefault();
|
||||
).FirstOrDefault();
|
||||
|
||||
if (contract != null)
|
||||
{
|
||||
@@ -88,5 +86,62 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
Log(orderEvent.ToString());
|
||||
}
|
||||
|
||||
/// <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", "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", "$1.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "0"},
|
||||
{"Return Over Maximum Drawdown", "0"},
|
||||
{"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", "687310345"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1708974186"}
|
||||
{"OrderListHash", "737971736"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Demonstration of how to chain a coarse and fine universe selection with an option chain universe selection model
|
||||
/// that will add and remove an <see cref="OptionChainUniverse"/> for each symbol selected on fine
|
||||
/// </summary>
|
||||
public class CoarseFineOptionUniverseChainRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
// initialize our changes to nothing
|
||||
private SecurityChanges _changes = SecurityChanges.None;
|
||||
private int _optionCount;
|
||||
private Symbol _lastEquityAdded;
|
||||
private Symbol _aapl;
|
||||
private Symbol _twx;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
_twx = QuantConnect.Symbol.Create("TWX", SecurityType.Equity, Market.USA);
|
||||
_aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
|
||||
UniverseSettings.Resolution = Resolution.Minute;
|
||||
|
||||
SetStartDate(2014, 06, 05);
|
||||
SetEndDate(2014, 06, 06);
|
||||
|
||||
var selectionUniverse = AddUniverse(enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl },
|
||||
enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl });
|
||||
|
||||
AddUniverseOptions(selectionUniverse, universe =>
|
||||
{
|
||||
if (universe.Underlying == null)
|
||||
{
|
||||
throw new Exception("Underlying data point is null! This shouldn't happen, each OptionChainUniverse handles and should provide this");
|
||||
}
|
||||
return universe.IncludeWeeklys()
|
||||
.FrontMonth()
|
||||
.Contracts(universe.Take(5));
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// if we have no changes, do nothing
|
||||
if (_changes == SecurityChanges.None ||
|
||||
_changes.AddedSecurities.Any(security => security.Price == 0))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// liquidate removed securities
|
||||
foreach (var security in _changes.RemovedSecurities)
|
||||
{
|
||||
if (security.Invested)
|
||||
{
|
||||
Liquidate(security.Symbol);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var security in _changes.AddedSecurities)
|
||||
{
|
||||
if (!security.Symbol.HasUnderlying)
|
||||
{
|
||||
_lastEquityAdded = security.Symbol;
|
||||
}
|
||||
else
|
||||
{
|
||||
// options added should all match prev added security
|
||||
if (security.Symbol.Underlying != _lastEquityAdded)
|
||||
{
|
||||
throw new Exception($"Unexpected symbol added {security.Symbol}");
|
||||
}
|
||||
|
||||
_optionCount++;
|
||||
}
|
||||
|
||||
SetHoldings(security.Symbol, 0.05m);
|
||||
|
||||
var config = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(security.Symbol).ToList();
|
||||
|
||||
if (!config.Any())
|
||||
{
|
||||
throw new Exception($"Was expecting configurations for {security.Symbol}");
|
||||
}
|
||||
if (config.Any(dataConfig => dataConfig.DataNormalizationMode != DataNormalizationMode.Raw))
|
||||
{
|
||||
throw new Exception($"Was expecting DataNormalizationMode.Raw configurations for {security.Symbol}");
|
||||
}
|
||||
}
|
||||
_changes = SecurityChanges.None;
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
_changes += changes;
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
var config = SubscriptionManager.Subscriptions.ToList();
|
||||
if (config.Any(dataConfig => dataConfig.Symbol == _twx || dataConfig.Symbol.Underlying == _twx))
|
||||
{
|
||||
throw new Exception($"Was NOT expecting any configurations for {_twx} or it's options, since coarse/fine should have deselected it");
|
||||
}
|
||||
|
||||
if (_optionCount == 0)
|
||||
{
|
||||
throw new Exception("Option universe chain did not add any option!");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "13"},
|
||||
{"Average Win", "0.65%"},
|
||||
{"Average Loss", "-0.05%"},
|
||||
{"Compounding Annual Return", "3216040423556140000000000%"},
|
||||
{"Drawdown", "0.500%"},
|
||||
{"Expectancy", "1.393"},
|
||||
{"Net Profit", "32.840%"},
|
||||
{"Sharpe Ratio", "7.14272222483913E+15"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "83%"},
|
||||
{"Win Rate", "17%"},
|
||||
{"Profit-Loss Ratio", "13.36"},
|
||||
{"Alpha", "2.59468989671647E+16"},
|
||||
{"Beta", "67.661"},
|
||||
{"Annual Standard Deviation", "3.633"},
|
||||
{"Annual Variance", "13.196"},
|
||||
{"Information Ratio", "7.24987266907741E+15"},
|
||||
{"Tracking Error", "3.579"},
|
||||
{"Treynor Ratio", "383485597312030"},
|
||||
{"Total Fees", "$13.00"},
|
||||
{"Fitness Score", "0.232"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0.232"},
|
||||
{"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", "1630141557"}
|
||||
};
|
||||
}
|
||||
}
|
||||
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>
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
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>
|
||||
/// Algorithm simply fetch one-day history prior current time.
|
||||
/// </summary>
|
||||
public class DailyHistoryForDailyResolutionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol[] _symbols = {
|
||||
QuantConnect.Symbol.Create("GBPUSD", SecurityType.Forex, market: Market.FXCM),
|
||||
QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, market: Market.Oanda),
|
||||
QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, market: Market.USA),
|
||||
QuantConnect.Symbol.Create("BTCUSD", SecurityType.Crypto, market: Market.GDAX),
|
||||
QuantConnect.Symbol.Create("XAUUSD", SecurityType.Cfd, market: Market.Oanda)
|
||||
};
|
||||
|
||||
private HashSet<Symbol> _received = new HashSet<Symbol>();
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2018, 3, 26);
|
||||
SetEndDate(2018, 4, 10);
|
||||
foreach (var symbol in _symbols)
|
||||
{
|
||||
AddSecurity(symbol, Resolution.Daily);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
using (var enumerator = data.GetEnumerator())
|
||||
{
|
||||
while (enumerator.MoveNext())
|
||||
{
|
||||
var current = enumerator.Current;
|
||||
var symbol = current.Key;
|
||||
_received.Add(symbol);
|
||||
|
||||
List<BaseData> history;
|
||||
|
||||
if (current.Value.DataType == MarketDataType.QuoteBar)
|
||||
{
|
||||
history = History(1, Resolution.Daily).Get<QuoteBar>(symbol).Cast<BaseData>().ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
history = History(1, Resolution.Daily).Get<TradeBar>(symbol).Cast<BaseData>().ToList();
|
||||
}
|
||||
|
||||
if (!history.Any()) throw new Exception($"No {symbol} data on the eve of {Time} {Time.DayOfWeek}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (_received.Count != _symbols.Length)
|
||||
{
|
||||
throw new Exception($"Data for symbols {string.Join(",", _symbols.Except(_received))} were not received");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <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", "0"},
|
||||
{"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.084"},
|
||||
{"Tracking Error", "0.183"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"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", "371857150"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
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>
|
||||
/// Algorithm simply fetch one-day history prior current time.
|
||||
/// </summary>
|
||||
public class DailyHistoryForMinuteResolutionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol[] _symbols = {
|
||||
QuantConnect.Symbol.Create("GBPUSD", SecurityType.Forex, market: Market.FXCM),
|
||||
QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, market: Market.Oanda),
|
||||
QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, market: Market.USA),
|
||||
QuantConnect.Symbol.Create("BTCUSD", SecurityType.Crypto, market: Market.GDAX),
|
||||
QuantConnect.Symbol.Create("XAUUSD", SecurityType.Cfd, market: Market.Oanda)
|
||||
};
|
||||
|
||||
private HashSet<Symbol> _received = new HashSet<Symbol>();
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2018, 3, 26);
|
||||
SetEndDate(2018, 4, 10);
|
||||
foreach (var symbol in _symbols)
|
||||
{
|
||||
AddSecurity(symbol, Resolution.Minute);
|
||||
}
|
||||
|
||||
Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromHours(1)), MakeHistoryCall);
|
||||
}
|
||||
|
||||
private void MakeHistoryCall()
|
||||
{
|
||||
foreach (var symbol in _symbols)
|
||||
{
|
||||
_received.Add(symbol);
|
||||
|
||||
bool hasHistory = false;
|
||||
|
||||
foreach (var dataType in SubscriptionManager.AvailableDataTypes[symbol.SecurityType])
|
||||
{
|
||||
if (dataType == TickType.Quote)
|
||||
{
|
||||
hasHistory |= History(1, Resolution.Daily).Get<QuoteBar>(symbol).Any();
|
||||
}
|
||||
else
|
||||
{
|
||||
hasHistory |= History(1, Resolution.Daily).Get<TradeBar>(symbol).Any();
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasHistory) throw new Exception($"No {symbol} data on the eve of {Time} {Time.DayOfWeek}");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (_received.Count != _symbols.Length)
|
||||
{
|
||||
throw new Exception($"Data for symbols {string.Join(",", _symbols.Except(_received))} were not received");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <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", "0"},
|
||||
{"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.096"},
|
||||
{"Tracking Error", "0.212"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"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", "371857150"}
|
||||
};
|
||||
}
|
||||
}
|
||||
118
Algorithm.CSharp/DaylightSavingTimeHistoryRegressionAlgorithm.cs
Normal file
118
Algorithm.CSharp/DaylightSavingTimeHistoryRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* 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 NodaTime;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression test algorithm simply fetch history on boarder of Daylight Saving Time shift
|
||||
/// </summary>
|
||||
public class DaylightSavingTimeHistoryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol[] _symbols = new[]
|
||||
{
|
||||
QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM),
|
||||
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(2011, 11, 10); //Set Start Date
|
||||
SetEndDate(2011, 11, 11); //Set End Date
|
||||
SetCash(100000); //Set Strategy Cash
|
||||
|
||||
for (int i = 0; i < _symbols.Length; i++)
|
||||
{
|
||||
var symbol = _symbols[i];
|
||||
var history = History<QuoteBar>(symbol, 10, Resolution.Daily);
|
||||
|
||||
var duplications = history
|
||||
.GroupBy(k => k.Time)
|
||||
.Where(g => g.Count() > 1);
|
||||
if (duplications.Any())
|
||||
{
|
||||
var time = duplications.First().Key;
|
||||
throw new Exception($"Duplicated bars were issued for time {time}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "0"},
|
||||
{"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", "$0.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"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", "371857150"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* 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>
|
||||
/// Checks that the Tick BidPrice and AskPrices are adjusted like Value.
|
||||
/// </summary>
|
||||
public class EquityTickQuoteAdjustedModeRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _ibm;
|
||||
private bool _bought;
|
||||
private bool _sold;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 10, 7);
|
||||
SetEndDate(2013, 10, 11);
|
||||
SetCash(100000);
|
||||
|
||||
_ibm = AddEquity("IBM", Resolution.Tick).Symbol;
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!data.Ticks.ContainsKey(_ibm))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var security = Securities[_ibm];
|
||||
if (!security.HasData)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var tick in data.Ticks[_ibm])
|
||||
{
|
||||
if (tick.BidPrice != 0 && !_bought && ((tick.Value - tick.BidPrice) <= 0.05m))
|
||||
{
|
||||
SetHoldings(_ibm, 1);
|
||||
_bought = true;
|
||||
return;
|
||||
}
|
||||
if (tick.AskPrice != 0 && _bought && !_sold && Math.Abs((double)tick.Value - (double)tick.AskPrice) <= 0.05)
|
||||
{
|
||||
Liquidate(_ibm);
|
||||
_sold = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.01%"},
|
||||
{"Compounding Annual Return", "-0.500%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.006%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-8.769"},
|
||||
{"Tracking Error", "0.22"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$6.41"},
|
||||
{"Fitness Score", "0.248"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-82.815"},
|
||||
{"Portfolio Turnover", "0.497"},
|
||||
{"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", "1213851303"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression algorithm testing doing some history requests outside market hours, reproducing GH issue #4783
|
||||
/// </summary>
|
||||
public class ExtendedMarketHoursHistoryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private int _minuteHistoryCount;
|
||||
private int _hourHistoryCount;
|
||||
private int _dailyHistoryCount;
|
||||
|
||||
/// <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, 09);
|
||||
SetCash(100000);
|
||||
|
||||
AddEquity("SPY", Resolution.Minute, extendedMarketHours:true, fillDataForward:false);
|
||||
|
||||
Schedule.On("RunHistoryCall", DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromHours(1)), RunHistoryCall);
|
||||
}
|
||||
|
||||
private void RunHistoryCall()
|
||||
{
|
||||
var spy = Securities["SPY"];
|
||||
var regularHours = spy.Exchange.Hours.IsOpen(Time, false);
|
||||
var extendedHours = !regularHours && spy.Exchange.Hours.IsOpen(Time, true);
|
||||
|
||||
if (regularHours)
|
||||
{
|
||||
_minuteHistoryCount++;
|
||||
var history = History(spy.Symbol, 5, Resolution.Minute).Count();
|
||||
if (history != 5)
|
||||
{
|
||||
throw new Exception($"Unexpected Minute data count: {history}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (extendedHours)
|
||||
{
|
||||
_hourHistoryCount++;
|
||||
var history = History(spy.Symbol, 5, Resolution.Hour).Count();
|
||||
if (history != 5)
|
||||
{
|
||||
throw new Exception($"Unexpected Hour data count {history}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_dailyHistoryCount++;
|
||||
var history = History(spy.Symbol, 5, Resolution.Daily).Count();
|
||||
if (history != 5)
|
||||
{
|
||||
throw new Exception($"Unexpected Daily data count {history}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (_minuteHistoryCount != 3 * 6)
|
||||
{
|
||||
throw new Exception($"Unexpected minute history requests count {_minuteHistoryCount}");
|
||||
}
|
||||
// 6 pre market from 4am to 9am + 4 post market 4pm to 7pm
|
||||
if (_hourHistoryCount != 3 * 10)
|
||||
{
|
||||
throw new Exception($"Unexpected hour history requests count {_hourHistoryCount}");
|
||||
}
|
||||
// 0am to 3am + 8pm to 11pm, last day ends at 8pm
|
||||
if (_dailyHistoryCount != (2 * 8 + 5))
|
||||
{
|
||||
throw new Exception($"Unexpected Daily history requests count: {_dailyHistoryCount}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "20"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0.00%"},
|
||||
{"Compounding Annual Return", "-74.182%"},
|
||||
{"Drawdown", "2.200%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-1.046%"},
|
||||
{"Sharpe Ratio", "-8.269"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.19"},
|
||||
{"Beta", "0.579"},
|
||||
{"Annual Standard Deviation", "0.065"},
|
||||
{"Annual Variance", "0.004"},
|
||||
{"Information Ratio", "1.326"},
|
||||
{"Tracking Error", "0.049"},
|
||||
{"Treynor Ratio", "-0.934"},
|
||||
{"Total Fees", "$22.26"},
|
||||
{"Fitness Score", "0.002"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-11.855"},
|
||||
{"Return Over Maximum Drawdown", "-70.945"},
|
||||
{"Portfolio Turnover", "0.342"},
|
||||
{"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", "-1961710414"}
|
||||
};
|
||||
}
|
||||
}
|
||||
147
Algorithm.CSharp/ExtendedMarketTradingRegressionAlgorithm.cs
Normal file
147
Algorithm.CSharp/ExtendedMarketTradingRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,147 @@
|
||||
/*
|
||||
* 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.Market;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This algorithm demonstrates extended market hours trading.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="assets" />
|
||||
/// <meta name="tag" content="regression test" />
|
||||
public class ExtendedMarketTradingRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private DateTime _lastAction;
|
||||
private Symbol _spy;
|
||||
|
||||
/// <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); //Set Start Date
|
||||
SetEndDate(2013, 10, 11); //Set End Date
|
||||
SetCash(100000); //Set Strategy Cash
|
||||
_spy = AddEquity("SPY", Resolution.Minute, Market.USA, true, 0m, true).Symbol;
|
||||
}
|
||||
|
||||
/// <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 void OnData(TradeBars data)
|
||||
{
|
||||
//Only take an action once a day.
|
||||
if (_lastAction.Date == Time.Date) return;
|
||||
TradeBar spyBar = data["SPY"];
|
||||
|
||||
//If it isnt during market hours, go ahead and buy ten!
|
||||
if (!InMarketHours())
|
||||
{
|
||||
LimitOrder(_spy, 10, spyBar.Low);
|
||||
_lastAction = Time;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Order events are triggered on order status changes. There are many order events including non-fill messages.
|
||||
/// </summary>
|
||||
/// <param name="orderEvent">OrderEvent object with details about the order status</param>
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (InMarketHours())
|
||||
{
|
||||
throw new Exception("Order processed during market hours.");
|
||||
}
|
||||
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check if we are in Market Hours, NYSE is open from (9:30 am to 4 pm)
|
||||
/// </summary>
|
||||
public bool InMarketHours()
|
||||
{
|
||||
TimeSpan now = Time.TimeOfDay;
|
||||
TimeSpan open = new TimeSpan(09, 30, 0);
|
||||
TimeSpan close = new TimeSpan(16, 0, 0);
|
||||
|
||||
return (open < now) && (close > now);
|
||||
}
|
||||
|
||||
/// <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", "4"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "8.332%"},
|
||||
{"Drawdown", "0.100%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.106%"},
|
||||
{"Sharpe Ratio", "7.474"},
|
||||
{"Probabilistic Sharpe Ratio", "85.145%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.007"},
|
||||
{"Beta", "0.036"},
|
||||
{"Annual Standard Deviation", "0.007"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-7.03"},
|
||||
{"Tracking Error", "0.186"},
|
||||
{"Treynor Ratio", "1.557"},
|
||||
{"Total Fees", "$4.00"},
|
||||
{"Fitness Score", "0.012"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "38.663"},
|
||||
{"Return Over Maximum Drawdown", "238.773"},
|
||||
{"Portfolio Turnover", "0.012"},
|
||||
{"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", "1717552327"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -178,7 +178,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-15.573"},
|
||||
{"Return Over Maximum Drawdown", "-15.574"},
|
||||
{"Portfolio Turnover", "2.056"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
|
||||
@@ -40,7 +40,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
SetEndDate(2013, 10, 8);
|
||||
SetCash(100000);
|
||||
|
||||
_eurusd = QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM);
|
||||
_eurusd = QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, Market.Oanda);
|
||||
var eurgbp = AddForex("EURGBP", Resolution.Daily);
|
||||
_dataPointsPerSymbol.Add(eurgbp.Symbol, 0);
|
||||
}
|
||||
@@ -94,7 +94,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
var expectedDataPointsPerSymbol = new Dictionary<string, int>
|
||||
{
|
||||
{ "EURGBP", 3 },
|
||||
{ "EURUSD", 48 }
|
||||
{ "EURUSD", 29 }
|
||||
};
|
||||
|
||||
foreach (var kvp in _dataPointsPerSymbol)
|
||||
@@ -141,8 +141,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "5.893"},
|
||||
{"Tracking Error", "0.131"},
|
||||
{"Information Ratio", "5.853"},
|
||||
{"Tracking Error", "0.107"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Fitness Score", "0"},
|
||||
|
||||
@@ -40,7 +40,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
SetEndDate(2013, 10, 8);
|
||||
SetCash(100000);
|
||||
|
||||
_eurusd = QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM);
|
||||
_eurusd = QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, Market.Oanda);
|
||||
var eurgbp = AddForex("EURGBP", Resolution.Daily);
|
||||
_dataPointsPerSymbol.Add(eurgbp.Symbol, 0);
|
||||
}
|
||||
@@ -145,8 +145,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "5.893"},
|
||||
{"Tracking Error", "0.131"},
|
||||
{"Information Ratio", "5.853"},
|
||||
{"Tracking Error", "0.107"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Fitness Score", "0"},
|
||||
|
||||
@@ -119,7 +119,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1459983342"}
|
||||
{"OrderListHash", "187652813"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
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"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ using QuantConnect.Interfaces;
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Demonstration of the Option Chain Provider -- a much faster mechanism for manually specifying the option contracts you'd like to recieve
|
||||
/// Demonstration of the Option Chain Provider -- a much faster mechanism for manually specifying the option contracts you'd like to receive
|
||||
/// data for and manually subscribing to them.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="strategy example" />
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Algorithm.Framework.Selection;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression algorithm making sure that the added universe selection does not remove the option chain during it's daily refresh
|
||||
/// </summary>
|
||||
public class OptionChainedAndUniverseSelectionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _aaplOption;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
UniverseSettings.Resolution = Resolution.Minute;
|
||||
|
||||
SetStartDate(2014, 06, 05);
|
||||
SetEndDate(2014, 06, 09);
|
||||
|
||||
_aaplOption = AddOption("AAPL").Symbol;
|
||||
AddUniverseSelection(new DailyUniverseSelectionModel("MyCustomSelectionModel", time => new[] { "AAPL" }, this));
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
Buy("AAPL", 1);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
var config = SubscriptionManager.Subscriptions.ToList();
|
||||
if (config.All(dataConfig => dataConfig.Symbol != "AAPL"))
|
||||
{
|
||||
throw new Exception("Was expecting configurations for AAPL");
|
||||
}
|
||||
if (config.All(dataConfig => dataConfig.Symbol.SecurityType != SecurityType.Option))
|
||||
{
|
||||
throw new Exception($"Was expecting configurations for {_aaplOption}");
|
||||
}
|
||||
}
|
||||
|
||||
private class DailyUniverseSelectionModel : CustomUniverseSelectionModel
|
||||
{
|
||||
private DateTime _lastRefresh;
|
||||
private IAlgorithm _algorithm;
|
||||
|
||||
public DailyUniverseSelectionModel(string name, Func<DateTime, IEnumerable<string>> selector, IAlgorithm algorithm) : base(name, selector)
|
||||
{
|
||||
_algorithm = algorithm;
|
||||
}
|
||||
|
||||
public override DateTime GetNextRefreshTimeUtc()
|
||||
{
|
||||
if (_lastRefresh != _algorithm.Time.Date)
|
||||
{
|
||||
_lastRefresh = _algorithm.Time.Date;
|
||||
return DateTime.MinValue;
|
||||
}
|
||||
return DateTime.MaxValue;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0.678%"},
|
||||
{"Drawdown", "3.700%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.009%"},
|
||||
{"Sharpe Ratio", "7.969"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.046"},
|
||||
{"Beta", "-0.032"},
|
||||
{"Annual Standard Deviation", "0.001"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-24.461"},
|
||||
{"Tracking Error", "0.044"},
|
||||
{"Treynor Ratio", "-0.336"},
|
||||
{"Total Fees", "$1.00"},
|
||||
{"Fitness Score", "0.003"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0.003"},
|
||||
{"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", "-1779427412"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -161,7 +161,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1018168907"}
|
||||
{"OrderListHash", "-1726463684"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,9 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
@@ -60,11 +62,24 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
contract.Symbol.ID.OptionRight == OptionRight.Call &&
|
||||
contract.Symbol.ID.Date == new DateTime(2016, 01, 15))
|
||||
{
|
||||
if (slice.Time.Date == new DateTime(2014, 06, 05) && contract.OpenInterest != 50)
|
||||
var history = History<OpenInterest>(contract.Symbol, TimeSpan.FromDays(1)).ToList();
|
||||
if (history.Count == 0)
|
||||
{
|
||||
throw new Exception("Regression test failed: open interest history request is empty");
|
||||
}
|
||||
|
||||
var security = Securities[contract.Symbol];
|
||||
var openInterestCache = security.Cache.GetData<OpenInterest>();
|
||||
if (openInterestCache == null)
|
||||
{
|
||||
throw new Exception("Regression test failed: current open interest isn't in the security cache");
|
||||
}
|
||||
|
||||
if (slice.Time.Date == new DateTime(2014, 06, 05) && (contract.OpenInterest != 50 || security.OpenInterest != 50))
|
||||
{
|
||||
throw new Exception("Regression test failed: current open interest was not correctly loaded and is not equal to 50");
|
||||
}
|
||||
if (slice.Time.Date == new DateTime(2014, 06, 06) && contract.OpenInterest != 70)
|
||||
if (slice.Time.Date == new DateTime(2014, 06, 06) && (contract.OpenInterest != 70 || security.OpenInterest != 70))
|
||||
{
|
||||
throw new Exception("Regression test failed: current open interest was not correctly loaded and is not equal to 70");
|
||||
}
|
||||
|
||||
188
Algorithm.CSharp/OrderImmutabilityRegressionAlgorithm.cs
Normal file
188
Algorithm.CSharp/OrderImmutabilityRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,188 @@
|
||||
/*
|
||||
* 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.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests that orders are unchangeable from the QCAlgorithm Layer
|
||||
/// Orders should only be modifiable via their ticket and only in permitted ways
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="backtesting brokerage" />
|
||||
/// <meta name="tag" content="regression test" />
|
||||
/// <meta name="tag" content="options" />
|
||||
public class OrderImmutabilityRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private readonly Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
|
||||
private OrderTicket _ticket;
|
||||
private Order _originalOrder;
|
||||
|
||||
/// <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, 08); //Set Start Date
|
||||
SetEndDate(2013, 10, 09); //Set End Date
|
||||
SetCash(100000); //Set Strategy Cash
|
||||
AddEquity("SPY", Resolution.Daily);
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
_ticket = LimitOrder(_spy, 10, 100);
|
||||
Debug("Purchased Stock");
|
||||
|
||||
// Here we will show how to correctly change an order, we will then verify at End of Algorithm!
|
||||
// First get the order as it is now, should be a copy, so it wont be updated!
|
||||
_originalOrder = Transactions.GetOrderById(_ticket.OrderId);
|
||||
|
||||
// Create an UpdateOrderRequest and send it to the ticket
|
||||
var updateFields = new UpdateOrderFields { Quantity = 20, Tag = "Pepe", LimitPrice = data[_spy].Low};
|
||||
var response = _ticket.Update(updateFields);
|
||||
|
||||
// Test order time
|
||||
if (_originalOrder.Time != UtcTime)
|
||||
{
|
||||
Error("Order Time should be UtcTime!");
|
||||
throw new Exception("Order Time should be UtcTime!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// All order events get pushed through this function
|
||||
/// This function will test that what we get from Transactions is indeed a clone
|
||||
/// The only authentic way to change the order is to change through the order ticket!
|
||||
/// </summary>
|
||||
/// <param name="orderEvent">OrderEvent object that contains all the information about the event</param>
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
|
||||
// Get the order twice, since they are clones they should NOT be the same
|
||||
var orderV1 = Transactions.GetOrderById(orderEvent.OrderId);
|
||||
var orderV2 = Transactions.GetOrderById(orderEvent.OrderId);
|
||||
|
||||
if (orderV1 == orderV2)
|
||||
{
|
||||
Error("Orders should be clones, hence not equal!");
|
||||
throw new Exception("Orders should be clones, hence not equal!");
|
||||
}
|
||||
|
||||
// Try and manipulate orderV2 using the only external accessor BrokerID, since we
|
||||
// are changing a clone the BrokerIDs should not be the same
|
||||
orderV2.BrokerId.Add("FAKE BROKER ID");
|
||||
var orderV3 = Transactions.GetOrderById(orderEvent.OrderId);
|
||||
|
||||
if (orderV2.BrokerId.SequenceEqual(orderV3.BrokerId))
|
||||
{
|
||||
Error("Broker IDs should not be the same!");
|
||||
throw new Exception("Broker IDs should not be the same!");
|
||||
}
|
||||
|
||||
//Try and manipulate the orderV1 using UpdateOrderRequest
|
||||
//NOTICE: Orders should only be updated through their tickets!
|
||||
var updateFields = new UpdateOrderFields { Quantity = 99, Tag = "Pepe2!" };
|
||||
var updateRequest = new UpdateOrderRequest(DateTime.Now, orderEvent.OrderId, updateFields);
|
||||
orderV1.ApplyUpdateOrderRequest(updateRequest);
|
||||
var orderV4 = Transactions.GetOrderById(orderEvent.OrderId);
|
||||
|
||||
if (orderV4.Quantity == orderV1.Quantity)
|
||||
{
|
||||
Error("Order quantity should not be the same!");
|
||||
throw new Exception("Order quantity should not be the same!");
|
||||
}
|
||||
|
||||
if (orderV4.Tag == orderV1.Tag)
|
||||
{
|
||||
Error("Order tag should not be the same!");
|
||||
throw new Exception("Order tag should not be the same!");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Will run at End of Algorithm
|
||||
/// We will be using this to check our order was updated!
|
||||
/// </summary>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
//Get an updated copy of the order and compare to our original
|
||||
var updatedOrder = Transactions.GetOrderById(_ticket.OrderId);
|
||||
|
||||
if (updatedOrder.Quantity == _originalOrder.Quantity)
|
||||
{
|
||||
Error("Quantities should have been updated!");
|
||||
throw new Exception("Quantities should have been updated!");
|
||||
}
|
||||
|
||||
if (updatedOrder.Tag == _originalOrder.Tag)
|
||||
{
|
||||
Error("Tag should have been updated!");
|
||||
throw new Exception("Tag should have been updated!");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "-5.591%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "-0.032%"},
|
||||
{"Sharpe Ratio", "-9.862"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.007"},
|
||||
{"Beta", "-0.582"},
|
||||
{"Annual Standard Deviation", "0.004"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-10.999"},
|
||||
{"Tracking Error", "0.011"},
|
||||
{"Treynor Ratio", "0.067"},
|
||||
{"Total Fees", "$1.00"},
|
||||
{"Fitness Score", "0.007"},
|
||||
{"OrderListHash", "1715759777"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -86,12 +86,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "18"},
|
||||
{"Average Win", "0.88%"},
|
||||
{"Average Loss", "-0.95%"},
|
||||
{"Compounding Annual Return", "292.584%"},
|
||||
{"Compounding Annual Return", "292.522%"},
|
||||
{"Drawdown", "3.400%"},
|
||||
{"Expectancy", "0.204"},
|
||||
{"Net Profit", "1.780%"},
|
||||
{"Sharpe Ratio", "11.819"},
|
||||
{"Probabilistic Sharpe Ratio", "66.758%"},
|
||||
{"Sharpe Ratio", "11.817"},
|
||||
{"Probabilistic Sharpe Ratio", "66.756%"},
|
||||
{"Loss Rate", "38%"},
|
||||
{"Win Rate", "62%"},
|
||||
{"Profit-Loss Ratio", "0.93"},
|
||||
@@ -99,15 +99,15 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Beta", "1.548"},
|
||||
{"Annual Standard Deviation", "0.34"},
|
||||
{"Annual Variance", "0.116"},
|
||||
{"Information Ratio", "17.385"},
|
||||
{"Information Ratio", "17.38"},
|
||||
{"Tracking Error", "0.12"},
|
||||
{"Treynor Ratio", "2.597"},
|
||||
{"Treynor Ratio", "2.596"},
|
||||
{"Total Fees", "$45.00"},
|
||||
{"Fitness Score", "0.986"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "9.332"},
|
||||
{"Return Over Maximum Drawdown", "45.085"},
|
||||
{"Sortino Ratio", "9.326"},
|
||||
{"Return Over Maximum Drawdown", "45.056"},
|
||||
{"Portfolio Turnover", "2.728"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -122,7 +122,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-809947807"}
|
||||
{"OrderListHash", "-46935513"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -527,7 +527,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1237222672"}
|
||||
{"OrderListHash", "-1594146186"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,6 +98,16 @@
|
||||
<IsLinux>false</IsLinux>
|
||||
<IsLinux Condition="'$(IsWindows)' != 'true' AND '$(IsOSX)' != 'true' AND '$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Linux)))' == 'true'">true</IsLinux>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'DebugDocker|AnyCPU'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<DebugType>portable</DebugType>
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<LangVersion>6</LangVersion>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>..\QuantConnect.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<Target Name="PrintRID" BeforeTargets="Build">
|
||||
<Message Text="IsWindows $(IsWindows)" Importance="high" />
|
||||
<Message Text="IsOSX $(IsOSX)" Importance="high" />
|
||||
@@ -132,6 +142,18 @@
|
||||
<Link>Properties\SharedAssemblyInfo.cs</Link>
|
||||
</Compile>
|
||||
<Compile Include="AddAlphaModelAlgorithm.cs" />
|
||||
<Compile Include="CustomBuyingPowerModelAlgorithm.cs" />
|
||||
<Compile Include="AddOptionContractExpiresRegressionAlgorithm.cs" />
|
||||
<Compile Include="ScaledFillForwardDataRegressionAlgorithm.cs" />
|
||||
<Compile Include="DailyHistoryForDailyResolutionRegressionAlgorithm.cs" />
|
||||
<Compile Include="DailyHistoryForMinuteResolutionRegressionAlgorithm.cs" />
|
||||
<Compile Include="ExtendedMarketHoursHistoryRegressionAlgorithm.cs" />
|
||||
<Compile Include="EquityTickQuoteAdjustedModeRegressionAlgorithm.cs" />
|
||||
<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" />
|
||||
<Compile Include="AddRiskManagementAlgorithm.cs" />
|
||||
@@ -148,7 +170,6 @@
|
||||
<Compile Include="Alphas\TriangleExchangeRateArbitrageAlpha.cs" />
|
||||
<Compile Include="Alphas\TripleLeveragedETFPairVolatilityDecayAlpha.cs" />
|
||||
<Compile Include="Alphas\VixDualThrustAlpha.cs" />
|
||||
<Compile Include="AltData\RobintrackHoldingsAlgorithm.cs" />
|
||||
<Compile Include="AltData\CachedAlternativeDataAlgorithm.cs" />
|
||||
<Compile Include="AltData\BenzingaNewsAlgorithm.cs" />
|
||||
<Compile Include="AltData\SECReport8KAlgorithm.cs" />
|
||||
@@ -158,6 +179,8 @@
|
||||
<Compile Include="AltData\TiingoNewsAlgorithm.cs" />
|
||||
<Compile Include="AutomaticIndicatorWarmupDataTypeRegressionAlgorithm.cs" />
|
||||
<Compile Include="AutomaticIndicatorWarmupRegressionAlgorithm.cs" />
|
||||
<Compile Include="BacktestingBrokerageRegressionAlgorithm.cs" />
|
||||
<Compile Include="ExtendedMarketTradingRegressionAlgorithm.cs" />
|
||||
<Compile Include="CoarseTiingoNewsUniverseSelectionAlgorithm.cs" />
|
||||
<Compile Include="DelistedFutureLiquidateRegressionAlgorithm.cs" />
|
||||
<Compile Include="EmaCrossFuturesFrontMonthAlgorithm.cs" />
|
||||
@@ -189,6 +212,7 @@
|
||||
<Compile Include="MarginRemainingRegressionAlgorithm.cs" />
|
||||
<Compile Include="NoMarginCallExpectedRegressionAlgorithm.cs" />
|
||||
<Compile Include="ObjectStoreExampleAlgorithm.cs" />
|
||||
<Compile Include="OrderImmutabilityRegressionAlgorithm.cs" />
|
||||
<Compile Include="OrderSubmissionDataRegressionAlgorithm.cs" />
|
||||
<Compile Include="RegisterIndicatorRegressionAlgorithm.cs" />
|
||||
<Compile Include="ScheduledEventsOrderRegressionAlgorithm.cs" />
|
||||
@@ -357,6 +381,7 @@
|
||||
<Compile Include="RegressionAlgorithm.cs" />
|
||||
<Compile Include="RenkoConsolidatorAlgorithm.cs" />
|
||||
<Compile Include="ScheduledEventsAlgorithm.cs" />
|
||||
<Compile Include="ScheduledQueuingAlgorithm.cs" />
|
||||
<Compile Include="StressSymbolsAlgorithm.cs" />
|
||||
<Compile Include="StressSymbols.cs" />
|
||||
<Compile Include="TickDataFilteringAlgorithm.cs" />
|
||||
@@ -416,6 +441,9 @@
|
||||
<Analyzer Include="..\packages\Microsoft.NetFramework.Analyzers.2.9.3\analyzers\dotnet\cs\Microsoft.NetFramework.Analyzers.dll" />
|
||||
<Analyzer Include="..\packages\Microsoft.NetFramework.Analyzers.2.9.3\analyzers\dotnet\cs\Microsoft.NetFramework.CSharp.Analyzers.dll" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="DaylightSavingTimeHistoryRegressionAlgorithm.cs" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
|
||||
<PropertyGroup>
|
||||
|
||||
143
Algorithm.CSharp/ScaledFillForwardDataRegressionAlgorithm.cs
Normal file
143
Algorithm.CSharp/ScaledFillForwardDataRegressionAlgorithm.cs
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.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression test algorithm reproduces issue https://github.com/QuantConnect/Lean/issues/4834
|
||||
/// fixed in PR https://github.com/QuantConnect/Lean/pull/4836
|
||||
/// Adjusted data of fill forward bars should use original scale factor
|
||||
/// </summary>
|
||||
public class ScaledFillForwardDataRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private TradeBar _lastRealBar;
|
||||
private Symbol _twx;
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 6, 5);
|
||||
SetEndDate(2014, 6, 9);
|
||||
|
||||
_twx = AddEquity("TWX", Resolution.Minute, extendedMarketHours: true).Symbol;
|
||||
Schedule.On(DateRules.EveryDay(_twx), TimeRules.Every(TimeSpan.FromHours(1)), PlotPrice);
|
||||
}
|
||||
|
||||
private void PlotPrice()
|
||||
{
|
||||
Plot($"{_twx}", "Ask", Securities[_twx].AskPrice);
|
||||
Plot($"{_twx}", "Bid", Securities[_twx].BidPrice);
|
||||
Plot($"{_twx}", "Price", Securities[_twx].Price);
|
||||
Plot("Portfolio.TPV", "Value", Portfolio.TotalPortfolioValue);
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
var current = data.Bars.FirstOrDefault().Value;
|
||||
if (current != null)
|
||||
{
|
||||
if (Time == new DateTime(2014, 06, 09, 4, 1, 0) && !Portfolio.Invested)
|
||||
{
|
||||
if (!current.IsFillForward)
|
||||
{
|
||||
throw new Exception($"Was expecting a first fill forward bar {Time}");
|
||||
}
|
||||
|
||||
// trade on the first bar after a factor price scale change. +10 so we fill ASAP. Limit so it fills in extended market hours
|
||||
LimitOrder(_twx, 1000, _lastRealBar.Close + 10);
|
||||
}
|
||||
|
||||
if (_lastRealBar == null || !current.IsFillForward)
|
||||
{
|
||||
_lastRealBar = current;
|
||||
}
|
||||
else if (_lastRealBar.Close != current.Close)
|
||||
{
|
||||
throw new Exception($"FillForwarded data point at {Time} was scaled. Actual: {current.Close}; Expected: {_lastRealBar.Close}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (_lastRealBar == null)
|
||||
{
|
||||
throw new Exception($"Not all expected data points were received.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "32.825%"},
|
||||
{"Drawdown", "0.800%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.377%"},
|
||||
{"Sharpe Ratio", "8.953"},
|
||||
{"Probabilistic Sharpe Ratio", "95.977%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.314"},
|
||||
{"Beta", "-0.104"},
|
||||
{"Annual Standard Deviation", "0.03"},
|
||||
{"Annual Variance", "0.001"},
|
||||
{"Information Ratio", "-3.498"},
|
||||
{"Tracking Error", "0.05"},
|
||||
{"Treynor Ratio", "-2.573"},
|
||||
{"Total Fees", "$5.00"},
|
||||
{"Fitness Score", "0.158"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0.158"},
|
||||
{"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", "960108217"}
|
||||
};
|
||||
}
|
||||
}
|
||||
96
Algorithm.CSharp/ScheduledQueuingAlgorithm.cs
Normal file
96
Algorithm.CSharp/ScheduledQueuingAlgorithm.cs
Normal file
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Algorithm.Framework.Alphas;
|
||||
using QuantConnect.Algorithm.Framework.Execution;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
using QuantConnect.Algorithm.Framework.Selection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Fundamental;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
public class TachyonDynamicGearbox : QCAlgorithm
|
||||
{
|
||||
private int numberOfSymbols;
|
||||
private int numberOfSymbolsFine;
|
||||
private Queue<Symbol> queue;
|
||||
private int dequeueSize;
|
||||
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 9, 1);
|
||||
SetEndDate(2020, 9, 2);
|
||||
SetCash(100000);
|
||||
|
||||
numberOfSymbols = 2000;
|
||||
numberOfSymbolsFine = 1000;
|
||||
SetUniverseSelection(new FineFundamentalUniverseSelectionModel(CoarseSelectionFunction, FineSelectionFunction));
|
||||
|
||||
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
|
||||
|
||||
SetExecution(new ImmediateExecutionModel());
|
||||
|
||||
queue = new Queue<Symbol>();
|
||||
dequeueSize = 100;
|
||||
|
||||
AddEquity("SPY", Resolution.Minute);
|
||||
Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(0, 0), FillQueue);
|
||||
Schedule.On(DateRules.EveryDay("SPY"), TimeRules.Every(TimeSpan.FromMinutes(60)), TakeFromQueue);
|
||||
}
|
||||
|
||||
public IEnumerable<Symbol> CoarseSelectionFunction(IEnumerable<CoarseFundamental> coarse)
|
||||
{
|
||||
var sortedByDollarVolume = coarse
|
||||
.Where(x => x.HasFundamentalData)
|
||||
.OrderByDescending(x => x.DollarVolume);
|
||||
return sortedByDollarVolume.Take(numberOfSymbols).Select(x => x.Symbol);
|
||||
}
|
||||
|
||||
public IEnumerable<Symbol> FineSelectionFunction(IEnumerable<FineFundamental> fine)
|
||||
{
|
||||
|
||||
var sortedByPeRatio = fine.OrderByDescending(x => x.ValuationRatios.PERatio);
|
||||
var topFine = sortedByPeRatio.Take(numberOfSymbolsFine);
|
||||
return topFine.Select(x => x.Symbol);
|
||||
}
|
||||
|
||||
private void FillQueue() {
|
||||
var securities = ActiveSecurities.Values.Where(x => x.Fundamentals != null);
|
||||
|
||||
// Fill queue with symbols sorted by PE ratio (decreasing order)
|
||||
queue.Clear();
|
||||
var sortedByPERatio = securities.OrderByDescending(x => x.Fundamentals.ValuationRatios.PERatio);
|
||||
foreach (Security security in sortedByPERatio)
|
||||
queue.Enqueue(security.Symbol);
|
||||
}
|
||||
|
||||
private void TakeFromQueue() {
|
||||
List<Symbol> symbols = new List<Symbol>();
|
||||
for (int i = 0; i < Math.Min(dequeueSize, queue.Count); i++)
|
||||
symbols.Add(queue.Dequeue());
|
||||
History(symbols, 10, Resolution.Daily);
|
||||
|
||||
Log("Symbols at " + Time + ": " + string.Join(", ", symbols.Select(x => x.ToString())));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -67,16 +67,16 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
if (dateTime.DayOfWeek == DayOfWeek.Tuesday || dateTime.DayOfWeek == DayOfWeek.Thursday)
|
||||
{
|
||||
yield return QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM);
|
||||
yield return QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, Market.Oanda);
|
||||
}
|
||||
else if (dateTime.DayOfWeek == DayOfWeek.Friday)
|
||||
{
|
||||
// given the date/time rules specified in Initialize, this symbol will never be selected (every 6 hours never lands on hour==1)
|
||||
yield return QuantConnect.Symbol.Create("EURGBP", SecurityType.Forex, Market.FXCM);
|
||||
yield return QuantConnect.Symbol.Create("EURGBP", SecurityType.Forex, Market.Oanda);
|
||||
}
|
||||
else
|
||||
{
|
||||
yield return QuantConnect.Symbol.Create("NZDUSD", SecurityType.Forex, Market.FXCM);
|
||||
yield return QuantConnect.Symbol.Create("NZDUSD", SecurityType.Forex, Market.Oanda);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,46 +192,46 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "52"},
|
||||
{"Average Win", "0.27%"},
|
||||
{"Average Loss", "-0.22%"},
|
||||
{"Compounding Annual Return", "41.076%"},
|
||||
{"Drawdown", "1.000%"},
|
||||
{"Expectancy", "0.618"},
|
||||
{"Net Profit", "3.112%"},
|
||||
{"Sharpe Ratio", "5.311"},
|
||||
{"Probabilistic Sharpe Ratio", "90.919%"},
|
||||
{"Loss Rate", "29%"},
|
||||
{"Win Rate", "71%"},
|
||||
{"Profit-Loss Ratio", "1.26"},
|
||||
{"Alpha", "0.31"},
|
||||
{"Beta", "0.054"},
|
||||
{"Annual Standard Deviation", "0.06"},
|
||||
{"Annual Variance", "0.004"},
|
||||
{"Information Ratio", "1.79"},
|
||||
{"Tracking Error", "0.079"},
|
||||
{"Treynor Ratio", "5.952"},
|
||||
{"Total Fees", "$36.83"},
|
||||
{"Fitness Score", "0.67"},
|
||||
{"Kelly Criterion Estimate", "25.099"},
|
||||
{"Kelly Criterion Probability Value", "0.068"},
|
||||
{"Sortino Ratio", "13.102"},
|
||||
{"Return Over Maximum Drawdown", "55.759"},
|
||||
{"Portfolio Turnover", "0.675"},
|
||||
{"Total Insights Generated", "54"},
|
||||
{"Total Insights Closed", "52"},
|
||||
{"Total Insights Analysis Completed", "52"},
|
||||
{"Long Insight Count", "54"},
|
||||
{"Total Trades", "86"},
|
||||
{"Average Win", "0.16%"},
|
||||
{"Average Loss", "-0.10%"},
|
||||
{"Compounding Annual Return", "51.162%"},
|
||||
{"Drawdown", "1.100%"},
|
||||
{"Expectancy", "0.793"},
|
||||
{"Net Profit", "3.748%"},
|
||||
{"Sharpe Ratio", "7.195"},
|
||||
{"Probabilistic Sharpe Ratio", "99.177%"},
|
||||
{"Loss Rate", "31%"},
|
||||
{"Win Rate", "69%"},
|
||||
{"Profit-Loss Ratio", "1.60"},
|
||||
{"Alpha", "0.366"},
|
||||
{"Beta", "0.161"},
|
||||
{"Annual Standard Deviation", "0.055"},
|
||||
{"Annual Variance", "0.003"},
|
||||
{"Information Ratio", "3.061"},
|
||||
{"Tracking Error", "0.07"},
|
||||
{"Treynor Ratio", "2.443"},
|
||||
{"Total Fees", "$33.96"},
|
||||
{"Fitness Score", "0.75"},
|
||||
{"Kelly Criterion Estimate", "23.91"},
|
||||
{"Kelly Criterion Probability Value", "0.076"},
|
||||
{"Sortino Ratio", "42.076"},
|
||||
{"Return Over Maximum Drawdown", "129.046"},
|
||||
{"Portfolio Turnover", "0.751"},
|
||||
{"Total Insights Generated", "55"},
|
||||
{"Total Insights Closed", "53"},
|
||||
{"Total Insights Analysis Completed", "53"},
|
||||
{"Long Insight Count", "55"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$814596.0814"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$888136.0054"},
|
||||
{"Mean Population Estimated Insight Value", "$17079.5386"},
|
||||
{"Mean Population Direction", "59.6154%"},
|
||||
{"Mean Population Estimated Insight Value", "$16757.2831"},
|
||||
{"Mean Population Direction", "58.4906%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "64.1791%"},
|
||||
{"Rolling Averaged Population Direction", "55.0223%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1450725184"}
|
||||
{"OrderListHash", "941404943"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,7 +259,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-142.421"},
|
||||
{"Return Over Maximum Drawdown", "-141.917"},
|
||||
{"Portfolio Turnover", "2.001"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
|
||||
@@ -197,29 +197,29 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "6"},
|
||||
{"Average Win", "0.40%"},
|
||||
{"Average Loss", "-0.86%"},
|
||||
{"Compounding Annual Return", "-17.124%"},
|
||||
{"Compounding Annual Return", "-15.825%"},
|
||||
{"Drawdown", "1.100%"},
|
||||
{"Expectancy", "-0.266"},
|
||||
{"Net Profit", "-0.464%"},
|
||||
{"Sharpe Ratio", "-1.547"},
|
||||
{"Probabilistic Sharpe Ratio", "33.672%"},
|
||||
{"Net Profit", "-0.463%"},
|
||||
{"Sharpe Ratio", "-1.475"},
|
||||
{"Probabilistic Sharpe Ratio", "33.116%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.47"},
|
||||
{"Alpha", "-0.21"},
|
||||
{"Beta", "0.104"},
|
||||
{"Annual Standard Deviation", "0.086"},
|
||||
{"Alpha", "-0.196"},
|
||||
{"Beta", "0.123"},
|
||||
{"Annual Standard Deviation", "0.081"},
|
||||
{"Annual Variance", "0.007"},
|
||||
{"Information Ratio", "-4.732"},
|
||||
{"Tracking Error", "0.184"},
|
||||
{"Treynor Ratio", "-1.286"},
|
||||
{"Total Fees", "$12.97"},
|
||||
{"Information Ratio", "-4.271"},
|
||||
{"Tracking Error", "0.174"},
|
||||
{"Treynor Ratio", "-0.972"},
|
||||
{"Total Fees", "$12.99"},
|
||||
{"Fitness Score", "0.031"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-3.761"},
|
||||
{"Return Over Maximum Drawdown", "-15.539"},
|
||||
{"Portfolio Turnover", "0.499"},
|
||||
{"Sortino Ratio", "-3.46"},
|
||||
{"Return Over Maximum Drawdown", "-14.323"},
|
||||
{"Portfolio Turnover", "0.445"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -233,7 +233,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-436429281"}
|
||||
{"OrderListHash", "-304070777"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
}
|
||||
|
||||
var eurUsdSubscription = SubscriptionManager.SubscriptionDataConfigService
|
||||
.GetSubscriptionDataConfigs(QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM),
|
||||
.GetSubscriptionDataConfigs(QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, Market.Oanda),
|
||||
includeInternalConfigs: true)
|
||||
.Single();
|
||||
if (!eurUsdSubscription.IsInternalFeed)
|
||||
@@ -100,29 +100,29 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "17.116%"},
|
||||
{"Compounding Annual Return", "16.445%"},
|
||||
{"Drawdown", "4.800%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.913%"},
|
||||
{"Sharpe Ratio", "0.93"},
|
||||
{"Probabilistic Sharpe Ratio", "48.592%"},
|
||||
{"Sharpe Ratio", "0.903"},
|
||||
{"Probabilistic Sharpe Ratio", "48.314%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.119"},
|
||||
{"Beta", "0.202"},
|
||||
{"Annual Standard Deviation", "0.161"},
|
||||
{"Annual Variance", "0.026"},
|
||||
{"Alpha", "0.113"},
|
||||
{"Beta", "0.203"},
|
||||
{"Annual Standard Deviation", "0.156"},
|
||||
{"Annual Variance", "0.024"},
|
||||
{"Information Ratio", "0.001"},
|
||||
{"Tracking Error", "0.203"},
|
||||
{"Treynor Ratio", "0.739"},
|
||||
{"Tracking Error", "0.198"},
|
||||
{"Treynor Ratio", "0.697"},
|
||||
{"Total Fees", "$2.60"},
|
||||
{"Fitness Score", "0.044"},
|
||||
{"Fitness Score", "0.041"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "1.683"},
|
||||
{"Return Over Maximum Drawdown", "3.545"},
|
||||
{"Portfolio Turnover", "0.055"},
|
||||
{"Sortino Ratio", "1.617"},
|
||||
{"Return Over Maximum Drawdown", "3.406"},
|
||||
{"Portfolio Turnover", "0.052"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
*/
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
@@ -22,7 +24,10 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <summary>
|
||||
/// The forex symbols.
|
||||
/// </summary>
|
||||
public static HashSet<string> ForexSymbols = new HashSet<string>(Currencies.CurrencyPairs);
|
||||
public static HashSet<string> ForexSymbols = new HashSet<string>(SymbolPropertiesDatabase
|
||||
.FromDataFolder()
|
||||
.GetSymbolPropertiesList(Market.Oanda, SecurityType.Forex)
|
||||
.Select(x => x.Key.Symbol));
|
||||
|
||||
/// <summary>
|
||||
/// The stock symbols.
|
||||
|
||||
142
Algorithm.CSharp/SwitchDataModeRegressionAlgorithm.cs
Normal file
142
Algorithm.CSharp/SwitchDataModeRegressionAlgorithm.cs
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.
|
||||
*
|
||||
*/
|
||||
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression test algorithm reproduces issue https://github.com/QuantConnect/Lean/issues/4031
|
||||
/// fixed in PR https://github.com/QuantConnect/Lean/pull/4650
|
||||
/// Adjusted data have already been all loaded by the workers so DataNormalizationMode change has no effect in the data itself
|
||||
/// </summary>
|
||||
public class SwitchDataModeRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private const string UnderlyingTicker = "AAPL";
|
||||
|
||||
private readonly Dictionary<DateTime, decimal?> _expectedCloseValues = new Dictionary<DateTime, decimal?>() {
|
||||
{ new DateTime(2014, 6, 6, 9, 57, 0), 86.04398m},
|
||||
{ new DateTime(2014, 6, 6, 9, 58, 0), 86.05196m},
|
||||
{ new DateTime(2014, 6, 6, 9, 59, 0), 648.29m},
|
||||
{ new DateTime(2014, 6, 6, 10, 0, 0), 647.86m},
|
||||
{ new DateTime(2014, 6, 6, 10, 1, 0), 646.84m},
|
||||
{ new DateTime(2014, 6, 6, 10, 2, 0), 647.64m},
|
||||
{ new DateTime(2014, 6, 6, 10, 3, 0), 646.9m}
|
||||
};
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 6, 6);
|
||||
SetEndDate(2014, 6, 6);
|
||||
|
||||
var aapl = AddEquity(UnderlyingTicker, Resolution.Minute);
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (Time.Hour == 9 && Time.Minute == 58)
|
||||
{
|
||||
AddOption(UnderlyingTicker);
|
||||
}
|
||||
|
||||
AssertValue(data);
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (_expectedCloseValues.Count > 0)
|
||||
{
|
||||
throw new Exception($"Not all expected data points were received.");
|
||||
}
|
||||
}
|
||||
|
||||
private void AssertValue(Slice data)
|
||||
{
|
||||
decimal? value;
|
||||
if (_expectedCloseValues.TryGetValue(data.Time, out value))
|
||||
{
|
||||
if (data.Bars.FirstOrDefault().Value?.Close.SmartRounding() != value)
|
||||
{
|
||||
throw new Exception($"Expected tradebar price, expected {value} but was {data.Bars.First().Value.Close.SmartRounding()}");
|
||||
}
|
||||
|
||||
_expectedCloseValues.Remove(data.Time);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "0"},
|
||||
{"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", "$0.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "0"},
|
||||
{"Return Over Maximum Drawdown", "0"},
|
||||
{"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", "371857150"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -189,7 +189,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-569072921"}
|
||||
{"OrderListHash", "359885308"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,32 +172,32 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "5"},
|
||||
{"Total Trades", "4"},
|
||||
{"Average Win", "0.64%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "-74.197%"},
|
||||
{"Drawdown", "6.600%"},
|
||||
{"Compounding Annual Return", "-56.577%"},
|
||||
{"Drawdown", "3.800%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "-6.115%"},
|
||||
{"Sharpe Ratio", "-2.281"},
|
||||
{"Probabilistic Sharpe Ratio", "11.870%"},
|
||||
{"Net Profit", "-3.811%"},
|
||||
{"Sharpe Ratio", "-2.773"},
|
||||
{"Probabilistic Sharpe Ratio", "13.961%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.684"},
|
||||
{"Beta", "-0.113"},
|
||||
{"Annual Standard Deviation", "0.292"},
|
||||
{"Annual Variance", "0.085"},
|
||||
{"Information Ratio", "-1.606"},
|
||||
{"Tracking Error", "0.312"},
|
||||
{"Treynor Ratio", "5.866"},
|
||||
{"Total Fees", "$5.00"},
|
||||
{"Fitness Score", "0.017"},
|
||||
{"Alpha", "-0.504"},
|
||||
{"Beta", "-0.052"},
|
||||
{"Annual Standard Deviation", "0.179"},
|
||||
{"Annual Variance", "0.032"},
|
||||
{"Information Ratio", "-1.599"},
|
||||
{"Tracking Error", "0.207"},
|
||||
{"Treynor Ratio", "9.508"},
|
||||
{"Total Fees", "$4.00"},
|
||||
{"Fitness Score", "0.008"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-2.584"},
|
||||
{"Return Over Maximum Drawdown", "-11.287"},
|
||||
{"Portfolio Turnover", "0.177"},
|
||||
{"Sortino Ratio", "-3.791"},
|
||||
{"Return Over Maximum Drawdown", "-14.846"},
|
||||
{"Portfolio Turnover", "0.136"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -211,7 +211,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1386253041"}
|
||||
{"OrderListHash", "1484950465"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,8 +152,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-31.646"},
|
||||
{"Tracking Error", "0.16"},
|
||||
{"Information Ratio", "-58.133"},
|
||||
{"Tracking Error", "0.173"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Fitness Score", "0"},
|
||||
|
||||
@@ -233,7 +233,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "124750474"}
|
||||
{"OrderListHash", "1536869386"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ namespace QuantConnect.Algorithm.Framework.Portfolio
|
||||
|
||||
/// <summary>
|
||||
/// Initialize a new instance of <see cref="SectorWeightingPortfolioConstructionModel"/>
|
||||
/// </summary>
|
||||
/// <param name="rebalance">Rebalancing func or if a date rule, timedelta will be converted into func.
|
||||
/// For a given algorithm UTC DateTime the func returns the next expected rebalance time
|
||||
/// or null if unknown, in which case the function will be called again in the next loop. Returning current time
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -61,7 +61,7 @@ namespace QuantConnect.Algorithm.Framework.Selection
|
||||
/// </summary>
|
||||
protected override FutureFilterUniverse Filter(FutureFilterUniverse filter)
|
||||
{
|
||||
return filter.Contracts(FilterByOpenInterest(filter.ToDictionary(x => x, x => _marketHoursDatabase.GetEntry(x.ID.Market, x, x.ID.SecurityType).ExchangeHours)));
|
||||
return filter.Contracts(FilterByOpenInterest(filter.ToDictionary(x => x, x => _marketHoursDatabase.GetEntry(x.ID.Market, x, x.ID.SecurityType))));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -69,7 +69,7 @@ namespace QuantConnect.Algorithm.Framework.Selection
|
||||
/// </summary>
|
||||
/// <param name="contracts">Contracts to filter</param>
|
||||
/// <returns>Filtered set</returns>
|
||||
public IEnumerable<Symbol> FilterByOpenInterest(IReadOnlyDictionary<Symbol, SecurityExchangeHours> contracts)
|
||||
public IEnumerable<Symbol> FilterByOpenInterest(IReadOnlyDictionary<Symbol, MarketHoursDatabase.Entry> contracts)
|
||||
{
|
||||
var symbols = new List<Symbol>(_chainContractsLookupLimit.HasValue ? contracts.Keys.OrderBy(x => x.ID.Date).Take(_chainContractsLookupLimit.Value) : contracts.Keys);
|
||||
var openInterest = symbols.GroupBy(x => contracts[x]).SelectMany(g => GetOpenInterest(g.Key, g.Select(i => i))).ToDictionary(x => x.Key, x => x.Value);
|
||||
@@ -91,11 +91,12 @@ namespace QuantConnect.Algorithm.Framework.Selection
|
||||
return filtered;
|
||||
}
|
||||
|
||||
private Dictionary<Symbol, decimal> GetOpenInterest(SecurityExchangeHours exchangeHours, IEnumerable<Symbol> symbols)
|
||||
private Dictionary<Symbol, decimal> GetOpenInterest(MarketHoursDatabase.Entry marketHours, IEnumerable<Symbol> symbols)
|
||||
{
|
||||
var current = _algorithm.UtcTime;
|
||||
var exchangeHours = marketHours.ExchangeHours;
|
||||
var endTime = Instant.FromDateTimeUtc(_algorithm.UtcTime).InZone(exchangeHours.TimeZone).ToDateTimeUnspecified();
|
||||
var previousDay = Time.GetStartTimeForTradeBars(exchangeHours, endTime, Time.OneDay, 1, true);
|
||||
var previousDay = Time.GetStartTimeForTradeBars(exchangeHours, endTime, Time.OneDay, 1, true, marketHours.DataTimeZone);
|
||||
var requests = symbols.Select(
|
||||
symbol => new HistoryRequest(
|
||||
previousDay,
|
||||
|
||||
@@ -15,12 +15,9 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Auxiliary;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Securities.Option;
|
||||
|
||||
namespace QuantConnect.Algorithm.Framework.Selection
|
||||
{
|
||||
@@ -107,53 +104,11 @@ namespace QuantConnect.Algorithm.Framework.Selection
|
||||
// prevent creating duplicate option chains -- one per underlying
|
||||
if (uniqueUnderlyingSymbols.Add(optionSymbol.Underlying))
|
||||
{
|
||||
yield return CreateOptionChain(algorithm, optionSymbol);
|
||||
yield return algorithm.CreateOptionChain(optionSymbol, Filter, _universeSettings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the canonical <see cref="Option"/> chain security for a given symbol
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance to create universes for</param>
|
||||
/// <param name="symbol">Symbol of the option</param>
|
||||
/// <param name="settings">Universe settings define attributes of created subscriptions, such as their resolution and the minimum time in universe before they can be removed</param>
|
||||
/// <param name="initializer">Performs extra initialization (such as setting models) after we create a new security object</param>
|
||||
/// <returns><see cref="Option"/> for the given symbol</returns>
|
||||
[Obsolete("This method is obsolete because SecurityInitializer is obsolete and will not be used.")]
|
||||
protected virtual Option CreateOptionChainSecurity(QCAlgorithm algorithm, Symbol symbol, UniverseSettings settings, ISecurityInitializer initializer)
|
||||
{
|
||||
return CreateOptionChainSecurity(
|
||||
algorithm.SubscriptionManager.SubscriptionDataConfigService,
|
||||
symbol,
|
||||
settings,
|
||||
algorithm.Securities);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the canonical <see cref="Option"/> chain security for a given symbol
|
||||
/// </summary>
|
||||
/// <param name="subscriptionDataConfigService">The service used to create new <see cref="SubscriptionDataConfig"/></param>
|
||||
/// <param name="symbol">Symbol of the option</param>
|
||||
/// <param name="settings">Universe settings define attributes of created subscriptions, such as their resolution and the minimum time in universe before they can be removed</param>
|
||||
/// <param name="securityManager">Used to create new <see cref="Security"/></param>
|
||||
/// <returns><see cref="Option"/> for the given symbol</returns>
|
||||
protected virtual Option CreateOptionChainSecurity(
|
||||
ISubscriptionDataConfigService subscriptionDataConfigService,
|
||||
Symbol symbol,
|
||||
UniverseSettings settings,
|
||||
SecurityManager securityManager)
|
||||
{
|
||||
var config = subscriptionDataConfigService.Add(
|
||||
typeof(ZipEntryName),
|
||||
symbol,
|
||||
settings.Resolution,
|
||||
settings.FillForward,
|
||||
settings.ExtendedMarketHours,
|
||||
false);
|
||||
return (Option)securityManager.CreateSecurity(symbol, config, settings.Leverage, false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines the option chain universe filter
|
||||
/// </summary>
|
||||
@@ -162,55 +117,5 @@ namespace QuantConnect.Algorithm.Framework.Selection
|
||||
// NOP
|
||||
return filter;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="OptionChainUniverse"/> for a given symbol
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance to create universes for</param>
|
||||
/// <param name="symbol">Symbol of the option</param>
|
||||
/// <returns><see cref="OptionChainUniverse"/> for the given symbol</returns>
|
||||
private OptionChainUniverse CreateOptionChain(QCAlgorithm algorithm, Symbol symbol)
|
||||
{
|
||||
if (symbol.SecurityType != SecurityType.Option)
|
||||
{
|
||||
throw new ArgumentException("CreateOptionChain requires an option symbol.");
|
||||
}
|
||||
|
||||
// rewrite non-canonical symbols to be canonical
|
||||
var market = symbol.ID.Market;
|
||||
var underlying = symbol.Underlying;
|
||||
if (!symbol.IsCanonical())
|
||||
{
|
||||
var alias = $"?{underlying.Value}";
|
||||
symbol = Symbol.Create(underlying.Value, SecurityType.Option, market, alias);
|
||||
}
|
||||
|
||||
// resolve defaults if not specified
|
||||
var settings = _universeSettings ?? algorithm.UniverseSettings;
|
||||
|
||||
// create canonical security object, but don't duplicate if it already exists
|
||||
Security security;
|
||||
Option optionChain;
|
||||
if (!algorithm.Securities.TryGetValue(symbol, out security))
|
||||
{
|
||||
optionChain = CreateOptionChainSecurity(
|
||||
algorithm.SubscriptionManager.SubscriptionDataConfigService,
|
||||
symbol,
|
||||
settings,
|
||||
algorithm.Securities);
|
||||
}
|
||||
else
|
||||
{
|
||||
optionChain = (Option)security;
|
||||
}
|
||||
|
||||
// set the option chain contract filter function
|
||||
optionChain.SetFilter(Filter);
|
||||
|
||||
// force option chain security to not be directly tradable AFTER it's configured to ensure it's not overwritten
|
||||
optionChain.IsTradable = false;
|
||||
|
||||
return new OptionChainUniverse(optionChain, settings, algorithm.LiveMode);
|
||||
}
|
||||
}
|
||||
}
|
||||
10
Algorithm.Python/.idea/Algorithm.Python.iml
generated
Normal file
10
Algorithm.Python/.idea/Algorithm.Python.iml
generated
Normal file
@@ -0,0 +1,10 @@
|
||||
<?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
Normal file
4
Algorithm.Python/.idea/misc.xml
generated
Normal file
@@ -0,0 +1,4 @@
|
||||
<?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
Normal file
8
Algorithm.Python/.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?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
Normal file
5
Algorithm.Python/.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"python.autoComplete.extraPaths": [
|
||||
"stubs"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
# 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 datetime import *
|
||||
|
||||
### <summary>
|
||||
### We add an option contract using 'QCAlgorithm.AddOptionContract' and place a trade, the underlying
|
||||
### gets deselected from the universe selection but should still be present since we manually added the option contract.
|
||||
### Later we call 'QCAlgorithm.RemoveOptionContract' and expect both option and underlying to be removed.
|
||||
### </summary>
|
||||
class AddOptionContractExpiresRegressionAlgorithm(QCAlgorithm):
|
||||
def Initialize(self):
|
||||
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
|
||||
|
||||
self.SetStartDate(2014, 6, 5)
|
||||
self.SetEndDate(2014, 6, 30)
|
||||
|
||||
self._expiration = datetime(2014, 6, 21)
|
||||
self._option = None
|
||||
self._traded = False
|
||||
|
||||
self._twx = Symbol.Create("TWX", SecurityType.Equity, Market.USA)
|
||||
|
||||
self.AddUniverse("my-daily-universe-name", self.Selector)
|
||||
|
||||
def Selector(self, time):
|
||||
return [ "AAPL" ]
|
||||
|
||||
def OnData(self, data):
|
||||
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
|
||||
Arguments:
|
||||
data: Slice object keyed by symbol containing the stock data
|
||||
'''
|
||||
if self._option == None:
|
||||
options = self.OptionChainProvider.GetOptionContractList(self._twx, self.Time)
|
||||
options = sorted(options, key=lambda x: x.ID.Symbol)
|
||||
|
||||
option = next((option for option in options if option.ID.Date == self._expiration and option.ID.OptionRight == OptionRight.Call and option.ID.OptionStyle == OptionStyle.American), None)
|
||||
if option != None:
|
||||
self._option = self.AddOptionContract(option).Symbol;
|
||||
|
||||
if self._option != None and self.Securities[self._option].Price != 0 and not self._traded:
|
||||
self._traded = True;
|
||||
self.Buy(self._option, 1);
|
||||
|
||||
if self.Time > self._expiration and self.Securities[self._twx].Invested:
|
||||
# we liquidate the option exercised position
|
||||
self.Liquidate(self._twx);
|
||||
@@ -0,0 +1,87 @@
|
||||
# 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 datetime import *
|
||||
|
||||
### <summary>
|
||||
### We add an option contract using 'QCAlgorithm.AddOptionContract' and place a trade, the underlying
|
||||
### gets deselected from the universe selection but should still be present since we manually added the option contract.
|
||||
### Later we call 'QCAlgorithm.RemoveOptionContract' and expect both option and underlying to be removed.
|
||||
### </summary>
|
||||
class AddOptionContractFromUniverseRegressionAlgorithm(QCAlgorithm):
|
||||
def Initialize(self):
|
||||
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
|
||||
|
||||
self.SetStartDate(2014, 6, 5)
|
||||
self.SetEndDate(2014, 6, 9)
|
||||
|
||||
self._expiration = datetime(2014, 6, 21)
|
||||
self._securityChanges = None
|
||||
self._option = None
|
||||
self._traded = False
|
||||
|
||||
self._twx = Symbol.Create("TWX", SecurityType.Equity, Market.USA)
|
||||
self._aapl = Symbol.Create("AAPL", SecurityType.Equity, Market.USA)
|
||||
self.UniverseSettings.Resolution = Resolution.Minute
|
||||
self.UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw
|
||||
|
||||
self.AddUniverse(self.Selector, self.Selector)
|
||||
|
||||
def Selector(self, fundamental):
|
||||
if self.Time <= datetime(2014, 6, 5):
|
||||
return [ self._twx ]
|
||||
return [ self._aapl ]
|
||||
|
||||
def OnData(self, data):
|
||||
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
|
||||
Arguments:
|
||||
data: Slice object keyed by symbol containing the stock data
|
||||
'''
|
||||
if self._option != None and self.Securities[self._option].Price != 0 and not self._traded:
|
||||
self._traded = True;
|
||||
self.Buy(self._option, 1);
|
||||
|
||||
if self.Time == datetime(2014, 6, 6, 14, 0, 0):
|
||||
# liquidate & remove the option
|
||||
self.RemoveOptionContract(self._option)
|
||||
|
||||
def OnSecuritiesChanged(self, changes):
|
||||
# keep track of all removed and added securities
|
||||
if self._securityChanges == None:
|
||||
self._securityChanges = changes
|
||||
else:
|
||||
self._securityChanges.op_Addition(self._securityChanges, changes)
|
||||
|
||||
if any(security.Symbol.SecurityType == SecurityType.Option for security in changes.AddedSecurities):
|
||||
return
|
||||
|
||||
for addedSecurity in changes.AddedSecurities:
|
||||
options = self.OptionChainProvider.GetOptionContractList(addedSecurity.Symbol, self.Time)
|
||||
options = sorted(options, key=lambda x: x.ID.Symbol)
|
||||
|
||||
option = next((option for option in options if option.ID.Date == self._expiration and option.ID.OptionRight == OptionRight.Call and option.ID.OptionStyle == OptionStyle.American), None)
|
||||
|
||||
self.AddOptionContract(option)
|
||||
|
||||
# just keep the first we got
|
||||
if self._option == None:
|
||||
self._option = option
|
||||
@@ -1,64 +0,0 @@
|
||||
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from clr import AddReference
|
||||
AddReference("System")
|
||||
AddReference("QuantConnect.Algorithm")
|
||||
AddReference("QuantConnect.Common")
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from System import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Custom.Robintrack import *
|
||||
|
||||
### <summary>
|
||||
### Looks at users holding the stock AAPL at a given point in time
|
||||
### and keeps track of changes in retail investor sentiment.
|
||||
###
|
||||
### We go long if the sentiment increases by 0.5%, and short if it decreases by -0.5%
|
||||
### </summary>
|
||||
class RobintrackHoldingsAlgorithm(QCAlgorithm):
|
||||
|
||||
def Initialize(self):
|
||||
self.lastValue = 0
|
||||
|
||||
self.SetStartDate(2018, 5, 1)
|
||||
self.SetEndDate(2020, 5, 5)
|
||||
self.SetCash(100000)
|
||||
|
||||
self.aapl = self.AddEquity("AAPL", Resolution.Daily).Symbol
|
||||
self.aaplHoldings = self.AddData(RobintrackHoldings, self.aapl).Symbol
|
||||
self.isLong = False
|
||||
|
||||
def OnData(self, data):
|
||||
for kvp in data.Get(RobintrackHoldings):
|
||||
holdings = kvp.Value
|
||||
|
||||
if self.lastValue != 0:
|
||||
percentChange = (holdings.UsersHolding - self.lastValue) / self.lastValue
|
||||
holdingInfo = f"There are {holdings.UsersHolding} unique users holding {kvp.Key.Underlying} - users holding % of U.S. equities universe: {holdings.UniverseHoldingPercent * 100.0}%"
|
||||
|
||||
if percentChange >= 0.005 and not self.isLong:
|
||||
self.Log(f"{self.UtcTime} - Buying AAPL - {holdingInfo}")
|
||||
self.SetHoldings(self.aapl, 0.5)
|
||||
self.isLong = True
|
||||
|
||||
elif percentChange <= -0.005 and self.isLong:
|
||||
self.Log(f"{self.UtcTime} - Shorting AAPL - {holdingInfo}")
|
||||
self.SetHoldings(self.aapl, -0.5)
|
||||
self.isLong = False
|
||||
|
||||
self.lastValue = holdings.UsersHolding;
|
||||
@@ -33,40 +33,39 @@ class BasicTemplateOptionsFilterUniverseAlgorithm(QCAlgorithm):
|
||||
UnderlyingTicker = "GOOG"
|
||||
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2015, 12, 16)
|
||||
self.SetStartDate(2015, 12, 24)
|
||||
self.SetEndDate(2015, 12, 24)
|
||||
self.SetCash(100000)
|
||||
|
||||
equity = self.AddEquity(self.UnderlyingTicker);
|
||||
equity = self.AddEquity(self.UnderlyingTicker)
|
||||
option = self.AddOption(self.UnderlyingTicker)
|
||||
self.option_symbol = option.Symbol
|
||||
self.OptionSymbol = option.Symbol
|
||||
|
||||
# set our strike/expiry filter for this option chain
|
||||
# SetFilter method accepts timedelta objects or integer for days.
|
||||
# The following statements yield the same filtering criteria
|
||||
option.SetFilter(-10, +10, 0, 10)
|
||||
# option.SetFilter(-10, 10, timedelta(0), timedelta(10))
|
||||
# Set our custom universe filter
|
||||
option.SetFilter(self.FilterFunction)
|
||||
|
||||
# use the underlying equity as the benchmark
|
||||
self.SetBenchmark(equity.Symbol)
|
||||
|
||||
def FilterFunction(self, universe):
|
||||
#Expires today, is a call, and is within 10 dollars of the current price
|
||||
universe = universe.WeeklysOnly().Expiration(0, 1)
|
||||
return [symbol for symbol in universe
|
||||
if symbol.ID.OptionRight != OptionRight.Put
|
||||
and -10 < universe.Underlying.Price - symbol.ID.StrikePrice < 10]
|
||||
|
||||
def OnData(self,slice):
|
||||
if self.Portfolio.Invested: return
|
||||
|
||||
for kvp in slice.OptionChains:
|
||||
if kvp.Key != self.option_symbol: continue
|
||||
chain = kvp.Value
|
||||
# find the call options expiring today
|
||||
contracts = [i for i in chain if i.Right == OptionRight.Call and i.Expiry.date() == self.Time.date()]
|
||||
# sorted the contracts by their strike, find the second strike under market price
|
||||
sorted_contracts = [i for i in sorted(contracts, key = lambda x:x.Strike, reverse = True) if i.Strike < chain.Underlying.Price]
|
||||
# if found, trade it
|
||||
if len(sorted_contracts) == 0:
|
||||
self.Log("No call contracts expiring today")
|
||||
return
|
||||
self.MarketOrder(sorted_contracts[1].Symbol, 1)
|
||||
|
||||
if kvp.Key != self.OptionSymbol: continue
|
||||
|
||||
def OnOrderEvent(self, orderEvent):
|
||||
# Order fill event handler. On an order fill update the resulting information is passed to this method.
|
||||
# <param name="orderEvent">Order event details containing details of the evemts</param>
|
||||
self.Log(str(orderEvent))
|
||||
# Get the first call strike under market price expiring today
|
||||
chain = kvp.Value
|
||||
contracts = [option for option in sorted(chain, key = lambda x:x.Strike, reverse = True)
|
||||
if option.Expiry.date() == self.Time.date()
|
||||
and option.Strike < chain.Underlying.Price]
|
||||
|
||||
if contracts:
|
||||
self.MarketOrder(contracts[0].Symbol, 1)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# 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.Core")
|
||||
AddReference("System.Collections")
|
||||
AddReference("QuantConnect.Common")
|
||||
AddReference("QuantConnect.Algorithm")
|
||||
|
||||
from System import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data.UniverseSelection import *
|
||||
from datetime import *
|
||||
|
||||
### <summary>
|
||||
### Demonstration of how to chain a coarse and fine universe selection with an option chain universe selection model
|
||||
### that will add and remove an'OptionChainUniverse' for each symbol selected on fine
|
||||
### </summary>
|
||||
class CoarseFineOptionUniverseChainRegressionAlgorithm(QCAlgorithm):
|
||||
|
||||
def Initialize(self):
|
||||
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
|
||||
|
||||
self.SetStartDate(2014,6,5) #Set Start Date
|
||||
self.SetEndDate(2014,6,6) #Set End Date
|
||||
|
||||
self.UniverseSettings.Resolution = Resolution.Minute
|
||||
self._twx = Symbol.Create("TWX", SecurityType.Equity, Market.USA)
|
||||
self._aapl = Symbol.Create("AAPL", SecurityType.Equity, Market.USA)
|
||||
self._lastEquityAdded = None
|
||||
self._changes = None
|
||||
self._optionCount = 0
|
||||
|
||||
universe = self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
|
||||
|
||||
self.AddUniverseOptions(universe, self.OptionFilterFunction)
|
||||
|
||||
def OptionFilterFunction(self, universe):
|
||||
universe.IncludeWeeklys().FrontMonth()
|
||||
|
||||
contracts = list()
|
||||
for symbol in universe:
|
||||
if len(contracts) == 5:
|
||||
break
|
||||
contracts.append(symbol)
|
||||
return universe.Contracts(contracts)
|
||||
|
||||
def CoarseSelectionFunction(self, coarse):
|
||||
if self.Time <= datetime(2014,6,5):
|
||||
return [ self._twx ]
|
||||
return [ self._aapl ]
|
||||
|
||||
def FineSelectionFunction(self, fine):
|
||||
if self.Time <= datetime(2014,6,5):
|
||||
return [ self._twx ]
|
||||
return [ self._aapl ]
|
||||
|
||||
def OnData(self, data):
|
||||
if self._changes == None or any(security.Price == 0 for security in self._changes.AddedSecurities):
|
||||
return
|
||||
|
||||
# liquidate removed securities
|
||||
for security in self._changes.RemovedSecurities:
|
||||
if security.Invested:
|
||||
self.Liquidate(security.Symbol);
|
||||
|
||||
for security in self._changes.AddedSecurities:
|
||||
if not security.Symbol.HasUnderlying:
|
||||
self._lastEquityAdded = security.Symbol;
|
||||
else:
|
||||
# options added should all match prev added security
|
||||
if security.Symbol.Underlying != self._lastEquityAdded:
|
||||
raise ValueError(f"Unexpected symbol added {security.Symbol}")
|
||||
self._optionCount += 1
|
||||
|
||||
self.SetHoldings(security.Symbol, 0.05)
|
||||
self._changes = None
|
||||
|
||||
# this event fires whenever we have changes to our universe
|
||||
def OnSecuritiesChanged(self, changes):
|
||||
if self._changes == None:
|
||||
self._changes = changes
|
||||
return
|
||||
self._changes = self._changes.op_Addition(self._changes, changes)
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
if self._optionCount == 0:
|
||||
raise ValueError("Option universe chain did not add any option!")
|
||||
@@ -22,7 +22,6 @@ from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Indicators import *
|
||||
from QuantConnect.Securities import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Data.Consolidators import *
|
||||
from CustomDataRegressionAlgorithm import Bitcoin
|
||||
from datetime import timedelta
|
||||
|
||||
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)
|
||||
179
Algorithm.Python/CustomConsolidatorRegressionAlgorithm.py
Normal file
179
Algorithm.Python/CustomConsolidatorRegressionAlgorithm.py
Normal file
@@ -0,0 +1,179 @@
|
||||
# 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.Common")
|
||||
AddReference("QuantConnect.Algorithm")
|
||||
AddReference("QuantConnect.Indicators")
|
||||
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Python import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Data.Consolidators import *
|
||||
from QuantConnect.Indicators import *
|
||||
from System import *
|
||||
from datetime import *
|
||||
|
||||
class CustomConsolidatorRegressionAlgorithm(QCAlgorithm):
|
||||
'''Custom Consolidator Regression Algorithm shows some examples of how to build custom
|
||||
consolidators in Python.'''
|
||||
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2013,10,4)
|
||||
self.SetEndDate(2013,10,11)
|
||||
self.SetCash(100000)
|
||||
self.AddEquity("SPY", Resolution.Minute)
|
||||
|
||||
#Create 5 day QuoteBarConsolidator; set consolidated function; add to subscription manager
|
||||
fiveDayConsolidator = QuoteBarConsolidator(timedelta(days=5))
|
||||
fiveDayConsolidator.DataConsolidated += self.OnQuoteBarDataConsolidated
|
||||
self.SubscriptionManager.AddConsolidator("SPY", fiveDayConsolidator)
|
||||
|
||||
#Create a 3:10PM custom quote bar consolidator
|
||||
timedConsolidator = DailyTimeQuoteBarConsolidator(time(hour=15, minute=10))
|
||||
timedConsolidator.DataConsolidated += self.OnQuoteBarDataConsolidated
|
||||
self.SubscriptionManager.AddConsolidator("SPY", timedConsolidator)
|
||||
|
||||
#Create our entirely custom 2 day quote bar consolidator
|
||||
self.customConsolidator = CustomQuoteBarConsolidator(timedelta(days=2))
|
||||
self.customConsolidator.DataConsolidated += (self.OnQuoteBarDataConsolidated)
|
||||
self.SubscriptionManager.AddConsolidator("SPY", self.customConsolidator)
|
||||
|
||||
#Create an indicator and register a consolidator to it
|
||||
self.movingAverage = SimpleMovingAverage(5)
|
||||
self.customConsolidator2 = CustomQuoteBarConsolidator(timedelta(hours=1))
|
||||
self.RegisterIndicator("SPY", self.movingAverage, self.customConsolidator2)
|
||||
|
||||
|
||||
def OnQuoteBarDataConsolidated(self, sender, bar):
|
||||
'''Function assigned to be triggered by consolidators.
|
||||
Designed to post debug messages to show how the examples work, including
|
||||
which consolidator is posting, as well as its values.
|
||||
|
||||
If using an inherited class and not overwriting OnDataConsolidated
|
||||
we expect to see the super C# class as the sender type.
|
||||
|
||||
Using sender.Period only works when all consolidators have a Period value.
|
||||
'''
|
||||
|
||||
consolidatorInfo = str(type(sender)) + str(sender.Period)
|
||||
|
||||
self.Debug("Bar Type: " + consolidatorInfo)
|
||||
self.Debug("Bar Range: " + bar.Time.ctime() + " - " + bar.EndTime.ctime())
|
||||
self.Debug("Bar value: " + str(bar.Close))
|
||||
|
||||
def OnData(self, slice):
|
||||
test = slice.get_Values()
|
||||
|
||||
if self.customConsolidator.Consolidated and slice.ContainsKey("SPY"):
|
||||
data = slice['SPY']
|
||||
|
||||
if self.movingAverage.IsReady:
|
||||
if data.Value > self.movingAverage.Current.Price:
|
||||
self.SetHoldings("SPY", .5)
|
||||
else :
|
||||
self.SetHoldings("SPY", 0)
|
||||
|
||||
|
||||
|
||||
class DailyTimeQuoteBarConsolidator(QuoteBarConsolidator):
|
||||
'''A custom QuoteBar consolidator that inherits from C# class QuoteBarConsolidator.
|
||||
|
||||
This class shows an example of building on top of an existing consolidator class, it is important
|
||||
to note that this class can leverage the functions of QuoteBarConsolidator but its private fields
|
||||
(_period, _workingbar, etc.) are separate from this Python. For that reason if we want Scan() to work
|
||||
we must overwrite the function with our desired Scan function and trigger OnDataConsolidated().
|
||||
|
||||
For this particular example we implemented the scan method to trigger a consolidated bar
|
||||
at closeTime everyday'''
|
||||
|
||||
def __init__(self, closeTime):
|
||||
self.closeTime = closeTime
|
||||
self.workingBar = None
|
||||
|
||||
def Update(self, data):
|
||||
'''Updates this consolidator with the specified data'''
|
||||
|
||||
#If we don't have bar yet, create one
|
||||
if self.workingBar is None:
|
||||
self.workingBar = QuoteBar(data.Time,data.Symbol,data.Bid,data.LastBidSize,
|
||||
data.Ask,data.LastAskSize)
|
||||
|
||||
#Update bar using QuoteBarConsolidator's AggregateBar()
|
||||
self.AggregateBar(self.workingBar, data)
|
||||
|
||||
|
||||
def Scan(self, time):
|
||||
'''Scans this consolidator to see if it should emit a bar due yet'''
|
||||
|
||||
#If its our desired bar end time take the steps to
|
||||
if time.hour == self.closeTime.hour and time.minute == self.closeTime.minute:
|
||||
|
||||
#Set end time
|
||||
self.workingBar.EndTime = time
|
||||
|
||||
#Emit event using QuoteBarConsolidator's OnDataConsolidated()
|
||||
self.OnDataConsolidated(self.workingBar)
|
||||
|
||||
#Reset the working bar to None
|
||||
self.workingBar = None
|
||||
|
||||
class CustomQuoteBarConsolidator(PythonConsolidator):
|
||||
'''A custom quote bar consolidator that inherits from PythonConsolidator and implements
|
||||
the IDataConsolidator interface, it must implement all of IDataConsolidator. Reference
|
||||
PythonConsolidator.cs and DataConsolidatorPythonWrapper.py for more information.
|
||||
|
||||
This class shows how to implement a consolidator from scratch in Python, this gives us more
|
||||
freedom to determine the behavior of the consolidator but can't leverage any of the built in
|
||||
functions of an inherited class.
|
||||
|
||||
For this example we implemented a Quotebar from scratch'''
|
||||
|
||||
def __init__(self, period):
|
||||
|
||||
#IDataConsolidator required vars for all consolidators
|
||||
self.Consolidated = None #Most recently consolidated piece of data.
|
||||
self.WorkingData = None #Data being currently consolidated
|
||||
self.InputType = QuoteBar #The type consumed by this consolidator
|
||||
self.OutputType = QuoteBar #The type produced by this consolidator
|
||||
|
||||
#Consolidator Variables
|
||||
self.Period = period
|
||||
|
||||
def Update(self, data):
|
||||
'''Updates this consolidator with the specified data'''
|
||||
|
||||
#If we don't have bar yet, create one
|
||||
if self.WorkingData is None:
|
||||
self.WorkingData = QuoteBar(data.Time,data.Symbol,data.Bid,data.LastBidSize,
|
||||
data.Ask,data.LastAskSize,self.Period)
|
||||
|
||||
#Update bar using QuoteBar's update()
|
||||
self.WorkingData.Update(data.Value, data.Bid.Close, data.Ask.Close, 0,
|
||||
data.LastBidSize, data.LastAskSize)
|
||||
|
||||
def Scan(self, time):
|
||||
'''Scans this consolidator to see if it should emit a bar due to time passing'''
|
||||
|
||||
if self.Period is not None and self.WorkingData is not None:
|
||||
if time - self.WorkingData.Time >= self.Period:
|
||||
|
||||
#Trigger the event handler with a copy of self and the data
|
||||
self.OnDataConsolidated(self, self.WorkingData)
|
||||
|
||||
#Set the most recent consolidated piece of data and then clear the workingData
|
||||
self.Consolidated = self.WorkingData
|
||||
self.WorkingData = None
|
||||
@@ -21,6 +21,7 @@ from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Algorithm.Framework.Selection import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Custom import *
|
||||
from QuantConnect.Data.Custom.SEC import *
|
||||
from QuantConnect.Data.UniverseSelection import *
|
||||
|
||||
|
||||
@@ -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
|
||||
64
Algorithm.Python/ExtendedMarketTradingRegressionAlgorithm.py
Normal file
64
Algorithm.Python/ExtendedMarketTradingRegressionAlgorithm.py
Normal file
@@ -0,0 +1,64 @@
|
||||
# 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.Common")
|
||||
AddReference("QuantConnect.Algorithm")
|
||||
|
||||
import datetime
|
||||
from System import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Orders import *
|
||||
from QuantConnect.Algorithm import QCAlgorithm
|
||||
|
||||
### <summary>
|
||||
### This algorithm demonstrates extended market hours trading.
|
||||
### </summary>
|
||||
### <meta name="tag" content="using data" />
|
||||
### <meta name="tag" content="assets" />
|
||||
### <meta name="tag" content="regression test" />
|
||||
class ExtendedMarketTradingRegressionAlgorithm(QCAlgorithm):
|
||||
|
||||
def Initialize(self):
|
||||
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
|
||||
self.SetStartDate(2013,10,7) #Set Start Date
|
||||
self.SetEndDate(2013,10,11) #Set End Date
|
||||
self.SetCash(100000) #Set Strategy Cash
|
||||
# Find more symbols here: http://quantconnect.com/data
|
||||
self.spy = self.AddEquity("SPY", Resolution.Minute, Market.USA, True, 1, True)
|
||||
|
||||
self._lastAction = None
|
||||
|
||||
def OnData(self, data):
|
||||
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
|
||||
if self._lastAction is not None and self._lastAction.date() == self.Time.date():
|
||||
return
|
||||
|
||||
spyBar = data.Bars['SPY']
|
||||
|
||||
if not self.InMarketHours():
|
||||
self.LimitOrder("SPY", 10, spyBar.Low);
|
||||
self._lastAction = self.Time
|
||||
|
||||
def OnOrderEvent(self, orderEvent):
|
||||
self.Log(str(orderEvent))
|
||||
if self.InMarketHours():
|
||||
raise Exception("Order processed during market hours.")
|
||||
|
||||
def InMarketHours(self):
|
||||
now = self.Time.time()
|
||||
open = datetime.time(9,30,0)
|
||||
close = datetime.time(16,0,0)
|
||||
return (open < now) and (close > now)
|
||||
|
||||
65
Algorithm.Python/FilterUniverseRegressionAlgorithm.py
Normal file
65
Algorithm.Python/FilterUniverseRegressionAlgorithm.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 datetime import timedelta
|
||||
|
||||
### <summary>
|
||||
### This regression algorithm is for testing a custom Python filter for options
|
||||
### that returns a OptionFilterUniverse.
|
||||
### </summary>
|
||||
### <meta name="tag" content="options" />
|
||||
### <meta name="tag" content="filter selection" />
|
||||
### <meta name="tag" content="regression test" />
|
||||
class FilterUniverseRegressionAlgorithm(QCAlgorithm):
|
||||
UnderlyingTicker = "GOOG"
|
||||
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2015, 12, 24)
|
||||
self.SetEndDate(2015, 12, 24)
|
||||
self.SetCash(100000)
|
||||
|
||||
equity = self.AddEquity(self.UnderlyingTicker)
|
||||
option = self.AddOption(self.UnderlyingTicker)
|
||||
self.OptionSymbol = option.Symbol
|
||||
|
||||
# Set our custom universe filter
|
||||
option.SetFilter(self.FilterFunction)
|
||||
|
||||
# use the underlying equity as the benchmark
|
||||
self.SetBenchmark(equity.Symbol)
|
||||
|
||||
def FilterFunction(self, universe):
|
||||
universe = universe.WeeklysOnly().Strikes(-5, +5).CallsOnly().Expiration(0, 1)
|
||||
return universe
|
||||
|
||||
def OnData(self,slice):
|
||||
if self.Portfolio.Invested: return
|
||||
|
||||
for kvp in slice.OptionChains:
|
||||
|
||||
if kvp.Key != self.OptionSymbol: continue
|
||||
|
||||
chain = kvp.Value
|
||||
contracts = [option for option in sorted(chain, key = lambda x:x.Strike, reverse = True)]
|
||||
|
||||
if contracts:
|
||||
self.MarketOrder(contracts[0].Symbol, 1)
|
||||
|
||||
@@ -12,15 +12,15 @@
|
||||
# limitations under the License.
|
||||
|
||||
from clr import AddReference
|
||||
AddReference("System.Core")
|
||||
AddReference("QuantConnect.Common")
|
||||
AddReference("System")
|
||||
AddReference("QuantConnect.Algorithm")
|
||||
AddReference("QuantConnect.Algorithm.Framework")
|
||||
AddReference("QuantConnect.Common")
|
||||
|
||||
from System import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import QCAlgorithm
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Algorithm.Framework.Selection import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.UniverseSelection import *
|
||||
from datetime import timedelta
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
from clr import AddReference
|
||||
AddReference("System")
|
||||
AddReference("QuantConnect.Algorithm")
|
||||
AddReference("QuantConnect.Algorithm.Framework")
|
||||
AddReference("QuantConnect.Common")
|
||||
|
||||
from QuantConnect import *
|
||||
@@ -24,7 +23,6 @@ from QuantConnect.Algorithm.Framework.Execution import *
|
||||
from QuantConnect.Algorithm.Framework.Portfolio import *
|
||||
from QuantConnect.Algorithm.Framework.Selection import *
|
||||
from QuantConnect.Brokerages import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Interfaces import *
|
||||
from QuantConnect.Orders import *
|
||||
from System import *
|
||||
|
||||
@@ -19,6 +19,7 @@ AddReference("QuantConnect.Common")
|
||||
from System import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
### <summary>
|
||||
@@ -48,9 +49,18 @@ class OptionOpenInterestRegressionAlgorithm(QCAlgorithm):
|
||||
if float(contract.Symbol.ID.StrikePrice) == 72.5 and \
|
||||
contract.Symbol.ID.OptionRight == OptionRight.Call and \
|
||||
contract.Symbol.ID.Date == datetime(2016, 1, 15):
|
||||
if slice.Time.date() == datetime(2014, 6, 5).date() and contract.OpenInterest != 50:
|
||||
|
||||
history = self.History(contract.Symbol, timedelta(1))["openinterest"]
|
||||
if len(history.index) == 0 or 0 in history.values:
|
||||
raise ValueError("Regression test failed: open interest history request is empty")
|
||||
|
||||
security = self.Securities[contract.Symbol]
|
||||
openInterestCache = security.Cache.GetData[OpenInterest]()
|
||||
if openInterestCache == None:
|
||||
raise ValueError("Regression test failed: current open interest isn't in the security cache")
|
||||
if slice.Time.date() == datetime(2014, 6, 5).date() and (contract.OpenInterest != 50 or security.OpenInterest != 50):
|
||||
raise ValueError("Regression test failed: current open interest was not correctly loaded and is not equal to 50")
|
||||
if slice.Time.date() == datetime(2014, 6, 6).date() and contract.OpenInterest != 70:
|
||||
if slice.Time.date() == datetime(2014, 6, 6).date() and (contract.OpenInterest != 70 or security.OpenInterest != 70):
|
||||
raise ValueError("Regression test failed: current open interest was not correctly loaded and is not equal to 70")
|
||||
if slice.Time.date() == datetime(2014, 6, 6).date():
|
||||
self.MarketOrder(contract.Symbol, 1)
|
||||
|
||||
@@ -46,6 +46,8 @@
|
||||
<ItemGroup>
|
||||
<Content Include="AccumulativeInsightPortfolioRegressionAlgorithm.py" />
|
||||
<Content Include="AddAlphaModelAlgorithm.py" />
|
||||
<Content Include="AddOptionContractExpiresRegressionAlgorithm.py" />
|
||||
<Content Include="AddOptionContractFromUniverseRegressionAlgorithm.py" />
|
||||
<Content Include="AddRiskManagementAlgorithm.py" />
|
||||
<Content Include="AddUniverseSelectionModelAlgorithm.py" />
|
||||
<Content Include="Alphas\ContingentClaimsAnalysisDefaultPredictionAlpha.py" />
|
||||
@@ -61,7 +63,6 @@
|
||||
<Content Include="Alphas\ShareClassMeanReversionAlpha.py" />
|
||||
<Content Include="Alphas\TripleLeverageETFPairVolatilityDecayAlpha.py" />
|
||||
<Content Include="Alphas\VIXDualThrustAlpha.py" />
|
||||
<Content Include="AltData\RobintrackHoldingsAlgorithm.py" />
|
||||
<Content Include="AltData\CachedAlternativeDataAlgorithm.py" />
|
||||
<Content Include="AltData\BenzingaNewsAlgorithm.py" />
|
||||
<Content Include="AltData\SECReport8KAlgorithm.py" />
|
||||
@@ -84,12 +85,17 @@
|
||||
<None Include="BasicTemplateOptionsPriceModel.py" />
|
||||
<Content Include="Benchmarks\SECReportBenchmarkAlgorithm.py" />
|
||||
<Content Include="Benchmarks\SmartInsiderEventBenchmarkAlgorithm.py" />
|
||||
<Content Include="CoarseFineOptionUniverseChainRegressionAlgorithm.py" />
|
||||
<Content Include="CoarseTiingoNewsUniverseSelectionAlgorithm.py" />
|
||||
<Content Include="ConsolidateRegressionAlgorithm.py" />
|
||||
<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="KerasNeuralNetworkAlgorithm.py" />
|
||||
<Content Include="CustomDataUsingMapFileRegressionAlgorithm.py" />
|
||||
@@ -225,6 +231,7 @@
|
||||
<None Include="RenkoConsolidatorAlgorithm.py" />
|
||||
<None Include="RollingWindowAlgorithm.py" />
|
||||
<None Include="ScheduledEventsAlgorithm.py" />
|
||||
<None Include="ScheduledQueuingAlgorithm.py" />
|
||||
<None Include="ScheduledUniverseSelectionModelRegressionAlgorithm.py" />
|
||||
<None Include="SectorExposureRiskFrameworkAlgorithm.py" />
|
||||
<None Include="StandardDeviationExecutionModelRegressionAlgorithm.py" />
|
||||
|
||||
@@ -6,8 +6,7 @@
|
||||
<ProjectHome>.</ProjectHome>
|
||||
<StartupFile>
|
||||
</StartupFile>
|
||||
<SearchPath>
|
||||
</SearchPath>
|
||||
<SearchPath>stubs</SearchPath>
|
||||
<WorkingDirectory>.</WorkingDirectory>
|
||||
<OutputPath>.</OutputPath>
|
||||
<Name>QuantConnect.Algorithm.PythonTools</Name>
|
||||
@@ -46,6 +45,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" />
|
||||
|
||||
76
Algorithm.Python/ScheduledQueuingAlgorithm.py
Normal file
76
Algorithm.Python/ScheduledQueuingAlgorithm.py
Normal file
@@ -0,0 +1,76 @@
|
||||
# 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.Algorithm.Framework")
|
||||
AddReference("QuantConnect.Common")
|
||||
|
||||
from System import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Orders import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Algorithm.Framework import *
|
||||
from QuantConnect.Algorithm.Framework.Alphas import *
|
||||
from QuantConnect.Algorithm.Framework.Execution import *
|
||||
from QuantConnect.Algorithm.Framework.Portfolio import *
|
||||
from QuantConnect.Algorithm.Framework.Selection import *
|
||||
|
||||
from queue import Queue
|
||||
|
||||
class ScheduledQueuingAlgorithm(QCAlgorithm):
|
||||
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2020, 9, 1)
|
||||
self.SetEndDate(2020, 9, 2)
|
||||
self.SetCash(100000)
|
||||
|
||||
self.__numberOfSymbols = 2000
|
||||
self.__numberOfSymbolsFine = 1000
|
||||
self.SetUniverseSelection(FineFundamentalUniverseSelectionModel(self.CoarseSelectionFunction, self.FineSelectionFunction, None, None))
|
||||
|
||||
self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())
|
||||
|
||||
self.SetExecution(ImmediateExecutionModel())
|
||||
|
||||
self.queue = Queue()
|
||||
self.dequeue_size = 100
|
||||
|
||||
self.AddEquity("SPY", Resolution.Minute)
|
||||
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.At(0, 0), self.FillQueue)
|
||||
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.Every(timedelta(minutes=60)), self.TakeFromQueue)
|
||||
|
||||
def CoarseSelectionFunction(self, coarse):
|
||||
has_fundamentals = [security for security in coarse if security.HasFundamentalData]
|
||||
sorted_by_dollar_volume = sorted(has_fundamentals, key=lambda x: x.DollarVolume, reverse=True)
|
||||
return [ x.Symbol for x in sorted_by_dollar_volume[:self.__numberOfSymbols] ]
|
||||
|
||||
def FineSelectionFunction(self, fine):
|
||||
sorted_by_pe_ratio = sorted(fine, key=lambda x: x.ValuationRatios.PERatio, reverse=True)
|
||||
return [ x.Symbol for x in sorted_by_pe_ratio[:self.__numberOfSymbolsFine] ]
|
||||
|
||||
def FillQueue(self):
|
||||
securities = [security for security in self.ActiveSecurities.Values if security.Fundamentals is not None]
|
||||
|
||||
# Fill queue with symbols sorted by PE ratio (decreasing order)
|
||||
self.queue.queue.clear()
|
||||
sorted_by_pe_ratio = sorted(securities, key=lambda x: x.Fundamentals.ValuationRatios.PERatio, reverse=True)
|
||||
for security in sorted_by_pe_ratio:
|
||||
self.queue.put(security.Symbol)
|
||||
|
||||
def TakeFromQueue(self):
|
||||
symbols = [self.queue.get() for _ in range(min(self.dequeue_size, self.queue.qsize()))]
|
||||
self.History(symbols, 10, Resolution.Daily)
|
||||
|
||||
self.Log(f"Symbols at {self.Time}: {[str(symbol) for symbol in symbols]}")
|
||||
@@ -66,12 +66,12 @@ class ScheduledUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):
|
||||
symbols.append(Symbol.Create('IBM', SecurityType.Equity, Market.USA))
|
||||
|
||||
if weekday == 1 or weekday == 3:
|
||||
symbols.append(Symbol.Create('EURUSD', SecurityType.Forex, Market.FXCM))
|
||||
symbols.append(Symbol.Create('EURUSD', SecurityType.Forex, Market.Oanda))
|
||||
elif weekday == 4:
|
||||
# given the date/time rules specified in Initialize, this symbol will never be selected (every 6 hours never lands on hour==1)
|
||||
symbols.append(Symbol.Create('EURGBP', SecurityType.Forex, Market.FXCM))
|
||||
symbols.append(Symbol.Create('EURGBP', SecurityType.Forex, Market.Oanda))
|
||||
else:
|
||||
symbols.append(Symbol.Create('NZDUSD', SecurityType.Forex, Market.FXCM))
|
||||
symbols.append(Symbol.Create('NZDUSD', SecurityType.Forex, Market.Oanda))
|
||||
|
||||
return symbols
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ AddReference("QuantConnect.Common")
|
||||
from System import *
|
||||
from QuantConnect import *
|
||||
from QuantConnect.Algorithm import *
|
||||
from QuantConnect.Data import *
|
||||
from QuantConnect.Data.Market import *
|
||||
from QuantConnect.Algorithm.Framework.Alphas import *
|
||||
from datetime import timedelta
|
||||
|
||||
@@ -13,14 +13,14 @@ Before we enable python support, follow the [installation instructions](https://
|
||||
3. Click **New**.
|
||||
- Name of the variable: `PYTHONHOME`.
|
||||
- Value of the variable: python installation path.
|
||||
4. Install [pandas=0.23.4](https://pandas.pydata.org/) and its [dependencies](https://pandas.pydata.org/pandas-docs/stable/install.html#dependencies).
|
||||
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.
|
||||
|
||||
#### [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.23.4](https://pandas.pydata.org/) and its [dependencies](https://pandas.pydata.org/pandas-docs/stable/install.html#dependencies).
|
||||
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.
|
||||
|
||||
*Note:* If you encounter the "System.DllNotFoundException: python3.6m" runtime error when running Python algorithms on macOS:
|
||||
@@ -46,7 +46,7 @@ rm -rf Miniconda3-4.5.12-Linux-x86_64.sh
|
||||
sudo ln -s $HOME/miniconda3/lib/libpython3.6m.so /usr/lib/libpython3.6m.so
|
||||
conda update -y python conda pip
|
||||
conda install -y cython=0.29.11
|
||||
conda install -y pandas=0.23.4
|
||||
conda install -y pandas=0.25.3
|
||||
conda install -y wrapt=1.11.2
|
||||
```
|
||||
|
||||
|
||||
402
Algorithm.Python/stubs/QuantConnect/API/__init__.py
Normal file
402
Algorithm.Python/stubs/QuantConnect/API/__init__.py
Normal file
@@ -0,0 +1,402 @@
|
||||
# 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
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# 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
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# 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
|
||||
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
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
|
||||
@@ -0,0 +1,85 @@
|
||||
# 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]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
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
|
||||
@@ -0,0 +1,100 @@
|
||||
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
|
||||
@@ -0,0 +1,226 @@
|
||||
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
|
||||
@@ -0,0 +1,109 @@
|
||||
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
|
||||
@@ -0,0 +1,149 @@
|
||||
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
|
||||
174
Algorithm.Python/stubs/QuantConnect/Algorithm/Framework/Risk.py
Normal file
174
Algorithm.Python/stubs/QuantConnect/Algorithm/Framework/Risk.py
Normal file
@@ -0,0 +1,174 @@
|
||||
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
|
||||
@@ -0,0 +1,195 @@
|
||||
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
|
||||
@@ -0,0 +1,153 @@
|
||||
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
|
||||
@@ -0,0 +1,158 @@
|
||||
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
|
||||
@@ -0,0 +1,243 @@
|
||||
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
|
||||
@@ -0,0 +1,58 @@
|
||||
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
|
||||
@@ -0,0 +1,184 @@
|
||||
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
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user