Compare commits
393 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
35873f26b2 | ||
|
|
1135667ea4 | ||
|
|
3b826535c7 | ||
|
|
59da486e30 | ||
|
|
f42d7bb3a2 | ||
|
|
87bd0d7792 | ||
|
|
8ca9258e70 | ||
|
|
72105539fc | ||
|
|
589e8a9293 | ||
|
|
dd27a382f7 | ||
|
|
62a8aee38c | ||
|
|
7e7c27416b | ||
|
|
26f2f88c67 | ||
|
|
c08c129860 | ||
|
|
bae10389ae | ||
|
|
4301d7cead | ||
|
|
d49f1d0d6c | ||
|
|
264c3c8374 | ||
|
|
8a1f67edfc | ||
|
|
5f434f2fa5 | ||
|
|
e37f8ae878 | ||
|
|
b4e95209f6 | ||
|
|
ea65c61dc8 | ||
|
|
6bf6ff1a6a | ||
|
|
d1a35e6281 | ||
|
|
fed1fa929b | ||
|
|
9e7962f5a2 | ||
|
|
3e66733413 | ||
|
|
c11a09e08a | ||
|
|
f06bab944d | ||
|
|
df63b6f5d6 | ||
|
|
1358bd8115 | ||
|
|
40cc7a808a | ||
|
|
e3a4fa1838 | ||
|
|
1d8243ecac | ||
|
|
a8c81cad2a | ||
|
|
5f95a9ba77 | ||
|
|
a9b914c9ef | ||
|
|
5436275901 | ||
|
|
0a315b0ae6 | ||
|
|
33599b473d | ||
|
|
325e788728 | ||
|
|
57ac4d6497 | ||
|
|
664dca2236 | ||
|
|
5415fe6bc0 | ||
|
|
b2517cbbb4 | ||
|
|
b8b0d18993 | ||
|
|
ad865e2a53 | ||
|
|
57f0d17c5d | ||
|
|
d234d69abc | ||
|
|
dd4da7ba95 | ||
|
|
27f5223cd2 | ||
|
|
b3d3df3a3c | ||
|
|
3c1ddb7b96 | ||
|
|
926ac3879a | ||
|
|
0327b2012c | ||
|
|
cd5e1d9c54 | ||
|
|
fc6ddc2120 | ||
|
|
013b9ea850 | ||
|
|
9f29e3bf4e | ||
|
|
4ecdf14ce8 | ||
|
|
ede2d4a5e4 | ||
|
|
8c71dbc8ba | ||
|
|
d17865b2cf | ||
|
|
7b3b560dea | ||
|
|
995f598999 | ||
|
|
43c271a568 | ||
|
|
2e4252c92b | ||
|
|
0f189aa2b4 | ||
|
|
f55588e4c6 | ||
|
|
58ccdee1b1 | ||
|
|
6bd2859f64 | ||
|
|
3ff7882dbf | ||
|
|
dace6d7ee1 | ||
|
|
71d9eed07e | ||
|
|
c4a4550a66 | ||
|
|
67081a8a05 | ||
|
|
a567053404 | ||
|
|
56b8ccc4b4 | ||
|
|
5f65677ede | ||
|
|
def916aed1 | ||
|
|
46ce138fa1 | ||
|
|
b8768ae274 | ||
|
|
db04b5e110 | ||
|
|
cff3640f15 | ||
|
|
b5574a7986 | ||
|
|
c638f82337 | ||
|
|
3a591c3a72 | ||
|
|
fdfb1b54c0 | ||
|
|
7cfdd1243f | ||
|
|
3fc042af33 | ||
|
|
1d6fed8843 | ||
|
|
2109394060 | ||
|
|
d2d99b1f10 | ||
|
|
659735946a | ||
|
|
29294cb1f4 | ||
|
|
4546bbe9b1 | ||
|
|
af958f0ce4 | ||
|
|
6c42a266be | ||
|
|
8b7da686ea | ||
|
|
d3280c5e60 | ||
|
|
fe1f22543f | ||
|
|
57ddbbbf05 | ||
|
|
9579c4263b | ||
|
|
f082a40f34 | ||
|
|
d739873daa | ||
|
|
0f7dfe8ec8 | ||
|
|
58968bf05f | ||
|
|
627f280100 | ||
|
|
9ca57c2de9 | ||
|
|
35c2951abb | ||
|
|
2c237b7f84 | ||
|
|
4e6e0c85c6 | ||
|
|
a2ac956d53 | ||
|
|
5fecb77c8a | ||
|
|
3e8f15a62f | ||
|
|
0931ae868a | ||
|
|
e13df5c901 | ||
|
|
7be1b7db1a | ||
|
|
024d416ddd | ||
|
|
eb2dbe2af7 | ||
|
|
8358c394e1 | ||
|
|
d7c7adbd0d | ||
|
|
1ab1f90e27 | ||
|
|
bf2ef35ada | ||
|
|
2001f9a181 | ||
|
|
8026785116 | ||
|
|
5083433f68 | ||
|
|
5d4f428906 | ||
|
|
da60daa60d | ||
|
|
7d88b5040b | ||
|
|
d76106b444 | ||
|
|
de09ec0933 | ||
|
|
c3874bc618 | ||
|
|
0e1e497fbf | ||
|
|
8eb023e854 | ||
|
|
b251cffc2f | ||
|
|
1d904e716c | ||
|
|
df57428bd7 | ||
|
|
9d734c4d8f | ||
|
|
765ce87df1 | ||
|
|
8a5766fa39 | ||
|
|
933e5ce6ca | ||
|
|
dc433493b7 | ||
|
|
9acf68ad19 | ||
|
|
5ebf451fb3 | ||
|
|
a4d49c05ca | ||
|
|
aaba566954 | ||
|
|
bf28a1d313 | ||
|
|
85a4d3364b | ||
|
|
eccca2c029 | ||
|
|
b0314e1c7c | ||
|
|
3410832ccf | ||
|
|
d573a0f6c7 | ||
|
|
7a3d8667c5 | ||
|
|
c3543f844a | ||
|
|
1fdb36ee89 | ||
|
|
cd9e451ead | ||
|
|
b4f6b51ad1 | ||
|
|
a5e395d298 | ||
|
|
a40329c70c | ||
|
|
6546647e08 | ||
|
|
46829f0f01 | ||
|
|
e722e72aaa | ||
|
|
e92230a7fe | ||
|
|
7881aeb3a5 | ||
|
|
32fdb51ab5 | ||
|
|
190fe012f1 | ||
|
|
893ca2b41d | ||
|
|
c30bd32fb0 | ||
|
|
e720147e50 | ||
|
|
b77f0122b2 | ||
|
|
646adb9131 | ||
|
|
e2ae173d99 | ||
|
|
1cfc044034 | ||
|
|
9b7af08b3e | ||
|
|
1a02fbaae5 | ||
|
|
ed835faf35 | ||
|
|
5ea70e2a89 | ||
|
|
2603694263 | ||
|
|
4a3a7a44f5 | ||
|
|
76c930a035 | ||
|
|
12f70aab46 | ||
|
|
650ce2e2b5 | ||
|
|
ef4fea7592 | ||
|
|
3cf9cc7d41 | ||
|
|
a9b634b096 | ||
|
|
1793add749 | ||
|
|
41636c94c3 | ||
|
|
2624b8c6f5 | ||
|
|
d8a86f182f | ||
|
|
0da9d626dc | ||
|
|
9888081cc0 | ||
|
|
611326b140 | ||
|
|
907a9f086c | ||
|
|
0c4e577885 | ||
|
|
e823dfdfb7 | ||
|
|
4469d18eb6 | ||
|
|
808ba17bff | ||
|
|
00f68b951f | ||
|
|
c07b643273 | ||
|
|
95f199eae5 | ||
|
|
2cb239a330 | ||
|
|
cb326788b3 | ||
|
|
e2e2b5f102 | ||
|
|
f75e81bd7d | ||
|
|
522fe14951 | ||
|
|
9cf4075957 | ||
|
|
1ed390c5f7 | ||
|
|
f5224f8be9 | ||
|
|
8d11bbf0ba | ||
|
|
1dcdfe79b0 | ||
|
|
e453635458 | ||
|
|
d84ad9ebfc | ||
|
|
f9adc6b136 | ||
|
|
e5f62fa4dd | ||
|
|
3430b46e6a | ||
|
|
00ac4f33af | ||
|
|
0d752abae6 | ||
|
|
2a77a8d3c0 | ||
|
|
49d6cb0021 | ||
|
|
9a81414a94 | ||
|
|
3f85c9ab82 | ||
|
|
f062b54450 | ||
|
|
64b95b2e8e | ||
|
|
7bcaaf8f23 | ||
|
|
8383163aae | ||
|
|
04f3c850ba | ||
|
|
5bd0675423 | ||
|
|
6eb3822193 | ||
|
|
12b62f6ec9 | ||
|
|
8d2455b629 | ||
|
|
171f0f19d5 | ||
|
|
e5a50109b4 | ||
|
|
c8d13080a8 | ||
|
|
8d352b6318 | ||
|
|
00cd8947a8 | ||
|
|
c211d04798 | ||
|
|
55195867a9 | ||
|
|
c9a3ad35e1 | ||
|
|
0d45bf5101 | ||
|
|
66552b49bd | ||
|
|
0642f58bda | ||
|
|
c7e6c96933 | ||
|
|
5c10b2cb82 | ||
|
|
4dd2ad85a9 | ||
|
|
10defd4928 | ||
|
|
891aeb87d3 | ||
|
|
2fa07561b1 | ||
|
|
148b9c8d45 | ||
|
|
65cecef030 | ||
|
|
4fed304eb7 | ||
|
|
a987e0231f | ||
|
|
f47775338c | ||
|
|
fa1e97bc60 | ||
|
|
8fb649ceb4 | ||
|
|
7d8754f33c | ||
|
|
080511fa5a | ||
|
|
5146329c0f | ||
|
|
47fb4e64f2 | ||
|
|
5361f87dd1 | ||
|
|
72fb362f96 | ||
|
|
24e3a71581 | ||
|
|
15555f710d | ||
|
|
3d13fb6935 | ||
|
|
74f0c89499 | ||
|
|
0991f089d0 | ||
|
|
424fa36703 | ||
|
|
afbd058dad | ||
|
|
66d2f42d01 | ||
|
|
11f8dc2958 | ||
|
|
03f56481d4 | ||
|
|
c367451c6d | ||
|
|
c4e6e7f8dc | ||
|
|
ef5f7fbc50 | ||
|
|
7f9d35f666 | ||
|
|
be0fc9a879 | ||
|
|
a882aadeef | ||
|
|
02f7742878 | ||
|
|
b7c18cbfe7 | ||
|
|
6e6a1631dc | ||
|
|
250ffa1fec | ||
|
|
7e2678d0f6 | ||
|
|
9f15ca4c9c | ||
|
|
d23ac25b67 | ||
|
|
8f7f862563 | ||
|
|
0f0eeaff82 | ||
|
|
e8cf002238 | ||
|
|
e875b111d7 | ||
|
|
a231a7d47a | ||
|
|
37cce922d3 | ||
|
|
5f9e4a6bca | ||
|
|
42c58d6e53 | ||
|
|
ab6027723f | ||
|
|
37473c4580 | ||
|
|
677661766b | ||
|
|
c66a26e01d | ||
|
|
effa2da594 | ||
|
|
572aa99743 | ||
|
|
e77e202373 | ||
|
|
f9c50e28ef | ||
|
|
4c773c348c | ||
|
|
41f9d9da94 | ||
|
|
5f6a40fd9c | ||
|
|
0335b49edf | ||
|
|
1175c304e1 | ||
|
|
6c42f58b68 | ||
|
|
22a5378604 | ||
|
|
2df6715301 | ||
|
|
459f812223 | ||
|
|
22caf9ef2a | ||
|
|
94fb9293dc | ||
|
|
59266d84bf | ||
|
|
8ee9432bda | ||
|
|
99088d6dd8 | ||
|
|
15183cefe8 | ||
|
|
9e96aeb440 | ||
|
|
a2beeffcde | ||
|
|
c384fe0e2a | ||
|
|
ee6631dd8a | ||
|
|
4fdb748b42 | ||
|
|
ff0ecc7ed2 | ||
|
|
dcdfc7fdb3 | ||
|
|
a83eb7bf88 | ||
|
|
4e0ef94c97 | ||
|
|
c4db451416 | ||
|
|
112c14e0e8 | ||
|
|
87b16bc20c | ||
|
|
bb8bd27fe5 | ||
|
|
978da37cda | ||
|
|
4bb7fc17a2 | ||
|
|
d903ca60ef | ||
|
|
ec77cf3ca5 | ||
|
|
76600a3a0e | ||
|
|
dcb578cdfb | ||
|
|
838e94ec18 | ||
|
|
9887a05d77 | ||
|
|
cd0c447bcc | ||
|
|
d91ccac4aa | ||
|
|
9d93dc1570 | ||
|
|
5bf72d2432 | ||
|
|
d24edf5a6c | ||
|
|
a0c2e38eae | ||
|
|
fe2ac131af | ||
|
|
b8e3294a5f | ||
|
|
25f4cdd92f | ||
|
|
82c9b6ccb7 | ||
|
|
9c1722d0b9 | ||
|
|
a475178dbb | ||
|
|
e6ffb1ac62 | ||
|
|
70996b0507 | ||
|
|
58793acae8 | ||
|
|
6af3f70fed | ||
|
|
373c41e568 | ||
|
|
96f42eb591 | ||
|
|
62c51ab17c | ||
|
|
bbcb81804c | ||
|
|
6dfe492212 | ||
|
|
d76bfaade4 | ||
|
|
ed077da501 | ||
|
|
1958ac2935 | ||
|
|
2847d9e27d | ||
|
|
cf7a26b8b6 | ||
|
|
f3c386663b | ||
|
|
865da14540 | ||
|
|
019ac01a4c | ||
|
|
4a8bcb82db | ||
|
|
7ddee34e86 | ||
|
|
f00d4655cf | ||
|
|
83431c956c | ||
|
|
772eb4650c | ||
|
|
a7e5acd8d3 | ||
|
|
83f9499b4a | ||
|
|
a3836a64c4 | ||
|
|
db61cea3db | ||
|
|
fd4e1dc0a0 | ||
|
|
bb9cde1cee | ||
|
|
c082f0dda3 | ||
|
|
845e874132 | ||
|
|
706091b25e | ||
|
|
fe040a55e9 | ||
|
|
ab82e75885 | ||
|
|
ba4e2b115c | ||
|
|
2b0fd2e607 | ||
|
|
5b10b3b509 | ||
|
|
a7b2d9450f | ||
|
|
6af20c3d8a | ||
|
|
cb9bc95c37 | ||
|
|
72b6a22230 | ||
|
|
6fbc3786b0 | ||
|
|
ea11fb41c9 | ||
|
|
f5b729dc0d | ||
|
|
9ba15b23e3 |
13
.editorconfig
Normal file
13
.editorconfig
Normal file
@@ -0,0 +1,13 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
indent_size = 4
|
||||
indent_style = space
|
||||
insert_final_newline = true
|
||||
|
||||
[*.{js,yml,json,config,csproj}]
|
||||
indent_size = 2
|
||||
|
||||
[*.sh]
|
||||
end_of_line = lf
|
||||
17
.github/workflows/gh-actions.yml
vendored
17
.github/workflows/gh-actions.yml
vendored
@@ -3,29 +3,28 @@ name: Build & Test Lean
|
||||
on:
|
||||
push:
|
||||
branches: ['*']
|
||||
tags: ['*']
|
||||
pull_request:
|
||||
branches: [master]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-16.04
|
||||
runs-on: ubuntu-20.04
|
||||
container:
|
||||
image: quantconnect/lean:foundation
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Restore nuget dependencies
|
||||
run: |
|
||||
nuget restore QuantConnect.Lean.sln -v quiet
|
||||
nuget install NUnit.Runners -Version 3.11.1 -OutputDirectory testrunner
|
||||
|
||||
- name: Build
|
||||
run: msbuild /p:Configuration=Release /p:VbcToolExe=vbnc.exe /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
|
||||
run: dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
|
||||
|
||||
- name: Run Tests
|
||||
run: mono ./testrunner/NUnit.ConsoleRunner.3.11.1/tools/nunit3-console.exe ./Tests/bin/Release/QuantConnect.Tests.dll --where "cat != TravisExclude" --labels=Off --params:log-handler=ConsoleErrorLogHandler
|
||||
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter TestCategory!=TravisExclude -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\)
|
||||
|
||||
- name: Generate & Publish python stubs
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
run: |
|
||||
chmod +x ci_build_stubs.sh
|
||||
./ci_build_stubs.sh -d -t -g #Ignore Publish as of since credentials are missing on CI
|
||||
./ci_build_stubs.sh -t -g -p
|
||||
env:
|
||||
PYPI_API_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
|
||||
|
||||
22
.github/workflows/regression-tests.yml
vendored
Normal file
22
.github/workflows/regression-tests.yml
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
name: Regression Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['*']
|
||||
tags: ['*']
|
||||
pull_request:
|
||||
branches: [master]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-20.04
|
||||
container:
|
||||
image: quantconnect/lean:foundation
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Build
|
||||
run: dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
|
||||
|
||||
- name: Run Tests
|
||||
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter TestCategory=RegressionTests -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\) TestRunParameters.Parameter\(name=\"reduced-disk-size\", value=\"true\"\)
|
||||
144
.idea/readme.md
generated
144
.idea/readme.md
generated
@@ -1,144 +0,0 @@
|
||||
<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
37
.idea/workspace.xml
generated
@@ -1,37 +0,0 @@
|
||||
<?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="6000" />
|
||||
<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="6000" />
|
||||
<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>
|
||||
15
.travis.yml
15
.travis.yml
@@ -1,9 +1,8 @@
|
||||
sudo: required
|
||||
language: csharp
|
||||
mono: none
|
||||
dotnet: 5.0
|
||||
mono:
|
||||
- 5.12.0
|
||||
solution: QuantConnect.Lean.sln
|
||||
os: linux
|
||||
dist: focal
|
||||
before_install:
|
||||
- export PATH="$HOME/miniconda3/bin:$PATH"
|
||||
- export PYTHONNET_PYDLL="$HOME/miniconda3/lib/libpython3.6m.so"
|
||||
@@ -18,11 +17,7 @@ before_install:
|
||||
- conda install -y cython=0.29.15
|
||||
- conda install -y scipy=1.4.1
|
||||
- conda install -y wrapt=1.12.1
|
||||
install:
|
||||
- nuget install NUnit.Runners -Version 3.11.1 -OutputDirectory testrunner
|
||||
script:
|
||||
- dotnet nuget add source $TRAVIS_BUILD_DIR/LocalPackages
|
||||
- dotnet build /p:Configuration=Release /p:VbcToolExe=vbnc.exe /v:quiet /p:WarningLevel=1 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 --params:log-handler=ConsoleErrorLogHandler
|
||||
- chmod +x ci_build_stubs.sh
|
||||
- sudo -E ./ci_build_stubs.sh -d -t -g -p
|
||||
- dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
|
||||
- dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter TestCategory!=TravisExclude -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\)
|
||||
117
.vs/readme.md
117
.vs/readme.md
@@ -1,64 +1,49 @@
|
||||
<h1>Local Development & Docker Integration with Visual Studio</h1>
|
||||
<h1>Local Development with Visual Studio</h1>
|
||||
|
||||
This document contains information regarding ways to use Visual Studio to work with the Lean engine, this includes a couple options that make lean easy to develop on any machine:
|
||||
|
||||
This document contains information regarding ways to use Visual Studio to work with the Lean's Docker image.
|
||||
- Using Lean CLI -> A great tool for working with your algorithms locally, while still being able to deploy to the cloud and have access to Lean data. It is also able to run algorithms locally through our official docker images **Recommended for algorithm development.
|
||||
|
||||
- Locally installing all dependencies to run Lean with Visual Studio on your OS.
|
||||
|
||||
<br />
|
||||
|
||||
<h1>Getting Setup</h1>
|
||||
<h1>Setup</h1>
|
||||
|
||||
<h2>Option 1: Lean CLI</h2>
|
||||
|
||||
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
|
||||
|
||||
To use Lean CLI follow the instructions for installation and tutorial for usage in our [documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli).
|
||||
|
||||
<br />
|
||||
|
||||
<h1>Develop Algorithms Locally, Run in Container</h1>
|
||||
<h2>Option 2: Install Locally</h2>
|
||||
|
||||
1. Install [.Net 5](https://dotnet.microsoft.com/download) for the project
|
||||
|
||||
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.
|
||||
2. (Optional) Get [Python 3.6.8](https://www.python.org/downloads/release/python-368/) for running Python algorithms
|
||||
- Follow Python instructions [here](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#installing-python-36) for your platform
|
||||
|
||||
Before we can use this method with Windows or Mac OS we need to share the Lean directory with Docker.
|
||||
3. Get [Visual Studio](https://visualstudio.microsoft.com/vs/)
|
||||
|
||||
4. Get Lean into VS
|
||||
- Download the repo or clone it using: _git clone [https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)_
|
||||
- Open the project file with VS (QuantConnect.Lean.sln)
|
||||
|
||||
Your environment is prepared and ready to run lean
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Activate File Sharing for Docker:</h2>
|
||||
<h1>How to use Lean</h1>
|
||||
|
||||
* 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)
|
||||
This section will cover configuring, launching and debugging lean. This is only applicable to option 2 from above. This does not apply to Lean CLI, please refer to [CLI documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli)
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Lean Configuration</h2>
|
||||
<h2>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.
|
||||
We need to be sure that our Lean configuration at **.\Launcher\config.json** is properly set.
|
||||
|
||||
You configuration file should look something like this for the following languages:
|
||||
Your configuration file should look something like this for the following languages:
|
||||
|
||||
<h3>Python:</h3>
|
||||
|
||||
@@ -78,59 +63,11 @@ You configuration file should look something like this for the following languag
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Important Note About C#</h2>
|
||||
<h2>Launching Lean</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.
|
||||
Now that lean is configured we can launch. Use Visual Studio's run option, Make sure QuantConnect.Lean.Launcher is selected as the launch project. Any breakpoints in Lean C# will be triggered.
|
||||
|
||||
<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.
|
||||
<h1>Common Issues</h1>
|
||||
Here we will cover some common issues with setting this up. Feel free to contribute to this section!
|
||||
|
||||
73
.vscode/launch.json
vendored
73
.vscode/launch.json
vendored
@@ -2,74 +2,39 @@
|
||||
/*
|
||||
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.
|
||||
Launch:
|
||||
Builds the project with dotnet 5 and then launches the program using coreclr; supports debugging.
|
||||
In order to use this you need dotnet 5 on your system path, As well as the C# 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):
|
||||
Attach to Python:
|
||||
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.
|
||||
|
||||
Requires Python extension from the marketplace. Currently only works with algorithms in
|
||||
Algorithm.Python directory. This is because we map that directory to our build directory
|
||||
that contains the py file at runtime. If using another location change "localRoot" value
|
||||
to the directory in use.
|
||||
*/
|
||||
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Launch w/ Mono (Local)",
|
||||
"type": "mono",
|
||||
"name": "Launch",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build",
|
||||
"cwd": "${workspaceFolder}/Launcher/bin/Debug/",
|
||||
"program": "${workspaceFolder}/Launcher/bin/Debug/QuantConnect.Lean.Launcher.exe",
|
||||
"program": "${workspaceFolder}/Launcher/bin/Debug/QuantConnect.Lean.Launcher.dll",
|
||||
"args": [
|
||||
"--data-folder",
|
||||
"${workspaceFolder}/Data",
|
||||
"--config",
|
||||
"${workspaceFolder}/Launcher/config.json"],
|
||||
"console": "externalTerminal"
|
||||
"${workspaceFolder}/Launcher/config.json"
|
||||
],
|
||||
"cwd": "${workspaceFolder}/Launcher/bin/Debug/",
|
||||
"stopAtEntry": false,
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen"
|
||||
},
|
||||
{
|
||||
"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)",
|
||||
"name": "Attach to Python",
|
||||
"type": "python",
|
||||
"request": "attach",
|
||||
"port": 5678,
|
||||
|
||||
173
.vscode/readme.md
vendored
173
.vscode/readme.md
vendored
@@ -1,71 +1,49 @@
|
||||
<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 a couple options that make lean easy to develop on any machine:
|
||||
|
||||
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.
|
||||
- Using Lean CLI -> A great tool for working with your algorithms locally, while still being able to deploy to the cloud and have access to Lean data. It is also able to run algorithms locally through our official docker images **Recommended for algorithm development.
|
||||
|
||||
- Locally installing all dependencies to run Lean with Visual Studio Code on your OS.
|
||||
|
||||
<br />
|
||||
|
||||
<h1>Getting Setup</h1>
|
||||
<h1>Setup</h1>
|
||||
|
||||
<h2>Option 1: Lean CLI</h2>
|
||||
|
||||
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 **15.8**](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
|
||||
|
||||
**NOTES**:
|
||||
- Mono Extension Version 16 and greater fails to debug the docker container remotely, please install **Version 15.8**. To install an older version from within VS Code go to the extensions tab, search "Mono Debug", and select "Install Another Version...".
|
||||
<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.
|
||||
To use Lean CLI follow the instructions for installation and tutorial for usage in our [documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli)
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Activate File Sharing for Docker:</h2>
|
||||
<h2>Option 2: Install Dependencies Locally</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
|
||||
1. Install [.Net 5](https://dotnet.microsoft.com/download) for the project
|
||||
|
||||
* Linux:
|
||||
* (No setup required)
|
||||
2. (Optional) Get [Python 3.6.8](https://www.python.org/downloads/release/python-368/) for running Python algorithms
|
||||
- Follow Python instructions [here](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#installing-python-36) for your platform
|
||||
|
||||
3. Get [Visual Studio Code](https://code.visualstudio.com/download)
|
||||
- Get the Extension [C#](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp) for C# Debugging
|
||||
- Get the Extension [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) for Python Debugging
|
||||
|
||||
4. 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
|
||||
|
||||
Your environment is prepared and ready to run lean
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Lean Configuration</h2>
|
||||
<h1>How to use Lean</h1>
|
||||
|
||||
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.
|
||||
This section will cover configuring, building, launching and debugging lean. This is only applicable to option 2 from above. This does not apply to Lean CLI, please refer to [CLI documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli)
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Configuration</h2>
|
||||
|
||||
We need to be sure that our Lean configuration at **.\Launcher\config.json** is properly set.
|
||||
|
||||
Your configuration file should look something like this for the following languages:
|
||||
|
||||
@@ -85,74 +63,34 @@ Your configuration file should look something like this for the following langua
|
||||
|
||||
"algorithm-location": "QuantConnect.Algorithm.CSharp.dll",
|
||||
|
||||
<br />
|
||||
|
||||
<h3>Important Note About C#</h3>
|
||||
<h2>Building</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 the “build” task under _“Terminal” > “Run Build Task”._
|
||||
Before running Lean, we must build the project. Currently the VS Code task will automatically build before launching. But find more information below about how to trigger building manually.
|
||||
|
||||
Python **does not** have this requirement as the engine will compile it on the fly.
|
||||
In VS Code run build task (Ctrl+Shift+B or "Terminal" dropdown); there are a few options:
|
||||
|
||||
- __Build__ - basic build task, just builds Lean once
|
||||
- __Rebuild__ - rebuild task, completely rebuilds the project. Use if having issues with debugging symbols being loaded for your algorithms.
|
||||
- __Autobuilder__ - Starts a script that builds then waits for files to change and rebuilds appropriately
|
||||
- __Clean__ - deletes out all project build files
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Running Lean in the Container</h2>
|
||||
<h2>Launching Lean</h2>
|
||||
|
||||
This section will cover how to actually launch Lean in the container with your desired configuration.
|
||||
Now that lean is configured and built we can launch Lean. Under "Run & Debug" use the launch option "Launch". This will start Lean with C# debugging. Any breakpoints in Lean C# will be triggered.
|
||||
|
||||
<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 arguments are:
|
||||
|
||||
"IMAGE=quantconnect/lean:latest",
|
||||
"CONFIG_FILE=${workspaceFolder}/Launcher/config.json",
|
||||
"DATA_DIR=${workspaceFolder}/Data",
|
||||
"RESULTS_DIR=${workspaceFolder}/Results",
|
||||
"DEBUGGING=Y",
|
||||
"PYHTON_DIR=${workspaceFolder}/Algorithm.Python"
|
||||
|
||||
As defaults these are all great! Feel free to change them as needed for your setup.
|
||||
|
||||
**NOTE:** VSCode may try and throw errors when launching this way regarding build on `QuantConnect.csx` and `Config.json` these errors can be ignored by selecting "*Debug Anyway*". To stop this error message in the future select "*Remember my choice in user settings*".
|
||||
|
||||
If using C# algorithms ensure that msbuild can build them successfully.
|
||||
|
||||
<h2>Debugging Python</h2>
|
||||
|
||||
Python algorithms require a little extra work in order to be able to debug them. Follow the steps below to get Python debugging working.
|
||||
|
||||
<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: .\Launcher\config.json]:
|
||||
* Enter absolute path to Data folder [default: .\Data\]:
|
||||
* Enter absolute path to store results [default: .\Results]:
|
||||
* Would you like to debug C#? (Requires mono debugger attachment) [default: N]:
|
||||
|
||||
2. Using the **run_docker.cfg** to store args for repeated use; any blank entries will resort to default values! example: **_./run_docker.bat run_docker.cfg_**
|
||||
|
||||
IMAGE=quantconnect/lean:latest
|
||||
CONFIG_FILE=
|
||||
DATA_DIR=
|
||||
RESULTS_DIR=
|
||||
DEBUGGING=
|
||||
PYTHON_DIR=
|
||||
|
||||
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>
|
||||
<h3>Modifying the Configuration</h3>
|
||||
|
||||
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:
|
||||
|
||||
@@ -163,27 +101,11 @@ In setting this we are telling Lean to expect a debugger connection using ‘Pyt
|
||||
|
||||
<br />
|
||||
|
||||
<h2>Using VS Code Launch Options to Connect</h2>
|
||||
<h3>Using VS Code Launch Options to Connect</h3>
|
||||
|
||||
Now that Lean is configured for the python debugger we can make use of the programmed launch options to connect.
|
||||
Now that Lean is configured for the python debugger we can make use of the programmed launch options to connect to Lean during runtime.
|
||||
|
||||
<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.
|
||||
Start Lean using the "Launch" option covered above. Once Lean starts you should see the messages in figure 2 If the message is displayed, use the launch option “Attach to Python”. Then press run, VS Code will now enter and debug any breakpoints you have set in your python algorithm.
|
||||
|
||||
<br />
|
||||
|
||||
@@ -201,6 +123,5 @@ _Figure 2: Python Debugger Messages_
|
||||
<h1>Common Issues</h1>
|
||||
Here we will cover some common issues with setting this up. This section will expand as we get user feedback!
|
||||
|
||||
* Any error messages about building in VSCode that point 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.
|
||||
* `Errors exist after running preLaunchTask 'run-docker'`This VSCode error appears to warn you of CSharp errors when trying to use `Debug in Container` select "Debug Anyway" as the errors are false flags for JSON comments as well as `QuantConnect.csx` not finding references. Neither of these will impact your debugging.
|
||||
* `The container name "/LeanEngine" is already in use by container "****"` This Docker error implies that another instance of lean is already running under the container name /LeanEngine. If this error appears either use Docker Desktop to delete the container or use `docker kill LeanEngine` from the command line.
|
||||
- Autocomplete and reference finding with omnisharp can sometimes bug, if this occurs use the command palette to restart omnisharp. (Ctrl+Shift+P "OmniSharp: Restart OmniSharp")
|
||||
- Any error messages about building in VSCode that point 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.
|
||||
|
||||
102
.vscode/tasks.json
vendored
102
.vscode/tasks.json
vendored
@@ -8,11 +8,12 @@
|
||||
{
|
||||
"label": "build",
|
||||
"type": "shell",
|
||||
"command": "msbuild",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"build",
|
||||
"/p:Configuration=Debug",
|
||||
"/p:DebugType=portable",
|
||||
"/t:build",
|
||||
"/p:WarningLevel=1"
|
||||
],
|
||||
"group": "build",
|
||||
"presentation": {
|
||||
@@ -23,11 +24,13 @@
|
||||
{
|
||||
"label": "rebuild",
|
||||
"type": "shell",
|
||||
"command": "msbuild",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"build",
|
||||
"--no-incremental",
|
||||
"/p:Configuration=Debug",
|
||||
"/p:DebugType=portable",
|
||||
"/t:rebuild",
|
||||
"/p:WarningLevel=1"
|
||||
],
|
||||
"group": "build",
|
||||
"presentation": {
|
||||
@@ -38,102 +41,15 @@
|
||||
{
|
||||
"label": "clean",
|
||||
"type": "shell",
|
||||
"command": "msbuild",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"/t:clean",
|
||||
"clean",
|
||||
],
|
||||
"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}/Results",
|
||||
"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/"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -77,44 +77,45 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "199"},
|
||||
{"Average Win", "0.00%"},
|
||||
{"Average Loss", "0.00%"},
|
||||
{"Compounding Annual Return", "-12.472%"},
|
||||
{"Compounding Annual Return", "-12.611%"},
|
||||
{"Drawdown", "0.200%"},
|
||||
{"Expectancy", "-0.586"},
|
||||
{"Net Profit", "-0.170%"},
|
||||
{"Sharpe Ratio", "-9.693"},
|
||||
{"Probabilistic Sharpe Ratio", "12.704%"},
|
||||
{"Loss Rate", "79%"},
|
||||
{"Win Rate", "21%"},
|
||||
{"Profit-Loss Ratio", "0.95"},
|
||||
{"Expectancy", "-0.585"},
|
||||
{"Net Profit", "-0.172%"},
|
||||
{"Sharpe Ratio", "-10.169"},
|
||||
{"Probabilistic Sharpe Ratio", "12.075%"},
|
||||
{"Loss Rate", "78%"},
|
||||
{"Win Rate", "22%"},
|
||||
{"Profit-Loss Ratio", "0.87"},
|
||||
{"Alpha", "-0.149"},
|
||||
{"Beta", "0.037"},
|
||||
{"Beta", "0.035"},
|
||||
{"Annual Standard Deviation", "0.008"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-9.471"},
|
||||
{"Tracking Error", "0.212"},
|
||||
{"Treynor Ratio", "-2.13"},
|
||||
{"Information Ratio", "-9.603"},
|
||||
{"Tracking Error", "0.215"},
|
||||
{"Treynor Ratio", "-2.264"},
|
||||
{"Total Fees", "$199.00"},
|
||||
{"Estimated Strategy Capacity", "$23000000.00"},
|
||||
{"Estimated Strategy Capacity", "$26000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.002"},
|
||||
{"Kelly Criterion Estimate", "38.64"},
|
||||
{"Kelly Criterion Probability Value", "0.229"},
|
||||
{"Sortino Ratio", "-21.545"},
|
||||
{"Return Over Maximum Drawdown", "-77.972"},
|
||||
{"Portfolio Turnover", "1.135"},
|
||||
{"Kelly Criterion Estimate", "38.796"},
|
||||
{"Kelly Criterion Probability Value", "0.228"},
|
||||
{"Sortino Ratio", "-22.493"},
|
||||
{"Return Over Maximum Drawdown", "-77.93"},
|
||||
{"Portfolio Turnover", "1.211"},
|
||||
{"Total Insights Generated", "100"},
|
||||
{"Total Insights Closed", "99"},
|
||||
{"Total Insights Analysis Completed", "99"},
|
||||
{"Long Insight Count", "100"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$126657.6305"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$20405.9516"},
|
||||
{"Mean Population Estimated Insight Value", "$206.1207"},
|
||||
{"Mean Population Direction", "54.5455%"},
|
||||
{"Mean Population Magnitude", "54.5455%"},
|
||||
{"Rolling Averaged Population Direction", "59.8056%"},
|
||||
{"Rolling Averaged Population Magnitude", "59.8056%"},
|
||||
{"OrderListHash", "0a28eedf6304023f5002ef672b489b88"}
|
||||
{"Estimated Monthly Alpha Value", "$135639.1761"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
|
||||
{"Mean Population Estimated Insight Value", "$220.7372"},
|
||||
{"Mean Population Direction", "53.5354%"},
|
||||
{"Mean Population Magnitude", "53.5354%"},
|
||||
{"Rolling Averaged Population Direction", "58.2788%"},
|
||||
{"Rolling Averaged Population Magnitude", "58.2788%"},
|
||||
{"OrderListHash", "3c4c4085810cc5ecdb927d3647b9bbf3"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,31 +111,32 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "9"},
|
||||
{"Average Win", "0.89%"},
|
||||
{"Average Win", "0.86%"},
|
||||
{"Average Loss", "-0.27%"},
|
||||
{"Compounding Annual Return", "196.104%"},
|
||||
{"Compounding Annual Return", "184.364%"},
|
||||
{"Drawdown", "1.700%"},
|
||||
{"Expectancy", "1.853"},
|
||||
{"Net Profit", "1.498%"},
|
||||
{"Sharpe Ratio", "4.275"},
|
||||
{"Probabilistic Sharpe Ratio", "60.462%"},
|
||||
{"Expectancy", "1.781"},
|
||||
{"Net Profit", "1.442%"},
|
||||
{"Sharpe Ratio", "4.86"},
|
||||
{"Probabilistic Sharpe Ratio", "59.497%"},
|
||||
{"Loss Rate", "33%"},
|
||||
{"Win Rate", "67%"},
|
||||
{"Profit-Loss Ratio", "3.28"},
|
||||
{"Alpha", "1.574"},
|
||||
{"Beta", "-0.289"},
|
||||
{"Annual Standard Deviation", "0.276"},
|
||||
{"Annual Variance", "0.076"},
|
||||
{"Information Ratio", "-0.495"},
|
||||
{"Tracking Error", "0.367"},
|
||||
{"Treynor Ratio", "-4.079"},
|
||||
{"Total Fees", "$14.33"},
|
||||
{"Estimated Strategy Capacity", "$38000000.00"},
|
||||
{"Profit-Loss Ratio", "3.17"},
|
||||
{"Alpha", "4.181"},
|
||||
{"Beta", "-1.322"},
|
||||
{"Annual Standard Deviation", "0.321"},
|
||||
{"Annual Variance", "0.103"},
|
||||
{"Information Ratio", "-0.795"},
|
||||
{"Tracking Error", "0.532"},
|
||||
{"Treynor Ratio", "-1.18"},
|
||||
{"Total Fees", "$14.78"},
|
||||
{"Estimated Strategy Capacity", "$47000000.00"},
|
||||
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.408"},
|
||||
{"Kelly Criterion Estimate", "16.447"},
|
||||
{"Kelly Criterion Probability Value", "0.315"},
|
||||
{"Sortino Ratio", "13.611"},
|
||||
{"Return Over Maximum Drawdown", "117.635"},
|
||||
{"Kelly Criterion Estimate", "16.559"},
|
||||
{"Kelly Criterion Probability Value", "0.316"},
|
||||
{"Sortino Ratio", "12.447"},
|
||||
{"Return Over Maximum Drawdown", "106.327"},
|
||||
{"Portfolio Turnover", "0.411"},
|
||||
{"Total Insights Generated", "3"},
|
||||
{"Total Insights Closed", "3"},
|
||||
@@ -143,14 +144,14 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "3"},
|
||||
{"Long/Short Ratio", "0%"},
|
||||
{"Estimated Monthly Alpha Value", "$19868365.6628"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$3421774.0864"},
|
||||
{"Mean Population Estimated Insight Value", "$1140591.3621"},
|
||||
{"Estimated Monthly Alpha Value", "$20784418.6104"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$3579538.7607"},
|
||||
{"Mean Population Estimated Insight Value", "$1193179.5869"},
|
||||
{"Mean Population Direction", "100%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "100%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "506e9fe18984ba6e569b2e327030de3a"}
|
||||
{"OrderListHash", "9da9afe1e9137638a55db1676adc2be1"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* 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 reproducing GH issue #5748 where in some cases an option underlying symbol was not being
|
||||
/// removed from all universes it was hold
|
||||
/// </summary>
|
||||
public class AddAndRemoveOptionContractRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _contract;
|
||||
private bool _hasRemoved;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 06, 06);
|
||||
SetEndDate(2014, 06, 09);
|
||||
|
||||
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
|
||||
UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero;
|
||||
|
||||
var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
|
||||
|
||||
_contract = OptionChainProvider.GetOptionContractList(aapl, Time)
|
||||
.OrderBy(symbol => symbol.ID.Symbol)
|
||||
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call
|
||||
&& optionContract.ID.OptionStyle == OptionStyle.American);
|
||||
AddOptionContract(_contract);
|
||||
}
|
||||
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (slice.HasData)
|
||||
{
|
||||
if (!_hasRemoved)
|
||||
{
|
||||
RemoveOptionContract(_contract);
|
||||
RemoveSecurity(_contract.Underlying);
|
||||
_hasRemoved = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (!_hasRemoved)
|
||||
{
|
||||
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "-9.486"},
|
||||
{"Tracking Error", "0.008"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", ""},
|
||||
{"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", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
151
Algorithm.CSharp/AddBetaIndicatorRegressionAlgorithm.cs
Normal file
151
Algorithm.CSharp/AddBetaIndicatorRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* 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.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression test to explain how Beta indicator works
|
||||
/// </summary>
|
||||
public class AddBetaIndicatorRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Beta _beta;
|
||||
private SimpleMovingAverage _sma;
|
||||
private decimal _lastSMAValue;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 10, 07);
|
||||
SetEndDate(2013, 10, 15);
|
||||
SetCash(10000);
|
||||
|
||||
AddEquity("IBM");
|
||||
AddEquity("SPY");
|
||||
|
||||
EnableAutomaticIndicatorWarmUp = true;
|
||||
_beta = B("IBM", "SPY", 3, Resolution.Daily);
|
||||
_sma = SMA("SPY", 3, Resolution.Daily);
|
||||
_lastSMAValue = 0;
|
||||
|
||||
if (!_beta.IsReady)
|
||||
{
|
||||
throw new Exception("_beta indicator was expected to be ready");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
var price = data["IBM"].Close;
|
||||
Buy("IBM", 10);
|
||||
LimitOrder("IBM", 10, price * 0.1m);
|
||||
StopMarketOrder("IBM", 10, price / 0.1m);
|
||||
}
|
||||
|
||||
if (_beta.Current.Value < 0m || _beta.Current.Value > 2.80m)
|
||||
{
|
||||
throw new Exception($"_beta value was expected to be between 0 and 2.80 but was {_beta.Current.Value}");
|
||||
}
|
||||
|
||||
Log($"Beta between IBM and SPY is: {_beta.Current.Value}");
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
var order = Transactions.GetOrderById(orderEvent.OrderId);
|
||||
var goUpwards = _lastSMAValue < _sma.Current.Value;
|
||||
_lastSMAValue = _sma.Current.Value;
|
||||
|
||||
if (order.Status == OrderStatus.Filled)
|
||||
{
|
||||
if (order.Type == OrderType.Limit && Math.Abs(_beta.Current.Value - 1) < 0.2m && goUpwards)
|
||||
{
|
||||
Transactions.CancelOpenOrders(order.Symbol);
|
||||
}
|
||||
}
|
||||
|
||||
if (order.Status == OrderStatus.Canceled)
|
||||
{
|
||||
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 virtual 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", "12.939%"},
|
||||
{"Drawdown", "0.300%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.289%"},
|
||||
{"Sharpe Ratio", "4.233"},
|
||||
{"Probabilistic Sharpe Ratio", "68.349%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.035"},
|
||||
{"Beta", "0.122"},
|
||||
{"Annual Standard Deviation", "0.024"},
|
||||
{"Annual Variance", "0.001"},
|
||||
{"Information Ratio", "-3.181"},
|
||||
{"Tracking Error", "0.142"},
|
||||
{"Treynor Ratio", "0.842"},
|
||||
{"Total Fees", "$1.00"},
|
||||
{"Estimated Strategy Capacity", "$35000000.00"},
|
||||
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.022"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "8.508"},
|
||||
{"Return Over Maximum Drawdown", "58.894"},
|
||||
{"Portfolio Turnover", "0.022"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "bd88c6a0e10c7e146b05377205101a12"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* 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.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Securities.Future;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Continuous Futures Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
|
||||
/// and a future contract at the same time
|
||||
/// </summary>
|
||||
public class AddFutureContractWithContinuousRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _currentMappedSymbol;
|
||||
private Future _continuousContract;
|
||||
private Future _futureContract;
|
||||
private bool _ended;
|
||||
|
||||
/// <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, 6);
|
||||
SetEndDate(2013, 10, 10);
|
||||
|
||||
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
|
||||
dataMappingMode: DataMappingMode.LastTradingDay,
|
||||
contractDepthOffset: 0
|
||||
);
|
||||
|
||||
_futureContract = AddFutureContract(FutureChainProvider.GetFutureContractList(_continuousContract.Symbol, Time).First());
|
||||
}
|
||||
|
||||
/// <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 (_ended)
|
||||
{
|
||||
throw new Exception($"Algorithm should of ended!");
|
||||
}
|
||||
if (data.Keys.Count > 2)
|
||||
{
|
||||
throw new Exception($"Getting data for more than 2 symbols! {string.Join(",", data.Keys.Select(symbol => symbol))}");
|
||||
}
|
||||
if (UniverseManager.Count != 3)
|
||||
{
|
||||
throw new Exception($"Expecting 3 universes (chain, continuous and user defined) but have {UniverseManager.Count}");
|
||||
}
|
||||
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
Buy(_futureContract.Symbol, 1);
|
||||
Buy(_continuousContract.Mapped, 1);
|
||||
|
||||
RemoveSecurity(_futureContract.Symbol);
|
||||
RemoveSecurity(_continuousContract.Symbol);
|
||||
|
||||
_ended = true;
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status == OrderStatus.Filled)
|
||||
{
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
Debug($"{Time}-{changes}");
|
||||
}
|
||||
|
||||
/// <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.03%"},
|
||||
{"Compounding Annual Return", "-2.503%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.032%"},
|
||||
{"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", "-0.678"},
|
||||
{"Tracking Error", "0.243"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Estimated Strategy Capacity", "$2100000.00"},
|
||||
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
|
||||
{"Fitness Score", "0.419"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-81.557"},
|
||||
{"Portfolio Turnover", "0.837"},
|
||||
{"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", "68775c18eb40c1bde212653faec4016e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetStartDate(2020, 1, 4);
|
||||
SetEndDate(2020, 1, 6);
|
||||
|
||||
_es20h20 = AddFutureContract(
|
||||
@@ -51,7 +51,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
QuantConnect.Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
var optionChains = OptionChainProvider.GetOptionContractList(_es20h20, Time)
|
||||
var optionChains = OptionChainProvider.GetOptionContractList(_es20h20, Time.AddDays(1))
|
||||
.Concat(OptionChainProvider.GetOptionContractList(_es19m20, Time));
|
||||
|
||||
foreach (var optionContract in optionChains)
|
||||
@@ -168,30 +168,31 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "217.585%"},
|
||||
{"Compounding Annual Return", "116.059%"},
|
||||
{"Drawdown", "0.600%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.635%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Sharpe Ratio", "17.16"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-14.395"},
|
||||
{"Tracking Error", "0.043"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Alpha", "2.25"},
|
||||
{"Beta", "-1.665"},
|
||||
{"Annual Standard Deviation", "0.071"},
|
||||
{"Annual Variance", "0.005"},
|
||||
{"Information Ratio", "5.319"},
|
||||
{"Tracking Error", "0.114"},
|
||||
{"Treynor Ratio", "-0.735"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Estimated Strategy Capacity", "$28000000.00"},
|
||||
{"Estimated Strategy Capacity", "$24000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
|
||||
{"Fitness Score", "1"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "3.199"},
|
||||
{"Portfolio Turnover", "2.133"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
|
||||
@@ -21,6 +21,7 @@ using QuantConnect.Data.Market;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Securities.Future;
|
||||
using QuantConnect.Securities.Option;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
@@ -41,7 +42,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetStartDate(2020, 1, 4);
|
||||
SetEndDate(2020, 1, 6);
|
||||
|
||||
_es = AddFuture(Futures.Indices.SP500EMini, Resolution.Minute, Market.CME);
|
||||
@@ -123,9 +124,33 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
if (!optionInvested && data.ContainsKey(option))
|
||||
{
|
||||
var optionContract = Securities[option];
|
||||
var marginModel = optionContract.BuyingPowerModel as FuturesOptionsMarginModel;
|
||||
if (marginModel.InitialIntradayMarginRequirement == 0
|
||||
|| marginModel.InitialOvernightMarginRequirement == 0
|
||||
|| marginModel.MaintenanceIntradayMarginRequirement == 0
|
||||
|| marginModel.MaintenanceOvernightMarginRequirement == 0)
|
||||
{
|
||||
throw new Exception("Unexpected margin requirements");
|
||||
}
|
||||
|
||||
if (marginModel.GetInitialMarginRequirement(optionContract, 1) == 0)
|
||||
{
|
||||
throw new Exception("Unexpected Initial Margin requirement");
|
||||
}
|
||||
if (marginModel.GetMaintenanceMargin(optionContract) != 0)
|
||||
{
|
||||
throw new Exception("Unexpected Maintenance Margin requirement");
|
||||
}
|
||||
|
||||
MarketOrder(option, 1);
|
||||
_invested = true;
|
||||
optionInvested = true;
|
||||
|
||||
if (marginModel.GetMaintenanceMargin(optionContract) == 0)
|
||||
{
|
||||
throw new Exception("Unexpected Maintenance Margin requirement");
|
||||
}
|
||||
}
|
||||
if (!futureInvested && data.ContainsKey(future))
|
||||
{
|
||||
@@ -202,30 +227,31 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "-15.625%"},
|
||||
{"Compounding Annual Return", "-10.708%"},
|
||||
{"Drawdown", "0.200%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "-0.093%"},
|
||||
{"Sharpe Ratio", "-11.181"},
|
||||
{"Sharpe Ratio", "-10.594"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.002"},
|
||||
{"Beta", "-0.016"},
|
||||
{"Annual Standard Deviation", "0.001"},
|
||||
{"Alpha", "-0.261"},
|
||||
{"Beta", "0.244"},
|
||||
{"Annual Standard Deviation", "0.01"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-14.343"},
|
||||
{"Tracking Error", "0.044"},
|
||||
{"Treynor Ratio", "0.479"},
|
||||
{"Information Ratio", "-22.456"},
|
||||
{"Tracking Error", "0.032"},
|
||||
{"Treynor Ratio", "-0.454"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Estimated Strategy Capacity", "$12000.00"},
|
||||
{"Fitness Score", "0.41"},
|
||||
{"Estimated Strategy Capacity", "$41000.00"},
|
||||
{"Lowest Capacity Asset", "ES 31C3JQTOYO9T0|ES XCZJLC9NOB29"},
|
||||
{"Fitness Score", "0.273"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-185.654"},
|
||||
{"Portfolio Turnover", "0.821"},
|
||||
{"Return Over Maximum Drawdown", "-123.159"},
|
||||
{"Portfolio Turnover", "0.547"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
|
||||
@@ -126,20 +126,21 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Drawdown", "0.300%"},
|
||||
{"Expectancy", "-0.042"},
|
||||
{"Net Profit", "-0.332%"},
|
||||
{"Sharpe Ratio", "-3.7"},
|
||||
{"Probabilistic Sharpe Ratio", "0.563%"},
|
||||
{"Sharpe Ratio", "-3.149"},
|
||||
{"Probabilistic Sharpe Ratio", "0.427%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.92"},
|
||||
{"Alpha", "-0.021"},
|
||||
{"Beta", "-0.01"},
|
||||
{"Annual Standard Deviation", "0.006"},
|
||||
{"Alpha", "-0.015"},
|
||||
{"Beta", "-0.012"},
|
||||
{"Annual Standard Deviation", "0.005"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-3.374"},
|
||||
{"Tracking Error", "0.058"},
|
||||
{"Treynor Ratio", "2.133"},
|
||||
{"Information Ratio", "-2.823"},
|
||||
{"Tracking Error", "0.049"},
|
||||
{"Treynor Ratio", "1.372"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$45000000.00"},
|
||||
{"Estimated Strategy Capacity", "$67000000.00"},
|
||||
{"Lowest Capacity Asset", "AOL VRKS95ENLBYE|AOL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -159,7 +160,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "486118a60d78f74811fe8d927c2c6b43"}
|
||||
{"OrderListHash", "4f50b8360ea317ef974801649088bd06"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,15 +183,16 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.027"},
|
||||
{"Beta", "-0.174"},
|
||||
{"Alpha", "0.024"},
|
||||
{"Beta", "-0.171"},
|
||||
{"Annual Standard Deviation", "0.006"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-11.586"},
|
||||
{"Tracking Error", "0.042"},
|
||||
{"Treynor Ratio", "0.286"},
|
||||
{"Information Ratio", "-11.082"},
|
||||
{"Tracking Error", "0.043"},
|
||||
{"Treynor Ratio", "0.291"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$2800000.00"},
|
||||
{"Lowest Capacity Asset", "AOL VRKS95ENLBYE|AOL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
|
||||
165
Algorithm.CSharp/AddOptionContractTwiceRegressionAlgorithm.cs
Normal file
165
Algorithm.CSharp/AddOptionContractTwiceRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
* 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 reproducing GH issue #6073 where we remove and re add an option and expect it to work
|
||||
/// </summary>
|
||||
public class AddOptionContractTwiceRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _contract;
|
||||
private bool _hasRemoved;
|
||||
private bool _reAdded;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 06, 06);
|
||||
SetEndDate(2014, 06, 09);
|
||||
|
||||
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
|
||||
UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero;
|
||||
UniverseSettings.FillForward = false;
|
||||
|
||||
AddEquity("SPY", Resolution.Daily);
|
||||
|
||||
var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
|
||||
|
||||
_contract = OptionChainProvider.GetOptionContractList(aapl, Time)
|
||||
.OrderBy(symbol => symbol.ID.Symbol)
|
||||
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call
|
||||
&& optionContract.ID.OptionStyle == OptionStyle.American);
|
||||
AddOptionContract(_contract);
|
||||
}
|
||||
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (_hasRemoved)
|
||||
{
|
||||
if (!_reAdded && slice.ContainsKey(_contract) && slice.ContainsKey(_contract.Underlying))
|
||||
{
|
||||
throw new Exception("Getting data for removed option and underlying!");
|
||||
}
|
||||
|
||||
if (!Portfolio.Invested && _reAdded)
|
||||
{
|
||||
var option = Securities[_contract];
|
||||
var optionUnderlying = Securities[_contract.Underlying];
|
||||
if (option.IsTradable && optionUnderlying.IsTradable
|
||||
&& slice.ContainsKey(_contract) && slice.ContainsKey(_contract.Underlying))
|
||||
{
|
||||
Buy(_contract, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (!Securities[_contract].IsTradable
|
||||
&& !Securities[_contract.Underlying].IsTradable
|
||||
&& !_reAdded)
|
||||
{
|
||||
// ha changed my mind!
|
||||
AddOptionContract(_contract);
|
||||
_reAdded = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (slice.ContainsKey(_contract) && slice.ContainsKey(_contract.Underlying))
|
||||
{
|
||||
if (!_hasRemoved)
|
||||
{
|
||||
RemoveOptionContract(_contract);
|
||||
RemoveSecurity(_contract.Underlying);
|
||||
_hasRemoved = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (!_hasRemoved)
|
||||
{
|
||||
throw new Exception("We did not remove the option contract!");
|
||||
}
|
||||
if (!_reAdded)
|
||||
{
|
||||
throw new Exception("We did not re add the option contract!");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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.05%"},
|
||||
{"Compounding Annual Return", "-4.548%"},
|
||||
{"Drawdown", "0.100%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.051%"},
|
||||
{"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", "-9.486"},
|
||||
{"Tracking Error", "0.008"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$30000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL VXBK4Q9ZIFD2|AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-89.181"},
|
||||
{"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", "7fbcd12db40304d50b3a34d7878eb3cf"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -79,19 +79,19 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
// things like manually added, auto added, internal, and any other boolean state we need to track against a single security)
|
||||
throw new Exception("The underlying equity data should NEVER be removed in this algorithm because it was manually added");
|
||||
}
|
||||
if (_expectedSecurities.AreDifferent(LinqExtensions.ToHashSet(Securities.Keys)))
|
||||
if (_expectedSecurities.AreDifferent(Securities.Keys.ToHashSet()))
|
||||
{
|
||||
var expected = string.Join(Environment.NewLine, _expectedSecurities.OrderBy(s => s.ToString()));
|
||||
var actual = string.Join(Environment.NewLine, Securities.Keys.OrderBy(s => s.ToString()));
|
||||
throw new Exception($"{Time}:: Detected differences in expected and actual securities{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
|
||||
}
|
||||
if (_expectedUniverses.AreDifferent(LinqExtensions.ToHashSet(UniverseManager.Keys)))
|
||||
if (_expectedUniverses.AreDifferent(UniverseManager.Keys.ToHashSet()))
|
||||
{
|
||||
var expected = string.Join(Environment.NewLine, _expectedUniverses.OrderBy(s => s.ToString()));
|
||||
var actual = string.Join(Environment.NewLine, UniverseManager.Keys.OrderBy(s => s.ToString()));
|
||||
throw new Exception($"{Time}:: Detected differences in expected and actual universes{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
|
||||
}
|
||||
if (_expectedData.AreDifferent(LinqExtensions.ToHashSet(data.Keys)))
|
||||
if (_expectedData.AreDifferent(data.Keys.ToHashSet()))
|
||||
{
|
||||
var expected = string.Join(Environment.NewLine, _expectedData.OrderBy(s => s.ToString()));
|
||||
var actual = string.Join(Environment.NewLine, data.Keys.OrderBy(s => s.ToString()));
|
||||
@@ -183,7 +183,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
if (changes.RemovedSecurities
|
||||
.Where(x => x.Symbol.SecurityType == SecurityType.Option)
|
||||
.ToHashSet(s => s.Symbol)
|
||||
.AreDifferent(LinqExtensions.ToHashSet(_expectedContracts)))
|
||||
.AreDifferent(_expectedContracts.ToHashSet()))
|
||||
{
|
||||
throw new Exception("Expected removed securities to equal expected contracts added");
|
||||
}
|
||||
@@ -230,7 +230,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$6.00"},
|
||||
{"Estimated Strategy Capacity", "$1500.00"},
|
||||
{"Estimated Strategy Capacity", "$2000.00"},
|
||||
{"Lowest Capacity Asset", "GOOCV 305RBQ2BZBZT2|GOOCV VP83T1ZUHROL"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -250,7 +251,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "cf8f76fa441c2a5e3b2dbbabcab32cd2"}
|
||||
{"OrderListHash", "1e7b3e90918777b9dbf46353a96f3329"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,31 +112,32 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "5"},
|
||||
{"Average Win", "0.47%"},
|
||||
{"Average Win", "0.46%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "293.067%"},
|
||||
{"Compounding Annual Return", "296.356%"},
|
||||
{"Drawdown", "1.400%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.765%"},
|
||||
{"Sharpe Ratio", "13.11"},
|
||||
{"Probabilistic Sharpe Ratio", "80.231%"},
|
||||
{"Net Profit", "1.776%"},
|
||||
{"Sharpe Ratio", "13.013"},
|
||||
{"Probabilistic Sharpe Ratio", "80.409%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.705"},
|
||||
{"Beta", "0.7"},
|
||||
{"Annual Standard Deviation", "0.157"},
|
||||
{"Annual Variance", "0.025"},
|
||||
{"Information Ratio", "1.76"},
|
||||
{"Alpha", "0.68"},
|
||||
{"Beta", "0.707"},
|
||||
{"Annual Standard Deviation", "0.16"},
|
||||
{"Annual Variance", "0.026"},
|
||||
{"Information Ratio", "1.378"},
|
||||
{"Tracking Error", "0.072"},
|
||||
{"Treynor Ratio", "2.933"},
|
||||
{"Total Fees", "$26.39"},
|
||||
{"Estimated Strategy Capacity", "$4400000.00"},
|
||||
{"Treynor Ratio", "2.946"},
|
||||
{"Total Fees", "$28.30"},
|
||||
{"Estimated Strategy Capacity", "$4700000.00"},
|
||||
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.374"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "373.973"},
|
||||
{"Return Over Maximum Drawdown", "372.086"},
|
||||
{"Portfolio Turnover", "0.374"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -151,7 +152,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "5f7ba8b5defb310a2eaf98b11abd3b74"}
|
||||
{"OrderListHash", "ac3f4dfcdeb98b488b715412ad2d6c4f"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,29 +67,30 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "3"},
|
||||
{"Average Win", "1.02%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "289.119%"},
|
||||
{"Compounding Annual Return", "296.066%"},
|
||||
{"Drawdown", "2.200%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.752%"},
|
||||
{"Sharpe Ratio", "9.235"},
|
||||
{"Probabilistic Sharpe Ratio", "68.013%"},
|
||||
{"Net Profit", "1.775%"},
|
||||
{"Sharpe Ratio", "9.373"},
|
||||
{"Probabilistic Sharpe Ratio", "68.302%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.105"},
|
||||
{"Beta", "1.022"},
|
||||
{"Annual Standard Deviation", "0.224"},
|
||||
{"Annual Variance", "0.05"},
|
||||
{"Information Ratio", "24.59"},
|
||||
{"Beta", "1.021"},
|
||||
{"Annual Standard Deviation", "0.227"},
|
||||
{"Annual Variance", "0.052"},
|
||||
{"Information Ratio", "25.083"},
|
||||
{"Tracking Error", "0.006"},
|
||||
{"Treynor Ratio", "2.029"},
|
||||
{"Total Fees", "$9.77"},
|
||||
{"Estimated Strategy Capacity", "$37000000.00"},
|
||||
{"Treynor Ratio", "2.086"},
|
||||
{"Total Fees", "$10.33"},
|
||||
{"Estimated Strategy Capacity", "$38000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.747"},
|
||||
{"Kelly Criterion Estimate", "38.64"},
|
||||
{"Kelly Criterion Probability Value", "0.229"},
|
||||
{"Kelly Criterion Estimate", "38.796"},
|
||||
{"Kelly Criterion Probability Value", "0.228"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "107.109"},
|
||||
{"Return Over Maximum Drawdown", "107.013"},
|
||||
{"Portfolio Turnover", "0.747"},
|
||||
{"Total Insights Generated", "100"},
|
||||
{"Total Insights Closed", "99"},
|
||||
@@ -97,14 +98,14 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Long Insight Count", "100"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$126657.6305"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$20405.9516"},
|
||||
{"Mean Population Estimated Insight Value", "$206.1207"},
|
||||
{"Mean Population Direction", "54.5455%"},
|
||||
{"Mean Population Magnitude", "54.5455%"},
|
||||
{"Rolling Averaged Population Direction", "59.8056%"},
|
||||
{"Rolling Averaged Population Magnitude", "59.8056%"},
|
||||
{"OrderListHash", "0b8cbbafdb77bae2f7abe3cf5e05ac5c"}
|
||||
{"Estimated Monthly Alpha Value", "$135639.1761"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
|
||||
{"Mean Population Estimated Insight Value", "$220.7372"},
|
||||
{"Mean Population Direction", "53.5354%"},
|
||||
{"Mean Population Magnitude", "53.5354%"},
|
||||
{"Rolling Averaged Population Direction", "58.2788%"},
|
||||
{"Rolling Averaged Population Magnitude", "58.2788%"},
|
||||
{"OrderListHash", "af3a9c98c190d1b6b36fad184e796b0b"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,33 +83,34 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "10"},
|
||||
{"Total Trades", "11"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.01%"},
|
||||
{"Compounding Annual Return", "-14.333%"},
|
||||
{"Compounding Annual Return", "-14.217%"},
|
||||
{"Drawdown", "3.300%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.169%"},
|
||||
{"Sharpe Ratio", "-0.131"},
|
||||
{"Probabilistic Sharpe Ratio", "45.057%"},
|
||||
{"Net Profit", "-0.168%"},
|
||||
{"Sharpe Ratio", "62.513"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-3.068"},
|
||||
{"Beta", "0.595"},
|
||||
{"Annual Standard Deviation", "0.382"},
|
||||
{"Annual Variance", "0.146"},
|
||||
{"Information Ratio", "-13.618"},
|
||||
{"Tracking Error", "0.376"},
|
||||
{"Treynor Ratio", "-0.084"},
|
||||
{"Total Fees", "$13.98"},
|
||||
{"Estimated Strategy Capacity", "$61000000.00"},
|
||||
{"Fitness Score", "0.146"},
|
||||
{"Alpha", "1.118"},
|
||||
{"Beta", "1.19"},
|
||||
{"Annual Standard Deviation", "0.213"},
|
||||
{"Annual Variance", "0.046"},
|
||||
{"Information Ratio", "70.862"},
|
||||
{"Tracking Error", "0.043"},
|
||||
{"Treynor Ratio", "11.209"},
|
||||
{"Total Fees", "$23.21"},
|
||||
{"Estimated Strategy Capacity", "$340000000.00"},
|
||||
{"Lowest Capacity Asset", "FB V6OIPNZEM8V9"},
|
||||
{"Fitness Score", "0.147"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "1"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-4.398"},
|
||||
{"Portfolio Turnover", "0.268"},
|
||||
{"Return Over Maximum Drawdown", "-4.352"},
|
||||
{"Portfolio Turnover", "0.269"},
|
||||
{"Total Insights Generated", "15"},
|
||||
{"Total Insights Closed", "12"},
|
||||
{"Total Insights Analysis Completed", "12"},
|
||||
@@ -123,7 +124,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "8971c92ba163cec8526379865d9b9ee4"}
|
||||
{"OrderListHash", "a7a0983c8413ff241e7d223438f3d508"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,10 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
// Set requested data resolution
|
||||
UniverseSettings.Resolution = Resolution.Daily;
|
||||
|
||||
// Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
|
||||
// Commented so regression algorithm is more sensitive
|
||||
//Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;
|
||||
|
||||
SetStartDate(2014, 03, 24);
|
||||
SetEndDate(2014, 04, 07);
|
||||
SetCash(100000);
|
||||
@@ -90,33 +94,34 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "23"},
|
||||
{"Average Win", "0.00%"},
|
||||
{"Total Trades", "27"},
|
||||
{"Average Win", "0.01%"},
|
||||
{"Average Loss", "-0.01%"},
|
||||
{"Compounding Annual Return", "-75.307%"},
|
||||
{"Compounding Annual Return", "-75.320%"},
|
||||
{"Drawdown", "5.800%"},
|
||||
{"Expectancy", "-0.859"},
|
||||
{"Net Profit", "-5.586%"},
|
||||
{"Sharpe Ratio", "-3.257"},
|
||||
{"Probabilistic Sharpe Ratio", "5.931%"},
|
||||
{"Loss Rate", "92%"},
|
||||
{"Win Rate", "8%"},
|
||||
{"Profit-Loss Ratio", "0.70"},
|
||||
{"Alpha", "-0.593"},
|
||||
{"Beta", "0.692"},
|
||||
{"Annual Standard Deviation", "0.204"},
|
||||
{"Annual Variance", "0.042"},
|
||||
{"Information Ratio", "-2.884"},
|
||||
{"Tracking Error", "0.194"},
|
||||
{"Treynor Ratio", "-0.962"},
|
||||
{"Total Fees", "$25.92"},
|
||||
{"Estimated Strategy Capacity", "$69000000.00"},
|
||||
{"Expectancy", "-0.731"},
|
||||
{"Net Profit", "-5.588%"},
|
||||
{"Sharpe Ratio", "-3.252"},
|
||||
{"Probabilistic Sharpe Ratio", "5.526%"},
|
||||
{"Loss Rate", "86%"},
|
||||
{"Win Rate", "14%"},
|
||||
{"Profit-Loss Ratio", "0.89"},
|
||||
{"Alpha", "-0.499"},
|
||||
{"Beta", "1.483"},
|
||||
{"Annual Standard Deviation", "0.196"},
|
||||
{"Annual Variance", "0.039"},
|
||||
{"Information Ratio", "-3.844"},
|
||||
{"Tracking Error", "0.142"},
|
||||
{"Treynor Ratio", "-0.43"},
|
||||
{"Total Fees", "$37.25"},
|
||||
{"Estimated Strategy Capacity", "$520000000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.004"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "1"},
|
||||
{"Sortino Ratio", "-4.462"},
|
||||
{"Return Over Maximum Drawdown", "-13.032"},
|
||||
{"Portfolio Turnover", "0.083"},
|
||||
{"Sortino Ratio", "-4.469"},
|
||||
{"Return Over Maximum Drawdown", "-13.057"},
|
||||
{"Portfolio Turnover", "0.084"},
|
||||
{"Total Insights Generated", "33"},
|
||||
{"Total Insights Closed", "30"},
|
||||
{"Total Insights Analysis Completed", "30"},
|
||||
@@ -130,7 +135,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "ce59e51c8e404b5dbbc02911473aed1c"}
|
||||
{"OrderListHash", "f837879b96f5e565b60fd040299d2123"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
205
Algorithm.CSharp/AdjustedVolumeRegressionAlgorithm.cs
Normal file
205
Algorithm.CSharp/AdjustedVolumeRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,205 @@
|
||||
/*
|
||||
* 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.Configuration;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Auxiliary;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Util;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression algorithm to test volume adjusted behavior
|
||||
/// </summary>
|
||||
public class AdjustedVolumeRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _aapl;
|
||||
private const string Ticker = "AAPL";
|
||||
private CorporateFactorProvider _factorFile;
|
||||
private readonly IEnumerator<decimal> _expectedAdjustedVolume = new List<decimal> { 6164842, 3044047, 3680347, 3468303, 2169943, 2652523,
|
||||
1499707, 1518215, 1655219, 1510487 }.GetEnumerator();
|
||||
private readonly IEnumerator<decimal> _expectedAdjustedAskSize = new List<decimal> { 215600, 5600, 25200, 8400, 5600, 5600, 2800,
|
||||
8400, 14000, 2800 }.GetEnumerator();
|
||||
private readonly IEnumerator<decimal> _expectedAdjustedBidSize = new List<decimal> { 2800, 11200, 2800, 2800, 2800, 5600, 11200,
|
||||
8400, 30800, 2800 }.GetEnumerator();
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 6, 5); //Set Start Date
|
||||
SetEndDate(2014, 6, 5); //Set End Date
|
||||
|
||||
UniverseSettings.DataNormalizationMode = DataNormalizationMode.SplitAdjusted;
|
||||
_aapl = AddEquity(Ticker, Resolution.Minute).Symbol;
|
||||
|
||||
var dataProvider =
|
||||
Composer.Instance.GetExportedValueByTypeName<IDataProvider>(Config.Get("data-provider",
|
||||
"DefaultDataProvider"));
|
||||
|
||||
var mapFileProvider = new LocalDiskMapFileProvider();
|
||||
mapFileProvider.Initialize(dataProvider);
|
||||
var factorFileProvider = new LocalDiskFactorFileProvider();
|
||||
factorFileProvider.Initialize(mapFileProvider, dataProvider);
|
||||
|
||||
|
||||
_factorFile = factorFileProvider.Get(_aapl) as CorporateFactorProvider;
|
||||
}
|
||||
|
||||
/// <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(_aapl, 1);
|
||||
}
|
||||
|
||||
if (data.Splits.ContainsKey(_aapl))
|
||||
{
|
||||
Log(data.Splits[_aapl].ToString());
|
||||
}
|
||||
|
||||
if (data.Bars.ContainsKey(_aapl))
|
||||
{
|
||||
var aaplData = data.Bars[_aapl];
|
||||
|
||||
// Assert our volume matches what we expect
|
||||
if (_expectedAdjustedVolume.MoveNext() && _expectedAdjustedVolume.Current != aaplData.Volume)
|
||||
{
|
||||
// Our values don't match lets try and give a reason why
|
||||
var dayFactor = _factorFile.GetPriceScale(aaplData.Time, DataNormalizationMode.SplitAdjusted);
|
||||
var probableAdjustedVolume = aaplData.Volume / dayFactor;
|
||||
|
||||
if (_expectedAdjustedVolume.Current == probableAdjustedVolume)
|
||||
{
|
||||
throw new ArgumentException($"Volume was incorrect; but manually adjusted value is correct." +
|
||||
$" Adjustment by multiplying volume by {1 / dayFactor} is not occurring.");
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"Volume was incorrect; even when adjusted manually by" +
|
||||
$" multiplying volume by {1 / dayFactor}. Data may have changed.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (data.QuoteBars.ContainsKey(_aapl))
|
||||
{
|
||||
var aaplQuoteData = data.QuoteBars[_aapl];
|
||||
|
||||
// Assert our askSize matches what we expect
|
||||
if (_expectedAdjustedAskSize.MoveNext() && _expectedAdjustedAskSize.Current != aaplQuoteData.LastAskSize)
|
||||
{
|
||||
// Our values don't match lets try and give a reason why
|
||||
var dayFactor = _factorFile.GetPriceScale(aaplQuoteData.Time, DataNormalizationMode.SplitAdjusted);
|
||||
var probableAdjustedAskSize = aaplQuoteData.LastAskSize / dayFactor;
|
||||
|
||||
if (_expectedAdjustedAskSize.Current == probableAdjustedAskSize)
|
||||
{
|
||||
throw new ArgumentException($"Ask size was incorrect; but manually adjusted value is correct." +
|
||||
$" Adjustment by multiplying size by {1 / dayFactor} is not occurring.");
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"Ask size was incorrect; even when adjusted manually by" +
|
||||
$" multiplying size by {1 / dayFactor}. Data may have changed.");
|
||||
}
|
||||
}
|
||||
|
||||
// Assert our bidSize matches what we expect
|
||||
if (_expectedAdjustedBidSize.MoveNext() && _expectedAdjustedBidSize.Current != aaplQuoteData.LastBidSize)
|
||||
{
|
||||
// Our values don't match lets try and give a reason why
|
||||
var dayFactor = _factorFile.GetPriceScale(aaplQuoteData.Time, DataNormalizationMode.SplitAdjusted);
|
||||
var probableAdjustedBidSize = aaplQuoteData.LastBidSize / dayFactor;
|
||||
|
||||
if (_expectedAdjustedBidSize.Current == probableAdjustedBidSize)
|
||||
{
|
||||
throw new ArgumentException($"Bid size was incorrect; but manually adjusted value is correct." +
|
||||
$" Adjustment by multiplying size by {1 / dayFactor} is not occurring.");
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"Bid size was incorrect; even when adjusted manually by" +
|
||||
$" multiplying size by {1 / dayFactor}. Data may have changed.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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%"},
|
||||
{"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", "$21.60"},
|
||||
{"Estimated Strategy Capacity", "$42000000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
|
||||
{"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", "18e41dded4f8cee548ee02b03ffb0814"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -101,7 +101,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var symbol in ActiveSecurities.Keys)
|
||||
foreach (var symbol in ActiveSecurities.Keys.OrderBy(symbol => symbol))
|
||||
{
|
||||
if (!Portfolio.ContainsKey(symbol) || !Portfolio[symbol].Invested)
|
||||
{
|
||||
@@ -194,30 +194,31 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "5"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "36.294%"},
|
||||
{"Compounding Annual Return", "19.147%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.340%"},
|
||||
{"Sharpe Ratio", "21.2"},
|
||||
{"Probabilistic Sharpe Ratio", "99.990%"},
|
||||
{"Net Profit", "0.192%"},
|
||||
{"Sharpe Ratio", "231.673"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.274"},
|
||||
{"Beta", "0.138"},
|
||||
{"Annual Standard Deviation", "0.011"},
|
||||
{"Alpha", "0.163"},
|
||||
{"Beta", "-0.007"},
|
||||
{"Annual Standard Deviation", "0.001"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "7.202"},
|
||||
{"Tracking Error", "0.068"},
|
||||
{"Treynor Ratio", "1.722"},
|
||||
{"Information Ratio", "4.804"},
|
||||
{"Tracking Error", "0.098"},
|
||||
{"Treynor Ratio", "-22.526"},
|
||||
{"Total Fees", "$307.50"},
|
||||
{"Estimated Strategy Capacity", "$2800000.00"},
|
||||
{"Fitness Score", "0.173"},
|
||||
{"Estimated Strategy Capacity", "$2600000.00"},
|
||||
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
|
||||
{"Fitness Score", "0.106"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0.173"},
|
||||
{"Portfolio Turnover", "0.106"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -231,7 +232,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "6b1b205e5a6461ffd5bed645099714cd"}
|
||||
{"OrderListHash", "0069f402ffcd2d91b9018b81badfab81"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
117
Algorithm.CSharp/AlphaStreamsBasicTemplateAlgorithm.cs
Normal file
117
Algorithm.CSharp/AlphaStreamsBasicTemplateAlgorithm.cs
Normal file
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* 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.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data.Custom.AlphaStreams;
|
||||
using QuantConnect.Algorithm.Framework.Alphas;
|
||||
using QuantConnect.Algorithm.Framework.Execution;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Example algorithm consuming an alpha streams portfolio state and trading based on it
|
||||
/// </summary>
|
||||
public class AlphaStreamsBasicTemplateAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2018, 04, 04);
|
||||
SetEndDate(2018, 04, 06);
|
||||
|
||||
SetAlpha(new AlphaStreamAlphaModule());
|
||||
SetExecution(new ImmediateExecutionModel());
|
||||
Settings.MinimumOrderMarginPortfolioPercentage = 0.01m;
|
||||
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
|
||||
SetSecurityInitializer(new BrokerageModelSecurityInitializer(BrokerageModel,
|
||||
new FuncSecuritySeeder(GetLastKnownPrices)));
|
||||
|
||||
foreach (var alphaId in new [] { "623b06b231eb1cc1aa3643a46", "9fc8ef73792331b11dbd5429a" })
|
||||
{
|
||||
AddData<AlphaStreamsPortfolioState>(alphaId);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
Log($"OnOrderEvent: {orderEvent}");
|
||||
}
|
||||
|
||||
/// <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 virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.12%"},
|
||||
{"Compounding Annual Return", "-14.722%"},
|
||||
{"Drawdown", "0.200%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.116%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "2.474"},
|
||||
{"Tracking Error", "0.339"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$83000.00"},
|
||||
{"Lowest Capacity Asset", "BTCUSD XJ"},
|
||||
{"Fitness Score", "0.017"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-138.588"},
|
||||
{"Portfolio Turnover", "0.034"},
|
||||
{"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", "2b94bc50a74caebe06c075cdab1bc6da"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Example algorithm with existing holdings consuming an alpha streams portfolio state and trading based on it
|
||||
/// </summary>
|
||||
public class AlphaStreamsDifferentAccountCurrencyBasicTemplateAlgorithm : AlphaStreamsWithHoldingsBasicTemplateAlgorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetAccountCurrency("EUR");
|
||||
base.Initialize();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0.01%"},
|
||||
{"Average Loss", "0.00%"},
|
||||
{"Compounding Annual Return", "-78.502%"},
|
||||
{"Drawdown", "3.100%"},
|
||||
{"Expectancy", "7.797"},
|
||||
{"Net Profit", "-1.134%"},
|
||||
{"Sharpe Ratio", "-2.456"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "16.59"},
|
||||
{"Alpha", "0.006"},
|
||||
{"Beta", "1.011"},
|
||||
{"Annual Standard Deviation", "0.343"},
|
||||
{"Annual Variance", "0.117"},
|
||||
{"Information Ratio", "-0.859"},
|
||||
{"Tracking Error", "0.004"},
|
||||
{"Treynor Ratio", "-0.832"},
|
||||
{"Total Fees", "$2.89"},
|
||||
{"Estimated Strategy Capacity", "$8900000000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.506"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0.506"},
|
||||
{"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", "a9dd0a0ab6070455479d1b9caaa4e69c"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using QuantConnect.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Data.Custom.AlphaStreams;
|
||||
using QuantConnect.Algorithm.Framework.Alphas;
|
||||
using QuantConnect.Algorithm.Framework.Execution;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
using QuantConnect.Algorithm.Framework.Selection;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Example algorithm consuming an alpha streams portfolio state and trading based on it
|
||||
/// </summary>
|
||||
public class AlphaStreamsUniverseSelectionTemplateAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2018, 04, 04);
|
||||
SetEndDate(2018, 04, 06);
|
||||
|
||||
SetAlpha(new AlphaStreamAlphaModule());
|
||||
SetExecution(new ImmediateExecutionModel());
|
||||
Settings.MinimumOrderMarginPortfolioPercentage = 0.01m;
|
||||
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
|
||||
|
||||
SetUniverseSelection(new ScheduledUniverseSelectionModel(
|
||||
DateRules.EveryDay(),
|
||||
TimeRules.Midnight,
|
||||
SelectAlphas,
|
||||
new UniverseSettings(UniverseSettings)
|
||||
{
|
||||
SubscriptionDataTypes = new List<Tuple<Type, TickType>>
|
||||
{new(typeof(AlphaStreamsPortfolioState), TickType.Trade)},
|
||||
FillForward = false,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
private IEnumerable<Symbol> SelectAlphas(DateTime dateTime)
|
||||
{
|
||||
Log($"SelectAlphas() {Time}");
|
||||
foreach (var alphaId in new[] {"623b06b231eb1cc1aa3643a46", "9fc8ef73792331b11dbd5429a"})
|
||||
{
|
||||
var alphaSymbol = new Symbol(SecurityIdentifier.GenerateBase(typeof(AlphaStreamsPortfolioState), alphaId, Market.USA),
|
||||
alphaId);
|
||||
|
||||
yield return alphaSymbol;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.12%"},
|
||||
{"Compounding Annual Return", "-13.200%"},
|
||||
{"Drawdown", "0.200%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.116%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "2.474"},
|
||||
{"Tracking Error", "0.339"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$83000.00"},
|
||||
{"Lowest Capacity Asset", "BTCUSD XJ"},
|
||||
{"Fitness Score", "0.011"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-113.513"},
|
||||
{"Portfolio Turnover", "0.023"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "2b94bc50a74caebe06c075cdab1bc6da"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using QuantConnect.Orders;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data.Custom.AlphaStreams;
|
||||
using QuantConnect.Algorithm.Framework.Execution;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Example algorithm with existing holdings consuming an alpha streams portfolio state and trading based on it
|
||||
/// </summary>
|
||||
public class AlphaStreamsWithHoldingsBasicTemplateAlgorithm : AlphaStreamsBasicTemplateAlgorithm
|
||||
{
|
||||
private decimal _expectedSpyQuantity;
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2018, 04, 04);
|
||||
SetEndDate(2018, 04, 06);
|
||||
SetCash(100000);
|
||||
|
||||
SetExecution(new ImmediateExecutionModel());
|
||||
UniverseSettings.Resolution = Resolution.Hour;
|
||||
Settings.MinimumOrderMarginPortfolioPercentage = 0.001m;
|
||||
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
|
||||
|
||||
// AAPL should be liquidated since it's not hold by the alpha
|
||||
// This is handled by the PCM
|
||||
var aapl = AddEquity("AAPL", Resolution.Hour);
|
||||
aapl.Holdings.SetHoldings(40, 10);
|
||||
|
||||
// SPY will be bought following the alpha streams portfolio
|
||||
// This is handled by the PCM + Execution Model
|
||||
var spy = AddEquity("SPY", Resolution.Hour);
|
||||
spy.Holdings.SetHoldings(246, -10);
|
||||
|
||||
AddData<AlphaStreamsPortfolioState>("94d820a93fff127fa46c15231d");
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (_expectedSpyQuantity == 0 && orderEvent.Symbol == "SPY" && orderEvent.Status == OrderStatus.Filled)
|
||||
{
|
||||
var security = Securities["SPY"];
|
||||
var priceInAccountCurrency = Portfolio.CashBook.ConvertToAccountCurrency(security.AskPrice, security.QuoteCurrency.Symbol);
|
||||
_expectedSpyQuantity = (Portfolio.TotalPortfolioValue - Settings.FreePortfolioValue) / priceInAccountCurrency;
|
||||
_expectedSpyQuantity = _expectedSpyQuantity.DiscretelyRoundBy(1, MidpointRounding.ToZero);
|
||||
}
|
||||
|
||||
base.OnOrderEvent(orderEvent);
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Securities["AAPL"].HoldStock)
|
||||
{
|
||||
throw new Exception("We should no longer hold AAPL since the alpha does not");
|
||||
}
|
||||
|
||||
// we allow some padding for small price differences
|
||||
if (Math.Abs(Securities["SPY"].Holdings.Quantity - _expectedSpyQuantity) > _expectedSpyQuantity * 0.03m)
|
||||
{
|
||||
throw new Exception($"Unexpected SPY holdings. Expected {_expectedSpyQuantity} was {Securities["SPY"].Holdings.Quantity}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0.01%"},
|
||||
{"Average Loss", "0.00%"},
|
||||
{"Compounding Annual Return", "-87.617%"},
|
||||
{"Drawdown", "3.100%"},
|
||||
{"Expectancy", "8.518"},
|
||||
{"Net Profit", "-1.515%"},
|
||||
{"Sharpe Ratio", "-2.45"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "18.04"},
|
||||
{"Alpha", "0.008"},
|
||||
{"Beta", "1.015"},
|
||||
{"Annual Standard Deviation", "0.344"},
|
||||
{"Annual Variance", "0.118"},
|
||||
{"Information Ratio", "-0.856"},
|
||||
{"Tracking Error", "0.005"},
|
||||
{"Treynor Ratio", "-0.83"},
|
||||
{"Total Fees", "$3.09"},
|
||||
{"Estimated Strategy Capacity", "$8900000000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.511"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "6113.173"},
|
||||
{"Portfolio Turnover", "0.511"},
|
||||
{"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", "788eb2c74715a78476ba0db3b2654eb6"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.Benzinga;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp.AltData
|
||||
{
|
||||
/// <summary>
|
||||
/// Benzinga is a provider of news data. Their news is made in-house
|
||||
/// and covers stock related news such as corporate events.
|
||||
/// </summary>
|
||||
public class BenzingaNewsAlgorithm : QCAlgorithm
|
||||
{
|
||||
// Predefine a dictionary of words with scores to scan for in the description
|
||||
// of the Benzinga news article
|
||||
private readonly Dictionary<string, double> _words = new Dictionary<string, double>()
|
||||
{
|
||||
{"bad", -0.5}, {"good", 0.5},
|
||||
{"negative", -0.5}, {"great", 0.5},
|
||||
{"growth", 0.5}, {"fail", -0.5},
|
||||
{"failed", -0.5}, {"success", 0.5},
|
||||
{"nailed", 0.5}, {"beat", 0.5},
|
||||
{"missed", -0.5}
|
||||
};
|
||||
|
||||
// Trade only every 5 days
|
||||
private DateTime _lastTrade = DateTime.MinValue;
|
||||
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2018, 6, 5);
|
||||
SetEndDate(2018, 8, 4);
|
||||
SetCash(100000);
|
||||
|
||||
var aapl = AddEquity("AAPL", Resolution.Hour).Symbol;
|
||||
var ibm = AddEquity("IBM", Resolution.Hour).Symbol;
|
||||
|
||||
AddData<BenzingaNews>(aapl);
|
||||
AddData<BenzingaNews>(ibm);
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if ((Time - _lastTrade) < TimeSpan.FromDays(5))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Get rid of our holdings after 5 days, and start fresh
|
||||
Liquidate();
|
||||
|
||||
// Get all Benzinga data and loop over it
|
||||
foreach (var article in data.Get<BenzingaNews>().Values)
|
||||
{
|
||||
// Select the same Symbol we're getting a data point for
|
||||
// from the articles list so that we can get the sentiment of the article.
|
||||
// We use the underlying Symbol because the Symbols included in the `Symbols` property
|
||||
// are equity Symbols.
|
||||
var selectedSymbol = article.Symbols.SingleOrDefault(s => s == article.Symbol.Underlying);
|
||||
if (selectedSymbol == null)
|
||||
{
|
||||
throw new Exception($"Could not find current Symbol {article.Symbol.Underlying} even though it should exist");
|
||||
}
|
||||
|
||||
// The intersection of the article contents and the pre-defined words are the words that are included in both collections
|
||||
var intersection = article.Contents.ToLowerInvariant().Split(' ').Intersect(_words.Keys);
|
||||
// Get the words, then get the aggregate sentiment
|
||||
var sentimentSum = intersection.Select(x => _words[x]).Sum();
|
||||
|
||||
if (sentimentSum >= 0.5)
|
||||
{
|
||||
Log($"Longing {article.Symbol.Underlying} with sentiment score of {sentimentSum}");
|
||||
SetHoldings(article.Symbol.Underlying, sentimentSum / 5);
|
||||
|
||||
_lastTrade = Time;
|
||||
}
|
||||
if (sentimentSum <= -0.5)
|
||||
{
|
||||
Log($"Shorting {article.Symbol.Underlying} with sentiment score of {sentimentSum}");
|
||||
SetHoldings(article.Symbol.Underlying, sentimentSum / 5);
|
||||
|
||||
_lastTrade = Time;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
foreach (var r in changes.RemovedSecurities)
|
||||
{
|
||||
// If removed from the universe, liquidate and remove the custom data from the algorithm
|
||||
Liquidate(r.Symbol);
|
||||
RemoveSecurity(QuantConnect.Symbol.CreateBase(typeof(BenzingaNews), r.Symbol, Market.USA));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,66 +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.CBOE;
|
||||
using QuantConnect.Data.Custom.Fred;
|
||||
using QuantConnect.Data.Custom.USEnergy;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp.AltData
|
||||
{
|
||||
public class CachedAlternativeDataAlgorithm : QCAlgorithm
|
||||
{
|
||||
private Symbol _cboeVix;
|
||||
private Symbol _usEnergy;
|
||||
private Symbol _fredPeakToTrough;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2003, 1, 1);
|
||||
SetEndDate(2019, 10, 11);
|
||||
SetCash(100000);
|
||||
|
||||
// QuantConnect caches a small subset of alternative data for easy consumption for the community.
|
||||
// You can use this in your algorithm as demonstrated below:
|
||||
|
||||
_cboeVix = AddData<CBOE>("VIX", Resolution.Daily).Symbol;
|
||||
// United States EIA data: https://eia.gov/
|
||||
_usEnergy = AddData<USEnergy>(USEnergy.Petroleum.UnitedStates.WeeklyGrossInputsIntoRefineries, Resolution.Daily).Symbol;
|
||||
// FRED data
|
||||
_fredPeakToTrough = AddData<Fred>(Fred.OECDRecessionIndicators.UnitedStatesFromPeakThroughTheTrough, Resolution.Daily).Symbol;
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (data.ContainsKey(_cboeVix))
|
||||
{
|
||||
var vix = data.Get<CBOE>(_cboeVix);
|
||||
Log($"VIX: {vix}");
|
||||
}
|
||||
|
||||
if (data.ContainsKey(_usEnergy))
|
||||
{
|
||||
var inputIntoRefineries = data.Get<USEnergy>(_usEnergy);
|
||||
Log($"U.S. Input Into Refineries: {Time}, {inputIntoRefineries.Value}");
|
||||
}
|
||||
|
||||
if (data.ContainsKey(_fredPeakToTrough))
|
||||
{
|
||||
var peakToTrough = data.Get<Fred>(_fredPeakToTrough);
|
||||
Log($"OECD based Recession Indicator for the United States from the Peak through the Trough: {peakToTrough}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.Quiver;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp.AltData
|
||||
{
|
||||
/// <summary>
|
||||
/// Quiver Quantitative is a provider of alternative data.
|
||||
/// This algorithm shows how to consume the <see cref="QuiverWallStreetBets"/>
|
||||
/// </summary>
|
||||
public class QuiverWallStreetBetsDataAlgorithm : QCAlgorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2019, 1, 1);
|
||||
SetEndDate(2020, 6, 1);
|
||||
SetCash(100000);
|
||||
|
||||
var aapl = AddEquity("AAPL", Resolution.Daily).Symbol;
|
||||
var quiverWSBSymbol = AddData<QuiverWallStreetBets>(aapl).Symbol;
|
||||
var history = History<QuiverWallStreetBets>(quiverWSBSymbol, 60, Resolution.Daily);
|
||||
|
||||
Debug($"We got {history.Count()} items from our history request");
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
var points = data.Get<QuiverWallStreetBets>();
|
||||
foreach (var point in points.Values)
|
||||
{
|
||||
// Go long in the stock if it was mentioned more than 5 times in the WallStreetBets daily discussion
|
||||
if (point.Mentions > 5)
|
||||
{
|
||||
SetHoldings(point.Symbol.Underlying, 1);
|
||||
}
|
||||
// Go short in the stock if it was mentioned less than 5 times in the WallStreetBets daily discussion
|
||||
if (point.Mentions < 5)
|
||||
{
|
||||
SetHoldings(point.Symbol.Underlying, -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Algorithm.Framework.Selection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.SEC;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
public class SECReport8KAlgorithm : QCAlgorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2019, 1, 1);
|
||||
SetEndDate(2019, 8, 21);
|
||||
SetCash(100000);
|
||||
|
||||
UniverseSettings.Resolution = Resolution.Minute;
|
||||
AddUniverseSelection(new CoarseFundamentalUniverseSelectionModel(CoarseSelector));
|
||||
|
||||
// Request underlying equity data.
|
||||
var ibm = AddEquity("IBM", Resolution.Minute).Symbol;
|
||||
// Add SEC report 10-Q data for the underlying IBM asset
|
||||
var earningsFiling = AddData<SECReport10Q>(ibm, Resolution.Daily).Symbol;
|
||||
// Request 120 days of history with the SECReport10Q IBM custom data Symbol.
|
||||
var history = History<SECReport10Q>(earningsFiling, 120, Resolution.Daily);
|
||||
|
||||
// Count the number of items we get from our history request
|
||||
Debug($"We got {history.Count()} items from our history request");
|
||||
}
|
||||
|
||||
public IEnumerable<Symbol> CoarseSelector(IEnumerable<CoarseFundamental> coarse)
|
||||
{
|
||||
// Add SEC data from the filtered coarse selection
|
||||
var symbols = coarse.Where(x => x.HasFundamentalData && x.DollarVolume > 50000000)
|
||||
.Select(x => x.Symbol)
|
||||
.Take(10);
|
||||
|
||||
foreach (var symbol in symbols)
|
||||
{
|
||||
AddData<SECReport8K>(symbol);
|
||||
}
|
||||
|
||||
return symbols;
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// Store the symbols we want to long in a list
|
||||
// so that we can have an equal-weighted portfolio
|
||||
var longEquitySymbols = new List<Symbol>();
|
||||
|
||||
// Get all SEC data and loop over it
|
||||
foreach (var report in data.Get<SECReport8K>().Values)
|
||||
{
|
||||
// Get the length of all contents contained within the report
|
||||
var reportTextLength = report.Report.Documents.Select(x => x.Text.Length).Sum();
|
||||
|
||||
if (reportTextLength > 20000)
|
||||
{
|
||||
longEquitySymbols.Add(report.Symbol.Underlying);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var equitySymbol in longEquitySymbols)
|
||||
{
|
||||
SetHoldings(equitySymbol, 1m / longEquitySymbols.Count);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
foreach (var r in changes.RemovedSecurities)
|
||||
{
|
||||
// If removed from the universe, liquidate and remove the custom data from the algorithm
|
||||
Liquidate(r.Symbol);
|
||||
RemoveSecurity(QuantConnect.Symbol.CreateBase(typeof(SECReport8K), r.Symbol, Market.USA));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Algorithm.Framework.Selection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.SmartInsider;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
public class SmartInsiderTransactionAlgorithm : QCAlgorithm
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2019, 3, 1);
|
||||
SetEndDate(2019, 7, 4);
|
||||
SetCash(1000000);
|
||||
|
||||
AddUniverseSelection(new CoarseFundamentalUniverseSelectionModel(CoarseUniverse));
|
||||
|
||||
// Request underlying equity data.
|
||||
var ibm = AddEquity("IBM", Resolution.Minute).Symbol;
|
||||
// Add Smart Insider stock buyback transaction data for the underlying IBM asset
|
||||
var si = AddData<SmartInsiderTransaction>(ibm).Symbol;
|
||||
// Request 60 days of history with the SmartInsiderTransaction IBM Custom Data Symbol.
|
||||
var history = History<SmartInsiderTransaction>(si, 60, Resolution.Daily);
|
||||
|
||||
// Count the number of items we get from our history request
|
||||
Debug($"We got {history.Count()} items from our history request");
|
||||
}
|
||||
|
||||
public IEnumerable<Symbol> CoarseUniverse(IEnumerable<CoarseFundamental> coarse)
|
||||
{
|
||||
var symbols = coarse.Where(x => x.HasFundamentalData && x.DollarVolume > 50000000)
|
||||
.Select(x => x.Symbol)
|
||||
.Take(10);
|
||||
|
||||
foreach (var symbol in symbols)
|
||||
{
|
||||
AddData<SmartInsiderTransaction>(symbol);
|
||||
}
|
||||
|
||||
return symbols;
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// Get all SmartInsider data available
|
||||
var transactions = data.Get<SmartInsiderTransaction>();
|
||||
|
||||
foreach (var transaction in transactions.Values)
|
||||
{
|
||||
if (transaction.VolumePercentage == null || transaction.EventType == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Using the Smart Insider transaction information, buy when company does a stock buyback
|
||||
if (transaction.EventType == SmartInsiderEventType.Transaction && transaction.VolumePercentage > 5)
|
||||
{
|
||||
SetHoldings(transaction.Symbol.Underlying, (decimal)transaction.VolumePercentage / 100);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
foreach (var r in changes.RemovedSecurities)
|
||||
{
|
||||
// If removed from the universe, liquidate and remove the custom data from the algorithm
|
||||
Liquidate(r.Symbol);
|
||||
RemoveSecurity(QuantConnect.Symbol.CreateBase(typeof(SmartInsiderTransaction), r.Symbol, Market.USA));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.Tiingo;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Look for positive and negative words in the news article description
|
||||
/// and trade based on the sum of the sentiment
|
||||
/// </summary>
|
||||
public class TiingoNewsAlgorithm : QCAlgorithm
|
||||
{
|
||||
private Symbol _tiingoSymbol;
|
||||
|
||||
// Predefine a dictionary of words with scores to scan for in the description
|
||||
// of the Tiingo news article
|
||||
private readonly Dictionary<string, double> _words = new Dictionary<string, double>()
|
||||
{
|
||||
{"bad", -0.5}, {"good", 0.5},
|
||||
{ "negative", -0.5}, {"great", 0.5},
|
||||
{"growth", 0.5}, {"fail", -0.5},
|
||||
{"failed", -0.5}, {"success", 0.5},
|
||||
{"nailed", 0.5}, {"beat", 0.5},
|
||||
{"missed", -0.5}
|
||||
};
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2019, 6, 10);
|
||||
SetEndDate(2019, 10, 3);
|
||||
SetCash(100000);
|
||||
|
||||
var aapl = AddEquity("AAPL", Resolution.Hour).Symbol;
|
||||
_tiingoSymbol = AddData<TiingoNews>(aapl).Symbol;
|
||||
|
||||
// Request underlying equity data
|
||||
var ibm = AddEquity("IBM", Resolution.Minute).Symbol;
|
||||
// Add news data for the underlying IBM asset
|
||||
var news = AddData<TiingoNews>(ibm).Symbol;
|
||||
// Request 60 days of history with the TiingoNews IBM Custom Data Symbol.
|
||||
var history = History<TiingoNews>(news, 60, Resolution.Daily);
|
||||
|
||||
// Count the number of items we get from our history request
|
||||
Debug($"We got {history.Count()} items from our history request");
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
//Confirm that the data is in the collection
|
||||
if (!data.ContainsKey(_tiingoSymbol)) return;
|
||||
|
||||
// Gets the first piece of data from the Slice
|
||||
var article = data.Get<TiingoNews>(_tiingoSymbol);
|
||||
|
||||
// Article descriptions come in all caps. Lower and split by word
|
||||
var descriptionWords = article.Description.ToLowerInvariant().Split(' ');
|
||||
|
||||
// Take the intersection of predefined words and the words in the
|
||||
// description to get a list of matching words
|
||||
var intersection = _words.Keys.Intersect(descriptionWords);
|
||||
|
||||
// Get the sum of the article's sentiment, and go long or short
|
||||
// depending if it's a positive or negative description
|
||||
var sentiment = intersection.Select(x => _words[x]).Sum();
|
||||
|
||||
SetHoldings(article.Symbol.Underlying, sentiment);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.TradingEconomics;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Trades on interest rate announcements from data provided by Trading Economics
|
||||
/// </summary>
|
||||
public class TradingEconomicsAlgorithm : QCAlgorithm
|
||||
{
|
||||
private Symbol _interestRate;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 11, 1);
|
||||
SetEndDate(2019, 10, 3);
|
||||
SetCash(100000);
|
||||
|
||||
AddEquity("AGG", Resolution.Hour);
|
||||
AddEquity("SPY", Resolution.Hour);
|
||||
|
||||
_interestRate = AddData<TradingEconomicsCalendar>(TradingEconomics.Calendar.UnitedStates.InterestRate).Symbol;
|
||||
|
||||
// Request 365 days of interest rate history with the TradingEconomicsCalendar custom data Symbol.
|
||||
// We should expect no historical data because 2013-11-01 is before the absolute first point of data
|
||||
var history = History<TradingEconomicsCalendar>(_interestRate, 365, Resolution.Daily);
|
||||
|
||||
// Count the number of items we get from our history request (should be zero)
|
||||
Debug($"We got {history.Count()} items from our history request");
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// Make sure we have an interest rate calendar event
|
||||
if (!data.ContainsKey(_interestRate))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var announcement = data.Get<TradingEconomicsCalendar>(_interestRate);
|
||||
|
||||
// Confirm it's a FED Rate Decision
|
||||
if (announcement.Event != TradingEconomics.Event.UnitedStates.FedInterestRateDecision)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// In the event of a rate increase, rebalance 50% to Bonds.
|
||||
var interestRateDecreased = announcement.Actual <= announcement.Previous;
|
||||
|
||||
if (interestRateDecreased)
|
||||
{
|
||||
SetHoldings("SPY", 1);
|
||||
SetHoldings("AGG", 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
SetHoldings("SPY", 0.5);
|
||||
SetHoldings("AGG", 0.5);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.USTreasury;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
public class USTreasuryYieldCurveRateAlgorithm : QCAlgorithm
|
||||
{
|
||||
private Symbol _yieldCurve;
|
||||
private Symbol _spy;
|
||||
private DateTime _lastInversion = DateTime.MinValue;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2000, 3, 1);
|
||||
SetEndDate(2019, 9, 15);
|
||||
SetCash(100000);
|
||||
|
||||
_spy = AddEquity("SPY", Resolution.Hour).Symbol;
|
||||
_yieldCurve = AddData<USTreasuryYieldCurveRate>("USTYCR", Resolution.Daily).Symbol;
|
||||
|
||||
// Request 60 days of history with the USTreasuryYieldCurveRate custom data Symbol.
|
||||
var history = History<USTreasuryYieldCurveRate>(_yieldCurve, 60, Resolution.Daily);
|
||||
|
||||
// Count the number of items we get from our history request
|
||||
Debug($"We got {history.Count()} items from our history request");
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!data.ContainsKey(_yieldCurve))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Preserve null values by getting the data with `slice.Get<T>`
|
||||
// Accessing the data using `data[_yieldCurve]` results in null
|
||||
// values becoming `default(decimal)` which is equal to 0
|
||||
var rates = data.Get<USTreasuryYieldCurveRate>().Values.First();
|
||||
|
||||
// Check for null before using the values
|
||||
if (!rates.TenYear.HasValue || !rates.TwoYear.HasValue)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Only advance if a year has gone by
|
||||
if (Time - _lastInversion < TimeSpan.FromDays(365))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// if there is a yield curve inversion after not having one for a year, short SPY for two years
|
||||
if (!Portfolio.Invested && rates.TwoYear > rates.TenYear)
|
||||
{
|
||||
Debug($"{Time} - Yield curve inversion! Shorting the market for two years");
|
||||
SetHoldings(_spy, -0.5);
|
||||
|
||||
_lastInversion = Time;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// If two years have passed, liquidate our position in SPY
|
||||
if (Time - _lastInversion >= TimeSpan.FromDays(365 * 2))
|
||||
{
|
||||
Liquidate(_spy);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,32 +78,33 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "65"},
|
||||
{"Total Trades", "52"},
|
||||
{"Average Win", "0.00%"},
|
||||
{"Average Loss", "0.00%"},
|
||||
{"Compounding Annual Return", "0.145%"},
|
||||
{"Compounding Annual Return", "0.096%"},
|
||||
{"Drawdown", "0.100%"},
|
||||
{"Expectancy", "2.190"},
|
||||
{"Net Profit", "0.134%"},
|
||||
{"Sharpe Ratio", "0.993"},
|
||||
{"Probabilistic Sharpe Ratio", "49.669%"},
|
||||
{"Loss Rate", "29%"},
|
||||
{"Win Rate", "71%"},
|
||||
{"Profit-Loss Ratio", "3.50"},
|
||||
{"Alpha", "0.001"},
|
||||
{"Beta", "0"},
|
||||
{"Expectancy", "3.321"},
|
||||
{"Net Profit", "0.089%"},
|
||||
{"Sharpe Ratio", "0.798"},
|
||||
{"Probabilistic Sharpe Ratio", "40.893%"},
|
||||
{"Loss Rate", "24%"},
|
||||
{"Win Rate", "76%"},
|
||||
{"Profit-Loss Ratio", "4.67"},
|
||||
{"Alpha", "-0.001"},
|
||||
{"Beta", "0.008"},
|
||||
{"Annual Standard Deviation", "0.001"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-2.168"},
|
||||
{"Tracking Error", "0.099"},
|
||||
{"Treynor Ratio", "-5.187"},
|
||||
{"Total Fees", "$65.00"},
|
||||
{"Estimated Strategy Capacity", "$16000000000.00"},
|
||||
{"Information Ratio", "-1.961"},
|
||||
{"Tracking Error", "0.092"},
|
||||
{"Treynor Ratio", "0.08"},
|
||||
{"Total Fees", "$52.00"},
|
||||
{"Estimated Strategy Capacity", "$32000000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "1.51"},
|
||||
{"Return Over Maximum Drawdown", "1.819"},
|
||||
{"Sortino Ratio", "1.266"},
|
||||
{"Return Over Maximum Drawdown", "1.622"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -118,7 +119,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "c4c9c272037cfd8f6887052b8d739466"}
|
||||
{"OrderListHash", "cf43585a8d1781f04b53a4f1ee3380cb"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
|
||||
EnableAutomaticIndicatorWarmUp = true;
|
||||
SetStartDate(2013, 10, 08);
|
||||
SetStartDate(2013, 10, 07);
|
||||
SetEndDate(2013, 10, 09);
|
||||
|
||||
var SP500 = QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME);
|
||||
@@ -151,30 +151,31 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "-99.999%"},
|
||||
{"Drawdown", "16.100%"},
|
||||
{"Compounding Annual Return", "-100.000%"},
|
||||
{"Drawdown", "19.800%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "-6.366%"},
|
||||
{"Sharpe Ratio", "1.194"},
|
||||
{"Net Profit", "-10.353%"},
|
||||
{"Sharpe Ratio", "-1.379"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "5.579"},
|
||||
{"Beta", "-63.972"},
|
||||
{"Annual Standard Deviation", "0.434"},
|
||||
{"Annual Variance", "0.188"},
|
||||
{"Information Ratio", "0.996"},
|
||||
{"Tracking Error", "0.441"},
|
||||
{"Treynor Ratio", "-0.008"},
|
||||
{"Alpha", "3.004"},
|
||||
{"Beta", "5.322"},
|
||||
{"Annual Standard Deviation", "0.725"},
|
||||
{"Annual Variance", "0.525"},
|
||||
{"Information Ratio", "-0.42"},
|
||||
{"Tracking Error", "0.589"},
|
||||
{"Treynor Ratio", "-0.188"},
|
||||
{"Total Fees", "$20.35"},
|
||||
{"Estimated Strategy Capacity", "$19000000.00"},
|
||||
{"Fitness Score", "0.138"},
|
||||
{"Estimated Strategy Capacity", "$13000000.00"},
|
||||
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
|
||||
{"Fitness Score", "0.125"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-1.727"},
|
||||
{"Return Over Maximum Drawdown", "-12.061"},
|
||||
{"Portfolio Turnover", "4.916"},
|
||||
{"Sortino Ratio", "-2.162"},
|
||||
{"Return Over Maximum Drawdown", "-8.144"},
|
||||
{"Portfolio Turnover", "3.184"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -188,7 +189,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "7c841ca58a4385f42236838e5bf0c382"}
|
||||
{"OrderListHash", "7ff48adafe9676f341e64ac9388d3c2c"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,29 +113,30 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "264.819%"},
|
||||
{"Compounding Annual Return", "271.453%"},
|
||||
{"Drawdown", "2.200%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.668%"},
|
||||
{"Sharpe Ratio", "8.749"},
|
||||
{"Probabilistic Sharpe Ratio", "67.311%"},
|
||||
{"Net Profit", "1.692%"},
|
||||
{"Sharpe Ratio", "8.888"},
|
||||
{"Probabilistic Sharpe Ratio", "67.609%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.005"},
|
||||
{"Beta", "0.996"},
|
||||
{"Annual Standard Deviation", "0.219"},
|
||||
{"Annual Variance", "0.048"},
|
||||
{"Information Ratio", "-14.189"},
|
||||
{"Annual Standard Deviation", "0.222"},
|
||||
{"Annual Variance", "0.049"},
|
||||
{"Information Ratio", "-14.565"},
|
||||
{"Tracking Error", "0.001"},
|
||||
{"Treynor Ratio", "1.922"},
|
||||
{"Total Fees", "$3.26"},
|
||||
{"Estimated Strategy Capacity", "$58000000.00"},
|
||||
{"Treynor Ratio", "1.978"},
|
||||
{"Total Fees", "$3.44"},
|
||||
{"Estimated Strategy Capacity", "$56000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.248"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "93.761"},
|
||||
{"Return Over Maximum Drawdown", "93.728"},
|
||||
{"Portfolio Turnover", "0.248"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -150,7 +151,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "25885f979ca8c7b44f5d0f7daf00b241"}
|
||||
{"OrderListHash", "9e4bfd2eb0b81ee5bc1b197a87ccedbe"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,9 +76,11 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <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);
|
||||
if (!_equityBought && data.ContainsKey(_spy))
|
||||
{
|
||||
//Buy our Equity.
|
||||
//Quantity is rounded down to an even number since it will be split in two equal halves
|
||||
var quantity = Math.Floor(CalculateOrderQuantity(_spy, .1m) / 2) * 2;
|
||||
_equityBuy = MarketOrder(_spy, quantity, asynchronous: true);
|
||||
_equityBought = true;
|
||||
}
|
||||
@@ -119,7 +121,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
var order = Transactions.GetOrderById(orderEvent.OrderId);
|
||||
|
||||
// Based on the type verify the order
|
||||
switch(order.Type)
|
||||
switch (order.Type)
|
||||
{
|
||||
case OrderType.Market:
|
||||
VerifyMarketOrder(order, orderEvent);
|
||||
@@ -140,7 +142,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <param name="order">Order object to analyze</param>
|
||||
public void VerifyMarketOrder(Order order, OrderEvent orderEvent)
|
||||
{
|
||||
switch(order.Status)
|
||||
switch (order.Status)
|
||||
{
|
||||
case OrderStatus.Submitted:
|
||||
break;
|
||||
@@ -152,7 +154,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
throw new Exception("LastFillTime should not be null");
|
||||
}
|
||||
|
||||
if (order.Quantity/2 != orderEvent.FillQuantity)
|
||||
if (order.Quantity / 2 != orderEvent.FillQuantity)
|
||||
{
|
||||
throw new Exception("Order size should be half");
|
||||
}
|
||||
@@ -215,9 +217,9 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
}
|
||||
|
||||
//Check equity holding, should be invested, profit should be
|
||||
//Quantity should be 50, AveragePrice should be ticket AverageFillPrice
|
||||
//Quantity should be 52, AveragePrice should be ticket AverageFillPrice
|
||||
var equityHolding = Portfolio[_equityBuy.Symbol];
|
||||
if (!equityHolding.Invested || equityHolding.Quantity != 50 || equityHolding.AveragePrice != _equityBuy.AverageFillPrice)
|
||||
if (!equityHolding.Invested || equityHolding.Quantity != 52 || equityHolding.AveragePrice != _equityBuy.AverageFillPrice)
|
||||
{
|
||||
throw new Exception("Equity holding does not match expected outcome");
|
||||
}
|
||||
@@ -299,30 +301,31 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "3"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.40%"},
|
||||
{"Compounding Annual Return", "-22.335%"},
|
||||
{"Compounding Annual Return", "-22.717%"},
|
||||
{"Drawdown", "0.400%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.323%"},
|
||||
{"Sharpe Ratio", "-11.098"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Net Profit", "-0.329%"},
|
||||
{"Sharpe Ratio", "-7.887"},
|
||||
{"Probabilistic Sharpe Ratio", "1.216%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.002"},
|
||||
{"Beta", "0.099"},
|
||||
{"Alpha", "-0.001"},
|
||||
{"Beta", "0.097"},
|
||||
{"Annual Standard Deviation", "0.002"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "9.899"},
|
||||
{"Tracking Error", "0.019"},
|
||||
{"Treynor Ratio", "-0.23"},
|
||||
{"Information Ratio", "7.39"},
|
||||
{"Tracking Error", "0.015"},
|
||||
{"Treynor Ratio", "-0.131"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0.213"},
|
||||
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
|
||||
{"Fitness Score", "0.212"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-73.456"},
|
||||
{"Portfolio Turnover", "0.426"},
|
||||
{"Return Over Maximum Drawdown", "-73.334"},
|
||||
{"Portfolio Turnover", "0.425"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -336,7 +339,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "72a6ced0ed0c2da7136f3be652eb4744"}
|
||||
{"OrderListHash", "f67306bc706a2cf66288f1cadf6148ed"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,6 +89,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$85000.00"},
|
||||
{"Lowest Capacity Asset", "BTCEUR XJ"},
|
||||
{"Fitness Score", "0.506"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
|
||||
@@ -80,29 +80,30 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "264.819%"},
|
||||
{"Compounding Annual Return", "271.453%"},
|
||||
{"Drawdown", "2.200%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.668%"},
|
||||
{"Sharpe Ratio", "8.749"},
|
||||
{"Probabilistic Sharpe Ratio", "67.311%"},
|
||||
{"Net Profit", "1.692%"},
|
||||
{"Sharpe Ratio", "8.888"},
|
||||
{"Probabilistic Sharpe Ratio", "67.609%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.005"},
|
||||
{"Beta", "0.996"},
|
||||
{"Annual Standard Deviation", "0.219"},
|
||||
{"Annual Variance", "0.048"},
|
||||
{"Information Ratio", "-14.189"},
|
||||
{"Annual Standard Deviation", "0.222"},
|
||||
{"Annual Variance", "0.049"},
|
||||
{"Information Ratio", "-14.565"},
|
||||
{"Tracking Error", "0.001"},
|
||||
{"Treynor Ratio", "1.922"},
|
||||
{"Total Fees", "$3.26"},
|
||||
{"Estimated Strategy Capacity", "$58000000.00"},
|
||||
{"Treynor Ratio", "1.978"},
|
||||
{"Total Fees", "$3.44"},
|
||||
{"Estimated Strategy Capacity", "$56000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.248"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "93.761"},
|
||||
{"Return Over Maximum Drawdown", "93.728"},
|
||||
{"Portfolio Turnover", "0.248"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -117,7 +118,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "25885f979ca8c7b44f5d0f7daf00b241"}
|
||||
{"OrderListHash", "9e4bfd2eb0b81ee5bc1b197a87ccedbe"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
130
Algorithm.CSharp/BasicTemplateAtreyuAlgorithm.cs
Normal file
130
Algorithm.CSharp/BasicTemplateAtreyuAlgorithm.cs
Normal file
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
* 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.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Brokerages;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Basic template algorithm for the Atreyu brokerage
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="using quantconnect" />
|
||||
/// <meta name="tag" content="trading and orders" />
|
||||
public class BasicTemplateAtreyuAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 10, 07);
|
||||
SetEndDate(2013, 10, 11);
|
||||
SetCash(100000);
|
||||
|
||||
SetBrokerageModel(BrokerageName.Atreyu);
|
||||
AddEquity("SPY", Resolution.Minute);
|
||||
|
||||
DefaultOrderProperties = new AtreyuOrderProperties
|
||||
{
|
||||
// Can specify the default exchange to execute an order on.
|
||||
// If not specified will default to the primary exchange
|
||||
Exchange = Exchange.BATS,
|
||||
// Currently only support order for the day
|
||||
TimeInForce = TimeInForce.Day
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
/// </summary>
|
||||
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
// will set 25% of our buying power with a market order that will be routed to exchange set in the default order properties (BATS)
|
||||
SetHoldings("SPY", 0.25m);
|
||||
// will increase our SPY holdings to 50% of our buying power with a market order that will be routed to ARCA
|
||||
SetHoldings("SPY", 0.50m, orderProperties: new AtreyuOrderProperties { Exchange = Exchange.ARCA });
|
||||
|
||||
Debug("Purchased SPY!");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "93.340%"},
|
||||
{"Drawdown", "1.100%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.846%"},
|
||||
{"Sharpe Ratio", "6.515"},
|
||||
{"Probabilistic Sharpe Ratio", "67.535%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0.11"},
|
||||
{"Annual Variance", "0.012"},
|
||||
{"Information Ratio", "6.515"},
|
||||
{"Tracking Error", "0.11"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$1.20"},
|
||||
{"Estimated Strategy Capacity", "$8600000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.124"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "78.222"},
|
||||
{"Portfolio Turnover", "0.124"},
|
||||
{"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", "01a751a837beafd90015b2fd82edf994"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using QuantConnect.Algorithm.Framework.Alphas;
|
||||
using QuantConnect.Algorithm.Framework.Execution;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Basic template algorithm which showcases <see cref="ConstituentsUniverse"/> simple use case
|
||||
/// </summary>
|
||||
public class BasicTemplateConstituentUniverseAlgorithm : QCAlgorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 10, 07);
|
||||
SetEndDate(2013, 10, 11);
|
||||
|
||||
// by default will use algorithms UniverseSettings
|
||||
AddUniverse(Universe.Constituent.Steel());
|
||||
|
||||
// we specify the UniverseSettings it should use
|
||||
AddUniverse(Universe.Constituent.AggressiveGrowth(
|
||||
new UniverseSettings(Resolution.Hour,
|
||||
2,
|
||||
false,
|
||||
false,
|
||||
UniverseSettings.MinimumTimeInUniverse)));
|
||||
|
||||
SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(1)));
|
||||
SetExecution(new ImmediateExecutionModel());
|
||||
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
|
||||
}
|
||||
}
|
||||
}
|
||||
161
Algorithm.CSharp/BasicTemplateContinuousFutureAlgorithm.cs
Normal file
161
Algorithm.CSharp/BasicTemplateContinuousFutureAlgorithm.cs
Normal file
@@ -0,0 +1,161 @@
|
||||
/*
|
||||
* 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.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Securities.Future;
|
||||
using Futures = QuantConnect.Securities.Futures;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Basic Continuous Futures Template Algorithm
|
||||
/// </summary>
|
||||
public class BasicTemplateContinuousFutureAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Future _continuousContract;
|
||||
private Security _currentContract;
|
||||
private SimpleMovingAverage _fast;
|
||||
private SimpleMovingAverage _slow;
|
||||
|
||||
/// <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, 7, 1);
|
||||
SetEndDate(2014, 1, 1);
|
||||
|
||||
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
|
||||
dataMappingMode: DataMappingMode.LastTradingDay,
|
||||
contractDepthOffset: 0
|
||||
);
|
||||
|
||||
_fast = SMA(_continuousContract.Symbol, 3, Resolution.Daily);
|
||||
_slow = SMA(_continuousContract.Symbol, 10, 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)
|
||||
{
|
||||
foreach (var changedEvent in data.SymbolChangedEvents.Values)
|
||||
{
|
||||
Log($"{Time} - SymbolChanged event: {changedEvent}");
|
||||
}
|
||||
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
if(_fast > _slow)
|
||||
{
|
||||
_currentContract = Securities[_continuousContract.Mapped];
|
||||
Buy(_currentContract.Symbol, 1);
|
||||
}
|
||||
}
|
||||
else if(_fast < _slow)
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
|
||||
if (_currentContract != null && _currentContract.Symbol != _continuousContract.Mapped)
|
||||
{
|
||||
Log($"{Time} - rolling position from {_currentContract.Symbol} to {_continuousContract.Mapped}");
|
||||
|
||||
var currentPositionSize = _currentContract.Holdings.Quantity;
|
||||
Liquidate(_currentContract.Symbol);
|
||||
Buy(_continuousContract.Mapped, currentPositionSize);
|
||||
_currentContract = Securities[_continuousContract.Mapped];
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
Debug($"{orderEvent}");
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
Debug($"{Time}-{changes}");
|
||||
}
|
||||
|
||||
/// <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.00%"},
|
||||
{"Compounding Annual Return", "-0.007%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.004%"},
|
||||
{"Sharpe Ratio", "-0.369"},
|
||||
{"Probabilistic Sharpe Ratio", "10.640%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-2.751"},
|
||||
{"Tracking Error", "0.082"},
|
||||
{"Treynor Ratio", "-0.616"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
|
||||
{"Fitness Score", "0.007"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-0.738"},
|
||||
{"Portfolio Turnover", "0.01"},
|
||||
{"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", "bd7fbe57802dfedb36c85609b7234016"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -224,6 +224,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$85.34"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "BTCEUR XJ"},
|
||||
{"Fitness Score", "0.5"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
|
||||
@@ -71,30 +71,31 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "246.000%"},
|
||||
{"Drawdown", "1.100%"},
|
||||
{"Compounding Annual Return", "246.546%"},
|
||||
{"Drawdown", "1.200%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "3.459%"},
|
||||
{"Sharpe Ratio", "10.11"},
|
||||
{"Probabilistic Sharpe Ratio", "83.150%"},
|
||||
{"Net Profit", "3.464%"},
|
||||
{"Sharpe Ratio", "19.148"},
|
||||
{"Probabilistic Sharpe Ratio", "97.754%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "1.935"},
|
||||
{"Beta", "-0.119"},
|
||||
{"Annual Standard Deviation", "0.16"},
|
||||
{"Annual Variance", "0.026"},
|
||||
{"Information Ratio", "-4.556"},
|
||||
{"Tracking Error", "0.221"},
|
||||
{"Treynor Ratio", "-13.568"},
|
||||
{"Total Fees", "$3.26"},
|
||||
{"Estimated Strategy Capacity", "$890000000.00"},
|
||||
{"Fitness Score", "0.111"},
|
||||
{"Alpha", "-0.005"},
|
||||
{"Beta", "0.998"},
|
||||
{"Annual Standard Deviation", "0.138"},
|
||||
{"Annual Variance", "0.019"},
|
||||
{"Information Ratio", "-34.028"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "2.651"},
|
||||
{"Total Fees", "$3.45"},
|
||||
{"Estimated Strategy Capacity", "$970000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.112"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "52.533"},
|
||||
{"Return Over Maximum Drawdown", "214.75"},
|
||||
{"Portfolio Turnover", "0.111"},
|
||||
{"Sortino Ratio", "53.951"},
|
||||
{"Return Over Maximum Drawdown", "209.464"},
|
||||
{"Portfolio Turnover", "0.112"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -108,7 +109,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "82fee25cd17100c53bb173834ab5f0b2"}
|
||||
{"OrderListHash", "33d01821923c397f999cfb2e5b5928ad"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
public virtual 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
|
||||
@@ -92,29 +92,30 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "3"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-1.01%"},
|
||||
{"Compounding Annual Return", "254.782%"},
|
||||
{"Compounding Annual Return", "261.134%"},
|
||||
{"Drawdown", "2.200%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "1.632%"},
|
||||
{"Sharpe Ratio", "8.371"},
|
||||
{"Probabilistic Sharpe Ratio", "66.555%"},
|
||||
{"Net Profit", "1.655%"},
|
||||
{"Sharpe Ratio", "8.505"},
|
||||
{"Probabilistic Sharpe Ratio", "66.840%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.088"},
|
||||
{"Alpha", "-0.091"},
|
||||
{"Beta", "1.006"},
|
||||
{"Annual Standard Deviation", "0.221"},
|
||||
{"Annual Variance", "0.049"},
|
||||
{"Information Ratio", "-32.586"},
|
||||
{"Annual Standard Deviation", "0.224"},
|
||||
{"Annual Variance", "0.05"},
|
||||
{"Information Ratio", "-33.445"},
|
||||
{"Tracking Error", "0.002"},
|
||||
{"Treynor Ratio", "1.839"},
|
||||
{"Total Fees", "$9.77"},
|
||||
{"Treynor Ratio", "1.893"},
|
||||
{"Total Fees", "$10.32"},
|
||||
{"Estimated Strategy Capacity", "$27000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.747"},
|
||||
{"Kelly Criterion Estimate", "38.64"},
|
||||
{"Kelly Criterion Probability Value", "0.229"},
|
||||
{"Kelly Criterion Estimate", "38.796"},
|
||||
{"Kelly Criterion Probability Value", "0.228"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "85.209"},
|
||||
{"Return Over Maximum Drawdown", "85.095"},
|
||||
{"Portfolio Turnover", "0.747"},
|
||||
{"Total Insights Generated", "100"},
|
||||
{"Total Insights Closed", "99"},
|
||||
@@ -122,14 +123,14 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Long Insight Count", "100"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$126657.6305"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$20405.9516"},
|
||||
{"Mean Population Estimated Insight Value", "$206.1207"},
|
||||
{"Mean Population Direction", "54.5455%"},
|
||||
{"Mean Population Magnitude", "54.5455%"},
|
||||
{"Rolling Averaged Population Direction", "59.8056%"},
|
||||
{"Rolling Averaged Population Magnitude", "59.8056%"},
|
||||
{"OrderListHash", "17e29d58e5dabd93569da752c4552c70"}
|
||||
{"Estimated Monthly Alpha Value", "$135639.1761"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
|
||||
{"Mean Population Estimated Insight Value", "$220.7372"},
|
||||
{"Mean Population Direction", "53.5354%"},
|
||||
{"Mean Population Magnitude", "53.5354%"},
|
||||
{"Rolling Averaged Population Direction", "58.2788%"},
|
||||
{"Rolling Averaged Population Magnitude", "58.2788%"},
|
||||
{"OrderListHash", "ad2216297c759d8e5aef48ff065f8919"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,20 +134,21 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Drawdown", "13.500%"},
|
||||
{"Expectancy", "-0.818"},
|
||||
{"Net Profit", "-13.517%"},
|
||||
{"Sharpe Ratio", "-2.678"},
|
||||
{"Sharpe Ratio", "-98.781"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "89%"},
|
||||
{"Win Rate", "11%"},
|
||||
{"Profit-Loss Ratio", "0.69"},
|
||||
{"Alpha", "4.398"},
|
||||
{"Beta", "-0.989"},
|
||||
{"Annual Standard Deviation", "0.373"},
|
||||
{"Annual Variance", "0.139"},
|
||||
{"Information Ratio", "-12.816"},
|
||||
{"Tracking Error", "0.504"},
|
||||
{"Treynor Ratio", "1.011"},
|
||||
{"Alpha", "-1.676"},
|
||||
{"Beta", "0.042"},
|
||||
{"Annual Standard Deviation", "0.01"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-73.981"},
|
||||
{"Tracking Error", "0.233"},
|
||||
{"Treynor Ratio", "-23.975"},
|
||||
{"Total Fees", "$15207.00"},
|
||||
{"Estimated Strategy Capacity", "$7700.00"},
|
||||
{"Estimated Strategy Capacity", "$8000.00"},
|
||||
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
|
||||
{"Fitness Score", "0.033"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
|
||||
152
Algorithm.CSharp/BasicTemplateFuturesDailyAlgorithm.cs
Normal file
152
Algorithm.CSharp/BasicTemplateFuturesDailyAlgorithm.cs
Normal file
@@ -0,0 +1,152 @@
|
||||
/*
|
||||
* 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.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This example demonstrates how to add futures with daily resolution.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="benchmarks" />
|
||||
/// <meta name="tag" content="futures" />
|
||||
public class BasicTemplateFuturesDailyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _contractSymbol;
|
||||
protected virtual Resolution Resolution => Resolution.Daily;
|
||||
|
||||
// S&P 500 EMini futures
|
||||
private const string RootSP500 = Futures.Indices.SP500EMini;
|
||||
|
||||
// Gold futures
|
||||
private const string RootGold = Futures.Metals.Gold;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize your algorithm and add desired assets.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 10, 08);
|
||||
SetEndDate(2013, 10, 10);
|
||||
SetCash(1000000);
|
||||
|
||||
var futureSP500 = AddFuture(RootSP500, Resolution);
|
||||
var futureGold = AddFuture(RootGold, Resolution);
|
||||
|
||||
// set our expiry filter for this futures chain
|
||||
// SetFilter method accepts TimeSpan objects or integer for days.
|
||||
// The following statements yield the same filtering criteria
|
||||
futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
|
||||
futureGold.SetFilter(0, 182);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
|
||||
/// </summary>
|
||||
/// <param name="slice">The current slice of data keyed by symbol string</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
foreach(var chain in slice.FutureChains)
|
||||
{
|
||||
// find the front contract expiring no earlier than in 90 days
|
||||
var contract = (
|
||||
from futuresContract in chain.Value.OrderBy(x => x.Expiry)
|
||||
where futuresContract.Expiry > Time.Date.AddDays(90)
|
||||
select futuresContract
|
||||
).FirstOrDefault();
|
||||
|
||||
// if found, trade it
|
||||
if (contract != null)
|
||||
{
|
||||
_contractSymbol = contract.Symbol;
|
||||
MarketOrder(_contractSymbol, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 virtual bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public virtual 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 virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "6"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.10%"},
|
||||
{"Compounding Annual Return", "-23.119%"},
|
||||
{"Drawdown", "0.300%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.276%"},
|
||||
{"Sharpe Ratio", "-13.736"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.526"},
|
||||
{"Beta", "0.057"},
|
||||
{"Annual Standard Deviation", "0.015"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-31.088"},
|
||||
{"Tracking Error", "0.189"},
|
||||
{"Treynor Ratio", "-3.51"},
|
||||
{"Total Fees", "$11.10"},
|
||||
{"Estimated Strategy Capacity", "$200000000.00"},
|
||||
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-17.118"},
|
||||
{"Return Over Maximum Drawdown", "-83.844"},
|
||||
{"Portfolio Turnover", "0.16"},
|
||||
{"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", "512f55519e5221c7e82e1d9f5ddd1b9f"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -142,20 +142,21 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Drawdown", "5.000%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "-3.312%"},
|
||||
{"Sharpe Ratio", "-7.795"},
|
||||
{"Probabilistic Sharpe Ratio", "0.164%"},
|
||||
{"Sharpe Ratio", "-6.305"},
|
||||
{"Probabilistic Sharpe Ratio", "9.342%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-1.347"},
|
||||
{"Beta", "0.257"},
|
||||
{"Annual Standard Deviation", "0.109"},
|
||||
{"Annual Variance", "0.012"},
|
||||
{"Information Ratio", "-14.763"},
|
||||
{"Tracking Error", "0.188"},
|
||||
{"Treynor Ratio", "-3.318"},
|
||||
{"Alpha", "-1.465"},
|
||||
{"Beta", "0.312"},
|
||||
{"Annual Standard Deviation", "0.134"},
|
||||
{"Annual Variance", "0.018"},
|
||||
{"Information Ratio", "-14.77"},
|
||||
{"Tracking Error", "0.192"},
|
||||
{"Treynor Ratio", "-2.718"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Estimated Strategy Capacity", "$52000000.00"},
|
||||
{"Lowest Capacity Asset", "GC VL5E74HP3EE5"},
|
||||
{"Fitness Score", "0.009"},
|
||||
{"Kelly Criterion Estimate", "-112.972"},
|
||||
{"Kelly Criterion Probability Value", "0.671"},
|
||||
|
||||
@@ -161,6 +161,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", ""},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
|
||||
96
Algorithm.CSharp/BasicTemplateFuturesHourlyAlgorithm.cs
Normal file
96
Algorithm.CSharp/BasicTemplateFuturesHourlyAlgorithm.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.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regressions tests the BasicTemplateFuturesDailyAlgorithm with hour data
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="benchmarks" />
|
||||
/// <meta name="tag" content="futures" />
|
||||
public class BasicTemplateFuturesHourlyAlgorithm : BasicTemplateFuturesDailyAlgorithm
|
||||
{
|
||||
private Symbol _contractSymbol;
|
||||
protected override Resolution Resolution => Resolution.Hour;
|
||||
|
||||
/// <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 override bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "140"},
|
||||
{"Average Win", "0.01%"},
|
||||
{"Average Loss", "-0.02%"},
|
||||
{"Compounding Annual Return", "-38.171%"},
|
||||
{"Drawdown", "0.400%"},
|
||||
{"Expectancy", "-0.369"},
|
||||
{"Net Profit", "-0.394%"},
|
||||
{"Sharpe Ratio", "-24.82"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "66%"},
|
||||
{"Win Rate", "34%"},
|
||||
{"Profit-Loss Ratio", "0.84"},
|
||||
{"Alpha", "0.42"},
|
||||
{"Beta", "-0.041"},
|
||||
{"Annual Standard Deviation", "0.01"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-65.112"},
|
||||
{"Tracking Error", "0.253"},
|
||||
{"Treynor Ratio", "6.024"},
|
||||
{"Total Fees", "$259.00"},
|
||||
{"Estimated Strategy Capacity", "$130000.00"},
|
||||
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-43.422"},
|
||||
{"Return Over Maximum Drawdown", "-100.459"},
|
||||
{"Portfolio Turnover", "4.716"},
|
||||
{"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", "320067074c8dd771f69602ab07001f1e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
124
Algorithm.CSharp/BasicTemplateHourlyAlgorithm.cs
Normal file
124
Algorithm.CSharp/BasicTemplateHourlyAlgorithm.cs
Normal file
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
* 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 QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Basic template algorithm simply initializes the date range and cash. This is a skeleton
|
||||
/// framework you can use for designing an algorithm.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="using quantconnect" />
|
||||
/// <meta name="tag" content="trading and orders" />
|
||||
public class BasicTemplateHourlyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
|
||||
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 10, 07); //Set Start Date
|
||||
SetEndDate(2013, 10, 11); //Set End Date
|
||||
SetCash(100000); //Set Strategy Cash
|
||||
|
||||
// Find more symbols here: http://quantconnect.com/data
|
||||
// Forex, CFD, Equities Resolutions: Tick, Second, Minute, Hour, Daily.
|
||||
// Futures Resolution: Tick, Second, Minute
|
||||
// Options Resolution: Minute Only.
|
||||
AddEquity("SPY", Resolution.Hour);
|
||||
|
||||
// There are other assets with similar methods. See "Selecting Options" etc for more details.
|
||||
// AddFuture, AddForex, AddCfd, AddOption
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
/// </summary>
|
||||
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
SetHoldings(_spy, 1);
|
||||
Debug("Purchased Stock");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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", "227.693%"},
|
||||
{"Drawdown", "2.000%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.529%"},
|
||||
{"Sharpe Ratio", "8.889"},
|
||||
{"Probabilistic Sharpe Ratio", "67.609%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.005"},
|
||||
{"Beta", "0.996"},
|
||||
{"Annual Standard Deviation", "0.222"},
|
||||
{"Annual Variance", "0.049"},
|
||||
{"Information Ratio", "-14.564"},
|
||||
{"Tracking Error", "0.001"},
|
||||
{"Treynor Ratio", "1.978"},
|
||||
{"Total Fees", "$3.44"},
|
||||
{"Estimated Strategy Capacity", "$110000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.247"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "12.105"},
|
||||
{"Return Over Maximum Drawdown", "112.047"},
|
||||
{"Portfolio Turnover", "0.249"},
|
||||
{"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", "f409be3a7c63d9c1394c2e6c005a15ee"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -30,36 +30,39 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <meta name="tag" content="indexes" />
|
||||
public class BasicTemplateIndexAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _spx;
|
||||
private Symbol _spxOption;
|
||||
protected Symbol Spx;
|
||||
protected Symbol SpxOption;
|
||||
private ExponentialMovingAverage _emaSlow;
|
||||
private ExponentialMovingAverage _emaFast;
|
||||
|
||||
protected virtual Resolution Resolution => Resolution.Minute;
|
||||
protected virtual int StartDay => 4;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize your algorithm and add desired assets.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2021, 1, 4);
|
||||
SetEndDate(2021, 1, 15);
|
||||
SetStartDate(2021, 1, StartDay);
|
||||
SetEndDate(2021, 1, 18);
|
||||
SetCash(1000000);
|
||||
|
||||
// Use indicator for signal; but it cannot be traded
|
||||
_spx = AddIndex("SPX", Resolution.Minute).Symbol;
|
||||
Spx = AddIndex("SPX", Resolution).Symbol;
|
||||
|
||||
// Trade on SPX ITM calls
|
||||
_spxOption = QuantConnect.Symbol.CreateOption(
|
||||
_spx,
|
||||
SpxOption = QuantConnect.Symbol.CreateOption(
|
||||
Spx,
|
||||
Market.USA,
|
||||
OptionStyle.European,
|
||||
OptionRight.Call,
|
||||
3200m,
|
||||
new DateTime(2021, 1, 15));
|
||||
|
||||
AddIndexOptionContract(_spxOption, Resolution.Minute);
|
||||
AddIndexOptionContract(SpxOption, Resolution);
|
||||
|
||||
_emaSlow = EMA(_spx, 80);
|
||||
_emaFast = EMA(_spx, 200);
|
||||
_emaSlow = EMA(Spx, 80);
|
||||
_emaFast = EMA(Spx, 200);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -67,7 +70,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!slice.Bars.ContainsKey(_spx) || !slice.Bars.ContainsKey(_spxOption))
|
||||
if (!slice.Bars.ContainsKey(Spx) || !slice.Bars.ContainsKey(SpxOption))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -80,7 +83,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
if (_emaFast > _emaSlow)
|
||||
{
|
||||
SetHoldings(_spxOption, 1);
|
||||
SetHoldings(SpxOption, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -90,7 +93,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio[_spx].TotalSaleVolume > 0)
|
||||
if (Portfolio[Spx].TotalSaleVolume > 0)
|
||||
{
|
||||
throw new Exception("Index is not tradable.");
|
||||
}
|
||||
@@ -99,45 +102,46 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <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;
|
||||
public virtual 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 };
|
||||
public virtual 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>
|
||||
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "4"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-53.10%"},
|
||||
{"Compounding Annual Return", "-96.172%"},
|
||||
{"Compounding Annual Return", "-92.544%"},
|
||||
{"Drawdown", "10.100%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-9.915%"},
|
||||
{"Sharpe Ratio", "-4.217"},
|
||||
{"Probabilistic Sharpe Ratio", "0.052%"},
|
||||
{"Sharpe Ratio", "-3.845"},
|
||||
{"Probabilistic Sharpe Ratio", "0.053%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0.139"},
|
||||
{"Annual Variance", "0.019"},
|
||||
{"Information Ratio", "-4.217"},
|
||||
{"Tracking Error", "0.139"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Alpha", "-0.558"},
|
||||
{"Beta", "0.313"},
|
||||
{"Annual Standard Deviation", "0.112"},
|
||||
{"Annual Variance", "0.013"},
|
||||
{"Information Ratio", "-6.652"},
|
||||
{"Tracking Error", "0.125"},
|
||||
{"Treynor Ratio", "-1.379"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$14000000.00"},
|
||||
{"Fitness Score", "0.044"},
|
||||
{"Estimated Strategy Capacity", "$13000000.00"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
|
||||
{"Fitness Score", "0.039"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-1.96"},
|
||||
{"Return Over Maximum Drawdown", "-10.171"},
|
||||
{"Portfolio Turnover", "0.34"},
|
||||
{"Sortino Ratio", "-1.763"},
|
||||
{"Return Over Maximum Drawdown", "-9.371"},
|
||||
{"Portfolio Turnover", "0.278"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -151,7 +155,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "52521ab779446daf4d38a7c9bbbdd893"}
|
||||
{"OrderListHash", "0668385036aba3e95127607dfc2f1a59"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
108
Algorithm.CSharp/BasicTemplateIndexDailyAlgorithm.cs
Normal file
108
Algorithm.CSharp/BasicTemplateIndexDailyAlgorithm.cs
Normal file
@@ -0,0 +1,108 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression for running an Index algorithm with Daily data
|
||||
/// </summary>
|
||||
public class BasicTemplateIndexDailyAlgorithm : BasicTemplateIndexAlgorithm
|
||||
{
|
||||
protected override Resolution Resolution => Resolution.Daily;
|
||||
protected override int StartDay => 1;
|
||||
|
||||
// two complete weeks starting from the 5th plus the 18th bar
|
||||
protected virtual int ExpectedBarCount => 2 * 5 + 1;
|
||||
protected int BarCounter = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Purchase a contract when we are not invested, liquidate otherwise
|
||||
/// </summary>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
// SPX Index is not tradable, but we can trade an option
|
||||
MarketOrder(SpxOption, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
|
||||
// Count how many slices we receive with SPX data in it to assert later
|
||||
if (slice.ContainsKey(Spx))
|
||||
{
|
||||
BarCounter++;
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (BarCounter != ExpectedBarCount)
|
||||
{
|
||||
throw new ArgumentException($"Bar Count {BarCounter} is not expected count of {ExpectedBarCount}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 override bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public override Language[] Languages { get; } = { Language.CSharp };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "9"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-39.42%"},
|
||||
{"Compounding Annual Return", "394.321%"},
|
||||
{"Drawdown", "0.200%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "8.219%"},
|
||||
{"Sharpe Ratio", "6.812"},
|
||||
{"Probabilistic Sharpe Ratio", "91.380%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "2.236"},
|
||||
{"Beta", "-1.003"},
|
||||
{"Annual Standard Deviation", "0.317"},
|
||||
{"Annual Variance", "0.101"},
|
||||
{"Information Ratio", "5.805"},
|
||||
{"Tracking Error", "0.359"},
|
||||
{"Treynor Ratio", "-2.153"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
|
||||
{"Fitness Score", "0.027"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "1776.081"},
|
||||
{"Portfolio Turnover", "0.027"},
|
||||
{"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", "474e8e0e28ee84c869f8c69ec3efe371"}
|
||||
};
|
||||
}
|
||||
}
|
||||
72
Algorithm.CSharp/BasicTemplateIndexHourlyAlgorithm.cs
Normal file
72
Algorithm.CSharp/BasicTemplateIndexHourlyAlgorithm.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression for running an Index algorithm with Hourly data
|
||||
/// </summary>
|
||||
public class BasicTemplateIndexHourlyAlgorithm : BasicTemplateIndexDailyAlgorithm
|
||||
{
|
||||
protected override Resolution Resolution => Resolution.Hour;
|
||||
protected override int ExpectedBarCount => base.ExpectedBarCount * 8;
|
||||
|
||||
/// <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 override bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public override Language[] Languages { get; } = { Language.CSharp };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "70"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.23%"},
|
||||
{"Compounding Annual Return", "-34.441%"},
|
||||
{"Drawdown", "2.000%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-2.028%"},
|
||||
{"Sharpe Ratio", "-11.139"},
|
||||
{"Probabilistic Sharpe Ratio", "0.000%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.269"},
|
||||
{"Beta", "0.086"},
|
||||
{"Annual Standard Deviation", "0.023"},
|
||||
{"Annual Variance", "0.001"},
|
||||
{"Information Ratio", "-3.624"},
|
||||
{"Tracking Error", "0.094"},
|
||||
{"Treynor Ratio", "-3.042"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$310000.00"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
|
||||
{"Fitness Score", "0.002"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-14.51"},
|
||||
{"Return Over Maximum Drawdown", "-17.213"},
|
||||
{"Portfolio Turnover", "0.299"},
|
||||
{"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", "3eb56c551f20e2ffa1c56c47c5ee6667"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -30,20 +30,22 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
private Symbol _spx;
|
||||
private ExponentialMovingAverage _emaSlow;
|
||||
private ExponentialMovingAverage _emaFast;
|
||||
protected virtual Resolution Resolution => Resolution.Minute;
|
||||
protected virtual int StartDay => 4;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize your algorithm and add desired assets.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2021, 1, 4);
|
||||
SetStartDate(2021, 1, StartDay);
|
||||
SetEndDate(2021, 2, 1);
|
||||
SetCash(1000000);
|
||||
|
||||
// Use indicator for signal; but it cannot be traded.
|
||||
// We will instead trade on SPX options
|
||||
_spx = AddIndex("SPX", Resolution.Minute).Symbol;
|
||||
var spxOptions = AddIndexOption(_spx, Resolution.Minute);
|
||||
_spx = AddIndex("SPX", Resolution).Symbol;
|
||||
var spxOptions = AddIndexOption(_spx, Resolution);
|
||||
spxOptions.SetFilter(filterFunc => filterFunc.CallsOnly());
|
||||
|
||||
_emaSlow = EMA(_spx, 80);
|
||||
@@ -122,17 +124,17 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <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; } = false;
|
||||
public virtual bool CanRunLocally { get; } = false;
|
||||
|
||||
/// <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 };
|
||||
public virtual 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>
|
||||
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "8220"},
|
||||
{"Average Win", "0.00%"},
|
||||
|
||||
117
Algorithm.CSharp/BasicTemplateIndexOptionsDailyAlgorithm.cs
Normal file
117
Algorithm.CSharp/BasicTemplateIndexOptionsDailyAlgorithm.cs
Normal file
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression for running an IndexOptions algorithm with Daily data
|
||||
/// </summary>
|
||||
public class BasicTemplateIndexOptionsDailyAlgorithm : BasicTemplateIndexOptionsAlgorithm
|
||||
{
|
||||
protected override Resolution Resolution => Resolution.Daily;
|
||||
protected override int StartDay => 1;
|
||||
|
||||
/// <summary>
|
||||
/// Index EMA Cross trading index options of the index.
|
||||
/// </summary>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
foreach (var chain in slice.OptionChains.Values)
|
||||
{
|
||||
// Select the contract with the lowest AskPrice
|
||||
var contract = chain.Contracts.OrderBy(x => x.Value.AskPrice).FirstOrDefault().Value;
|
||||
|
||||
if (contract == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
else
|
||||
{
|
||||
MarketOrder(contract.Symbol, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 override bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public override Language[] Languages { get; } = { Language.CSharp };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "9"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.01%"},
|
||||
{"Compounding Annual Return", "-0.091%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.008%"},
|
||||
{"Sharpe Ratio", "-4.033"},
|
||||
{"Probabilistic Sharpe Ratio", "0.013%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.001"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.447"},
|
||||
{"Tracking Error", "0.136"},
|
||||
{"Treynor Ratio", "-4.612"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P59H5E6M|SPX 31"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-50718.291"},
|
||||
{"Return Over Maximum Drawdown", "-11.386"},
|
||||
{"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", "5f5df233d68d9115a0d81785de54e71d"}
|
||||
};
|
||||
}
|
||||
}
|
||||
87
Algorithm.CSharp/BasicTemplateIndexOptionsHourlyAlgorithm.cs
Normal file
87
Algorithm.CSharp/BasicTemplateIndexOptionsHourlyAlgorithm.cs
Normal file
@@ -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.
|
||||
*
|
||||
*/
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression for running an IndexOptions algorithm with Hourly data
|
||||
/// </summary>
|
||||
public class BasicTemplateIndexOptionsHourlyAlgorithm : BasicTemplateIndexOptionsDailyAlgorithm
|
||||
{
|
||||
protected override Resolution Resolution => Resolution.Hour;
|
||||
|
||||
/// <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 override bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public override Language[] Languages { get; } = { Language.CSharp };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "70"},
|
||||
{"Average Win", "0.00%"},
|
||||
{"Average Loss", "0.00%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "0.000"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "36.504%"},
|
||||
{"Loss Rate", "97%"},
|
||||
{"Win Rate", "3%"},
|
||||
{"Profit-Loss Ratio", "34.00"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "-0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.449"},
|
||||
{"Tracking Error", "0.138"},
|
||||
{"Treynor Ratio", "-0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P59H5E6M|SPX 31"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"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", "f21910eb98ceaa39e02020de95354d86"}
|
||||
};
|
||||
}
|
||||
}
|
||||
132
Algorithm.CSharp/BasicTemplateIndiaAlgorithm.cs
Normal file
132
Algorithm.CSharp/BasicTemplateIndiaAlgorithm.cs
Normal file
@@ -0,0 +1,132 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Orders;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Basic template India algorithm simply initializes the date range and cash. This is a skeleton
|
||||
/// framework you can use for designing an algorithm.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="using quantconnect" />
|
||||
/// <meta name="tag" content="trading and orders" />
|
||||
public class BasicTemplateIndiaAlgorithm : QCAlgorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2003, 10, 07); //Set Start Date
|
||||
SetEndDate(2003, 10, 11); //Set End Date
|
||||
SetCash(100000); //Set Strategy Cash
|
||||
|
||||
// Find more symbols here: http://quantconnect.com/data
|
||||
// Equities Resolutions: Tick, Second, Minute, Hour, Daily.
|
||||
AddEquity("UNIONBANK", Resolution.Second, Market.India);
|
||||
|
||||
//Set Order Prperties as per the requirements for order placement
|
||||
DefaultOrderProperties = new IndiaOrderProperties(exchange: Exchange.NSE);
|
||||
//override default productType value set in config.json if needed - order specific productType value
|
||||
//DefaultOrderProperties = new IndiaOrderProperties(exchange: Exchange.NSE, IndiaOrderProperties.IndiaProductType.CNC);
|
||||
|
||||
// General Debug statement for acknowledgement
|
||||
Debug("Intialization Done");
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
var marketTicket = MarketOrder("UNIONBANK", 1);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status.IsFill())
|
||||
{
|
||||
Debug($"Purchased Complete: {orderEvent.Symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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; } = false;
|
||||
|
||||
/// <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", "-1.01%"},
|
||||
{"Compounding Annual Return", "261.134%"},
|
||||
{"Drawdown", "2.200%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "1.655%"},
|
||||
{"Sharpe Ratio", "8.505"},
|
||||
{"Probabilistic Sharpe Ratio", "66.840%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.091"},
|
||||
{"Beta", "1.006"},
|
||||
{"Annual Standard Deviation", "0.224"},
|
||||
{"Annual Variance", "0.05"},
|
||||
{"Information Ratio", "-33.445"},
|
||||
{"Tracking Error", "0.002"},
|
||||
{"Treynor Ratio", "1.893"},
|
||||
{"Total Fees", "$10.32"},
|
||||
{"Estimated Strategy Capacity", "$27000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.747"},
|
||||
{"Kelly Criterion Estimate", "38.796"},
|
||||
{"Kelly Criterion Probability Value", "0.228"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "85.095"},
|
||||
{"Portfolio Turnover", "0.747"},
|
||||
{"Total Insights Generated", "100"},
|
||||
{"Total Insights Closed", "99"},
|
||||
{"Total Insights Analysis Completed", "99"},
|
||||
{"Long Insight Count", "100"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$135639.1761"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
|
||||
{"Mean Population Estimated Insight Value", "$220.7372"},
|
||||
{"Mean Population Direction", "53.5354%"},
|
||||
{"Mean Population Magnitude", "53.5354%"},
|
||||
{"Rolling Averaged Population Direction", "58.2788%"},
|
||||
{"Rolling Averaged Population Magnitude", "58.2788%"},
|
||||
{"OrderListHash", "ad2216297c759d8e5aef48ff065f8919"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
private readonly Identity _brent = new Identity("Brent");
|
||||
private readonly Identity _wti = new Identity("WTI");
|
||||
|
||||
private CompositeIndicator<IndicatorDataPoint> _spread;
|
||||
private CompositeIndicator _spread;
|
||||
|
||||
private ExponentialMovingAverage _emaWti;
|
||||
|
||||
|
||||
151
Algorithm.CSharp/BasicTemplateOptionEquityStrategyAlgorithm.cs
Normal file
151
Algorithm.CSharp/BasicTemplateOptionEquityStrategyAlgorithm.cs
Normal file
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Data.Market;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Securities.Option;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Basic template algorithm trading a Call Butterfly option equity strategy
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="options" />
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="using quantconnect" />
|
||||
/// <meta name="tag" content="trading and orders" />
|
||||
public class BasicTemplateOptionEquityStrategyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
protected Symbol _optionSymbol;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2015, 12, 24);
|
||||
SetEndDate(2015, 12, 24);
|
||||
|
||||
var equity = AddEquity("GOOG", leverage: 4);
|
||||
var option = AddOption(equity.Symbol);
|
||||
_optionSymbol = option.Symbol;
|
||||
|
||||
// set our strike/expiry filter for this option chain
|
||||
option.SetFilter(u => u.Strikes(-2, +2)
|
||||
// Expiration method accepts TimeSpan objects or integer for days.
|
||||
// The following statements yield the same filtering criteria
|
||||
.Expiration(0, 180));
|
||||
}
|
||||
/// <summary>
|
||||
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
/// </summary>
|
||||
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
OptionChain chain;
|
||||
if (IsMarketOpen(_optionSymbol) && slice.OptionChains.TryGetValue(_optionSymbol, out chain))
|
||||
{
|
||||
var callContracts = chain.Where(contract => contract.Right == OptionRight.Call)
|
||||
.GroupBy(x => x.Expiry)
|
||||
.OrderBy(grouping => grouping.Key)
|
||||
.First()
|
||||
.OrderBy(x => x.Strike)
|
||||
.ToList();
|
||||
|
||||
var expiry = callContracts[0].Expiry;
|
||||
var lowerStrike = callContracts[0].Strike;
|
||||
var middleStrike = callContracts[1].Strike;
|
||||
var higherStrike = callContracts[2].Strike;
|
||||
|
||||
var optionStrategy = OptionStrategies.CallButterfly(_optionSymbol, higherStrike, middleStrike, lowerStrike, expiry);
|
||||
|
||||
Order(optionStrategy, 10);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Order fill event handler. On an order fill update the resulting information is passed to this method.
|
||||
/// </summary>
|
||||
/// <param name="orderEvent">Order event details containing details of the evemts</param>
|
||||
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally => true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public 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", "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", "$10.00"},
|
||||
{"Estimated Strategy Capacity", "$84000.00"},
|
||||
{"Lowest Capacity Asset", "GOOCV W78ZERHAOVVQ|GOOCV VP83T1ZUHROL"},
|
||||
{"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", "82c29cc9db9a300074d6ff136253f4ac"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -134,7 +134,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$778.00"},
|
||||
{"Estimated Strategy Capacity", "$720.00"},
|
||||
{"Estimated Strategy Capacity", "$1000.00"},
|
||||
{"Lowest Capacity Asset", "GOOCV W78ZFMEBBB2E|GOOCV VP83T1ZUHROL"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -154,7 +155,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "5484aef1443064c826e0071f757cb0f7"}
|
||||
{"OrderListHash", "6a88f302b7f29a2c59e4b1e978161da1"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,6 +132,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$1300000.00"},
|
||||
{"Lowest Capacity Asset", "GOOCV 30AKMEIPOSS1Y|GOOCV VP83T1ZUHROL"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
|
||||
171
Algorithm.CSharp/BasicTemplateOptionsDailyAlgorithm.cs
Normal file
171
Algorithm.CSharp/BasicTemplateOptionsDailyAlgorithm.cs
Normal file
@@ -0,0 +1,171 @@
|
||||
/*
|
||||
* 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.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This example demonstrates how to add options for a given underlying equity security.
|
||||
/// It also shows how you can prefilter contracts easily based on strikes and expirations, and how you
|
||||
/// can inspect the option chain to pick a specific option contract to trade.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="options" />
|
||||
/// <meta name="tag" content="filter selection" />
|
||||
public class BasicTemplateOptionsDailyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private const string UnderlyingTicker = "GOOG";
|
||||
public Symbol OptionSymbol;
|
||||
private bool _optionExpired;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2015, 12, 23);
|
||||
SetEndDate(2016, 1, 20);
|
||||
SetCash(100000);
|
||||
|
||||
var equity = AddEquity(UnderlyingTicker, Resolution.Daily);
|
||||
var option = AddOption(UnderlyingTicker, Resolution.Daily);
|
||||
OptionSymbol = option.Symbol;
|
||||
|
||||
option.SetFilter(x => x.CallsOnly().Strikes(0, 1).Expiration(0, 30));
|
||||
|
||||
// use the underlying equity as the benchmark
|
||||
SetBenchmark(equity.Symbol);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
|
||||
/// </summary>
|
||||
/// <param name="slice">The current slice of data keyed by symbol string</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
OptionChain chain;
|
||||
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
|
||||
{
|
||||
// Grab us the contract nearest expiry that is not today
|
||||
var contractsByExpiration = chain.Where(x => x.Expiry != Time.Date).OrderBy(x => x.Expiry);
|
||||
var contract = contractsByExpiration.FirstOrDefault();
|
||||
|
||||
if (contract != null)
|
||||
{
|
||||
// if found, trade it
|
||||
MarketOrder(contract.Symbol, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Order fill event handler. On an order fill update the resulting information is passed to this method.
|
||||
/// </summary>
|
||||
/// <param name="orderEvent">Order event details containing details of the evemts</param>
|
||||
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
Log(orderEvent.ToString());
|
||||
|
||||
// Check for our expected OTM option expiry
|
||||
if (orderEvent.Message == "OTM")
|
||||
{
|
||||
// Assert it is at midnight (5AM UTC)
|
||||
if (orderEvent.UtcTime != new DateTime(2016, 1, 16, 5, 0, 0))
|
||||
{
|
||||
throw new ArgumentException($"Expiry event was not at the correct time, {orderEvent.UtcTime}");
|
||||
}
|
||||
|
||||
_optionExpired = true;
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
// Assert we had our option expire and fill a liquidation order
|
||||
if (_optionExpired != true)
|
||||
{
|
||||
throw new ArgumentException("Algorithm did not process the option expiration like expected");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp, 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", "-1.31%"},
|
||||
{"Compounding Annual Return", "-15.304%"},
|
||||
{"Drawdown", "1.300%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-1.311%"},
|
||||
{"Sharpe Ratio", "-3.31"},
|
||||
{"Probabilistic Sharpe Ratio", "0.035%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0.034"},
|
||||
{"Annual Variance", "0.001"},
|
||||
{"Information Ratio", "-3.31"},
|
||||
{"Tracking Error", "0.034"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$1.00"},
|
||||
{"Estimated Strategy Capacity", "$18000.00"},
|
||||
{"Lowest Capacity Asset", "GOOCV W78ZFMML01JA|GOOCV VP83T1ZUHROL"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-1.496"},
|
||||
{"Return Over Maximum Drawdown", "-11.673"},
|
||||
{"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", "c6d089f1fb86379c74a7413a9c2f8553"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2015, 12, 24);
|
||||
SetEndDate(2015, 12, 24);
|
||||
SetEndDate(2015, 12, 28);
|
||||
SetCash(100000);
|
||||
|
||||
var equity = AddEquity(UnderlyingTicker);
|
||||
@@ -104,14 +104,14 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Average Loss", "-0.40%"},
|
||||
{"Compounding Annual Return", "-21.622%"},
|
||||
{"Drawdown", "0.300%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.311%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
@@ -123,12 +123,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$1.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
|
||||
{"Fitness Score", "0.188"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "0"},
|
||||
{"Return Over Maximum Drawdown", "0"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-73.268"},
|
||||
{"Portfolio Turnover", "0.376"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -142,7 +143,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "92d8a50efe230524512404dab66b19dd"}
|
||||
{"OrderListHash", "452e7a36e0a95e33d3457a908add3ead"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
UniverseSettings.Resolution = Resolution.Minute;
|
||||
|
||||
SetStartDate(2014, 06, 05);
|
||||
SetEndDate(2014, 06, 06);
|
||||
SetEndDate(2014, 06, 09);
|
||||
SetCash(100000);
|
||||
|
||||
// set framework models
|
||||
@@ -142,46 +142,47 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "4"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Average Win", "0.14%"},
|
||||
{"Average Loss", "-0.28%"},
|
||||
{"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"},
|
||||
{"Drawdown", "385.400%"},
|
||||
{"Expectancy", "-0.249"},
|
||||
{"Net Profit", "-386.489%"},
|
||||
{"Sharpe Ratio", "-0.033"},
|
||||
{"Probabilistic Sharpe Ratio", "1.235%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.50"},
|
||||
{"Alpha", "-95.983"},
|
||||
{"Beta", "263.726"},
|
||||
{"Annual Standard Deviation", "30.617"},
|
||||
{"Annual Variance", "937.371"},
|
||||
{"Information Ratio", "-0.044"},
|
||||
{"Tracking Error", "30.604"},
|
||||
{"Treynor Ratio", "-0.004"},
|
||||
{"Total Fees", "$3.00"},
|
||||
{"Estimated Strategy Capacity", "$74000.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.168"},
|
||||
{"Kelly Criterion Estimate", "0.327"},
|
||||
{"Kelly Criterion Probability Value", "1"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "26"},
|
||||
{"Return Over Maximum Drawdown", "0"},
|
||||
{"Portfolio Turnover", "0.224"},
|
||||
{"Total Insights Generated", "28"},
|
||||
{"Total Insights Closed", "24"},
|
||||
{"Total Insights Analysis Completed", "24"},
|
||||
{"Long Insight Count", "26"},
|
||||
{"Long Insight Count", "28"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$31.01809"},
|
||||
{"Estimated Monthly Alpha Value", "$13.64796"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$1.89555"},
|
||||
{"Mean Population Estimated Insight Value", "$0.07898125"},
|
||||
{"Mean Population Direction", "50%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "50.0482%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "ce06ddfa4b2ffeb666a8910ac8836992"}
|
||||
{"OrderListHash", "87603bd45898dd9c456745fa51f989a5"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
158
Algorithm.CSharp/BasicTemplateOptionsHourlyAlgorithm.cs
Normal file
158
Algorithm.CSharp/BasicTemplateOptionsHourlyAlgorithm.cs
Normal file
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* 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.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This example demonstrates how to add options for a given underlying equity security.
|
||||
/// It also shows how you can prefilter contracts easily based on strikes and expirations, and how you
|
||||
/// can inspect the option chain to pick a specific option contract to trade.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="options" />
|
||||
/// <meta name="tag" content="filter selection" />
|
||||
public class BasicTemplateOptionsHourlyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private const string UnderlyingTicker = "AAPL";
|
||||
public Symbol OptionSymbol;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 6, 6);
|
||||
SetEndDate(2014, 6, 9);
|
||||
SetCash(100000);
|
||||
|
||||
var equity = AddEquity(UnderlyingTicker, Resolution.Hour);
|
||||
var option = AddOption(UnderlyingTicker, Resolution.Hour);
|
||||
OptionSymbol = option.Symbol;
|
||||
|
||||
// set our strike/expiry filter for this option chain
|
||||
option.SetFilter(u => u.Strikes(-2, +2)
|
||||
// Expiration method accepts TimeSpan objects or integer for days.
|
||||
// The following statements yield the same filtering criteria
|
||||
.Expiration(0, 180));
|
||||
// .Expiration(TimeSpan.Zero, TimeSpan.FromDays(180)));
|
||||
|
||||
// use the underlying equity as the benchmark
|
||||
SetBenchmark(equity.Symbol);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
|
||||
/// </summary>
|
||||
/// <param name="slice">The current slice of data keyed by symbol string</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!Portfolio.Invested && IsMarketOpen(OptionSymbol))
|
||||
{
|
||||
OptionChain chain;
|
||||
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
|
||||
{
|
||||
// we find at the money (ATM) put contract with farthest expiration
|
||||
var atmContract = chain
|
||||
.OrderByDescending(x => x.Expiry)
|
||||
.ThenBy(x => Math.Abs(chain.Underlying.Price - x.Strike))
|
||||
.ThenByDescending(x => x.Right)
|
||||
.FirstOrDefault();
|
||||
|
||||
if (atmContract != null)
|
||||
{
|
||||
// if found, trade it
|
||||
MarketOrder(atmContract.Symbol, 1);
|
||||
MarketOnCloseOrder(atmContract.Symbol, -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Order fill event handler. On an order fill update the resulting information is passed to this method.
|
||||
/// </summary>
|
||||
/// <param name="orderEvent">Order event details containing details of the evemts</param>
|
||||
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
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", "4"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.07%"},
|
||||
{"Compounding Annual Return", "-12.496%"},
|
||||
{"Drawdown", "0.200%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.134%"},
|
||||
{"Sharpe Ratio", "-8.839"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.083"},
|
||||
{"Beta", "-0.054"},
|
||||
{"Annual Standard Deviation", "0.008"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-18.699"},
|
||||
{"Tracking Error", "0.155"},
|
||||
{"Treynor Ratio", "1.296"},
|
||||
{"Total Fees", "$4.00"},
|
||||
{"Estimated Strategy Capacity", "$1000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL 2ZTXYMUAHCIAU|AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.04"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-118.28"},
|
||||
{"Portfolio Turnover", "0.081"},
|
||||
{"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", "81e8a822d43de2165c1d3f52964ec312"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.SEC;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp.Benchmarks
|
||||
{
|
||||
public class SECReportBenchmarkAlgorithm : QCAlgorithm
|
||||
{
|
||||
private List<Security> _securities;
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2018, 1, 1);
|
||||
SetEndDate(2019, 1, 1);
|
||||
|
||||
var tickers = new List<string> {"AAPL", "AMZN", "MSFT", "IBM", "FB", "QQQ",
|
||||
"IWM", "BAC", "BNO", "AIG", "UW", "WM" };
|
||||
_securities = new List<Security>();
|
||||
|
||||
foreach (var ticker in tickers)
|
||||
{
|
||||
var equity = AddEquity(ticker);
|
||||
_securities.Add(equity);
|
||||
|
||||
AddData<SECReport8K>(equity.Symbol, Resolution.Daily);
|
||||
AddData<SECReport10K>(equity.Symbol, Resolution.Daily);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
foreach (var security in _securities)
|
||||
{
|
||||
SECReport8K report8K = security.Data.Get<SECReport8K>();
|
||||
SECReport10K report10K = security.Data.Get<SECReport10K>();
|
||||
|
||||
if (!security.HoldStock && report8K != null && report10K != null)
|
||||
{
|
||||
SetHoldings(security.Symbol, 1d / _securities.Count);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.SmartInsider;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp.Benchmarks
|
||||
{
|
||||
public class SmartInsiderEventBenchmarkAlgorithm : QCAlgorithm
|
||||
{
|
||||
private List<Security> _securities;
|
||||
private List<Symbol> _customSymbols;
|
||||
private int _historySymbolCount;
|
||||
|
||||
/// <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(2010, 1, 1);
|
||||
SetEndDate(2019, 1, 1);
|
||||
|
||||
var tickers = new List<string> {"AAPL", "AMZN", "MSFT", "IBM", "FB", "QQQ",
|
||||
"IWM", "BAC", "BNO", "AIG", "UW", "WM" };
|
||||
_securities = new List<Security>();
|
||||
_customSymbols = new List<Symbol>();
|
||||
|
||||
foreach (var ticker in tickers)
|
||||
{
|
||||
var equity = AddEquity(ticker, Resolution.Hour);
|
||||
_securities.Add(equity);
|
||||
|
||||
_customSymbols.Add(
|
||||
AddData<SmartInsiderIntention>(equity.Symbol, Resolution.Daily).Symbol);
|
||||
_customSymbols.Add(
|
||||
AddData<SmartInsiderTransaction>(equity.Symbol, Resolution.Daily).Symbol);
|
||||
}
|
||||
|
||||
Schedule.On(DateRules.EveryDay(), TimeRules.At(16, 0), () =>
|
||||
{
|
||||
foreach (var slice in History(_customSymbols, TimeSpan.FromDays(5)))
|
||||
{
|
||||
_historySymbolCount += slice.Count;
|
||||
}
|
||||
|
||||
foreach (var security in _securities)
|
||||
{
|
||||
SmartInsiderIntention intention = security.Data.Get<SmartInsiderIntention>();
|
||||
SmartInsiderTransaction transaction = security.Data.Get<SmartInsiderTransaction>();
|
||||
|
||||
if (!security.HoldStock && intention != null && transaction != null)
|
||||
{
|
||||
SetHoldings(security.Symbol, 1d / _securities.Count);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
var intentions = data.Get<SmartInsiderIntention>();
|
||||
var transactions = data.Get<SmartInsiderTransaction>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,10 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
// Set requested data resolution
|
||||
UniverseSettings.Resolution = Resolution.Minute;
|
||||
|
||||
// Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
|
||||
// Commented so regression algorithm is more sensitive
|
||||
//Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;
|
||||
|
||||
SetStartDate(2013, 10, 07); //Set Start Date
|
||||
SetEndDate(2013, 10, 11); //Set End Date
|
||||
SetCash(100000); //Set Strategy Cash
|
||||
@@ -74,47 +78,48 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "18"},
|
||||
{"Total Trades", "20"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.16%"},
|
||||
{"Compounding Annual Return", "72.164%"},
|
||||
{"Average Loss", "-0.13%"},
|
||||
{"Compounding Annual Return", "62.435%"},
|
||||
{"Drawdown", "1.100%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "0.747%"},
|
||||
{"Sharpe Ratio", "4.086"},
|
||||
{"Probabilistic Sharpe Ratio", "61.091%"},
|
||||
{"Net Profit", "0.667%"},
|
||||
{"Sharpe Ratio", "3.993"},
|
||||
{"Probabilistic Sharpe Ratio", "58.777%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.305"},
|
||||
{"Beta", "0.564"},
|
||||
{"Annual Standard Deviation", "0.113"},
|
||||
{"Annual Variance", "0.013"},
|
||||
{"Information Ratio", "-10.007"},
|
||||
{"Tracking Error", "0.09"},
|
||||
{"Treynor Ratio", "0.82"},
|
||||
{"Total Fees", "$41.70"},
|
||||
{"Estimated Strategy Capacity", "$3000000.00"},
|
||||
{"Fitness Score", "0.634"},
|
||||
{"Kelly Criterion Estimate", "13.656"},
|
||||
{"Kelly Criterion Probability Value", "0.228"},
|
||||
{"Alpha", "-0.598"},
|
||||
{"Beta", "0.569"},
|
||||
{"Annual Standard Deviation", "0.133"},
|
||||
{"Annual Variance", "0.018"},
|
||||
{"Information Ratio", "-13.973"},
|
||||
{"Tracking Error", "0.104"},
|
||||
{"Treynor Ratio", "0.932"},
|
||||
{"Total Fees", "$46.20"},
|
||||
{"Estimated Strategy Capacity", "$2300000.00"},
|
||||
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.645"},
|
||||
{"Kelly Criterion Estimate", "13.787"},
|
||||
{"Kelly Criterion Probability Value", "0.231"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "80.05"},
|
||||
{"Portfolio Turnover", "0.634"},
|
||||
{"Total Insights Generated", "17"},
|
||||
{"Total Insights Closed", "14"},
|
||||
{"Total Insights Analysis Completed", "14"},
|
||||
{"Return Over Maximum Drawdown", "65.642"},
|
||||
{"Portfolio Turnover", "0.645"},
|
||||
{"Total Insights Generated", "13"},
|
||||
{"Total Insights Closed", "10"},
|
||||
{"Total Insights Analysis Completed", "10"},
|
||||
{"Long Insight Count", "6"},
|
||||
{"Short Insight Count", "7"},
|
||||
{"Long/Short Ratio", "85.71%"},
|
||||
{"Estimated Monthly Alpha Value", "$72447.6813"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$12477.1007"},
|
||||
{"Mean Population Estimated Insight Value", "$891.2215"},
|
||||
{"Mean Population Direction", "50%"},
|
||||
{"Mean Population Magnitude", "50%"},
|
||||
{"Rolling Averaged Population Direction", "12.6429%"},
|
||||
{"Rolling Averaged Population Magnitude", "12.6429%"},
|
||||
{"OrderListHash", "3edd51956c7c97af4863aa6059c11f1a"}
|
||||
{"Estimated Monthly Alpha Value", "$52003.0716"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$8956.0846"},
|
||||
{"Mean Population Estimated Insight Value", "$895.6085"},
|
||||
{"Mean Population Direction", "70%"},
|
||||
{"Mean Population Magnitude", "70%"},
|
||||
{"Rolling Averaged Population Direction", "94.5154%"},
|
||||
{"Rolling Averaged Population Magnitude", "94.5154%"},
|
||||
{"OrderListHash", "0945ff7a39bb8f8a07b3dcc817c070aa"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,6 +148,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$370000.00"},
|
||||
{"Lowest Capacity Asset", "ETHUSD XJ"},
|
||||
{"Fitness Score", "0.501"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
|
||||
@@ -81,8 +81,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
algorithm.DateRules.MonthStart(benchmark.Symbol),
|
||||
algorithm.TimeRules.AfterMarketOpen(benchmark.Symbol),
|
||||
datetime => SelectPair(algorithm, datetime),
|
||||
algorithm.UniverseSettings,
|
||||
algorithm.SecurityInitializer);
|
||||
algorithm.UniverseSettings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -33,7 +33,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
SetAccountCurrency("EUR");
|
||||
|
||||
SetStartDate(2019, 2, 20);
|
||||
SetStartDate(2019, 2, 19);
|
||||
SetEndDate(2019, 2, 21);
|
||||
SetCash("EUR", 100000);
|
||||
|
||||
@@ -75,33 +75,34 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "167"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Total Trades", "279"},
|
||||
{"Average Win", "0.01%"},
|
||||
{"Average Loss", "-0.01%"},
|
||||
{"Compounding Annual Return", "-33.650%"},
|
||||
{"Drawdown", "0.300%"},
|
||||
{"Expectancy", "-0.345"},
|
||||
{"Net Profit", "-0.337%"},
|
||||
{"Sharpe Ratio", "-19.772"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Loss Rate", "68%"},
|
||||
{"Win Rate", "32%"},
|
||||
{"Profit-Loss Ratio", "1.07"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Standard Deviation", "0.014"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Information Ratio", "-19.772"},
|
||||
{"Tracking Error", "0.014"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0.5"},
|
||||
{"Estimated Strategy Capacity", "$670000.00"},
|
||||
{"Lowest Capacity Asset", "DE30EUR 8I"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-325.922"},
|
||||
{"Portfolio Turnover", "9.561"},
|
||||
{"Sortino Ratio", "-101.587"},
|
||||
{"Return Over Maximum Drawdown", "-110.633"},
|
||||
{"Portfolio Turnover", "9.513"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -115,7 +116,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "6ea6184a2a8d0d69e552ad866933bfb6"}
|
||||
{"OrderListHash", "64c098abe3c1e7206424b0c3825b0069"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <meta name="tag" content="indicators" />
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="consolidating data" />
|
||||
public class RenkoConsolidatorAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
public class ClassicRenkoConsolidatorAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes the algorithm state.
|
||||
@@ -43,7 +43,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
// property of the data it receives.
|
||||
|
||||
// break SPY into $2.5 renko bricks and send that data to our 'OnRenkoBar' method
|
||||
var renkoClose = new RenkoConsolidator(2.5m);
|
||||
var renkoClose = new ClassicRenkoConsolidator(2.5m);
|
||||
renkoClose.DataConsolidated += (sender, consolidated) =>
|
||||
{
|
||||
// call our event handler for renko data
|
||||
@@ -58,7 +58,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
// this allows us to perform the renko logic on values other than Close, even computed values!
|
||||
|
||||
// break SPY into (2*o + h + l + 3*c)/7
|
||||
var renko7bar = new RenkoConsolidator<TradeBar>(2.5m, x => (2 * x.Open + x.High + x.Low + 3 * x.Close) / 7m, x => x.Volume);
|
||||
var renko7bar = new ClassicRenkoConsolidator<TradeBar>(2.5m, x => (2 * x.Open + x.High + x.Low + 3 * x.Close) / 7m, x => x.Volume);
|
||||
renko7bar.DataConsolidated += (sender, consolidated) =>
|
||||
{
|
||||
HandleRenko7Bar(consolidated);
|
||||
@@ -117,31 +117,32 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "29"},
|
||||
{"Average Win", "1.14%"},
|
||||
{"Average Loss", "-1.76%"},
|
||||
{"Compounding Annual Return", "-2.045%"},
|
||||
{"Drawdown", "11.000%"},
|
||||
{"Expectancy", "-0.059"},
|
||||
{"Net Profit", "-2.050%"},
|
||||
{"Sharpe Ratio", "-0.148"},
|
||||
{"Probabilistic Sharpe Ratio", "10.284%"},
|
||||
{"Average Win", "1.85%"},
|
||||
{"Average Loss", "-1.49%"},
|
||||
{"Compounding Annual Return", "7.819%"},
|
||||
{"Drawdown", "6.800%"},
|
||||
{"Expectancy", "0.281"},
|
||||
{"Net Profit", "7.841%"},
|
||||
{"Sharpe Ratio", "0.799"},
|
||||
{"Probabilistic Sharpe Ratio", "39.344%"},
|
||||
{"Loss Rate", "43%"},
|
||||
{"Win Rate", "57%"},
|
||||
{"Profit-Loss Ratio", "0.65"},
|
||||
{"Alpha", "-0.013"},
|
||||
{"Beta", "0.001"},
|
||||
{"Annual Standard Deviation", "0.089"},
|
||||
{"Annual Variance", "0.008"},
|
||||
{"Information Ratio", "-1.032"},
|
||||
{"Tracking Error", "0.145"},
|
||||
{"Treynor Ratio", "-25.917"},
|
||||
{"Total Fees", "$117.46"},
|
||||
{"Estimated Strategy Capacity", "$570000000.00"},
|
||||
{"Fitness Score", "0.044"},
|
||||
{"Profit-Loss Ratio", "1.24"},
|
||||
{"Alpha", "0.009"},
|
||||
{"Beta", "0.411"},
|
||||
{"Annual Standard Deviation", "0.07"},
|
||||
{"Annual Variance", "0.005"},
|
||||
{"Information Ratio", "-0.703"},
|
||||
{"Tracking Error", "0.083"},
|
||||
{"Treynor Ratio", "0.136"},
|
||||
{"Total Fees", "$129.35"},
|
||||
{"Estimated Strategy Capacity", "$1000000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.062"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.219"},
|
||||
{"Return Over Maximum Drawdown", "-0.185"},
|
||||
{"Sortino Ratio", "1.023"},
|
||||
{"Return Over Maximum Drawdown", "1.142"},
|
||||
{"Portfolio Turnover", "0.094"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -156,7 +157,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "f6815165e259f48000413986baa32b75"}
|
||||
{"OrderListHash", "b2286d2421294408c3a390e614f40ef9"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -164,29 +164,30 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "1.16%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "32.515%"},
|
||||
{"Compounding Annual Return", "32.505%"},
|
||||
{"Drawdown", "1.400%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.164%"},
|
||||
{"Sharpe Ratio", "2.857"},
|
||||
{"Probabilistic Sharpe Ratio", "64.822%"},
|
||||
{"Net Profit", "1.163%"},
|
||||
{"Sharpe Ratio", "2.754"},
|
||||
{"Probabilistic Sharpe Ratio", "64.748%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.237"},
|
||||
{"Beta", "-0.182"},
|
||||
{"Annual Standard Deviation", "0.09"},
|
||||
{"Annual Variance", "0.008"},
|
||||
{"Information Ratio", "2.425"},
|
||||
{"Tracking Error", "0.149"},
|
||||
{"Treynor Ratio", "-1.405"},
|
||||
{"Alpha", "0.277"},
|
||||
{"Beta", "0.436"},
|
||||
{"Annual Standard Deviation", "0.086"},
|
||||
{"Annual Variance", "0.007"},
|
||||
{"Information Ratio", "3.572"},
|
||||
{"Tracking Error", "0.092"},
|
||||
{"Treynor Ratio", "0.54"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$42000000.00"},
|
||||
{"Estimated Strategy Capacity", "$49000000.00"},
|
||||
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.076"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "27.329"},
|
||||
{"Return Over Maximum Drawdown", "24.003"},
|
||||
{"Sortino Ratio", "27.328"},
|
||||
{"Return Over Maximum Drawdown", "24.002"},
|
||||
{"Portfolio Turnover", "0.076"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -201,7 +202,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "edd9e9ffc8a1cdfb7a1e6ae601e61b12"}
|
||||
{"OrderListHash", "159887a90516df8ba8e8d35b9c30b227"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
_aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
|
||||
UniverseSettings.Resolution = Resolution.Minute;
|
||||
|
||||
SetStartDate(2014, 06, 05);
|
||||
SetStartDate(2014, 06, 04);
|
||||
SetEndDate(2014, 06, 06);
|
||||
|
||||
var selectionUniverse = AddUniverse(enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl },
|
||||
@@ -144,33 +144,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </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"},
|
||||
{"Estimated Strategy Capacity", "$3000000.00"},
|
||||
{"Fitness Score", "0.232"},
|
||||
{"Fitness Score", "0.12"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0.232"},
|
||||
{"Portfolio Turnover", "0.12"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -184,7 +163,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "12470afd9a74ad9c9802361f6f092777"}
|
||||
{"OrderListHash", "2a6319d0d474f976e653dd1ebc42caac"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,33 +116,34 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "11"},
|
||||
{"Average Win", "0.51%"},
|
||||
{"Average Loss", "-0.33%"},
|
||||
{"Compounding Annual Return", "-31.082%"},
|
||||
{"Drawdown", "2.700%"},
|
||||
{"Expectancy", "0.263"},
|
||||
{"Net Profit", "-1.518%"},
|
||||
{"Sharpe Ratio", "-2.118"},
|
||||
{"Probabilistic Sharpe Ratio", "23.259%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "1.53"},
|
||||
{"Alpha", "-0.208"},
|
||||
{"Beta", "0.415"},
|
||||
{"Annual Standard Deviation", "0.119"},
|
||||
{"Total Trades", "12"},
|
||||
{"Average Win", "0.55%"},
|
||||
{"Average Loss", "-0.26%"},
|
||||
{"Compounding Annual Return", "16.717%"},
|
||||
{"Drawdown", "1.700%"},
|
||||
{"Expectancy", "0.850"},
|
||||
{"Net Profit", "0.637%"},
|
||||
{"Sharpe Ratio", "1.088"},
|
||||
{"Probabilistic Sharpe Ratio", "50.223%"},
|
||||
{"Loss Rate", "40%"},
|
||||
{"Win Rate", "60%"},
|
||||
{"Profit-Loss Ratio", "2.08"},
|
||||
{"Alpha", "0.198"},
|
||||
{"Beta", "0.741"},
|
||||
{"Annual Standard Deviation", "0.118"},
|
||||
{"Annual Variance", "0.014"},
|
||||
{"Information Ratio", "-1.167"},
|
||||
{"Tracking Error", "0.126"},
|
||||
{"Treynor Ratio", "-0.607"},
|
||||
{"Total Fees", "$11.63"},
|
||||
{"Estimated Strategy Capacity", "$46000000.00"},
|
||||
{"Fitness Score", "0.013"},
|
||||
{"Information Ratio", "2.294"},
|
||||
{"Tracking Error", "0.097"},
|
||||
{"Treynor Ratio", "0.173"},
|
||||
{"Total Fees", "$27.94"},
|
||||
{"Estimated Strategy Capacity", "$200000000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.28"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-5.1"},
|
||||
{"Return Over Maximum Drawdown", "-11.717"},
|
||||
{"Portfolio Turnover", "0.282"},
|
||||
{"Sortino Ratio", "3"},
|
||||
{"Return Over Maximum Drawdown", "9.559"},
|
||||
{"Portfolio Turnover", "0.308"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -156,7 +157,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "3d1ae61492b34c39115b76757510c058"}
|
||||
{"OrderListHash", "de456413f89396bd6f920686219ed0a5"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,11 +110,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-1.383"},
|
||||
{"Information Ratio", "-1.388"},
|
||||
{"Tracking Error", "0.096"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", ""},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
|
||||
@@ -103,29 +103,30 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "58.336%"},
|
||||
{"Drawdown", "0.900%"},
|
||||
{"Compounding Annual Return", "57.657%"},
|
||||
{"Drawdown", "1.000%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.012%"},
|
||||
{"Sharpe Ratio", "5.09"},
|
||||
{"Probabilistic Sharpe Ratio", "68.472%"},
|
||||
{"Net Profit", "1.003%"},
|
||||
{"Sharpe Ratio", "5.36"},
|
||||
{"Probabilistic Sharpe Ratio", "69.521%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.322"},
|
||||
{"Beta", "0.265"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "1.003"},
|
||||
{"Annual Standard Deviation", "0.087"},
|
||||
{"Annual Variance", "0.008"},
|
||||
{"Information Ratio", "-0.088"},
|
||||
{"Tracking Error", "0.105"},
|
||||
{"Treynor Ratio", "1.667"},
|
||||
{"Total Fees", "$2.91"},
|
||||
{"Estimated Strategy Capacity", "$670000000.00"},
|
||||
{"Annual Variance", "0.007"},
|
||||
{"Information Ratio", "6.477"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0.462"},
|
||||
{"Total Fees", "$3.08"},
|
||||
{"Estimated Strategy Capacity", "$720000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.141"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "9.731"},
|
||||
{"Return Over Maximum Drawdown", "61.515"},
|
||||
{"Sortino Ratio", "10.385"},
|
||||
{"Return Over Maximum Drawdown", "58.709"},
|
||||
{"Portfolio Turnover", "0.143"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -140,7 +141,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "718d73fbddccb63aeacbf4659938b4b8"}
|
||||
{"OrderListHash", "50145c3c1d58b09f38ec1b77cfe69eae"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using QuantConnect.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.Tiingo;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Example algorithm of a custom universe selection using coarse data and adding TiingoNews
|
||||
/// If conditions are met will add the underlying and trade it
|
||||
/// </summary>
|
||||
public class CoarseTiingoNewsUniverseSelectionAlgorithm : QCAlgorithm
|
||||
{
|
||||
private const int NumberOfSymbols = 3;
|
||||
private List<Symbol> _symbols;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 03, 24);
|
||||
SetEndDate(2014, 04, 07);
|
||||
|
||||
UniverseSettings.FillForward = false;
|
||||
|
||||
AddUniverse(new CustomDataCoarseFundamentalUniverse(UniverseSettings, SecurityInitializer, CoarseSelectionFunction));
|
||||
|
||||
_symbols = new List<Symbol>();
|
||||
}
|
||||
|
||||
// sort the data by daily dollar volume and take the top 'NumberOfSymbols'
|
||||
public IEnumerable<Symbol> CoarseSelectionFunction(IEnumerable<CoarseFundamental> coarse)
|
||||
{
|
||||
// sort descending by daily dollar volume
|
||||
var sortedByDollarVolume = coarse.OrderByDescending(x => x.DollarVolume);
|
||||
|
||||
// take the top entries from our sorted collection
|
||||
var top = sortedByDollarVolume.Take(NumberOfSymbols);
|
||||
|
||||
// we need to return only the symbol objects
|
||||
return top.Select(x => QuantConnect.Symbol.CreateBase(typeof(TiingoNews), x.Symbol, x.Symbol.ID.Market));
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
var articles = data.Get<TiingoNews>();
|
||||
|
||||
foreach (var kvp in articles)
|
||||
{
|
||||
var news = kvp.Value;
|
||||
if (news.Title.IndexOf("Stocks Drop", 0, StringComparison.CurrentCultureIgnoreCase) != -1)
|
||||
{
|
||||
if (!Securities.ContainsKey(kvp.Key.Underlying))
|
||||
{
|
||||
// add underlying we want to trade
|
||||
AddSecurity(kvp.Key.Underlying);
|
||||
_symbols.Add(kvp.Key.Underlying);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var symbol in _symbols)
|
||||
{
|
||||
if (Securities[symbol].HasData)
|
||||
{
|
||||
SetHoldings(symbol, 1m / _symbols.Count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
changes.FilterCustomSecurities = false;
|
||||
Log($"{Time} {changes}");
|
||||
}
|
||||
|
||||
private class CustomDataCoarseFundamentalUniverse : CoarseFundamentalUniverse
|
||||
{
|
||||
public CustomDataCoarseFundamentalUniverse(UniverseSettings universeSettings, ISecurityInitializer securityInitializer, Func<IEnumerable<CoarseFundamental>, IEnumerable<Symbol>> selector)
|
||||
: base(universeSettings, securityInitializer, selector)
|
||||
{ }
|
||||
|
||||
public override IEnumerable<SubscriptionRequest> GetSubscriptionRequests(Security security, DateTime currentTimeUtc, DateTime maximumEndTimeUtc,
|
||||
ISubscriptionDataConfigService subscriptionService)
|
||||
{
|
||||
var config = subscriptionService.Add(
|
||||
typeof(TiingoNews),
|
||||
security.Symbol,
|
||||
UniverseSettings.Resolution,
|
||||
UniverseSettings.FillForward,
|
||||
UniverseSettings.ExtendedMarketHours,
|
||||
dataNormalizationMode: UniverseSettings.DataNormalizationMode);
|
||||
return new[]{new SubscriptionRequest(isUniverseSubscription: false,
|
||||
universe: this,
|
||||
security: security,
|
||||
configuration: config,
|
||||
startTimeUtc: currentTimeUtc,
|
||||
endTimeUtc: maximumEndTimeUtc)};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,29 +74,30 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "7"},
|
||||
{"Average Win", "0.01%"},
|
||||
{"Average Loss", "-0.40%"},
|
||||
{"Compounding Annual Return", "1114.772%"},
|
||||
{"Compounding Annual Return", "1143.086%"},
|
||||
{"Drawdown", "1.800%"},
|
||||
{"Expectancy", "-0.319"},
|
||||
{"Net Profit", "3.244%"},
|
||||
{"Sharpe Ratio", "23.478"},
|
||||
{"Probabilistic Sharpe Ratio", "80.383%"},
|
||||
{"Net Profit", "3.275%"},
|
||||
{"Sharpe Ratio", "23.495"},
|
||||
{"Probabilistic Sharpe Ratio", "80.494%"},
|
||||
{"Loss Rate", "33%"},
|
||||
{"Win Rate", "67%"},
|
||||
{"Profit-Loss Ratio", "0.02"},
|
||||
{"Alpha", "4.314"},
|
||||
{"Beta", "1.239"},
|
||||
{"Annual Standard Deviation", "0.285"},
|
||||
{"Annual Variance", "0.081"},
|
||||
{"Information Ratio", "47.452"},
|
||||
{"Tracking Error", "0.101"},
|
||||
{"Treynor Ratio", "5.409"},
|
||||
{"Total Fees", "$67.00"},
|
||||
{"Estimated Strategy Capacity", "$3200000.00"},
|
||||
{"Alpha", "4.366"},
|
||||
{"Beta", "1.255"},
|
||||
{"Annual Standard Deviation", "0.292"},
|
||||
{"Annual Variance", "0.085"},
|
||||
{"Information Ratio", "47.955"},
|
||||
{"Tracking Error", "0.102"},
|
||||
{"Treynor Ratio", "5.461"},
|
||||
{"Total Fees", "$71.37"},
|
||||
{"Estimated Strategy Capacity", "$3500000.00"},
|
||||
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.501"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "148.636"},
|
||||
{"Return Over Maximum Drawdown", "1502.912"},
|
||||
{"Sortino Ratio", "148.07"},
|
||||
{"Return Over Maximum Drawdown", "1487.238"},
|
||||
{"Portfolio Turnover", "0.501"},
|
||||
{"Total Insights Generated", "2"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -111,7 +112,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "ba44309886ea8ff515ef593a24456c47"}
|
||||
{"OrderListHash", "5a171f804d47cd27f84aaef791da8594"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,31 +66,32 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "7"},
|
||||
{"Average Win", "1.02%"},
|
||||
{"Average Win", "1.01%"},
|
||||
{"Average Loss", "-1.01%"},
|
||||
{"Compounding Annual Return", "205.606%"},
|
||||
{"Compounding Annual Return", "210.936%"},
|
||||
{"Drawdown", "2.200%"},
|
||||
{"Expectancy", "0.339"},
|
||||
{"Net Profit", "1.439%"},
|
||||
{"Sharpe Ratio", "7.166"},
|
||||
{"Probabilistic Sharpe Ratio", "64.794%"},
|
||||
{"Net Profit", "1.461%"},
|
||||
{"Sharpe Ratio", "7.289"},
|
||||
{"Probabilistic Sharpe Ratio", "65.077%"},
|
||||
{"Loss Rate", "33%"},
|
||||
{"Win Rate", "67%"},
|
||||
{"Profit-Loss Ratio", "1.01"},
|
||||
{"Alpha", "-0.341"},
|
||||
{"Alpha", "-0.349"},
|
||||
{"Beta", "0.968"},
|
||||
{"Annual Standard Deviation", "0.213"},
|
||||
{"Annual Variance", "0.045"},
|
||||
{"Information Ratio", "-46.719"},
|
||||
{"Annual Standard Deviation", "0.216"},
|
||||
{"Annual Variance", "0.046"},
|
||||
{"Information Ratio", "-47.59"},
|
||||
{"Tracking Error", "0.009"},
|
||||
{"Treynor Ratio", "1.575"},
|
||||
{"Total Fees", "$22.77"},
|
||||
{"Estimated Strategy Capacity", "$22000000.00"},
|
||||
{"Treynor Ratio", "1.623"},
|
||||
{"Total Fees", "$24.07"},
|
||||
{"Estimated Strategy Capacity", "$23000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.999"},
|
||||
{"Kelly Criterion Estimate", "38.64"},
|
||||
{"Kelly Criterion Probability Value", "0.229"},
|
||||
{"Kelly Criterion Estimate", "38.796"},
|
||||
{"Kelly Criterion Probability Value", "0.228"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "69.159"},
|
||||
{"Return Over Maximum Drawdown", "69.017"},
|
||||
{"Portfolio Turnover", "1.242"},
|
||||
{"Total Insights Generated", "100"},
|
||||
{"Total Insights Closed", "99"},
|
||||
@@ -98,14 +99,14 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Long Insight Count", "100"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$126657.6305"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$20405.9516"},
|
||||
{"Mean Population Estimated Insight Value", "$206.1207"},
|
||||
{"Mean Population Direction", "54.5455%"},
|
||||
{"Mean Population Magnitude", "54.5455%"},
|
||||
{"Rolling Averaged Population Direction", "59.8056%"},
|
||||
{"Rolling Averaged Population Magnitude", "59.8056%"},
|
||||
{"OrderListHash", "e0f388bf9e88b34388c866150b292573"}
|
||||
{"Estimated Monthly Alpha Value", "$135639.1761"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
|
||||
{"Mean Population Estimated Insight Value", "$220.7372"},
|
||||
{"Mean Population Direction", "53.5354%"},
|
||||
{"Mean Population Magnitude", "53.5354%"},
|
||||
{"Rolling Averaged Population Direction", "58.2788%"},
|
||||
{"Rolling Averaged Population Magnitude", "58.2788%"},
|
||||
{"OrderListHash", "d8d556bcf963ba50f85cea387c55922b"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,10 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
// Set requested data resolution
|
||||
UniverseSettings.Resolution = Resolution.Minute;
|
||||
|
||||
// Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
|
||||
// Commented so regression algorithm is more sensitive
|
||||
//Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;
|
||||
|
||||
SetStartDate(2013, 10, 07); //Set Start Date
|
||||
SetEndDate(2013, 10, 11); //Set End Date
|
||||
SetCash(100000); //Set Strategy Cash
|
||||
@@ -74,47 +78,48 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "6"},
|
||||
{"Average Win", "0.00%"},
|
||||
{"Total Trades", "17"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0.00%"},
|
||||
{"Compounding Annual Return", "38.059%"},
|
||||
{"Compounding Annual Return", "37.229%"},
|
||||
{"Drawdown", "0.600%"},
|
||||
{"Expectancy", "-0.502"},
|
||||
{"Net Profit", "0.413%"},
|
||||
{"Sharpe Ratio", "5.518"},
|
||||
{"Probabilistic Sharpe Ratio", "66.933%"},
|
||||
{"Loss Rate", "67%"},
|
||||
{"Win Rate", "33%"},
|
||||
{"Profit-Loss Ratio", "0.50"},
|
||||
{"Alpha", "-0.178"},
|
||||
{"Beta", "0.249"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "0.405%"},
|
||||
{"Sharpe Ratio", "5.424"},
|
||||
{"Probabilistic Sharpe Ratio", "66.818%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.191"},
|
||||
{"Beta", "0.247"},
|
||||
{"Annual Standard Deviation", "0.055"},
|
||||
{"Annual Variance", "0.003"},
|
||||
{"Information Ratio", "-9.844"},
|
||||
{"Tracking Error", "0.165"},
|
||||
{"Treynor Ratio", "1.212"},
|
||||
{"Total Fees", "$6.00"},
|
||||
{"Estimated Strategy Capacity", "$42000000.00"},
|
||||
{"Fitness Score", "0.063"},
|
||||
{"Kelly Criterion Estimate", "38.64"},
|
||||
{"Kelly Criterion Probability Value", "0.229"},
|
||||
{"Information Ratio", "-10.052"},
|
||||
{"Tracking Error", "0.168"},
|
||||
{"Treynor Ratio", "1.207"},
|
||||
{"Total Fees", "$17.00"},
|
||||
{"Estimated Strategy Capacity", "$45000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.067"},
|
||||
{"Kelly Criterion Estimate", "38.796"},
|
||||
{"Kelly Criterion Probability Value", "0.228"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "70.188"},
|
||||
{"Portfolio Turnover", "0.063"},
|
||||
{"Return Over Maximum Drawdown", "65.855"},
|
||||
{"Portfolio Turnover", "0.067"},
|
||||
{"Total Insights Generated", "100"},
|
||||
{"Total Insights Closed", "99"},
|
||||
{"Total Insights Analysis Completed", "99"},
|
||||
{"Long Insight Count", "100"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$126657.6305"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$20405.9516"},
|
||||
{"Mean Population Estimated Insight Value", "$206.1207"},
|
||||
{"Mean Population Direction", "54.5455%"},
|
||||
{"Mean Population Magnitude", "54.5455%"},
|
||||
{"Rolling Averaged Population Direction", "59.8056%"},
|
||||
{"Rolling Averaged Population Magnitude", "59.8056%"},
|
||||
{"OrderListHash", "07eb3e2c199575b547459a534057eb5e"}
|
||||
{"Estimated Monthly Alpha Value", "$135639.1761"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
|
||||
{"Mean Population Estimated Insight Value", "$220.7372"},
|
||||
{"Mean Population Direction", "53.5354%"},
|
||||
{"Mean Population Magnitude", "53.5354%"},
|
||||
{"Rolling Averaged Population Direction", "58.2788%"},
|
||||
{"Rolling Averaged Population Magnitude", "58.2788%"},
|
||||
{"OrderListHash", "8a8c913e5ad4ea956a345c84430649c2"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,24 +147,25 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "-99.999%"},
|
||||
{"Drawdown", "16.100%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "-6.366%"},
|
||||
{"Sharpe Ratio", "1.194"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "5.579"},
|
||||
{"Beta", "-63.972"},
|
||||
{"Annual Standard Deviation", "0.434"},
|
||||
{"Annual Variance", "0.188"},
|
||||
{"Information Ratio", "0.996"},
|
||||
{"Tracking Error", "0.441"},
|
||||
{"Treynor Ratio", "-0.008"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$20.35"},
|
||||
{"Estimated Strategy Capacity", "$19000000.00"},
|
||||
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
|
||||
{"Fitness Score", "0.138"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
|
||||
@@ -35,7 +35,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
SetCash(100000); // Set Strategy Cash
|
||||
|
||||
// Add QC500 Universe
|
||||
AddUniverse(Universe.Index.QC500);
|
||||
AddUniverse(Universe.QC500);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,30 +172,31 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.52%"},
|
||||
{"Compounding Annual Return", "-31.636%"},
|
||||
{"Average Loss", "-0.54%"},
|
||||
{"Compounding Annual Return", "-32.671%"},
|
||||
{"Drawdown", "0.900%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.520%"},
|
||||
{"Sharpe Ratio", "-3.097"},
|
||||
{"Probabilistic Sharpe Ratio", "24.675%"},
|
||||
{"Net Profit", "-0.540%"},
|
||||
{"Sharpe Ratio", "-3.349"},
|
||||
{"Probabilistic Sharpe Ratio", "25.715%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.443"},
|
||||
{"Beta", "0.157"},
|
||||
{"Annual Standard Deviation", "0.074"},
|
||||
{"Annual Variance", "0.005"},
|
||||
{"Information Ratio", "-9.046"},
|
||||
{"Tracking Error", "0.176"},
|
||||
{"Treynor Ratio", "-1.46"},
|
||||
{"Total Fees", "$7.82"},
|
||||
{"Estimated Strategy Capacity", "$12000000.00"},
|
||||
{"Alpha", "-0.724"},
|
||||
{"Beta", "0.22"},
|
||||
{"Annual Standard Deviation", "0.086"},
|
||||
{"Annual Variance", "0.007"},
|
||||
{"Information Ratio", "-12.125"},
|
||||
{"Tracking Error", "0.187"},
|
||||
{"Treynor Ratio", "-1.304"},
|
||||
{"Total Fees", "$32.32"},
|
||||
{"Estimated Strategy Capacity", "$95000000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.1"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-35.683"},
|
||||
{"Return Over Maximum Drawdown", "-36.199"},
|
||||
{"Portfolio Turnover", "0.2"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -210,7 +211,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "71984e154883ece4aef1d71bafbfccaf"}
|
||||
{"OrderListHash", "3b9c93151bf191a82529e6e915961356"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
/*
|
||||
* 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.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Data.Market;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Securities.Future;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Continuous Back Month Raw Futures Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
|
||||
/// </summary>
|
||||
public class ContinuousBackMonthRawFutureRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private List<SymbolChangedEvent> _mappings = new();
|
||||
private Future _continuousContract;
|
||||
private DateTime _lastDateLog;
|
||||
|
||||
/// <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, 7, 1);
|
||||
SetEndDate(2014, 1, 1);
|
||||
|
||||
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.Raw,
|
||||
dataMappingMode: DataMappingMode.FirstDayMonth,
|
||||
contractDepthOffset: 1
|
||||
);
|
||||
}
|
||||
|
||||
/// <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 (data.Keys.Count != 1)
|
||||
{
|
||||
throw new Exception($"We are getting data for more than one symbols! {string.Join(",", data.Keys.Select(symbol => symbol))}");
|
||||
}
|
||||
|
||||
foreach (var changedEvent in data.SymbolChangedEvents.Values)
|
||||
{
|
||||
if (changedEvent.Symbol == _continuousContract.Symbol)
|
||||
{
|
||||
_mappings.Add(changedEvent);
|
||||
Log($"SymbolChanged event: {changedEvent}");
|
||||
|
||||
var currentExpiration = changedEvent.Symbol.Underlying.ID.Date;
|
||||
// +4 months cause we are actually using the back month, es is quarterly contract
|
||||
var frontMonthExpiration = FuturesExpiryFunctions.FuturesExpiryFunction(_continuousContract.Symbol)(Time.AddMonths(1 + 4));
|
||||
|
||||
if (currentExpiration != frontMonthExpiration.Date)
|
||||
{
|
||||
throw new Exception($"Unexpected current mapped contract expiration {currentExpiration}" +
|
||||
$" @ {Time} it should be AT front month expiration {frontMonthExpiration}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (_lastDateLog.Month != Time.Month && _continuousContract.HasData)
|
||||
{
|
||||
_lastDateLog = Time;
|
||||
|
||||
Log($"{Time}- {Securities[_continuousContract.Symbol].GetLastData()}");
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
else
|
||||
{
|
||||
// This works because we set this contract as tradable, even if it's a canonical security
|
||||
Buy(_continuousContract.Symbol, 1);
|
||||
}
|
||||
|
||||
if(Time.Month == 1 && Time.Year == 2013)
|
||||
{
|
||||
var response = History(new[] { _continuousContract.Symbol }, 60 * 24 * 90);
|
||||
if (!response.Any())
|
||||
{
|
||||
throw new Exception("Unexpected empty history response");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status == OrderStatus.Filled)
|
||||
{
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
var expectedMappingCounts = 2;
|
||||
if (_mappings.Count != expectedMappingCounts)
|
||||
{
|
||||
throw new Exception($"Unexpected symbol changed events: {_mappings.Count}, was expecting {expectedMappingCounts}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "1.16%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "2.311%"},
|
||||
{"Drawdown", "1.600%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.159%"},
|
||||
{"Sharpe Ratio", "0.753"},
|
||||
{"Probabilistic Sharpe Ratio", "39.483%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.006"},
|
||||
{"Beta", "0.099"},
|
||||
{"Annual Standard Deviation", "0.022"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-2.732"},
|
||||
{"Tracking Error", "0.076"},
|
||||
{"Treynor Ratio", "0.165"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Estimated Strategy Capacity", "$3900000.00"},
|
||||
{"Lowest Capacity Asset", "ES 1S1"},
|
||||
{"Fitness Score", "0.007"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "0.563"},
|
||||
{"Return Over Maximum Drawdown", "1.87"},
|
||||
{"Portfolio Turnover", "0.01"},
|
||||
{"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", "8aa2ed1319e8bb5beb403476a5aebfef"}
|
||||
};
|
||||
}
|
||||
}
|
||||
197
Algorithm.CSharp/ContinuousFutureBackMonthRegressionAlgorithm.cs
Normal file
197
Algorithm.CSharp/ContinuousFutureBackMonthRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* 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.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Data.Market;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Securities.Future;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Continuous Futures Back Month #1 Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
|
||||
/// </summary>
|
||||
public class ContinuousFutureBackMonthRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private List<SymbolChangedEvent> _mappings = new();
|
||||
private Future _continuousContract;
|
||||
private DateTime _lastDateLog;
|
||||
|
||||
/// <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, 7, 1);
|
||||
SetEndDate(2014, 1, 1);
|
||||
|
||||
try
|
||||
{
|
||||
AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.BackwardsPanamaCanal,
|
||||
dataMappingMode: DataMappingMode.OpenInterest,
|
||||
contractDepthOffset: 5
|
||||
);
|
||||
throw new Exception("Expected out of rage exception. We don't support that many back months");
|
||||
}
|
||||
catch (ArgumentOutOfRangeException)
|
||||
{
|
||||
// expected
|
||||
}
|
||||
|
||||
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.BackwardsPanamaCanal,
|
||||
dataMappingMode: DataMappingMode.OpenInterest,
|
||||
contractDepthOffset: 1
|
||||
);
|
||||
}
|
||||
|
||||
/// <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 (data.Keys.Count != 1)
|
||||
{
|
||||
throw new Exception($"We are getting data for more than one symbols! {string.Join(",", data.Keys.Select(symbol => symbol))}");
|
||||
}
|
||||
|
||||
foreach (var changedEvent in data.SymbolChangedEvents.Values)
|
||||
{
|
||||
if (changedEvent.Symbol == _continuousContract.Symbol)
|
||||
{
|
||||
_mappings.Add(changedEvent);
|
||||
Log($"SymbolChanged event: {changedEvent}");
|
||||
|
||||
var backMonthExpiration = changedEvent.Symbol.Underlying.ID.Date;
|
||||
var frontMonthExpiration = FuturesExpiryFunctions.FuturesExpiryFunction(_continuousContract.Symbol)(Time.AddMonths(1));
|
||||
|
||||
if (backMonthExpiration <= frontMonthExpiration.Date)
|
||||
{
|
||||
throw new Exception($"Unexpected current mapped contract expiration {backMonthExpiration}" +
|
||||
$" @ {Time} it should be AFTER front month expiration {frontMonthExpiration}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (_lastDateLog.Month != Time.Month && _continuousContract.HasData)
|
||||
{
|
||||
_lastDateLog = Time;
|
||||
|
||||
Log($"{Time}- {Securities[_continuousContract.Symbol].GetLastData()}");
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
else
|
||||
{
|
||||
// This works because we set this contract as tradable, even if it's a canonical security
|
||||
Buy(_continuousContract.Symbol, 1);
|
||||
}
|
||||
|
||||
if(Time.Month == 1 && Time.Year == 2013)
|
||||
{
|
||||
var response = History(new[] { _continuousContract.Symbol }, 60 * 24 * 90);
|
||||
if (!response.Any())
|
||||
{
|
||||
throw new Exception("Unexpected empty history response");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status == OrderStatus.Filled)
|
||||
{
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
var expectedMappingCounts = 2;
|
||||
if (_mappings.Count != expectedMappingCounts)
|
||||
{
|
||||
throw new Exception($"Unexpected symbol changed events: {_mappings.Count}, was expecting {expectedMappingCounts}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "1.16%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "2.229%"},
|
||||
{"Drawdown", "1.600%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.118%"},
|
||||
{"Sharpe Ratio", "0.726"},
|
||||
{"Probabilistic Sharpe Ratio", "38.511%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.007"},
|
||||
{"Beta", "0.099"},
|
||||
{"Annual Standard Deviation", "0.022"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-2.74"},
|
||||
{"Tracking Error", "0.076"},
|
||||
{"Treynor Ratio", "0.159"},
|
||||
{"Total Fees", "$5.55"},
|
||||
{"Estimated Strategy Capacity", "$290000.00"},
|
||||
{"Lowest Capacity Asset", "ES 1S1"},
|
||||
{"Fitness Score", "0.009"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "0.498"},
|
||||
{"Return Over Maximum Drawdown", "1.803"},
|
||||
{"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", "e669103cc598f59d85f5e8d5f0b8df30"}
|
||||
};
|
||||
}
|
||||
}
|
||||
152
Algorithm.CSharp/ContinuousFutureHistoryRegressionAlgorithm.cs
Normal file
152
Algorithm.CSharp/ContinuousFutureHistoryRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,152 @@
|
||||
/*
|
||||
* 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 QuantConnect.Securities;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Securities.Future;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Continuous Futures History Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
|
||||
/// </summary>
|
||||
public class ContinuousFutureHistoryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Future _continuousContract;
|
||||
private bool _warmedUp;
|
||||
|
||||
/// <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, 10);
|
||||
SetEndDate(2013, 10, 11);
|
||||
|
||||
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
|
||||
dataMappingMode: DataMappingMode.OpenInterest,
|
||||
contractDepthOffset: 1
|
||||
);
|
||||
SetWarmup(10);
|
||||
}
|
||||
|
||||
/// <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 (IsWarmingUp)
|
||||
{
|
||||
// warm up data
|
||||
_warmedUp = true;
|
||||
|
||||
if (!_continuousContract.HasData)
|
||||
{
|
||||
throw new Exception($"ContinuousContract did not get any data during warmup!");
|
||||
}
|
||||
|
||||
var backMonthExpiration = data.Keys.Single().Underlying.ID.Date;
|
||||
var frontMonthExpiration = FuturesExpiryFunctions.FuturesExpiryFunction(_continuousContract.Symbol)(Time.AddMonths(1));
|
||||
if (backMonthExpiration <= frontMonthExpiration.Date)
|
||||
{
|
||||
throw new Exception($"Unexpected current mapped contract expiration {backMonthExpiration}" +
|
||||
$" @ {Time} it should be AFTER front month expiration {frontMonthExpiration}");
|
||||
}
|
||||
}
|
||||
if (data.Keys.Count != 1)
|
||||
{
|
||||
throw new Exception($"We are getting data for more than one symbols! {string.Join(",", data.Keys.Select(symbol => symbol))}");
|
||||
}
|
||||
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
Buy(_continuousContract.Symbol, 1);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (!_warmedUp)
|
||||
{
|
||||
throw new Exception("Algorithm didn't warm up!");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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%"},
|
||||
{"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.85"},
|
||||
{"Estimated Strategy Capacity", "$42000000.00"},
|
||||
{"Lowest Capacity Asset", "ES 1S1"},
|
||||
{"Fitness Score", "0.76"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0.76"},
|
||||
{"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", "4de9344671d542e30066338e2bf9d400"}
|
||||
};
|
||||
}
|
||||
}
|
||||
207
Algorithm.CSharp/ContinuousFutureRegressionAlgorithm.cs
Normal file
207
Algorithm.CSharp/ContinuousFutureRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,207 @@
|
||||
/*
|
||||
* 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.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Data.Market;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Securities.Future;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Continuous Futures Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
|
||||
/// </summary>
|
||||
public class ContinuousFutureRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private List<SymbolChangedEvent> _mappings = new();
|
||||
private Symbol _currentMappedSymbol;
|
||||
private Future _continuousContract;
|
||||
private DateTime _lastMonth;
|
||||
|
||||
/// <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, 7, 1);
|
||||
SetEndDate(2014, 1, 1);
|
||||
|
||||
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
|
||||
dataMappingMode: DataMappingMode.LastTradingDay,
|
||||
contractDepthOffset: 0
|
||||
);
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
// we subtract a minute cause we can get data on the market close, from the previous minute
|
||||
if (!_continuousContract.Exchange.DateTimeIsOpen(Time.AddMinutes(-1)))
|
||||
{
|
||||
if (data.Bars.Count > 0 || data.QuoteBars.Count > 0)
|
||||
{
|
||||
throw new Exception($"We are getting data during closed market!");
|
||||
}
|
||||
}
|
||||
|
||||
var currentlyMappedSecurity = Securities[_continuousContract.Mapped];
|
||||
|
||||
if (data.Keys.Count != 1)
|
||||
{
|
||||
throw new Exception($"We are getting data for more than one symbols! {string.Join(",", data.Keys.Select(symbol => symbol))}");
|
||||
}
|
||||
|
||||
foreach (var changedEvent in data.SymbolChangedEvents.Values)
|
||||
{
|
||||
if (changedEvent.Symbol == _continuousContract.Symbol)
|
||||
{
|
||||
_mappings.Add(changedEvent);
|
||||
Log($"{Time} - SymbolChanged event: {changedEvent}");
|
||||
|
||||
if (_currentMappedSymbol == _continuousContract.Mapped)
|
||||
{
|
||||
throw new Exception($"Continuous contract current symbol did not change! {_continuousContract.Mapped}");
|
||||
}
|
||||
|
||||
var currentExpiration = changedEvent.Symbol.Underlying.ID.Date;
|
||||
var frontMonthExpiration = FuturesExpiryFunctions.FuturesExpiryFunction(_continuousContract.Symbol)(Time.AddMonths(1));
|
||||
|
||||
if (currentExpiration != frontMonthExpiration.Date)
|
||||
{
|
||||
throw new Exception($"Unexpected current mapped contract expiration {currentExpiration}" +
|
||||
$" @ {Time} it should be AT front month expiration {frontMonthExpiration}");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (_lastMonth.Month != Time.Month && currentlyMappedSecurity.HasData)
|
||||
{
|
||||
_lastMonth = Time;
|
||||
|
||||
Log($"{Time}- {currentlyMappedSecurity.GetLastData()}");
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
else
|
||||
{
|
||||
// This works because we set this contract as tradable, even if it's a canonical security
|
||||
Buy(currentlyMappedSecurity.Symbol, 1);
|
||||
}
|
||||
|
||||
if(Time.Month == 1 && Time.Year == 2013)
|
||||
{
|
||||
var response = History(new[] { _continuousContract.Symbol }, 60 * 24 * 90);
|
||||
if (!response.Any())
|
||||
{
|
||||
throw new Exception("Unexpected empty history response");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_currentMappedSymbol = _continuousContract.Mapped;
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status == OrderStatus.Filled)
|
||||
{
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
Debug($"{Time}-{changes}");
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
var expectedMappingCounts = 2;
|
||||
if (_mappings.Count != expectedMappingCounts)
|
||||
{
|
||||
throw new Exception($"Unexpected symbol changed events: {_mappings.Count}, was expecting {expectedMappingCounts}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "3"},
|
||||
{"Average Win", "1.21%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "2.392%"},
|
||||
{"Drawdown", "1.600%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.199%"},
|
||||
{"Sharpe Ratio", "0.775"},
|
||||
{"Probabilistic Sharpe Ratio", "40.287%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.006"},
|
||||
{"Beta", "0.099"},
|
||||
{"Annual Standard Deviation", "0.022"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-2.726"},
|
||||
{"Tracking Error", "0.076"},
|
||||
{"Treynor Ratio", "0.169"},
|
||||
{"Total Fees", "$5.55"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
|
||||
{"Fitness Score", "0.01"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "0.516"},
|
||||
{"Return Over Maximum Drawdown", "1.935"},
|
||||
{"Portfolio Turnover", "0.016"},
|
||||
{"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", "8ad040c62ad255e4f9cd423364147e85"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -128,29 +128,30 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
{"Total Trades", "85"},
|
||||
{"Average Win", "4.85%"},
|
||||
{"Average Loss", "-4.21%"},
|
||||
{"Compounding Annual Return", "-3.100%"},
|
||||
{"Drawdown", "52.900%"},
|
||||
{"Expectancy", "-0.052"},
|
||||
{"Net Profit", "-29.298%"},
|
||||
{"Sharpe Ratio", "-0.076"},
|
||||
{"Probabilistic Sharpe Ratio", "0.004%"},
|
||||
{"Average Loss", "-4.22%"},
|
||||
{"Compounding Annual Return", "-3.124%"},
|
||||
{"Drawdown", "53.000%"},
|
||||
{"Expectancy", "-0.053"},
|
||||
{"Net Profit", "-29.486%"},
|
||||
{"Sharpe Ratio", "-0.072"},
|
||||
{"Probabilistic Sharpe Ratio", "0.001%"},
|
||||
{"Loss Rate", "56%"},
|
||||
{"Win Rate", "44%"},
|
||||
{"Profit-Loss Ratio", "1.15"},
|
||||
{"Alpha", "-0.013"},
|
||||
{"Beta", "0.009"},
|
||||
{"Annual Standard Deviation", "0.164"},
|
||||
{"Annual Variance", "0.027"},
|
||||
{"Information Ratio", "-0.391"},
|
||||
{"Tracking Error", "0.239"},
|
||||
{"Treynor Ratio", "-1.435"},
|
||||
{"Total Fees", "$755.29"},
|
||||
{"Estimated Strategy Capacity", "$1100000000.00"},
|
||||
{"Alpha", "-0.004"},
|
||||
{"Beta", "-0.095"},
|
||||
{"Annual Standard Deviation", "0.149"},
|
||||
{"Annual Variance", "0.022"},
|
||||
{"Information Ratio", "-0.34"},
|
||||
{"Tracking Error", "0.23"},
|
||||
{"Treynor Ratio", "0.113"},
|
||||
{"Total Fees", "$796.82"},
|
||||
{"Estimated Strategy Capacity", "$1200000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.024"},
|
||||
{"Kelly Criterion Estimate", "-0.84"},
|
||||
{"Kelly Criterion Probability Value", "0.53"},
|
||||
{"Sortino Ratio", "-0.224"},
|
||||
{"Kelly Criterion Estimate", "-0.9"},
|
||||
{"Kelly Criterion Probability Value", "0.532"},
|
||||
{"Sortino Ratio", "-0.228"},
|
||||
{"Return Over Maximum Drawdown", "-0.058"},
|
||||
{"Portfolio Turnover", "0.05"},
|
||||
{"Total Insights Generated", "85"},
|
||||
@@ -159,14 +160,14 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Long Insight Count", "42"},
|
||||
{"Short Insight Count", "43"},
|
||||
{"Long/Short Ratio", "97.67%"},
|
||||
{"Estimated Monthly Alpha Value", "$-617339.2"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$-82686580"},
|
||||
{"Mean Population Estimated Insight Value", "$-972783.3"},
|
||||
{"Estimated Monthly Alpha Value", "$-719932.6"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$-96427970"},
|
||||
{"Mean Population Estimated Insight Value", "$-1134447"},
|
||||
{"Mean Population Direction", "51.7647%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "48.2217%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "95f34359f25a7a7a2725f0343a75a105"}
|
||||
{"OrderListHash", "177fb7f308a252864365442a30dd9eeb"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,29 +82,30 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "264.819%"},
|
||||
{"Compounding Annual Return", "272.157%"},
|
||||
{"Drawdown", "2.200%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.668%"},
|
||||
{"Sharpe Ratio", "8.749"},
|
||||
{"Probabilistic Sharpe Ratio", "67.311%"},
|
||||
{"Net Profit", "1.694%"},
|
||||
{"Sharpe Ratio", "8.897"},
|
||||
{"Probabilistic Sharpe Ratio", "67.609%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "1.119"},
|
||||
{"Beta", "0.805"},
|
||||
{"Annual Standard Deviation", "0.219"},
|
||||
{"Annual Variance", "0.048"},
|
||||
{"Information Ratio", "5.494"},
|
||||
{"Tracking Error", "0.168"},
|
||||
{"Treynor Ratio", "2.38"},
|
||||
{"Total Fees", "$3.26"},
|
||||
{"Estimated Strategy Capacity", "$300000000.00"},
|
||||
{"Fitness Score", "0.245"},
|
||||
{"Alpha", "1.144"},
|
||||
{"Beta", "0.842"},
|
||||
{"Annual Standard Deviation", "0.222"},
|
||||
{"Annual Variance", "0.049"},
|
||||
{"Information Ratio", "5.987"},
|
||||
{"Tracking Error", "0.165"},
|
||||
{"Treynor Ratio", "2.347"},
|
||||
{"Total Fees", "$3.45"},
|
||||
{"Estimated Strategy Capacity", "$310000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.246"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "9.606"},
|
||||
{"Return Over Maximum Drawdown", "105.85"},
|
||||
{"Sortino Ratio", "9.761"},
|
||||
{"Return Over Maximum Drawdown", "107.509"},
|
||||
{"Portfolio Turnover", "0.249"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -119,7 +120,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "9cd604d2c1e3c273697e2ff2cc7faef1"}
|
||||
{"OrderListHash", "e10039d74166b161f3ea2851a5e85843"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,12 +79,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "37.355%"},
|
||||
{"Compounding Annual Return", "34.768%"},
|
||||
{"Drawdown", "2.300%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.407%"},
|
||||
{"Sharpe Ratio", "5.521"},
|
||||
{"Probabilistic Sharpe Ratio", "60.177%"},
|
||||
{"Net Profit", "0.382%"},
|
||||
{"Sharpe Ratio", "5.488"},
|
||||
{"Probabilistic Sharpe Ratio", "60.047%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
@@ -92,17 +92,18 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Beta", "0.997"},
|
||||
{"Annual Standard Deviation", "0.179"},
|
||||
{"Annual Variance", "0.032"},
|
||||
{"Information Ratio", "-7.662"},
|
||||
{"Information Ratio", "-7.724"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0.988"},
|
||||
{"Total Fees", "$7.78"},
|
||||
{"Estimated Strategy Capacity", "$8700000.00"},
|
||||
{"Fitness Score", "0.031"},
|
||||
{"Treynor Ratio", "0.986"},
|
||||
{"Total Fees", "$32.11"},
|
||||
{"Estimated Strategy Capacity", "$66000000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.029"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-2.145"},
|
||||
{"Return Over Maximum Drawdown", "-8.479"},
|
||||
{"Portfolio Turnover", "0.25"},
|
||||
{"Sortino Ratio", "-2.336"},
|
||||
{"Return Over Maximum Drawdown", "-8.991"},
|
||||
{"Portfolio Turnover", "0.251"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -116,7 +117,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "be3334e4aeb9dd7cca4ecc07419d0f95"}
|
||||
{"OrderListHash", "b7b8e83e4456e143c2c4c11fa31a1cf2"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,7 +74,11 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public override HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerForOrder(
|
||||
HasSufficientBuyingPowerForOrderParameters parameters)
|
||||
{
|
||||
return new HasSufficientBuyingPowerForOrderResult(true);
|
||||
// if portfolio doesn't have enough buying power:
|
||||
// parameters.Insufficient()
|
||||
|
||||
// this model never allows a lack of funds get in the way of buying securities
|
||||
return parameters.Sufficient();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,30 +100,31 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "5672.520%"},
|
||||
{"Drawdown", "22.500%"},
|
||||
{"Compounding Annual Return", "4775.196%"},
|
||||
{"Drawdown", "21.600%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "40.601%"},
|
||||
{"Sharpe Ratio", "40.201"},
|
||||
{"Probabilistic Sharpe Ratio", "77.339%"},
|
||||
{"Net Profit", "38.619%"},
|
||||
{"Sharpe Ratio", "14.33"},
|
||||
{"Probabilistic Sharpe Ratio", "75.756%"},
|
||||
{"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"},
|
||||
{"Alpha", "10.389"},
|
||||
{"Beta", "8.754"},
|
||||
{"Annual Standard Deviation", "0.95"},
|
||||
{"Annual Variance", "0.903"},
|
||||
{"Information Ratio", "15.703"},
|
||||
{"Tracking Error", "0.844"},
|
||||
{"Treynor Ratio", "1.555"},
|
||||
{"Total Fees", "$30.00"},
|
||||
{"Estimated Strategy Capacity", "$20000000.00"},
|
||||
{"Fitness Score", "0.418"},
|
||||
{"Estimated Strategy Capacity", "$22000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.395"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "113.05"},
|
||||
{"Return Over Maximum Drawdown", "442.81"},
|
||||
{"Portfolio Turnover", "0.418"},
|
||||
{"Sortino Ratio", "98.148"},
|
||||
{"Return Over Maximum Drawdown", "384.626"},
|
||||
{"Portfolio Turnover", "0.395"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -133,7 +138,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "b88362c462e9ab2942cbcb8dfddc6ce0"}
|
||||
{"OrderListHash", "eba70a03119f2e8fe526d1092fbc36d0"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
@@ -172,4 +172,4 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user