Compare commits
340 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d94a1d09a4 | ||
|
|
2c843cae9e | ||
|
|
039fdf7e4a | ||
|
|
2c63546c37 | ||
|
|
58682e1bbd | ||
|
|
d11a375fdb | ||
|
|
6ab91a13e1 | ||
|
|
beaa705646 | ||
|
|
4c830c8235 | ||
|
|
395c1123da | ||
|
|
8e50645640 | ||
|
|
68ca504d3a | ||
|
|
12df1c9a31 | ||
|
|
4de25b6cd4 | ||
|
|
cdef9e709a | ||
|
|
3579fecc58 | ||
|
|
3a390cfa9f | ||
|
|
58dae061e7 | ||
|
|
3f2479393f | ||
|
|
4849588c3b | ||
|
|
3d84c76abb | ||
|
|
1c3d849ad5 | ||
|
|
271220083b | ||
|
|
b29d0cbfaf | ||
|
|
27a25cd663 | ||
|
|
5ed61db2bb | ||
|
|
4a1485a291 | ||
|
|
d6072c88a5 | ||
|
|
20910ca2dc | ||
|
|
c333ccdc4a | ||
|
|
88c4a332bc | ||
|
|
5d762d16b2 | ||
|
|
e2a0873b7c | ||
|
|
31ebaaeaa9 | ||
|
|
7625e232f4 | ||
|
|
63f3af7afe | ||
|
|
87b42f6fb5 | ||
|
|
f9dc38efab | ||
|
|
5587efaadd | ||
|
|
a642d53bf9 | ||
|
|
002151eab2 | ||
|
|
4c085ff853 | ||
|
|
3aa76d4289 | ||
|
|
5236fc202d | ||
|
|
1ca4389ed2 | ||
|
|
b8397db0b7 | ||
|
|
d4ea5f7b04 | ||
|
|
458272b2ea | ||
|
|
6c7353d09a | ||
|
|
834d4a4d58 | ||
|
|
561aa3cf25 | ||
|
|
e4af2ef856 | ||
|
|
3f8158a5be | ||
|
|
0c4a641590 | ||
|
|
20986059a9 | ||
|
|
c22a538bad | ||
|
|
5dcda56a73 | ||
|
|
8076782ea6 | ||
|
|
e869765759 | ||
|
|
c7fb6165e2 | ||
|
|
d9d02bc2d0 | ||
|
|
caedddddf0 | ||
|
|
4e00324b57 | ||
|
|
1b6301d813 | ||
|
|
d24695856d | ||
|
|
17e13665eb | ||
|
|
8c6aa6a3b3 | ||
|
|
83da0affc5 | ||
|
|
60798df64c | ||
|
|
bb20f9d9df | ||
|
|
32686db739 | ||
|
|
7d97f05133 | ||
|
|
8b173f2306 | ||
|
|
9cde4344fc | ||
|
|
785c706d4c | ||
|
|
0dc521f787 | ||
|
|
94d9996b21 | ||
|
|
67b3873205 | ||
|
|
acd9ef4cfd | ||
|
|
7f934b2adf | ||
|
|
596e940ccd | ||
|
|
f38ff0d1f2 | ||
|
|
37d26a35ce | ||
|
|
834326760d | ||
|
|
d4ebd93586 | ||
|
|
0645513f5e | ||
|
|
ecf91546e6 | ||
|
|
c834a1c902 | ||
|
|
43a540cbb1 | ||
|
|
c5bb840bde | ||
|
|
4632840da9 | ||
|
|
ba4c45d729 | ||
|
|
9232427663 | ||
|
|
c30929f612 | ||
|
|
df6e133833 | ||
|
|
2d99afc8c3 | ||
|
|
b3835510d0 | ||
|
|
239fa29bf3 | ||
|
|
df4abd3c3a | ||
|
|
7d93f43d38 | ||
|
|
c435caa7d1 | ||
|
|
643e8754ed | ||
|
|
d17fe34c74 | ||
|
|
512000d500 | ||
|
|
f5e730d776 | ||
|
|
a0f39ec6a4 | ||
|
|
54bbdacd76 | ||
|
|
096e34212c | ||
|
|
6d8e38a692 | ||
|
|
fefac8ab34 | ||
|
|
3f53ba9b2f | ||
|
|
e2964dd4b1 | ||
|
|
a1cbe13bb0 | ||
|
|
17dbadea5b | ||
|
|
d077651f32 | ||
|
|
c02ad0a89f | ||
|
|
aef2a47892 | ||
|
|
bc4dbf5707 | ||
|
|
fe1948d0ae | ||
|
|
254d0896f1 | ||
|
|
115dcab789 | ||
|
|
5117609ea5 | ||
|
|
6040cc8e90 | ||
|
|
eb25dce462 | ||
|
|
0d0389ef6a | ||
|
|
3e962b2e76 | ||
|
|
f263fd49a7 | ||
|
|
9b38bf3d91 | ||
|
|
7d70698c9a | ||
|
|
1606b12475 | ||
|
|
3a483fc4ec | ||
|
|
fe74d037c6 | ||
|
|
43e9cad2d6 | ||
|
|
403ea22606 | ||
|
|
6cb103b17a | ||
|
|
8cbdfcaf28 | ||
|
|
1778462505 | ||
|
|
472896c2d0 | ||
|
|
15cb846570 | ||
|
|
553b50a92e | ||
|
|
5f73a05e04 | ||
|
|
a5eaa43e35 | ||
|
|
e91af0814f | ||
|
|
a2850fb20c | ||
|
|
c86fceac97 | ||
|
|
9997df45af | ||
|
|
1ef92b3eca | ||
|
|
c6d29c8be5 | ||
|
|
97deb4bbc6 | ||
|
|
6ab40c102b | ||
|
|
41417593aa | ||
|
|
3ccf428498 | ||
|
|
5d8a62c2e1 | ||
|
|
5df29f16dd | ||
|
|
56a0d52212 | ||
|
|
765f2cab3b | ||
|
|
f175ac6c6b | ||
|
|
79c544d3a2 | ||
|
|
5dcbed535d | ||
|
|
35393b66a3 | ||
|
|
ce42c888ce | ||
|
|
f2fd10d9d2 | ||
|
|
94d766ff89 | ||
|
|
592d037085 | ||
|
|
17ab10531a | ||
|
|
9d576a4121 | ||
|
|
7aefe07274 | ||
|
|
6de9a146a9 | ||
|
|
4d4ad92fa7 | ||
|
|
345fe7357e | ||
|
|
3e7af17e02 | ||
|
|
a2a874e333 | ||
|
|
96592b3387 | ||
|
|
7e3741d983 | ||
|
|
e6d16882f7 | ||
|
|
d5aa9e65f3 | ||
|
|
ec1c4b7142 | ||
|
|
9a0d943f1d | ||
|
|
771244aaa0 | ||
|
|
659a57884c | ||
|
|
3f2a558f91 | ||
|
|
9bb7c77fb7 | ||
|
|
c8eb9e0099 | ||
|
|
b85a32a391 | ||
|
|
31d101253c | ||
|
|
7531046f14 | ||
|
|
6b99266669 | ||
|
|
8d48996948 | ||
|
|
7f381cb135 | ||
|
|
2b7372783a | ||
|
|
54fce3f666 | ||
|
|
12db2261dc | ||
|
|
c6d4888e70 | ||
|
|
33b58b0dbc | ||
|
|
56cb9fbec5 | ||
|
|
194e6f6b58 | ||
|
|
612c4f8b66 | ||
|
|
d3b9f8bc7a | ||
|
|
c4a1c245a7 | ||
|
|
050dadc21f | ||
|
|
7b0ea0982e | ||
|
|
f8cf923d7b | ||
|
|
14b44bbe17 | ||
|
|
2ed221b623 | ||
|
|
3f1c33e1c5 | ||
|
|
017b464e21 | ||
|
|
4dec21ccc0 | ||
|
|
529d0a3634 | ||
|
|
9c89e8d403 | ||
|
|
1988ad1ae5 | ||
|
|
3658fb1405 | ||
|
|
0ac79487d7 | ||
|
|
38120a3217 | ||
|
|
01a13a095a | ||
|
|
704a5cb00e | ||
|
|
490ad08c89 | ||
|
|
a60cd95611 | ||
|
|
eed8e9c763 | ||
|
|
365f53dfc7 | ||
|
|
48a86c2626 | ||
|
|
2de9c21b6d | ||
|
|
649aafc952 | ||
|
|
25fa4c6fb6 | ||
|
|
d1b35f7974 | ||
|
|
4006ba01e4 | ||
|
|
6d824b40a6 | ||
|
|
8e410fcaf1 | ||
|
|
d136428556 | ||
|
|
40d81965be | ||
|
|
c650eb6c1c | ||
|
|
aa2f9f927a | ||
|
|
c698a65a84 | ||
|
|
181283a4cd | ||
|
|
b247724a34 | ||
|
|
dde3576161 | ||
|
|
e8734a0797 | ||
|
|
7f5d69bbec | ||
|
|
f6be7a41a5 | ||
|
|
7f30c0cd00 | ||
|
|
6694fe01f8 | ||
|
|
32ab4fdea1 | ||
|
|
fc81f606e4 | ||
|
|
ec74abd4d0 | ||
|
|
bd3ead3480 | ||
|
|
45849962a3 | ||
|
|
8279cf7eac | ||
|
|
4c4a699cb0 | ||
|
|
31a2c31c0a | ||
|
|
877a123276 | ||
|
|
4134b05bfd | ||
|
|
43c6d5cc5a | ||
|
|
f39acceadc | ||
|
|
921ddced04 | ||
|
|
ff8563244f | ||
|
|
041f1d9db5 | ||
|
|
eb1181f5f7 | ||
|
|
9d4014b7db | ||
|
|
a4f66628fd | ||
|
|
b9974e6f54 | ||
|
|
474c5cd890 | ||
|
|
0dfb368cb4 | ||
|
|
fbf5300bb6 | ||
|
|
c67845bd45 | ||
|
|
54ddbfbe24 | ||
|
|
bd7be31ede | ||
|
|
041a111b92 | ||
|
|
fa94bcc46a | ||
|
|
2988f7ec3c | ||
|
|
b785877d33 | ||
|
|
5dbb0db2f9 | ||
|
|
a489436743 | ||
|
|
ff2013b0d0 | ||
|
|
567e7b7679 | ||
|
|
646f22a63f | ||
|
|
fd138ec397 | ||
|
|
e98b31fc4c | ||
|
|
d2eae2f652 | ||
|
|
0f0a2bc9a8 | ||
|
|
8ad81dca71 | ||
|
|
f965f34a3f | ||
|
|
06a7d54c38 | ||
|
|
7174fcb9d7 | ||
|
|
29e9d678f2 | ||
|
|
098ac7d0a9 | ||
|
|
6cb4411f6e | ||
|
|
46ef9a9dbb | ||
|
|
d8d8134437 | ||
|
|
9a30c9bd5f | ||
|
|
f76a0efb0e | ||
|
|
7238fcd0f3 | ||
|
|
91e8393aac | ||
|
|
5771635265 | ||
|
|
914486fdb6 | ||
|
|
61fda8b62c | ||
|
|
124ac3b98e | ||
|
|
9dca43bccb | ||
|
|
6efeee07dc | ||
|
|
c452dd3726 | ||
|
|
c602fd0a3f | ||
|
|
104071cda5 | ||
|
|
a5d9526d65 | ||
|
|
8e525c63fc | ||
|
|
d0e9134cc9 | ||
|
|
883d354a98 | ||
|
|
76a53eb096 | ||
|
|
c02ee1b0d8 | ||
|
|
9167882ab2 | ||
|
|
854b987cd0 | ||
|
|
a26414d273 | ||
|
|
84264ca7ef | ||
|
|
b2ed398687 | ||
|
|
e8c316cbcf | ||
|
|
724e52c0b3 | ||
|
|
4252c79e45 | ||
|
|
cbb40dfa43 | ||
|
|
8792fa2600 | ||
|
|
20e9fd7899 | ||
|
|
e05a6bffd0 | ||
|
|
c2f0fdc47a | ||
|
|
b1b8da1e17 | ||
|
|
01a0454c57 | ||
|
|
90e2c48404 | ||
|
|
888c443264 | ||
|
|
03efc1b735 | ||
|
|
6ef2ead929 | ||
|
|
bfd319c91e | ||
|
|
5f61456df8 | ||
|
|
a46a551c03 | ||
|
|
cf9b547e2e | ||
|
|
faa4e91e04 | ||
|
|
cc83f19528 | ||
|
|
54af12b06a | ||
|
|
1d1c8f5f82 | ||
|
|
3966c0e91f | ||
|
|
28160e1301 | ||
|
|
f4679785a5 | ||
|
|
79b9009452 | ||
|
|
e5b5f80d9d | ||
|
|
027fde8f09 | ||
|
|
c7ccd60bf2 |
31
.github/workflows/gh-actions.yml
vendored
Normal file
31
.github/workflows/gh-actions.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
name: Build & Test Lean
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['*']
|
||||
pull_request:
|
||||
branches: [master]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-16.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
|
||||
|
||||
- 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
|
||||
|
||||
- name: Generate & Publish python stubs
|
||||
run: |
|
||||
chmod +x ci_build_stubs.sh
|
||||
./ci_build_stubs.sh -d -t -g #Ignore Publish as of since credentials are missing on CI
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -144,6 +144,7 @@ $tf/
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings
|
||||
*.DotSettings.user
|
||||
|
||||
# JustCode is a .NET coding addin-in
|
||||
@@ -195,6 +196,7 @@ publish/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
!LocalPackages/*
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/packages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
@@ -203,6 +205,7 @@ publish/
|
||||
#!**/packages/repositories.config
|
||||
# ignore sln level nuget
|
||||
.nuget/
|
||||
!.nuget/NuGet.config
|
||||
|
||||
# Windows Azure Build Output
|
||||
csx/
|
||||
@@ -271,3 +274,6 @@ QuantConnect.Lean.sln.DotSettings*
|
||||
|
||||
#User notebook files
|
||||
Research/Notebooks
|
||||
|
||||
#Docker result files
|
||||
Results/
|
||||
18
.idea/Lean.iml
generated
18
.idea/Lean.iml
generated
@@ -1,18 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/Algorithm.Python" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/Algorithm.Python/stubs" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
<component name="PyDocumentationSettings">
|
||||
<option name="format" value="PLAIN" />
|
||||
<option name="myDocStringFormat" value="Plain" />
|
||||
</component>
|
||||
<component name="TestRunnerService">
|
||||
<option name="PROJECT_TEST_RUNNER" value="pytest" />
|
||||
</component>
|
||||
</module>
|
||||
14
.idea/readme.md
generated
14
.idea/readme.md
generated
@@ -91,14 +91,14 @@ From a terminal; Pycharm has a built in terminal on the bottom taskbar labeled *
|
||||
|
||||
2. Using the **run_docker.cfg** to store args for repeated use; any blank entries will resort to default values! example: **_./run_docker.bat run_docker.cfg_**
|
||||
|
||||
image=quantconnect/lean:latest
|
||||
config_file=
|
||||
data_dir=
|
||||
results_dir=
|
||||
debugging=
|
||||
python_dir=
|
||||
IMAGE=quantconnect/lean:latest
|
||||
CONFIG_FILE=
|
||||
DATA_DIR=
|
||||
RESULTS_DIR=
|
||||
DEBUGGING=
|
||||
PYTHON_DIR=
|
||||
|
||||
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat debugging=y_**
|
||||
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat DEBUGGING=y_**
|
||||
* Accepted args for inline include all listed in the file in #2; must follow the **key=value** format
|
||||
|
||||
<br />
|
||||
|
||||
4
.idea/workspace.xml
generated
4
.idea/workspace.xml
generated
@@ -3,7 +3,7 @@
|
||||
<component name="RunManager" selected="Python Debug Server.Debug in Container">
|
||||
<configuration name="Debug Local" type="PyRemoteDebugConfigurationType" factoryName="Python Remote Debug">
|
||||
<module name="LEAN" />
|
||||
<option name="PORT" value="5678" />
|
||||
<option name="PORT" value="6000" />
|
||||
<option name="HOST" value="localhost" />
|
||||
<PathMappingSettings>
|
||||
<option name="pathMappings">
|
||||
@@ -16,7 +16,7 @@
|
||||
</configuration>
|
||||
<configuration name="Debug in Container" type="PyRemoteDebugConfigurationType" factoryName="Python Remote Debug">
|
||||
<module name="LEAN" />
|
||||
<option name="PORT" value="5678" />
|
||||
<option name="PORT" value="6000" />
|
||||
<option name="HOST" value="localhost" />
|
||||
<PathMappingSettings>
|
||||
<option name="pathMappings">
|
||||
|
||||
10
.nuget/NuGet.config
Normal file
10
.nuget/NuGet.config
Normal file
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<packageRestore>
|
||||
<add key="enabled" value="true" />
|
||||
<add key="automatic" value="true" />
|
||||
</packageRestore>
|
||||
<packageSources>
|
||||
<add key="LocalPackages" value="../LocalPackages" />
|
||||
</packageSources>
|
||||
</configuration>
|
||||
12
.travis.yml
12
.travis.yml
@@ -1,11 +1,13 @@
|
||||
sudo: required
|
||||
language: csharp
|
||||
dotnet: 5.0
|
||||
mono:
|
||||
- 5.12.0
|
||||
solution: QuantConnect.Lean.sln
|
||||
before_install:
|
||||
- export PATH="$HOME/miniconda3/bin:$PATH"
|
||||
- wget https://cdn.quantconnect.com/miniconda/Miniconda3-4.5.12-Linux-x86_64.sh
|
||||
- export PYTHONNET_PYDLL="$HOME/miniconda3/lib/libpython3.6m.so"
|
||||
- wget -q https://cdn.quantconnect.com/miniconda/Miniconda3-4.5.12-Linux-x86_64.sh
|
||||
- bash Miniconda3-4.5.12-Linux-x86_64.sh -b
|
||||
- rm -rf Miniconda3-4.5.12-Linux-x86_64.sh
|
||||
- sudo ln -s $HOME/miniconda3/lib/libpython3.6m.so /usr/lib/libpython3.6m.so
|
||||
@@ -17,10 +19,10 @@ before_install:
|
||||
- conda install -y scipy=1.4.1
|
||||
- conda install -y wrapt=1.12.1
|
||||
install:
|
||||
- nuget restore QuantConnect.Lean.sln
|
||||
- nuget install NUnit.Runners -Version 3.11.1 -OutputDirectory testrunner
|
||||
script:
|
||||
- msbuild /p:Configuration=Release /p:VbcToolExe=vbnc.exe QuantConnect.Lean.sln
|
||||
- mono ./testrunner/NUnit.ConsoleRunner.3.11.1/tools/nunit3-console.exe ./Tests/bin/Release/QuantConnect.Tests.dll --where "cat != TravisExclude" --labels=Off
|
||||
- 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 -ipy -g -p
|
||||
- sudo -E ./ci_build_stubs.sh -d -t -g -p
|
||||
|
||||
@@ -106,14 +106,14 @@ From a terminal launch the run_docker.bat/.sh script; there are a few choices on
|
||||
|
||||
2. Using the **run_docker.cfg** to store args for repeated use; any blank entries will resort to default values! example: **_./run_docker.bat run_docker.cfg_**
|
||||
|
||||
image=quantconnect/lean:latest
|
||||
config_file=
|
||||
data_dir=
|
||||
results_dir=
|
||||
debugging=
|
||||
python_dir=
|
||||
IMAGE=quantconnect/lean:latest
|
||||
CONFIG_FILE=
|
||||
DATA_DIR=
|
||||
RESULTS_DIR=
|
||||
DEBUGGING=
|
||||
PYTHON_DIR=
|
||||
|
||||
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat debugging=y_**
|
||||
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat DEBUGGING=y_**
|
||||
* Accepted args for inline include all listed in the file in #2
|
||||
|
||||
<br />
|
||||
|
||||
51
.vscode/readme.md
vendored
51
.vscode/readme.md
vendored
@@ -13,7 +13,7 @@ Before anything we need to ensure a few things have been done:
|
||||
|
||||
|
||||
1. Get [Visual Studio Code](https://code.visualstudio.com/download)
|
||||
* Get the Extension [Mono Debug](https://marketplace.visualstudio.com/items?itemName=ms-vscode.mono-debug) for C# Debugging
|
||||
* Get the Extension [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/):
|
||||
@@ -35,7 +35,8 @@ Before anything we need to ensure a few things have been done:
|
||||
* 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>
|
||||
@@ -66,7 +67,7 @@ Before we can use this method with Windows or Mac OS we need to share the Lean d
|
||||
|
||||
Next we need to be sure that our Lean configuration at **.\Launcher\config.json** is properly set. Just like running lean locally the config must reflect what we want Lean to run.
|
||||
|
||||
You configuration file should look something like this for the following languages:
|
||||
Your configuration file should look something like this for the following languages:
|
||||
|
||||
<h3>Python:</h3>
|
||||
|
||||
@@ -101,17 +102,23 @@ This section will cover how to actually launch Lean in the container with your d
|
||||
|
||||
<h3>Option 1 (Recommended)</h3>
|
||||
|
||||
In VS Code click on the debug/run icon on the left toolbar, at the top you should see a drop down menu with launch options, be sure to select **Debug in Container**. This option will kick off a launch script that will start the docker. With this specific launch option the parameters are already configured in VS Codes **tasks.json** under the **run-docker** task args. These set arguements are:
|
||||
In VS Code click on the debug/run icon on the left toolbar, at the top you should see a drop down menu with launch options, be sure to select **Debug in Container**. This option will kick off a launch script that will start the docker. With this specific launch option the parameters are already configured in VS Codes **tasks.json** under the **run-docker** task args. These set arguments are:
|
||||
|
||||
"image=quantconnect/lean:latest",
|
||||
"config_file=${workspaceFolder}/Launcher/config.json",
|
||||
"data_dir=${workspaceFolder}/Data",
|
||||
"results_dir=${workspaceFolder}/",
|
||||
"debugging=Y",
|
||||
"python_location=${workspaceFolder}/Algorithm.Python"
|
||||
"IMAGE=quantconnect/lean:latest",
|
||||
"CONFIG_FILE=${workspaceFolder}/Launcher/config.json",
|
||||
"DATA_DIR=${workspaceFolder}/Data",
|
||||
"RESULTS_DIR=${workspaceFolder}/Results",
|
||||
"DEBUGGING=Y",
|
||||
"PYHTON_DIR=${workspaceFolder}/Algorithm.Python"
|
||||
|
||||
As defaults these are all great! Feel free to change them as needed for your setup.
|
||||
|
||||
**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.
|
||||
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
<h3>Option 2</h3>
|
||||
@@ -120,21 +127,21 @@ From a terminal launch the run_docker.bat/.sh script; there are a few choices on
|
||||
1. Launch with no parameters and answer the questions regarding configuration (Press enter for defaults)
|
||||
|
||||
* Enter docker image [default: quantconnect/lean:latest]:
|
||||
* Enter absolute path to Lean config file [default: _~currentDir_\Launcher\config.json]:
|
||||
* Enter absolute path to Data folder [default: ~_currentDir_\Data\]:
|
||||
* Enter absolute path to store results [default: ~_currentDir_\]:
|
||||
* Enter absolute path to Lean config file [default: .\Launcher\config.json]:
|
||||
* Enter absolute path to Data folder [default: .\Data\]:
|
||||
* Enter absolute path to store results [default: .\Results]:
|
||||
* Would you like to debug C#? (Requires mono debugger attachment) [default: N]:
|
||||
|
||||
2. Using the **run_docker.cfg** to store args for repeated use; any blank entries will resort to default values! example: **_./run_docker.bat run_docker.cfg_**
|
||||
|
||||
image=quantconnect/lean:latest
|
||||
config_file=
|
||||
data_dir=
|
||||
results_dir=
|
||||
debugging=
|
||||
python_dir=
|
||||
IMAGE=quantconnect/lean:latest
|
||||
CONFIG_FILE=
|
||||
DATA_DIR=
|
||||
RESULTS_DIR=
|
||||
DEBUGGING=
|
||||
PYTHON_DIR=
|
||||
|
||||
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat debugging=y_**
|
||||
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat DEBUGGING=y_**
|
||||
* Accepted args for inline include all listed in the file in #2
|
||||
|
||||
<br />
|
||||
@@ -194,4 +201,6 @@ _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!
|
||||
|
||||
* Error messages about build in VSCode points to comments in JSON. Either select **ignore** or follow steps described [here](https://stackoverflow.com/questions/47834825/in-vs-code-disable-error-comments-are-not-permitted-in-json) to remove the errors entirely.
|
||||
* 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.
|
||||
|
||||
5
.vscode/settings.json
vendored
5
.vscode/settings.json
vendored
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"python.autoComplete.extraPaths": [
|
||||
"Algorithm.Python/stubs"
|
||||
]
|
||||
}
|
||||
42
.vscode/tasks.json
vendored
42
.vscode/tasks.json
vendored
@@ -20,6 +20,34 @@
|
||||
},
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "rebuild",
|
||||
"type": "shell",
|
||||
"command": "msbuild",
|
||||
"args": [
|
||||
"/p:Configuration=Debug",
|
||||
"/p:DebugType=portable",
|
||||
"/t:rebuild",
|
||||
],
|
||||
"group": "build",
|
||||
"presentation": {
|
||||
"reveal": "silent"
|
||||
},
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "clean",
|
||||
"type": "shell",
|
||||
"command": "msbuild",
|
||||
"args": [
|
||||
"/t:clean",
|
||||
],
|
||||
"group": "build",
|
||||
"presentation": {
|
||||
"reveal": "silent"
|
||||
},
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "force build linux",
|
||||
"type": "shell",
|
||||
@@ -51,13 +79,13 @@
|
||||
"command": "${workspaceFolder}/run_docker.sh"
|
||||
},
|
||||
"args": [
|
||||
"image=quantconnect/lean:latest",
|
||||
"config_file=${workspaceFolder}/Launcher/config.json",
|
||||
"data_dir=${workspaceFolder}/Data",
|
||||
"results_dir=${workspaceFolder}/",
|
||||
"debugging=Y",
|
||||
"python_dir=${workspaceFolder}/Algorithm.Python",
|
||||
"exit=Y"
|
||||
"IMAGE=quantconnect/lean:latest",
|
||||
"CONFIG_FILE=${workspaceFolder}/Launcher/config.json",
|
||||
"DATA_DIR=${workspaceFolder}/Data",
|
||||
"RESULTS_DIR=${workspaceFolder}/Results",
|
||||
"DEBUGGING=Y",
|
||||
"PYTHON_DIR=${workspaceFolder}/Algorithm.Python",
|
||||
"EXIT=Y"
|
||||
],
|
||||
"problemMatcher": [
|
||||
{
|
||||
|
||||
@@ -94,6 +94,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.212"},
|
||||
{"Treynor Ratio", "-2.13"},
|
||||
{"Total Fees", "$199.00"},
|
||||
{"Estimated Strategy Capacity", "$23000000.00"},
|
||||
{"Fitness Score", "0.002"},
|
||||
{"Kelly Criterion Estimate", "38.64"},
|
||||
{"Kelly Criterion Probability Value", "0.229"},
|
||||
@@ -113,7 +114,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "54.5455%"},
|
||||
{"Rolling Averaged Population Direction", "59.8056%"},
|
||||
{"Rolling Averaged Population Magnitude", "59.8056%"},
|
||||
{"OrderListHash", "1256341962"}
|
||||
{"OrderListHash", "0a28eedf6304023f5002ef672b489b88"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,6 +130,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.367"},
|
||||
{"Treynor Ratio", "-4.079"},
|
||||
{"Total Fees", "$14.33"},
|
||||
{"Estimated Strategy Capacity", "$38000000.00"},
|
||||
{"Fitness Score", "0.408"},
|
||||
{"Kelly Criterion Estimate", "16.447"},
|
||||
{"Kelly Criterion Probability Value", "0.315"},
|
||||
@@ -149,7 +150,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "100%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-887015098"}
|
||||
{"OrderListHash", "506e9fe18984ba6e569b2e327030de3a"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests that we receive the expected data when
|
||||
/// we add future option contracts individually using <see cref="AddFutureOptionContract"/>
|
||||
/// </summary>
|
||||
public class AddFutureOptionContractDataStreamingRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private bool _onDataReached;
|
||||
private bool _invested;
|
||||
private Symbol _es20h20;
|
||||
private Symbol _es19m20;
|
||||
|
||||
private readonly HashSet<Symbol> _symbolsReceived = new HashSet<Symbol>();
|
||||
private readonly HashSet<Symbol> _expectedSymbolsReceived = new HashSet<Symbol>();
|
||||
private readonly Dictionary<Symbol, List<QuoteBar>> _dataReceived = new Dictionary<Symbol, List<QuoteBar>>();
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 1, 6);
|
||||
|
||||
_es20h20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 3, 20)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
_es19m20 = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)),
|
||||
Resolution.Minute).Symbol;
|
||||
|
||||
var optionChains = OptionChainProvider.GetOptionContractList(_es20h20, Time)
|
||||
.Concat(OptionChainProvider.GetOptionContractList(_es19m20, Time));
|
||||
|
||||
foreach (var optionContract in optionChains)
|
||||
{
|
||||
_expectedSymbolsReceived.Add(AddFutureOptionContract(optionContract, Resolution.Minute).Symbol);
|
||||
}
|
||||
|
||||
if (_expectedSymbolsReceived.Count == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Expected Symbols receive count is 0, expected >0");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!data.HasData)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_onDataReached = true;
|
||||
|
||||
var hasOptionQuoteBars = false;
|
||||
foreach (var qb in data.QuoteBars.Values)
|
||||
{
|
||||
if (qb.Symbol.SecurityType != SecurityType.FutureOption)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
hasOptionQuoteBars = true;
|
||||
|
||||
_symbolsReceived.Add(qb.Symbol);
|
||||
if (!_dataReceived.ContainsKey(qb.Symbol))
|
||||
{
|
||||
_dataReceived[qb.Symbol] = new List<QuoteBar>();
|
||||
}
|
||||
|
||||
_dataReceived[qb.Symbol].Add(qb);
|
||||
}
|
||||
|
||||
if (_invested || !hasOptionQuoteBars)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.ContainsKey(_es20h20) && data.ContainsKey(_es19m20))
|
||||
{
|
||||
SetHoldings(_es20h20, 0.2);
|
||||
SetHoldings(_es19m20, 0.2);
|
||||
|
||||
_invested = true;
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
base.OnEndOfAlgorithm();
|
||||
|
||||
if (!_onDataReached)
|
||||
{
|
||||
throw new Exception("OnData() was never called.");
|
||||
}
|
||||
if (_symbolsReceived.Count != _expectedSymbolsReceived.Count)
|
||||
{
|
||||
throw new AggregateException($"Expected {_expectedSymbolsReceived.Count} option contracts Symbols, found {_symbolsReceived.Count}");
|
||||
}
|
||||
|
||||
var missingSymbols = new List<Symbol>();
|
||||
foreach (var expectedSymbol in _expectedSymbolsReceived)
|
||||
{
|
||||
if (!_symbolsReceived.Contains(expectedSymbol))
|
||||
{
|
||||
missingSymbols.Add(expectedSymbol);
|
||||
}
|
||||
}
|
||||
|
||||
if (missingSymbols.Count > 0)
|
||||
{
|
||||
throw new Exception($"Symbols: \"{string.Join(", ", missingSymbols)}\" were not found in OnData");
|
||||
}
|
||||
|
||||
foreach (var expectedSymbol in _expectedSymbolsReceived)
|
||||
{
|
||||
var data = _dataReceived[expectedSymbol];
|
||||
var nonDupeDataCount = data.Select(x =>
|
||||
{
|
||||
x.EndTime = default(DateTime);
|
||||
return x;
|
||||
}).Distinct().Count();
|
||||
|
||||
if (nonDupeDataCount < 1000)
|
||||
{
|
||||
throw new Exception($"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "217.585%"},
|
||||
{"Drawdown", "0.600%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.635%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-14.395"},
|
||||
{"Tracking Error", "0.043"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Estimated Strategy Capacity", "$28000000.00"},
|
||||
{"Fitness Score", "1"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "3.199"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "35738733ff791eeeaf508faec804cab0"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Securities.Future;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests that we only receive the option chain for a single future contract
|
||||
/// in the option universe filter.
|
||||
/// </summary>
|
||||
public class AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private bool _invested;
|
||||
private bool _onDataReached;
|
||||
private bool _optionFilterRan;
|
||||
private readonly HashSet<Symbol> _symbolsReceived = new HashSet<Symbol>();
|
||||
private readonly HashSet<Symbol> _expectedSymbolsReceived = new HashSet<Symbol>();
|
||||
private readonly Dictionary<Symbol, List<QuoteBar>> _dataReceived = new Dictionary<Symbol, List<QuoteBar>>();
|
||||
|
||||
private Future _es;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 5);
|
||||
SetEndDate(2020, 1, 6);
|
||||
|
||||
_es = AddFuture(Futures.Indices.SP500EMini, Resolution.Minute, Market.CME);
|
||||
_es.SetFilter((futureFilter) =>
|
||||
{
|
||||
return futureFilter.Expiration(0, 365).ExpirationCycle(new[] { 3, 6 });
|
||||
});
|
||||
|
||||
AddFutureOption(_es.Symbol, optionContracts =>
|
||||
{
|
||||
_optionFilterRan = true;
|
||||
|
||||
var expiry = new HashSet<DateTime>(optionContracts.Select(x => x.Underlying.ID.Date)).SingleOrDefault();
|
||||
// Cast to IEnumerable<Symbol> because OptionFilterContract overrides some LINQ operators like `Select` and `Where`
|
||||
// and cause it to mutate the underlying Symbol collection when using those operators.
|
||||
var symbol = new HashSet<Symbol>(((IEnumerable<Symbol>)optionContracts).Select(x => x.Underlying)).SingleOrDefault();
|
||||
|
||||
if (expiry == null || symbol == null)
|
||||
{
|
||||
throw new InvalidOperationException("Expected a single Option contract in the chain, found 0 contracts");
|
||||
}
|
||||
|
||||
var enumerator = optionContracts.GetEnumerator();
|
||||
while (enumerator.MoveNext())
|
||||
{
|
||||
_expectedSymbolsReceived.Add(enumerator.Current);
|
||||
}
|
||||
|
||||
return optionContracts;
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!data.HasData)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_onDataReached = true;
|
||||
|
||||
var hasOptionQuoteBars = false;
|
||||
foreach (var qb in data.QuoteBars.Values)
|
||||
{
|
||||
if (qb.Symbol.SecurityType != SecurityType.FutureOption)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
hasOptionQuoteBars = true;
|
||||
|
||||
_symbolsReceived.Add(qb.Symbol);
|
||||
if (!_dataReceived.ContainsKey(qb.Symbol))
|
||||
{
|
||||
_dataReceived[qb.Symbol] = new List<QuoteBar>();
|
||||
}
|
||||
|
||||
_dataReceived[qb.Symbol].Add(qb);
|
||||
}
|
||||
|
||||
if (_invested || !hasOptionQuoteBars)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var chain in data.OptionChains.Values)
|
||||
{
|
||||
var futureInvested = false;
|
||||
var optionInvested = false;
|
||||
|
||||
foreach (var option in chain.Contracts.Keys)
|
||||
{
|
||||
if (futureInvested && optionInvested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var future = option.Underlying;
|
||||
|
||||
if (!optionInvested && data.ContainsKey(option))
|
||||
{
|
||||
MarketOrder(option, 1);
|
||||
_invested = true;
|
||||
optionInvested = true;
|
||||
}
|
||||
if (!futureInvested && data.ContainsKey(future))
|
||||
{
|
||||
MarketOrder(future, 1);
|
||||
_invested = true;
|
||||
futureInvested = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
base.OnEndOfAlgorithm();
|
||||
|
||||
if (!_optionFilterRan)
|
||||
{
|
||||
throw new InvalidOperationException("Option chain filter was never ran");
|
||||
}
|
||||
if (!_onDataReached)
|
||||
{
|
||||
throw new Exception("OnData() was never called.");
|
||||
}
|
||||
if (_symbolsReceived.Count != _expectedSymbolsReceived.Count)
|
||||
{
|
||||
throw new AggregateException($"Expected {_expectedSymbolsReceived.Count} option contracts Symbols, found {_symbolsReceived.Count}");
|
||||
}
|
||||
|
||||
var missingSymbols = new List<Symbol>();
|
||||
foreach (var expectedSymbol in _expectedSymbolsReceived)
|
||||
{
|
||||
if (!_symbolsReceived.Contains(expectedSymbol))
|
||||
{
|
||||
missingSymbols.Add(expectedSymbol);
|
||||
}
|
||||
}
|
||||
|
||||
if (missingSymbols.Count > 0)
|
||||
{
|
||||
throw new Exception($"Symbols: \"{string.Join(", ", missingSymbols)}\" were not found in OnData");
|
||||
}
|
||||
|
||||
foreach (var expectedSymbol in _expectedSymbolsReceived)
|
||||
{
|
||||
var data = _dataReceived[expectedSymbol];
|
||||
var nonDupeDataCount = data.Select(x =>
|
||||
{
|
||||
x.EndTime = default(DateTime);
|
||||
return x;
|
||||
}).Distinct().Count();
|
||||
|
||||
if (nonDupeDataCount < 1000)
|
||||
{
|
||||
throw new Exception($"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "-15.625%"},
|
||||
{"Drawdown", "0.200%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "-0.093%"},
|
||||
{"Sharpe Ratio", "-11.181"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.002"},
|
||||
{"Beta", "-0.016"},
|
||||
{"Annual Standard Deviation", "0.001"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-14.343"},
|
||||
{"Tracking Error", "0.044"},
|
||||
{"Treynor Ratio", "0.479"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Estimated Strategy Capacity", "$12000.00"},
|
||||
{"Fitness Score", "0.41"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-185.654"},
|
||||
{"Portfolio Turnover", "0.821"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "9347e3b610cfa21f7cbd968a0135c8af"}
|
||||
};
|
||||
}
|
||||
}
|
||||
165
Algorithm.CSharp/AddOptionContractExpiresRegressionAlgorithm.cs
Normal file
165
Algorithm.CSharp/AddOptionContractExpiresRegressionAlgorithm.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>
|
||||
/// We add an option contract using <see cref="QCAlgorithm.AddOptionContract"/> and place a trade and wait till it expires
|
||||
/// later will liquidate the resulting equity position and assert both option and underlying get removed
|
||||
/// </summary>
|
||||
public class AddOptionContractExpiresRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private DateTime _expiration = new DateTime(2014, 06, 21);
|
||||
private Symbol _option;
|
||||
private Symbol _twx;
|
||||
private bool _traded;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 06, 05);
|
||||
SetEndDate(2014, 06, 30);
|
||||
|
||||
_twx = QuantConnect.Symbol.Create("TWX", SecurityType.Equity, Market.USA);
|
||||
|
||||
AddUniverse("my-daily-universe-name", time => new List<string> { "AAPL" });
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (_option == null)
|
||||
{
|
||||
var option = OptionChainProvider.GetOptionContractList(_twx, Time)
|
||||
.OrderBy(symbol => symbol.ID.Symbol)
|
||||
.FirstOrDefault(optionContract => optionContract.ID.Date == _expiration
|
||||
&& optionContract.ID.OptionRight == OptionRight.Call
|
||||
&& optionContract.ID.OptionStyle == OptionStyle.American);
|
||||
if (option != null)
|
||||
{
|
||||
_option = AddOptionContract(option).Symbol;
|
||||
}
|
||||
}
|
||||
|
||||
if (_option != null && Securities[_option].Price != 0 && !_traded)
|
||||
{
|
||||
_traded = true;
|
||||
Buy(_option, 1);
|
||||
|
||||
foreach (var symbol in new [] { _option, _option.Underlying })
|
||||
{
|
||||
var config = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol).ToList();
|
||||
|
||||
if (!config.Any())
|
||||
{
|
||||
throw new Exception($"Was expecting configurations for {symbol}");
|
||||
}
|
||||
if (config.Any(dataConfig => dataConfig.DataNormalizationMode != DataNormalizationMode.Raw))
|
||||
{
|
||||
throw new Exception($"Was expecting DataNormalizationMode.Raw configurations for {symbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Time.Date > _expiration)
|
||||
{
|
||||
if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_option).Any())
|
||||
{
|
||||
throw new Exception($"Unexpected configurations for {_option} after it has been delisted");
|
||||
}
|
||||
|
||||
if (Securities[_twx].Invested)
|
||||
{
|
||||
if (!SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_twx).Any())
|
||||
{
|
||||
throw new Exception($"Was expecting configurations for {_twx}");
|
||||
}
|
||||
|
||||
// first we liquidate the option exercised position
|
||||
Liquidate(_twx);
|
||||
}
|
||||
}
|
||||
else if (Time.Date > _expiration && !Securities[_twx].Invested)
|
||||
{
|
||||
if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_twx).Any())
|
||||
{
|
||||
throw new Exception($"Unexpected configurations for {_twx} after it has been liquidated");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "3"},
|
||||
{"Average Win", "2.73%"},
|
||||
{"Average Loss", "-2.98%"},
|
||||
{"Compounding Annual Return", "-4.619%"},
|
||||
{"Drawdown", "0.300%"},
|
||||
{"Expectancy", "-0.042"},
|
||||
{"Net Profit", "-0.332%"},
|
||||
{"Sharpe Ratio", "-3.7"},
|
||||
{"Probabilistic Sharpe Ratio", "0.563%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.92"},
|
||||
{"Alpha", "-0.021"},
|
||||
{"Beta", "-0.01"},
|
||||
{"Annual Standard Deviation", "0.006"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-3.374"},
|
||||
{"Tracking Error", "0.058"},
|
||||
{"Treynor Ratio", "2.133"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$45000000.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-43.418"},
|
||||
{"Return Over Maximum Drawdown", "-14.274"},
|
||||
{"Portfolio Turnover", "0.007"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "486118a60d78f74811fe8d927c2c6b43"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// We add an option contract using <see cref="QCAlgorithm.AddOptionContract"/> and place a trade, the underlying
|
||||
/// gets deselected from the universe selection but should still be present since we manually added the option contract.
|
||||
/// Later we call <see cref="QCAlgorithm.RemoveOptionContract"/> and expect both option and underlying to be removed.
|
||||
/// </summary>
|
||||
public class AddOptionContractFromUniverseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private DateTime _expiration = new DateTime(2014, 06, 21);
|
||||
private SecurityChanges _securityChanges = SecurityChanges.None;
|
||||
private Symbol _option;
|
||||
private Symbol _aapl;
|
||||
private Symbol _twx;
|
||||
private bool _traded;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
_twx = QuantConnect.Symbol.Create("TWX", SecurityType.Equity, Market.USA);
|
||||
_aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
|
||||
UniverseSettings.Resolution = Resolution.Minute;
|
||||
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
|
||||
|
||||
SetStartDate(2014, 06, 05);
|
||||
SetEndDate(2014, 06, 09);
|
||||
|
||||
AddUniverse(enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl },
|
||||
enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl });
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (_option != null && Securities[_option].Price != 0 && !_traded)
|
||||
{
|
||||
_traded = true;
|
||||
Buy(_option, 1);
|
||||
}
|
||||
|
||||
if (Time.Date > new DateTime(2014, 6, 5))
|
||||
{
|
||||
if (Time < new DateTime(2014, 6, 6, 14, 0, 0))
|
||||
{
|
||||
var configs = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_twx);
|
||||
// assert underlying still there after the universe selection removed it, still used by the manually added option contract
|
||||
if (!configs.Any())
|
||||
{
|
||||
throw new Exception($"Was expecting configurations for {_twx}" +
|
||||
$" even after it has been deselected from coarse universe because we still have the option contract.");
|
||||
}
|
||||
}
|
||||
else if (Time == new DateTime(2014, 6, 6, 14, 0, 0))
|
||||
{
|
||||
// liquidate & remove the option
|
||||
RemoveOptionContract(_option);
|
||||
}
|
||||
// assert underlying was finally removed
|
||||
else if(Time > new DateTime(2014, 6, 6, 14, 0, 0))
|
||||
{
|
||||
foreach (var symbol in new[] { _option, _option.Underlying })
|
||||
{
|
||||
var configs = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol);
|
||||
if (configs.Any())
|
||||
{
|
||||
throw new Exception($"Unexpected configuration for {symbol} after it has been deselected from coarse universe and option contract is removed.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
if (_securityChanges.RemovedSecurities.Intersect(changes.RemovedSecurities).Any())
|
||||
{
|
||||
throw new Exception($"SecurityChanges.RemovedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!");
|
||||
}
|
||||
if (_securityChanges.AddedSecurities.Intersect(changes.AddedSecurities).Any())
|
||||
{
|
||||
throw new Exception($"SecurityChanges.AddedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!");
|
||||
}
|
||||
// keep track of all removed and added securities
|
||||
_securityChanges += changes;
|
||||
|
||||
if (changes.AddedSecurities.Any(security => security.Symbol.SecurityType == SecurityType.Option))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var addedSecurity in changes.AddedSecurities)
|
||||
{
|
||||
var option = OptionChainProvider.GetOptionContractList(addedSecurity.Symbol, Time)
|
||||
.OrderBy(symbol => symbol.ID.Symbol)
|
||||
.First(optionContract => optionContract.ID.Date == _expiration
|
||||
&& optionContract.ID.OptionRight == OptionRight.Call
|
||||
&& optionContract.ID.OptionStyle == OptionStyle.American);
|
||||
AddOptionContract(option);
|
||||
|
||||
foreach (var symbol in new[] { option, option.Underlying })
|
||||
{
|
||||
var config = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol).ToList();
|
||||
|
||||
if (!config.Any())
|
||||
{
|
||||
throw new Exception($"Was expecting configurations for {symbol}");
|
||||
}
|
||||
if (config.Any(dataConfig => dataConfig.DataNormalizationMode != DataNormalizationMode.Raw))
|
||||
{
|
||||
throw new Exception($"Was expecting DataNormalizationMode.Raw configurations for {symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
// just keep the first we got
|
||||
if (_option == null)
|
||||
{
|
||||
_option = option;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (SubscriptionManager.Subscriptions.Any(dataConfig => dataConfig.Symbol == _twx || dataConfig.Symbol.Underlying == _twx))
|
||||
{
|
||||
throw new Exception($"Was NOT expecting any configurations for {_twx} or it's options, since we removed the contract");
|
||||
}
|
||||
|
||||
if (SubscriptionManager.Subscriptions.All(dataConfig => dataConfig.Symbol != _aapl))
|
||||
{
|
||||
throw new Exception($"Was expecting configurations for {_aapl}");
|
||||
}
|
||||
if (SubscriptionManager.Subscriptions.All(dataConfig => dataConfig.Symbol.Underlying != _aapl))
|
||||
{
|
||||
throw new Exception($"Was expecting options configurations for {_aapl}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.23%"},
|
||||
{"Compounding Annual Return", "-15.596%"},
|
||||
{"Drawdown", "0.200%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.232%"},
|
||||
{"Sharpe Ratio", "-7.739"},
|
||||
{"Probabilistic Sharpe Ratio", "1.216%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.027"},
|
||||
{"Beta", "-0.174"},
|
||||
{"Annual Standard Deviation", "0.006"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-11.586"},
|
||||
{"Tracking Error", "0.042"},
|
||||
{"Treynor Ratio", "0.286"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$2800000.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-19.883"},
|
||||
{"Return Over Maximum Drawdown", "-67.224"},
|
||||
{"Portfolio Turnover", "0.014"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "ae0b430e9c728966e3736fb352a689c6"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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(Securities.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(Securities.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,6 +230,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$6.00"},
|
||||
{"Estimated Strategy Capacity", "$1500.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -249,7 +250,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "731140098"}
|
||||
{"OrderListHash", "cf8f76fa441c2a5e3b2dbbabcab32cd2"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,6 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.072"},
|
||||
{"Treynor Ratio", "2.933"},
|
||||
{"Total Fees", "$26.39"},
|
||||
{"Estimated Strategy Capacity", "$4400000.00"},
|
||||
{"Fitness Score", "0.374"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -150,7 +151,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1779055144"}
|
||||
{"OrderListHash", "5f7ba8b5defb310a2eaf98b11abd3b74"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,6 +84,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.006"},
|
||||
{"Treynor Ratio", "2.029"},
|
||||
{"Total Fees", "$9.77"},
|
||||
{"Estimated Strategy Capacity", "$37000000.00"},
|
||||
{"Fitness Score", "0.747"},
|
||||
{"Kelly Criterion Estimate", "38.64"},
|
||||
{"Kelly Criterion Probability Value", "0.229"},
|
||||
@@ -103,7 +104,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "54.5455%"},
|
||||
{"Rolling Averaged Population Direction", "59.8056%"},
|
||||
{"Rolling Averaged Population Magnitude", "59.8056%"},
|
||||
{"OrderListHash", "-887190565"}
|
||||
{"OrderListHash", "0b8cbbafdb77bae2f7abe3cf5e05ac5c"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,6 +103,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.376"},
|
||||
{"Treynor Ratio", "-0.084"},
|
||||
{"Total Fees", "$13.98"},
|
||||
{"Estimated Strategy Capacity", "$61000000.00"},
|
||||
{"Fitness Score", "0.146"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "1"},
|
||||
@@ -122,7 +123,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1917702312"}
|
||||
{"OrderListHash", "8971c92ba163cec8526379865d9b9ee4"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,6 +110,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.194"},
|
||||
{"Treynor Ratio", "-0.962"},
|
||||
{"Total Fees", "$25.92"},
|
||||
{"Estimated Strategy Capacity", "$69000000.00"},
|
||||
{"Fitness Score", "0.004"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "1"},
|
||||
@@ -129,7 +130,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1674230481"}
|
||||
{"OrderListHash", "ce59e51c8e404b5dbbc02911473aed1c"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
/*
|
||||
* 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.Brokerages;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Shortable;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests filtering in coarse selection by shortable quantity
|
||||
/// </summary>
|
||||
public class AllShortableSymbolsCoarseSelectionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private static readonly DateTime _20140325 = new DateTime(2014, 3, 25);
|
||||
private static readonly DateTime _20140326 = new DateTime(2014, 3, 26);
|
||||
private static readonly DateTime _20140327 = new DateTime(2014, 3, 27);
|
||||
private static readonly DateTime _20140328 = new DateTime(2014, 3, 28);
|
||||
private static readonly DateTime _20140329 = new DateTime(2014, 3, 29);
|
||||
|
||||
private static readonly Symbol _aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
|
||||
private static readonly Symbol _bac = QuantConnect.Symbol.Create("BAC", SecurityType.Equity, Market.USA);
|
||||
private static readonly Symbol _gme = QuantConnect.Symbol.Create("GME", SecurityType.Equity, Market.USA);
|
||||
private static readonly Symbol _goog = QuantConnect.Symbol.Create("GOOG", SecurityType.Equity, Market.USA);
|
||||
private static readonly Symbol _qqq = QuantConnect.Symbol.Create("QQQ", SecurityType.Equity, Market.USA);
|
||||
private static readonly Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
|
||||
private DateTime _lastTradeDate;
|
||||
|
||||
private static readonly Dictionary<DateTime, bool> _coarseSelected = new Dictionary<DateTime, bool>
|
||||
{
|
||||
{ _20140325, false },
|
||||
{ _20140326, false },
|
||||
{ _20140327, false },
|
||||
{ _20140328, false },
|
||||
};
|
||||
|
||||
private static readonly Dictionary<DateTime, Symbol[]> _expectedSymbols = new Dictionary<DateTime, Symbol[]>
|
||||
{
|
||||
{ _20140325, new[]
|
||||
{
|
||||
_bac,
|
||||
_qqq,
|
||||
_spy
|
||||
}
|
||||
},
|
||||
{ _20140326, new[]
|
||||
{
|
||||
_spy
|
||||
}
|
||||
},
|
||||
{ _20140327, new[]
|
||||
{
|
||||
_aapl,
|
||||
_bac,
|
||||
_gme,
|
||||
_qqq,
|
||||
_spy,
|
||||
}
|
||||
},
|
||||
{ _20140328, new[]
|
||||
{
|
||||
_goog
|
||||
}
|
||||
},
|
||||
{ _20140329, new Symbol[0] }
|
||||
};
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 3, 25);
|
||||
SetEndDate(2014, 3, 29);
|
||||
SetCash(10000000);
|
||||
|
||||
AddUniverse(CoarseSelection);
|
||||
UniverseSettings.Resolution = Resolution.Daily;
|
||||
|
||||
SetBrokerageModel(new AllShortableSymbolsRegressionAlgorithmBrokerageModel());
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (Time.Date == _lastTradeDate)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var symbol in ActiveSecurities.Keys)
|
||||
{
|
||||
if (!Portfolio.ContainsKey(symbol) || !Portfolio[symbol].Invested)
|
||||
{
|
||||
if (!Shortable(symbol))
|
||||
{
|
||||
throw new Exception($"Expected {symbol} to be shortable on {Time:yyyy-MM-dd}");
|
||||
}
|
||||
|
||||
// Buy at least once into all Symbols. Since daily data will always use
|
||||
// MOO orders, it makes the testing of liquidating buying into Symbols difficult.
|
||||
MarketOrder(symbol, -(decimal)ShortableQuantity(symbol));
|
||||
_lastTradeDate = Time.Date;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerable<Symbol> CoarseSelection(IEnumerable<CoarseFundamental> coarse)
|
||||
{
|
||||
var shortableSymbols = AllShortableSymbols();
|
||||
var selectedSymbols = coarse
|
||||
.Select(x => x.Symbol)
|
||||
.Where(s => shortableSymbols.ContainsKey(s) && shortableSymbols[s] >= 500)
|
||||
.OrderBy(s => s)
|
||||
.ToList();
|
||||
|
||||
var expectedMissing = 0;
|
||||
if (Time.Date == _20140327)
|
||||
{
|
||||
var gme = QuantConnect.Symbol.Create("GME", SecurityType.Equity, Market.USA);
|
||||
if (!shortableSymbols.ContainsKey(gme))
|
||||
{
|
||||
throw new Exception("Expected unmapped GME in shortable symbols list on 2014-03-27");
|
||||
}
|
||||
if (!coarse.Select(x => x.Symbol.Value).Contains("GME"))
|
||||
{
|
||||
throw new Exception("Expected mapped GME in coarse symbols on 2014-03-27");
|
||||
}
|
||||
|
||||
expectedMissing = 1;
|
||||
}
|
||||
|
||||
var missing = _expectedSymbols[Time.Date].Except(selectedSymbols).ToList();
|
||||
if (missing.Count != expectedMissing)
|
||||
{
|
||||
throw new Exception($"Expected Symbols selected on {Time.Date:yyyy-MM-dd} to match expected Symbols, but the following Symbols were missing: {string.Join(", ", missing.Select(s => s.ToString()))}");
|
||||
}
|
||||
|
||||
_coarseSelected[Time.Date] = true;
|
||||
return selectedSymbols;
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (!_coarseSelected.Values.All(x => x))
|
||||
{
|
||||
throw new AggregateException($"Expected coarse selection on all dates, but didn't run on: {string.Join(", ", _coarseSelected.Where(kvp => !kvp.Value).Select(kvp => kvp.Key.ToStringInvariant("yyyy-MM-dd")))}");
|
||||
}
|
||||
}
|
||||
|
||||
private class AllShortableSymbolsRegressionAlgorithmBrokerageModel : DefaultBrokerageModel
|
||||
{
|
||||
public AllShortableSymbolsRegressionAlgorithmBrokerageModel() : base()
|
||||
{
|
||||
ShortableProvider = new RegressionTestShortableProvider();
|
||||
}
|
||||
}
|
||||
|
||||
private class RegressionTestShortableProvider : LocalDiskShortableProvider
|
||||
{
|
||||
public RegressionTestShortableProvider() : base(SecurityType.Equity, "testbrokerage", Market.USA)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "5"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "36.294%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.340%"},
|
||||
{"Sharpe Ratio", "21.2"},
|
||||
{"Probabilistic Sharpe Ratio", "99.990%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.274"},
|
||||
{"Beta", "0.138"},
|
||||
{"Annual Standard Deviation", "0.011"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "7.202"},
|
||||
{"Tracking Error", "0.068"},
|
||||
{"Treynor Ratio", "1.722"},
|
||||
{"Total Fees", "$307.50"},
|
||||
{"Estimated Strategy Capacity", "$2800000.00"},
|
||||
{"Fitness Score", "0.173"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0.173"},
|
||||
{"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", "6b1b205e5a6461ffd5bed645099714cd"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -19,28 +19,27 @@ using QuantConnect.Indicators;
|
||||
using QuantConnect.Orders.Fees;
|
||||
using QuantConnect.Data.Custom;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Algorithm.Framework;
|
||||
using QuantConnect.Algorithm.Framework.Alphas;
|
||||
using QuantConnect.Algorithm.Framework.Execution;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
using QuantConnect.Algorithm.Framework.Risk;
|
||||
using QuantConnect.Algorithm.Framework.Selection;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
namespace QuantConnect.Algorithm.CSharp.Alphas
|
||||
{
|
||||
/// <summary>
|
||||
/// This Alpha Model uses Wells Fargo 30-year Fixed Rate Mortgage data from Quandl to
|
||||
/// generate Insights about the movement of Real Estate ETFs. Mortgage rates can provide information
|
||||
/// regarding the general price trend of real estate, and ETFs provide good continuous-time instruments
|
||||
/// to measure the impact against. Volatility in mortgage rates tends to put downward pressure on real
|
||||
/// estate prices, whereas stable mortgage rates, regardless of true rate, lead to stable or higher real
|
||||
/// estate prices. This Alpha model seeks to take advantage of this correlation by emitting insights
|
||||
/// based on volatility and rate deviation from its historic mean.
|
||||
|
||||
/// This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
|
||||
///<summary>
|
||||
/// This Alpha Model uses Wells Fargo 30-year Fixed Rate Mortgage data from Quandl to
|
||||
/// generate Insights about the movement of Real Estate ETFs. Mortgage rates can provide information
|
||||
/// regarding the general price trend of real estate, and ETFs provide good continuous-time instruments
|
||||
/// to measure the impact against. Volatility in mortgage rates tends to put downward pressure on real
|
||||
/// estate prices, whereas stable mortgage rates, regardless of true rate, lead to stable or higher real
|
||||
/// estate prices. This Alpha model seeks to take advantage of this correlation by emitting insights
|
||||
/// based on volatility and rate deviation from its historic mean.
|
||||
///
|
||||
/// This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
|
||||
/// sourced so the community and client funds can see an example of an alpha.
|
||||
/// <summary>
|
||||
public class MortgageRateVolatilityAlgorithm : QCAlgorithmFramework
|
||||
///</summary>
|
||||
public class MortgageRateVolatilityAlgorithm : QCAlgorithm
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
@@ -51,8 +50,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
SetSecurityInitializer(security => security.FeeModel = new ConstantFeeModel(0));
|
||||
|
||||
// Basket of 6 liquid real estate ETFs
|
||||
Func<string, Symbol> ToSymbol = x => QuantConnect.Symbol.Create(x, SecurityType.Equity, Market.USA);
|
||||
var realEstateETFs = new[] { "VNQ", "REET", "TAO", "FREL", "SRET", "HIPS" }.Select(ToSymbol).ToArray();
|
||||
Func<string, Symbol> toSymbol = x => QuantConnect.Symbol.Create(x, SecurityType.Equity, Market.USA);
|
||||
var realEstateETFs = new[] { "VNQ", "REET", "TAO", "FREL", "SRET", "HIPS" }.Select(toSymbol).ToArray();
|
||||
SetUniverseSelection(new ManualUniverseSelectionModel(realEstateETFs));
|
||||
|
||||
SetAlpha(new MortgageRateVolatilityAlphaModel(this));
|
||||
@@ -64,8 +63,6 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
SetRiskManagement(new NullRiskManagementModel());
|
||||
|
||||
}
|
||||
|
||||
public void OnData(QuandlMortgagePriceColumns data) { }
|
||||
|
||||
private class MortgageRateVolatilityAlphaModel : AlphaModel
|
||||
{
|
||||
@@ -79,7 +76,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
private readonly StandardDeviation _mortgageRateStd;
|
||||
|
||||
public MortgageRateVolatilityAlphaModel(
|
||||
QCAlgorithmFramework algorithm,
|
||||
QCAlgorithm algorithm,
|
||||
int indicatorPeriod = 15,
|
||||
double insightMagnitude = 0.0005,
|
||||
int deviations = 2,
|
||||
@@ -102,7 +99,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
WarmUpIndicators(algorithm);
|
||||
}
|
||||
|
||||
public override IEnumerable<Insight> Update(QCAlgorithmFramework algorithm, Slice data)
|
||||
public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
|
||||
{
|
||||
var insights = new List<Insight>();
|
||||
|
||||
@@ -141,7 +138,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
return insights;
|
||||
}
|
||||
|
||||
private void WarmUpIndicators(QCAlgorithmFramework algorithm)
|
||||
private void WarmUpIndicators(QCAlgorithm algorithm)
|
||||
{
|
||||
// Make a history call and update the indicators
|
||||
algorithm.History(new[] { _mortgageRate }, _indicatorPeriod, _resolution).PushThrough(bar =>
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.Quiver;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp.AltData
|
||||
{
|
||||
/// <summary>
|
||||
/// Quiver Quantitative is a provider of alternative data.
|
||||
/// This algorithm shows how to consume the <see cref="QuiverWallStreetBets"/>
|
||||
/// </summary>
|
||||
public class QuiverWallStreetBetsDataAlgorithm : QCAlgorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2019, 1, 1);
|
||||
SetEndDate(2020, 6, 1);
|
||||
SetCash(100000);
|
||||
|
||||
var aapl = AddEquity("AAPL", Resolution.Daily).Symbol;
|
||||
var quiverWSBSymbol = AddData<QuiverWallStreetBets>(aapl).Symbol;
|
||||
var history = History<QuiverWallStreetBets>(quiverWSBSymbol, 60, Resolution.Daily);
|
||||
|
||||
Debug($"We got {history.Count()} items from our history request");
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
var points = data.Get<QuiverWallStreetBets>();
|
||||
foreach (var point in points.Values)
|
||||
{
|
||||
// Go long in the stock if it was mentioned more than 5 times in the WallStreetBets daily discussion
|
||||
if (point.Mentions > 5)
|
||||
{
|
||||
SetHoldings(point.Symbol.Underlying, 1);
|
||||
}
|
||||
// Go short in the stock if it was mentioned less than 5 times in the WallStreetBets daily discussion
|
||||
if (point.Mentions < 5)
|
||||
{
|
||||
SetHoldings(point.Symbol.Underlying, -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression algorithm to test the behaviour of ARMA versus AR models at the same order of differencing.
|
||||
/// In particular, an ARIMA(1,1,1) and ARIMA(1,1,0) are instantiated while orders are placed if their difference
|
||||
/// is sufficiently large (which would be due to the inclusion of the MA(1) term).
|
||||
/// </summary>
|
||||
public class AutoRegressiveIntegratedMovingAverageRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private AutoRegressiveIntegratedMovingAverage _arima;
|
||||
private AutoRegressiveIntegratedMovingAverage _ar;
|
||||
private decimal _last;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 1, 07);
|
||||
SetEndDate(2013, 12, 11);
|
||||
|
||||
EnableAutomaticIndicatorWarmUp = true;
|
||||
AddEquity("SPY", Resolution.Daily);
|
||||
_arima = ARIMA("SPY", 1, 1, 1, 50);
|
||||
_ar = ARIMA("SPY", 1, 1, 0, 50);
|
||||
}
|
||||
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (_arima.IsReady)
|
||||
{
|
||||
if (Math.Abs(_ar.Current.Value - _arima.Current.Value) > 1) // Difference due to MA(1) being included.
|
||||
{
|
||||
if (_arima.Current.Value > _last)
|
||||
{
|
||||
MarketOrder("SPY", 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
MarketOrder("SPY", -1);
|
||||
}
|
||||
}
|
||||
|
||||
_last = _arima.Current.Value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "65"},
|
||||
{"Average Win", "0.00%"},
|
||||
{"Average Loss", "0.00%"},
|
||||
{"Compounding Annual Return", "0.145%"},
|
||||
{"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"},
|
||||
{"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"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "1.51"},
|
||||
{"Return Over Maximum Drawdown", "1.819"},
|
||||
{"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", "c4c9c272037cfd8f6887052b8d739466"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -168,6 +168,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.441"},
|
||||
{"Treynor Ratio", "-0.008"},
|
||||
{"Total Fees", "$20.35"},
|
||||
{"Estimated Strategy Capacity", "$19000000.00"},
|
||||
{"Fitness Score", "0.138"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -187,7 +188,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1453269600"}
|
||||
{"OrderListHash", "7c841ca58a4385f42236838e5bf0c382"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,6 +130,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.001"},
|
||||
{"Treynor Ratio", "1.922"},
|
||||
{"Total Fees", "$3.26"},
|
||||
{"Estimated Strategy Capacity", "$58000000.00"},
|
||||
{"Fitness Score", "0.248"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -149,7 +150,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "491919591"}
|
||||
{"OrderListHash", "25885f979ca8c7b44f5d0f7daf00b241"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
@@ -183,9 +183,9 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
throw new Exception("OptionExercise order price should be strike price!!");
|
||||
}
|
||||
|
||||
if (orderEvent.Quantity != 1)
|
||||
if (orderEvent.Quantity != -1)
|
||||
{
|
||||
throw new Exception("OrderEvent Quantity should be 1");
|
||||
throw new Exception("OrderEvent Quantity should be -1");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,21 +303,40 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Drawdown", "0.400%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.323%"},
|
||||
{"Sharpe Ratio", "-0.888"},
|
||||
{"Sharpe Ratio", "-11.098"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.035"},
|
||||
{"Beta", "0.183"},
|
||||
{"Annual Standard Deviation", "0.004"},
|
||||
{"Alpha", "-0.002"},
|
||||
{"Beta", "0.099"},
|
||||
{"Annual Standard Deviation", "0.002"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "12.058"},
|
||||
{"Tracking Error", "0.017"},
|
||||
{"Treynor Ratio", "-0.018"},
|
||||
{"Information Ratio", "9.899"},
|
||||
{"Tracking Error", "0.019"},
|
||||
{"Treynor Ratio", "-0.23"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0.213"},
|
||||
{"OrderListHash", "-2119400842"}
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-73.456"},
|
||||
{"Portfolio Turnover", "0.426"},
|
||||
{"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", "72a6ced0ed0c2da7136f3be652eb4744"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,6 +88,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$85000.00"},
|
||||
{"Fitness Score", "0.506"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -107,7 +108,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "498372354"}
|
||||
{"OrderListHash", "18dc611407abec4ea47092e71f33f983"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,6 +97,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.001"},
|
||||
{"Treynor Ratio", "1.922"},
|
||||
{"Total Fees", "$3.26"},
|
||||
{"Estimated Strategy Capacity", "$58000000.00"},
|
||||
{"Fitness Score", "0.248"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -116,7 +117,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "491919591"}
|
||||
{"OrderListHash", "25885f979ca8c7b44f5d0f7daf00b241"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,12 +222,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$85.33"},
|
||||
{"Total Fees", "$85.34"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0.5"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-43.937"},
|
||||
{"Return Over Maximum Drawdown", "-43.943"},
|
||||
{"Portfolio Turnover", "1.028"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -242,7 +243,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1073240275"}
|
||||
{"OrderListHash", "1bf1a6d9dd921982b72a6178f9e50e68"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,6 +88,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.221"},
|
||||
{"Treynor Ratio", "-13.568"},
|
||||
{"Total Fees", "$3.26"},
|
||||
{"Estimated Strategy Capacity", "$890000000.00"},
|
||||
{"Fitness Score", "0.111"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -107,7 +108,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1268340653"}
|
||||
{"OrderListHash", "82fee25cd17100c53bb173834ab5f0b2"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,6 +109,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.002"},
|
||||
{"Treynor Ratio", "1.839"},
|
||||
{"Total Fees", "$9.77"},
|
||||
{"Estimated Strategy Capacity", "$27000000.00"},
|
||||
{"Fitness Score", "0.747"},
|
||||
{"Kelly Criterion Estimate", "38.64"},
|
||||
{"Kelly Criterion Probability Value", "0.229"},
|
||||
@@ -128,7 +129,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "54.5455%"},
|
||||
{"Rolling Averaged Population Direction", "59.8056%"},
|
||||
{"Rolling Averaged Population Magnitude", "59.8056%"},
|
||||
{"OrderListHash", "951346025"}
|
||||
{"OrderListHash", "17e29d58e5dabd93569da752c4552c70"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,6 +147,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.504"},
|
||||
{"Treynor Ratio", "1.011"},
|
||||
{"Total Fees", "$15207.00"},
|
||||
{"Estimated Strategy Capacity", "$7700.00"},
|
||||
{"Fitness Score", "0.033"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -166,7 +167,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1197265007"}
|
||||
{"OrderListHash", "35b3f4b7a225468d42ca085386a2383e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,6 +155,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.188"},
|
||||
{"Treynor Ratio", "-3.318"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Estimated Strategy Capacity", "$52000000.00"},
|
||||
{"Fitness Score", "0.009"},
|
||||
{"Kelly Criterion Estimate", "-112.972"},
|
||||
{"Kelly Criterion Probability Value", "0.671"},
|
||||
@@ -174,7 +175,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1624258832"}
|
||||
{"OrderListHash", "18ffd3a774c68da83d867e3b09e3e05d"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
@@ -160,6 +160,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -179,7 +180,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "371857150"}
|
||||
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
157
Algorithm.CSharp/BasicTemplateIndexAlgorithm.cs
Normal file
157
Algorithm.CSharp/BasicTemplateIndexAlgorithm.cs
Normal file
@@ -0,0 +1,157 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
using System;
|
||||
using QuantConnect.Data;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This example demonstrates how to add index asset types.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="benchmarks" />
|
||||
/// <meta name="tag" content="indexes" />
|
||||
public class BasicTemplateIndexAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _spx;
|
||||
private Symbol _spxOption;
|
||||
private ExponentialMovingAverage _emaSlow;
|
||||
private ExponentialMovingAverage _emaFast;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize your algorithm and add desired assets.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2021, 1, 4);
|
||||
SetEndDate(2021, 1, 15);
|
||||
SetCash(1000000);
|
||||
|
||||
// Use indicator for signal; but it cannot be traded
|
||||
_spx = AddIndex("SPX", Resolution.Minute).Symbol;
|
||||
|
||||
// Trade on SPX ITM calls
|
||||
_spxOption = QuantConnect.Symbol.CreateOption(
|
||||
_spx,
|
||||
Market.USA,
|
||||
OptionStyle.European,
|
||||
OptionRight.Call,
|
||||
3200m,
|
||||
new DateTime(2021, 1, 15));
|
||||
|
||||
AddIndexOptionContract(_spxOption, Resolution.Minute);
|
||||
|
||||
_emaSlow = EMA(_spx, 80);
|
||||
_emaFast = EMA(_spx, 200);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Index EMA Cross trading underlying.
|
||||
/// </summary>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!slice.Bars.ContainsKey(_spx) || !slice.Bars.ContainsKey(_spxOption))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Warm up indicators
|
||||
if (!_emaSlow.IsReady)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_emaFast > _emaSlow)
|
||||
{
|
||||
SetHoldings(_spxOption, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio[_spx].TotalSaleVolume > 0)
|
||||
{
|
||||
throw new Exception("Index is not tradable.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "-53.10%"},
|
||||
{"Compounding Annual Return", "-96.172%"},
|
||||
{"Drawdown", "10.100%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-9.915%"},
|
||||
{"Sharpe Ratio", "-4.217"},
|
||||
{"Probabilistic Sharpe Ratio", "0.052%"},
|
||||
{"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"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$14000000.00"},
|
||||
{"Fitness Score", "0.044"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-1.96"},
|
||||
{"Return Over Maximum Drawdown", "-10.171"},
|
||||
{"Portfolio Turnover", "0.34"},
|
||||
{"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", "52521ab779446daf4d38a7c9bbbdd893"}
|
||||
};
|
||||
}
|
||||
}
|
||||
180
Algorithm.CSharp/BasicTemplateIndexOptionsAlgorithm.cs
Normal file
180
Algorithm.CSharp/BasicTemplateIndexOptionsAlgorithm.cs
Normal file
@@ -0,0 +1,180 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
using System;
|
||||
using QuantConnect.Data;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This example demonstrates how to add index asset types and trade index options on SPX.
|
||||
/// </summary>
|
||||
public class BasicTemplateIndexOptionsAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _spx;
|
||||
private ExponentialMovingAverage _emaSlow;
|
||||
private ExponentialMovingAverage _emaFast;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize your algorithm and add desired assets.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2021, 1, 4);
|
||||
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);
|
||||
spxOptions.SetFilter(filterFunc => filterFunc.CallsOnly());
|
||||
|
||||
_emaSlow = EMA(_spx, 80);
|
||||
_emaFast = EMA(_spx, 200);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Index EMA Cross trading index options of the index.
|
||||
/// </summary>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!slice.Bars.ContainsKey(_spx))
|
||||
{
|
||||
Debug($"No SPX on {Time}");
|
||||
return;
|
||||
}
|
||||
|
||||
// Warm up indicators
|
||||
if (!_emaSlow.IsReady)
|
||||
{
|
||||
Debug($"EMA slow not ready on {Time}");
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var chain in slice.OptionChains.Values)
|
||||
{
|
||||
foreach (var contract in chain.Contracts.Values)
|
||||
{
|
||||
if (contract.Expiry.Month == 3 && contract.Symbol.ID.StrikePrice == 3700m && contract.Right == OptionRight.Call && slice.QuoteBars.ContainsKey(contract.Symbol))
|
||||
{
|
||||
Log($"{Time} {contract.Strike}{(contract.Right == OptionRight.Call ? 'C' : 'P')} -- {slice.QuoteBars[contract.Symbol]}");
|
||||
}
|
||||
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (_emaFast > _emaSlow && contract.Right == OptionRight.Call)
|
||||
{
|
||||
Liquidate(InvertOption(contract.Symbol));
|
||||
MarketOrder(contract.Symbol, 1);
|
||||
}
|
||||
else if (_emaFast < _emaSlow && contract.Right == OptionRight.Put)
|
||||
{
|
||||
Liquidate(InvertOption(contract.Symbol));
|
||||
MarketOrder(contract.Symbol, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio[_spx].TotalSaleVolume > 0)
|
||||
{
|
||||
throw new Exception("Index is not tradable.");
|
||||
}
|
||||
if (Portfolio.TotalSaleVolume == 0)
|
||||
{
|
||||
throw new Exception("Trade volume should be greater than zero by the end of this algorithm");
|
||||
}
|
||||
}
|
||||
|
||||
public Symbol InvertOption(Symbol symbol)
|
||||
{
|
||||
return QuantConnect.Symbol.CreateOption(
|
||||
symbol.Underlying,
|
||||
symbol.ID.Market,
|
||||
symbol.ID.OptionStyle,
|
||||
symbol.ID.OptionRight == OptionRight.Call ? OptionRight.Put : OptionRight.Call,
|
||||
symbol.ID.StrikePrice,
|
||||
symbol.ID.Date);
|
||||
}
|
||||
|
||||
/// <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, 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", "8220"},
|
||||
{"Average Win", "0.00%"},
|
||||
{"Average Loss", "0.00%"},
|
||||
{"Compounding Annual Return", "-100.000%"},
|
||||
{"Drawdown", "13.500%"},
|
||||
{"Expectancy", "-0.818"},
|
||||
{"Net Profit", "-13.517%"},
|
||||
{"Sharpe Ratio", "-2.678"},
|
||||
{"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"},
|
||||
{"Total Fees", "$15207.00"},
|
||||
{"Estimated Strategy Capacity", "$8800000.00"},
|
||||
{"Fitness Score", "0.033"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-8.62"},
|
||||
{"Return Over Maximum Drawdown", "-7.81"},
|
||||
{"Portfolio Turnover", "302.321"},
|
||||
{"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", "35b3f4b7a225468d42ca085386a2383e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -134,6 +134,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$778.00"},
|
||||
{"Estimated Strategy Capacity", "$720.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -153,7 +154,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-702975961"}
|
||||
{"OrderListHash", "5484aef1443064c826e0071f757cb0f7"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,6 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$1300000.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -150,7 +151,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1130102123"}
|
||||
{"OrderListHash", "9d9f9248ee8fe30d87ff0a6f6fea5112"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
@@ -102,7 +102,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "1"},
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
@@ -122,6 +122,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$1.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -141,7 +142,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1438496252"}
|
||||
{"OrderListHash", "92d8a50efe230524512404dab66b19dd"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,7 +160,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$4.00"},
|
||||
{"Total Fees", "$3.00"},
|
||||
{"Estimated Strategy Capacity", "$74000.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0.327"},
|
||||
{"Kelly Criterion Probability Value", "1"},
|
||||
@@ -180,7 +181,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "50.0482%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "352959406"}
|
||||
{"OrderListHash", "ce06ddfa4b2ffeb666a8910ac8836992"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,11 +28,11 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
|
||||
_symbol = AddEquity("SPY").Symbol;
|
||||
}
|
||||
|
||||
public override void OnEndOfDay()
|
||||
public override void OnEndOfDay(Symbol symbol)
|
||||
{
|
||||
var minuteHistory = History(_symbol, 60, Resolution.Minute);
|
||||
var minuteHistory = History(symbol, 60, Resolution.Minute);
|
||||
var lastHourHigh = minuteHistory.Select(minuteBar => minuteBar.High).DefaultIfEmpty(0).Max();
|
||||
var dailyHistory = History(_symbol, 1, Resolution.Daily).First();
|
||||
var dailyHistory = History(symbol, 1, Resolution.Daily).First();
|
||||
var dailyHigh = dailyHistory.High;
|
||||
var dailyLow = dailyHistory.Low;
|
||||
var dailyOpen = dailyHistory.Open;
|
||||
|
||||
@@ -94,6 +94,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"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"},
|
||||
@@ -113,7 +114,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "50%"},
|
||||
{"Rolling Averaged Population Direction", "12.6429%"},
|
||||
{"Rolling Averaged Population Magnitude", "12.6429%"},
|
||||
{"OrderListHash", "-2004493274"}
|
||||
{"OrderListHash", "3edd51956c7c97af4863aa6059c11f1a"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
/*
|
||||
* 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.IO;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom.CBOE;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests the consolidation of custom data with random data
|
||||
/// </summary>
|
||||
public class CBOECustomDataConsolidationRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _vix;
|
||||
private BollingerBands _bb;
|
||||
private bool _invested;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the algorithm with fake VIX data
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 10, 7);
|
||||
SetEndDate(2013, 10, 11);
|
||||
SetCash(100000);
|
||||
|
||||
_vix = AddData<IncrementallyGeneratedCustomData>("VIX", Resolution.Daily).Symbol;
|
||||
_bb = BB(_vix, 30, 2, MovingAverageType.Simple, Resolution.Daily);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
/// </summary>
|
||||
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (_bb.Current.Value == 0)
|
||||
{
|
||||
throw new Exception("Bollinger Band value is zero when we expect non-zero value.");
|
||||
}
|
||||
|
||||
if (!_invested && _bb.Current.Value > 0.05m)
|
||||
{
|
||||
MarketOrder(_vix, 1);
|
||||
_invested = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Incrementally updating data
|
||||
/// </summary>
|
||||
private class IncrementallyGeneratedCustomData : CBOE
|
||||
{
|
||||
private const decimal _start = 10.01m;
|
||||
private static decimal _step;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the source of the subscription. In this case, we set it to existing
|
||||
/// equity data so that we can pass fake data from Reader
|
||||
/// </summary>
|
||||
/// <param name="config">Subscription configuration</param>
|
||||
/// <param name="date">Date we're making this request</param>
|
||||
/// <param name="isLiveMode">Is live mode</param>
|
||||
/// <returns>Source of subscription</returns>
|
||||
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
|
||||
{
|
||||
return new SubscriptionDataSource(Path.Combine(Globals.DataFolder, "equity", "usa", "minute", "spy", $"{date:yyyyMMdd}_trade.zip#{date:yyyyMMdd}_spy_minute_trade.csv"), SubscriptionTransportMedium.LocalFile, FileFormat.Csv);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the data, which in this case is fake incremental data
|
||||
/// </summary>
|
||||
/// <param name="config">Subscription configuration</param>
|
||||
/// <param name="line">Line of data</param>
|
||||
/// <param name="date">Date of the request</param>
|
||||
/// <param name="isLiveMode">Is live mode</param>
|
||||
/// <returns>Incremental BaseData instance</returns>
|
||||
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
|
||||
{
|
||||
var vix = new CBOE();
|
||||
_step += 0.10m;
|
||||
var open = _start + _step;
|
||||
var close = _start + _step + 0.02m;
|
||||
var high = close;
|
||||
var low = open;
|
||||
|
||||
return new IncrementallyGeneratedCustomData
|
||||
{
|
||||
Open = open,
|
||||
High = high,
|
||||
Low = low,
|
||||
Close = close,
|
||||
Time = date,
|
||||
Symbol = new Symbol(
|
||||
SecurityIdentifier.GenerateBase(typeof(IncrementallyGeneratedCustomData), "VIX", Market.USA, false),
|
||||
"VIX"),
|
||||
Period = vix.Period,
|
||||
DataType = vix.DataType
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// <remarks>
|
||||
/// Unable to be tested in Python, due to pythonnet not supporting overriding of methods from Python
|
||||
/// </remarks>
|
||||
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.029%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.000%"},
|
||||
{"Sharpe Ratio", "28.4"},
|
||||
{"Probabilistic Sharpe Ratio", "88.597%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-7.067"},
|
||||
{"Tracking Error", "0.193"},
|
||||
{"Treynor Ratio", "7.887"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"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", "918912ee4f64cd0290f3d58deca02713"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -147,12 +147,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$370000.00"},
|
||||
{"Fitness Score", "0.501"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-30.28"},
|
||||
{"Portfolio Turnover", "1.029"},
|
||||
{"Return Over Maximum Drawdown", "-30.158"},
|
||||
{"Portfolio Turnover", "1.033"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -166,7 +167,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1708974186"}
|
||||
{"OrderListHash", "aea2e321d17414c1f3c6fa2491f10c88"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
102
Algorithm.CSharp/CapacityTests/BeastVsPenny.cs
Normal file
102
Algorithm.CSharp/CapacityTests/BeastVsPenny.cs
Normal file
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
* 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.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests capacity by trading SPY (beast) alongside a small cap stock ABUS (penny)
|
||||
/// </summary>
|
||||
public class BeastVsPenny : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _spy;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 1);
|
||||
SetEndDate(2020, 3, 31);
|
||||
SetCash(10000);
|
||||
|
||||
_spy = AddEquity("SPY", Resolution.Hour).Symbol;
|
||||
var penny = AddEquity("ABUS", Resolution.Hour).Symbol;
|
||||
|
||||
Schedule.On(DateRules.EveryDay(_spy), TimeRules.AfterMarketOpen(_spy, 1, false), () =>
|
||||
{
|
||||
SetHoldings(_spy, 0.5m);
|
||||
SetHoldings(penny, 0.5m);
|
||||
});
|
||||
}
|
||||
|
||||
/// <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", "70"},
|
||||
{"Average Win", "0.07%"},
|
||||
{"Average Loss", "-0.51%"},
|
||||
{"Compounding Annual Return", "-89.548%"},
|
||||
{"Drawdown", "49.900%"},
|
||||
{"Expectancy", "-0.514"},
|
||||
{"Net Profit", "-42.920%"},
|
||||
{"Sharpe Ratio", "-0.797"},
|
||||
{"Probabilistic Sharpe Ratio", "9.019%"},
|
||||
{"Loss Rate", "57%"},
|
||||
{"Win Rate", "43%"},
|
||||
{"Profit-Loss Ratio", "0.13"},
|
||||
{"Alpha", "-0.24"},
|
||||
{"Beta", "1.101"},
|
||||
{"Annual Standard Deviation", "1.031"},
|
||||
{"Annual Variance", "1.063"},
|
||||
{"Information Ratio", "-0.351"},
|
||||
{"Tracking Error", "0.836"},
|
||||
{"Treynor Ratio", "-0.747"},
|
||||
{"Total Fees", "$81.45"},
|
||||
{"Estimated Strategy Capacity", "$21000.00"},
|
||||
{"Fitness Score", "0.01"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-1.284"},
|
||||
{"Return Over Maximum Drawdown", "-1.789"},
|
||||
{"Portfolio Turnover", "0.038"},
|
||||
{"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", "67c9083f604ed16fb68481e7c26878dc"}
|
||||
};
|
||||
}
|
||||
}
|
||||
147
Algorithm.CSharp/CapacityTests/CheeseMilkHourlyRebalance.cs
Normal file
147
Algorithm.CSharp/CapacityTests/CheeseMilkHourlyRebalance.cs
Normal file
@@ -0,0 +1,147 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests an illiquid asset that has bursts of liquidity around 11:00 A.M. Central Time
|
||||
/// with an hourly in and out strategy.
|
||||
/// </summary>
|
||||
public class CheeseMilkHourlyRebalance : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private ExponentialMovingAverage _fast;
|
||||
private ExponentialMovingAverage _slow;
|
||||
private Symbol _contract;
|
||||
private DateTime _lastTrade;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2021, 1, 1);
|
||||
SetEndDate(2021, 2, 17);
|
||||
SetTimeZone(TimeZones.Chicago);
|
||||
SetCash(100000);
|
||||
SetWarmup(1000);
|
||||
|
||||
var dc = AddFuture("DC", Resolution.Minute, Market.CME);
|
||||
dc.SetFilter(0, 10000);
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
var contract = data.FutureChains.Values.SelectMany(c => c.Contracts.Values)
|
||||
.OrderBy(c => c.Symbol.ID.Date)
|
||||
.FirstOrDefault()?
|
||||
.Symbol;
|
||||
|
||||
if (contract == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_contract != contract || (_fast == null && _slow == null))
|
||||
{
|
||||
_fast = EMA(contract, 600);
|
||||
_slow = EMA(contract, 1200);
|
||||
_contract = contract;
|
||||
}
|
||||
|
||||
if (!_fast.IsReady || !_slow.IsReady)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (Time - _lastTrade <= TimeSpan.FromHours(1) || Time.TimeOfDay <= new TimeSpan(10, 50, 0) || Time.TimeOfDay >= new TimeSpan(12, 30, 0))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Portfolio.ContainsKey(contract) || (Portfolio[contract].Quantity <= 0 && _fast > _slow))
|
||||
{
|
||||
SetHoldings(contract, 0.5);
|
||||
_lastTrade = Time;
|
||||
}
|
||||
else if (Portfolio.ContainsKey(contract) && Portfolio[contract].Quantity >= 0 && _fast < _slow)
|
||||
{
|
||||
SetHoldings(contract, -0.5);
|
||||
_lastTrade = Time;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = 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", "19"},
|
||||
{"Average Win", "39.16%"},
|
||||
{"Average Loss", "-8.81%"},
|
||||
{"Compounding Annual Return", "-99.857%"},
|
||||
{"Drawdown", "82.900%"},
|
||||
{"Expectancy", "-0.359"},
|
||||
{"Net Profit", "-57.725%"},
|
||||
{"Sharpe Ratio", "-0.555"},
|
||||
{"Probabilistic Sharpe Ratio", "10.606%"},
|
||||
{"Loss Rate", "88%"},
|
||||
{"Win Rate", "12%"},
|
||||
{"Profit-Loss Ratio", "4.45"},
|
||||
{"Alpha", "-1.188"},
|
||||
{"Beta", "0.603"},
|
||||
{"Annual Standard Deviation", "1.754"},
|
||||
{"Annual Variance", "3.075"},
|
||||
{"Information Ratio", "-0.759"},
|
||||
{"Tracking Error", "1.753"},
|
||||
{"Treynor Ratio", "-1.612"},
|
||||
{"Total Fees", "$2558.55"},
|
||||
{"Estimated Strategy Capacity", "$20000.00"},
|
||||
{"Fitness Score", "0.351"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.602"},
|
||||
{"Return Over Maximum Drawdown", "-1.415"},
|
||||
{"Portfolio Turnover", "14.226"},
|
||||
{"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", "4f5fd2fb25e957bd0cb7cb6d275ddb97"}
|
||||
};
|
||||
}
|
||||
}
|
||||
231
Algorithm.CSharp/CapacityTests/EmaPortfolioRebalance100.cs
Normal file
231
Algorithm.CSharp/CapacityTests/EmaPortfolioRebalance100.cs
Normal file
@@ -0,0 +1,231 @@
|
||||
/*
|
||||
* 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.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests a wide variety of liquid and illiquid stocks together, with bins
|
||||
/// of 20 ranging from micro-cap to mega-cap stocks.
|
||||
/// </summary>
|
||||
public class EmaPortfolioRebalance100 : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
public List<SymbolData> Data;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 1);
|
||||
SetEndDate(2020, 2, 5);
|
||||
SetWarmup(1000);
|
||||
SetCash(100000);
|
||||
|
||||
Data = new List<SymbolData> {
|
||||
new SymbolData(this, AddEquity("AADR", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AAMC", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AAU", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ABDC", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ABIO", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ABUS", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AC", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACER", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACES", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACGLO", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACH", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACHV", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACIO", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACIU", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACNB", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACRS", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACSI", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACT", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACT", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACTG", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZYNE", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZYME", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZUO", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZUMZ", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZTR", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZSL", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZSAN", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZROZ", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZLAB", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZIXI", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZIV", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZIOP", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZGNX", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZG", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZEUS", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZAGG", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("YYY", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("YRD", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("YRCW", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("YPF", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AA", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AAN", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AAP", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AAXN", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ABB", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ABC", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACAD", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACC", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACGL", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACIW", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACM", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACWV", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ACWX", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ADM", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ADPT", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ADS", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ADUS", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AEM", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AEO", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AEP", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ZTS", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("YUM", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("XLY", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("XLV", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("XLRE", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("XLP", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("XLNX", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("XLF", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("XLC", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("XLB", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("XEL", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("XBI", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("X", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("WYNN", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("WW", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("WORK", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("WMB", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("WM", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("WELL", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("WEC", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AAPL", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("ADBE", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AGG", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AMD", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("AMZN", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("BA", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("BABA", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("BAC", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("BMY", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("C", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("CMCSA", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("CRM", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("CSCO", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("DIS", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("EEM", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("EFA", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("FB", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("GDX", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("GE", Resolution.Minute).Symbol),
|
||||
new SymbolData(this, AddEquity("SPY", Resolution.Minute).Symbol)
|
||||
};
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
var fastFactor = 0.005m;
|
||||
|
||||
foreach (var sd in Data)
|
||||
{
|
||||
if (!Portfolio.Invested && sd.Fast * (1 + fastFactor) > sd.Slow)
|
||||
{
|
||||
SetHoldings(sd.Symbol, 0.01);
|
||||
}
|
||||
else if (Portfolio.Invested && sd.Fast * (1 - fastFactor) < sd.Slow)
|
||||
{
|
||||
Liquidate(sd.Symbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class SymbolData
|
||||
{
|
||||
public Symbol Symbol;
|
||||
public ExponentialMovingAverage Fast;
|
||||
public ExponentialMovingAverage Slow;
|
||||
public bool IsCrossed => Fast > Slow;
|
||||
|
||||
public SymbolData(QCAlgorithm algorithm, Symbol symbol) {
|
||||
Symbol = symbol;
|
||||
Fast = algorithm.EMA(symbol, 20);
|
||||
Slow = algorithm.EMA(symbol, 300);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "1015"},
|
||||
{"Average Win", "0.01%"},
|
||||
{"Average Loss", "0.00%"},
|
||||
{"Compounding Annual Return", "-12.674%"},
|
||||
{"Drawdown", "1.400%"},
|
||||
{"Expectancy", "-0.761"},
|
||||
{"Net Profit", "-1.328%"},
|
||||
{"Sharpe Ratio", "-12.258"},
|
||||
{"Probabilistic Sharpe Ratio", "0.000%"},
|
||||
{"Loss Rate", "95%"},
|
||||
{"Win Rate", "5%"},
|
||||
{"Profit-Loss Ratio", "3.67"},
|
||||
{"Alpha", "-0.142"},
|
||||
{"Beta", "0.038"},
|
||||
{"Annual Standard Deviation", "0.01"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-4.389"},
|
||||
{"Tracking Error", "0.123"},
|
||||
{"Treynor Ratio", "-3.359"},
|
||||
{"Total Fees", "$1125.52"},
|
||||
{"Estimated Strategy Capacity", "$300.00"},
|
||||
{"Fitness Score", "0.007"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-14.315"},
|
||||
{"Return Over Maximum Drawdown", "-9.589"},
|
||||
{"Portfolio Turnover", "0.406"},
|
||||
{"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", "4c165e8d648d54a85bb7b564050a6f85"}
|
||||
};
|
||||
}
|
||||
}
|
||||
117
Algorithm.CSharp/CapacityTests/IntradayMinuteScalping.cs
Normal file
117
Algorithm.CSharp/CapacityTests/IntradayMinuteScalping.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.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Scalps SPY using an EMA cross strategy at minute resolution.
|
||||
/// This tests equity strategies that trade at a higher frequency, which
|
||||
/// should have a reduced capacity estimate as a result.
|
||||
/// </summary>
|
||||
public class IntradayMinuteScalping : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _spy;
|
||||
private ExponentialMovingAverage _fast;
|
||||
private ExponentialMovingAverage _slow;
|
||||
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 1);
|
||||
SetEndDate(2020, 1, 30);
|
||||
SetCash(100000);
|
||||
SetWarmup(100);
|
||||
|
||||
_spy = AddEquity("SPY", Resolution.Minute).Symbol;
|
||||
_fast = EMA(_spy, 20);
|
||||
_slow = EMA(_spy, 40);
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (Portfolio[_spy].Quantity <= 0 && _fast > _slow)
|
||||
{
|
||||
SetHoldings(_spy, 1);
|
||||
}
|
||||
else if (Portfolio[_spy].Quantity >= 0 && _fast < _slow)
|
||||
{
|
||||
SetHoldings(_spy, -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 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", "150"},
|
||||
{"Average Win", "0.16%"},
|
||||
{"Average Loss", "-0.11%"},
|
||||
{"Compounding Annual Return", "-19.320%"},
|
||||
{"Drawdown", "3.900%"},
|
||||
{"Expectancy", "-0.193"},
|
||||
{"Net Profit", "-1.730%"},
|
||||
{"Sharpe Ratio", "-1.606"},
|
||||
{"Probabilistic Sharpe Ratio", "21.397%"},
|
||||
{"Loss Rate", "67%"},
|
||||
{"Win Rate", "33%"},
|
||||
{"Profit-Loss Ratio", "1.45"},
|
||||
{"Alpha", "-0.357"},
|
||||
{"Beta", "0.635"},
|
||||
{"Annual Standard Deviation", "0.119"},
|
||||
{"Annual Variance", "0.014"},
|
||||
{"Information Ratio", "-4.249"},
|
||||
{"Tracking Error", "0.106"},
|
||||
{"Treynor Ratio", "-0.302"},
|
||||
{"Total Fees", "$449.14"},
|
||||
{"Estimated Strategy Capacity", "$27000000.00"},
|
||||
{"Fitness Score", "0.088"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-3.259"},
|
||||
{"Return Over Maximum Drawdown", "-7.992"},
|
||||
{"Portfolio Turnover", "14.605"},
|
||||
{"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", "f5a0e9547f7455004fa6c3eb136534e9"}
|
||||
};
|
||||
}
|
||||
}
|
||||
123
Algorithm.CSharp/CapacityTests/IntradayMinuteScalpingBTCETH.cs
Normal file
123
Algorithm.CSharp/CapacityTests/IntradayMinuteScalpingBTCETH.cs
Normal file
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* 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.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Scalps BTCETH using an EMA cross strategy at minute resolution.
|
||||
/// This tests crypto strategies that trade at a higher frequency, which
|
||||
/// should have a reduced capacity estimate as a result. This also tests
|
||||
/// that currency conversions are handled properly in the strategy capacity
|
||||
/// calculation class.
|
||||
/// </summary>
|
||||
public class IntradayMinuteScalpingBTCETH : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _ethbtc;
|
||||
private ExponentialMovingAverage _fast;
|
||||
private ExponentialMovingAverage _slow;
|
||||
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2021, 1, 1);
|
||||
SetEndDate(2021, 1, 30);
|
||||
SetCash(100000);
|
||||
SetWarmup(100);
|
||||
|
||||
var ethbtc = AddCrypto("ETHBTC", Resolution.Minute, Market.GDAX);
|
||||
ethbtc.BuyingPowerModel = new BuyingPowerModel();
|
||||
_ethbtc = ethbtc.Symbol;
|
||||
|
||||
_fast = EMA(_ethbtc, 20);
|
||||
_slow = EMA(_ethbtc, 40);
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (Portfolio[_ethbtc].Quantity <= 0 && _fast > _slow)
|
||||
{
|
||||
SetHoldings(_ethbtc, 1);
|
||||
}
|
||||
else if (Portfolio[_ethbtc].Quantity >= 0 && _fast < _slow)
|
||||
{
|
||||
SetHoldings(_ethbtc, -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 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", "1005"},
|
||||
{"Average Win", "0.96%"},
|
||||
{"Average Loss", "-0.33%"},
|
||||
{"Compounding Annual Return", "76.267%"},
|
||||
{"Drawdown", "77.100%"},
|
||||
{"Expectancy", "-0.012"},
|
||||
{"Net Profit", "4.768%"},
|
||||
{"Sharpe Ratio", "1.01909630017278E+24"},
|
||||
{"Probabilistic Sharpe Ratio", "93.814%"},
|
||||
{"Loss Rate", "75%"},
|
||||
{"Win Rate", "25%"},
|
||||
{"Profit-Loss Ratio", "2.95"},
|
||||
{"Alpha", "1.3466330963256E+25"},
|
||||
{"Beta", "25.59"},
|
||||
{"Annual Standard Deviation", "13.214"},
|
||||
{"Annual Variance", "174.61"},
|
||||
{"Information Ratio", "1.02164274756513E+24"},
|
||||
{"Tracking Error", "13.181"},
|
||||
{"Treynor Ratio", "5.2622435344112E+23"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$1300000.00"},
|
||||
{"Fitness Score", "0.38"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.239"},
|
||||
{"Return Over Maximum Drawdown", "-1.385"},
|
||||
{"Portfolio Turnover", "81.433"},
|
||||
{"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", "6a779e7a8d12b4808845c75b88d43b3a"}
|
||||
};
|
||||
}
|
||||
}
|
||||
117
Algorithm.CSharp/CapacityTests/IntradayMinuteScalpingEURUSD.cs
Normal file
117
Algorithm.CSharp/CapacityTests/IntradayMinuteScalpingEURUSD.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.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Scalps EURUSD using an EMA cross strategy at minute resolution.
|
||||
/// This tests FOREX strategies that trade at a higher frequency, which
|
||||
/// should have a reduced capacity estimate as a result.
|
||||
/// </summary>
|
||||
public class IntradayMinuteScalpingEURUSD : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _eurusd;
|
||||
private ExponentialMovingAverage _fast;
|
||||
private ExponentialMovingAverage _slow;
|
||||
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2021, 1, 1);
|
||||
SetEndDate(2021, 1, 30);
|
||||
SetCash(100000);
|
||||
SetWarmup(100);
|
||||
|
||||
_eurusd = AddForex("EURUSD", Resolution.Minute, Market.Oanda).Symbol;
|
||||
_fast = EMA(_eurusd, 20);
|
||||
_slow = EMA(_eurusd, 40);
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (Portfolio[_eurusd].Quantity <= 0 && _fast > _slow)
|
||||
{
|
||||
SetHoldings(_eurusd, 1);
|
||||
}
|
||||
else if (Portfolio[_eurusd].Quantity >= 0 && _fast < _slow)
|
||||
{
|
||||
SetHoldings(_eurusd, -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 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", "671"},
|
||||
{"Average Win", "0.07%"},
|
||||
{"Average Loss", "-0.04%"},
|
||||
{"Compounding Annual Return", "-80.820%"},
|
||||
{"Drawdown", "12.200%"},
|
||||
{"Expectancy", "-0.447"},
|
||||
{"Net Profit", "-12.180%"},
|
||||
{"Sharpe Ratio", "-13.121"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "79%"},
|
||||
{"Win Rate", "21%"},
|
||||
{"Profit-Loss Ratio", "1.61"},
|
||||
{"Alpha", "-0.746"},
|
||||
{"Beta", "-0.02"},
|
||||
{"Annual Standard Deviation", "0.057"},
|
||||
{"Annual Variance", "0.003"},
|
||||
{"Information Ratio", "-4.046"},
|
||||
{"Tracking Error", "0.161"},
|
||||
{"Treynor Ratio", "37.346"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$44000000.00"},
|
||||
{"Fitness Score", "0.025"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-16.609"},
|
||||
{"Return Over Maximum Drawdown", "-7.115"},
|
||||
{"Portfolio Turnover", "52.476"},
|
||||
{"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", "74ee44736b9300c0262dc75c0cd140e1"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Scalps ES futures contracts (E-mini SP500) using an EMA cross strategy at minute resolution.
|
||||
/// This tests futures strategies that trade at a higher frequency, which
|
||||
/// should have a reduced capacity estimate as a result.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The insanely high capacity estimate of this strategy is realistic.
|
||||
/// ES notional contract value traded is around $600 Billion USD per day (!!!), which
|
||||
/// is what the capacity is set to.
|
||||
/// </remarks>
|
||||
public class IntradayMinuteScalpingFuturesES : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private ExponentialMovingAverage _fast;
|
||||
private ExponentialMovingAverage _slow;
|
||||
private Symbol _contract;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2021, 1, 1);
|
||||
SetEndDate(2021, 1, 31);
|
||||
SetCash(100000);
|
||||
SetWarmup(1000);
|
||||
|
||||
var a = AddFuture("ES", Resolution.Minute, Market.CME);
|
||||
a.SetFilter(0, 10000);
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
var contract = data.FutureChains.Values.SelectMany(c => c.Contracts.Values)
|
||||
.OrderBy(c => c.Symbol.ID.Date)
|
||||
.FirstOrDefault()?
|
||||
.Symbol;
|
||||
|
||||
if (contract == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_contract != contract || (_fast == null && _slow == null))
|
||||
{
|
||||
_fast = EMA(contract, 10);
|
||||
_slow = EMA(contract, 20);
|
||||
_contract = contract;
|
||||
}
|
||||
|
||||
if (!_fast.IsReady || !_slow.IsReady)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Portfolio.ContainsKey(contract) || (Portfolio[contract].Quantity <= 0 && _fast > _slow))
|
||||
{
|
||||
SetHoldings(contract, 1);
|
||||
}
|
||||
else if (Portfolio.ContainsKey(contract) && Portfolio[contract].Quantity >= 0 && _fast < _slow)
|
||||
{
|
||||
SetHoldings(contract, -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 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", "1217"},
|
||||
{"Average Win", "2.69%"},
|
||||
{"Average Loss", "-0.93%"},
|
||||
{"Compounding Annual Return", "-99.756%"},
|
||||
{"Drawdown", "77.200%"},
|
||||
{"Expectancy", "-0.047"},
|
||||
{"Net Profit", "-40.013%"},
|
||||
{"Sharpe Ratio", "-0.52"},
|
||||
{"Probabilistic Sharpe Ratio", "19.865%"},
|
||||
{"Loss Rate", "75%"},
|
||||
{"Win Rate", "25%"},
|
||||
{"Profit-Loss Ratio", "2.88"},
|
||||
{"Alpha", "-1.279"},
|
||||
{"Beta", "-3.686"},
|
||||
{"Annual Standard Deviation", "1.85"},
|
||||
{"Annual Variance", "3.422"},
|
||||
{"Information Ratio", "-0.463"},
|
||||
{"Tracking Error", "1.895"},
|
||||
{"Treynor Ratio", "0.261"},
|
||||
{"Total Fees", "$19843.10"},
|
||||
{"Estimated Strategy Capacity", "$560000000.00"},
|
||||
{"Fitness Score", "0.334"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.837"},
|
||||
{"Return Over Maximum Drawdown", "-1.402"},
|
||||
{"Portfolio Turnover", "1174.125"},
|
||||
{"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", "f353843132df7b0604eff3a37b134ca2"}
|
||||
};
|
||||
}
|
||||
}
|
||||
118
Algorithm.CSharp/CapacityTests/IntradayMinuteScalpingGBPJPY.cs
Normal file
118
Algorithm.CSharp/CapacityTests/IntradayMinuteScalpingGBPJPY.cs
Normal file
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Scalps GBPJPY using an EMA cross strategy at minute resolution.
|
||||
/// This tests FOREX strategies that trade at a higher frequency, which
|
||||
/// should have a reduced capacity estimate as a result. This test also
|
||||
/// tests that currency conversion rates are applied and calculated correctly.
|
||||
/// </summary>
|
||||
public class IntradayMinuteScalpingGBPJPY : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _gbpjpy;
|
||||
private ExponentialMovingAverage _fast;
|
||||
private ExponentialMovingAverage _slow;
|
||||
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2021, 1, 1);
|
||||
SetEndDate(2021, 1, 30);
|
||||
SetCash(100000);
|
||||
SetWarmup(100);
|
||||
|
||||
_gbpjpy = AddForex("GBPJPY", Resolution.Minute, Market.Oanda).Symbol;
|
||||
_fast = EMA(_gbpjpy, 20);
|
||||
_slow = EMA(_gbpjpy, 40);
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (Portfolio[_gbpjpy].Quantity <= 0 && _fast > _slow)
|
||||
{
|
||||
SetHoldings(_gbpjpy, 1);
|
||||
}
|
||||
else if (Portfolio[_gbpjpy].Quantity >= 0 && _fast < _slow)
|
||||
{
|
||||
SetHoldings(_gbpjpy, -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 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", "735"},
|
||||
{"Average Win", "0.08%"},
|
||||
{"Average Loss", "-0.05%"},
|
||||
{"Compounding Annual Return", "-93.946%"},
|
||||
{"Drawdown", "19.900%"},
|
||||
{"Expectancy", "-0.592"},
|
||||
{"Net Profit", "-19.794%"},
|
||||
{"Sharpe Ratio", "-10.054"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "84%"},
|
||||
{"Win Rate", "16%"},
|
||||
{"Profit-Loss Ratio", "1.56"},
|
||||
{"Alpha", "-0.895"},
|
||||
{"Beta", "0.068"},
|
||||
{"Annual Standard Deviation", "0.09"},
|
||||
{"Annual Variance", "0.008"},
|
||||
{"Information Ratio", "-4.929"},
|
||||
{"Tracking Error", "0.164"},
|
||||
{"Treynor Ratio", "-13.276"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$49000000.00"},
|
||||
{"Fitness Score", "0.049"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-10.846"},
|
||||
{"Return Over Maximum Drawdown", "-4.904"},
|
||||
{"Portfolio Turnover", "58.921"},
|
||||
{"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", "66f04c9622ab242993c8ce951418e6d9"}
|
||||
};
|
||||
}
|
||||
}
|
||||
118
Algorithm.CSharp/CapacityTests/IntradayMinuteScalpingTRYJPY.cs
Normal file
118
Algorithm.CSharp/CapacityTests/IntradayMinuteScalpingTRYJPY.cs
Normal file
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Scalps TRYJPY using an EMA cross strategy at minute resolution.
|
||||
/// This tests FOREX strategies that trade at a higher frequency, which
|
||||
/// should have a reduced capacity estimate as a result. This tests that
|
||||
/// currency conversions are applied properly to the capacity estimate calculation.
|
||||
/// </summary>
|
||||
public class IntradayMinuteScalpingTRYJPY : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _tryjpy;
|
||||
private ExponentialMovingAverage _fast;
|
||||
private ExponentialMovingAverage _slow;
|
||||
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2021, 1, 1);
|
||||
SetEndDate(2021, 1, 30);
|
||||
SetCash(100000);
|
||||
SetWarmup(100);
|
||||
|
||||
_tryjpy = AddForex("TRYJPY", Resolution.Minute, Market.Oanda).Symbol;
|
||||
_fast = EMA(_tryjpy, 20);
|
||||
_slow = EMA(_tryjpy, 40);
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (Portfolio[_tryjpy].Quantity <= 0 && _fast > _slow)
|
||||
{
|
||||
SetHoldings(_tryjpy, 1);
|
||||
}
|
||||
else if (Portfolio[_tryjpy].Quantity >= 0 && _fast < _slow)
|
||||
{
|
||||
SetHoldings(_tryjpy, -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 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", "603"},
|
||||
{"Average Win", "0.20%"},
|
||||
{"Average Loss", "-0.26%"},
|
||||
{"Compounding Annual Return", "-100.000%"},
|
||||
{"Drawdown", "73.200%"},
|
||||
{"Expectancy", "-0.849"},
|
||||
{"Net Profit", "-73.118%"},
|
||||
{"Sharpe Ratio", "-2.046"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "91%"},
|
||||
{"Win Rate", "9%"},
|
||||
{"Profit-Loss Ratio", "0.75"},
|
||||
{"Alpha", "-0.95"},
|
||||
{"Beta", "0.541"},
|
||||
{"Annual Standard Deviation", "0.489"},
|
||||
{"Annual Variance", "0.239"},
|
||||
{"Information Ratio", "-1.863"},
|
||||
{"Tracking Error", "0.487"},
|
||||
{"Treynor Ratio", "-1.849"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$4400000.00"},
|
||||
{"Fitness Score", "0.259"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-2.135"},
|
||||
{"Return Over Maximum Drawdown", "-1.389"},
|
||||
{"Portfolio Turnover", "49.501"},
|
||||
{"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", "4eb4d703a9f200b6bb3d8b0ebbc9db7f"}
|
||||
};
|
||||
}
|
||||
}
|
||||
111
Algorithm.CSharp/CapacityTests/MonthlyRebalanceDaily.cs
Normal file
111
Algorithm.CSharp/CapacityTests/MonthlyRebalanceDaily.cs
Normal file
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* 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.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Rebalances ultra-liquid stocks monthly, testing
|
||||
/// bursts of orders centered around the start of the month at Daily resolution
|
||||
/// </summary>
|
||||
public class MonthlyRebalanceDaily : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2019, 12, 31);
|
||||
SetEndDate(2020, 4, 5);
|
||||
SetCash(100000);
|
||||
|
||||
var spy = AddEquity("SPY", Resolution.Daily).Symbol;
|
||||
AddEquity("GE", Resolution.Daily);
|
||||
AddEquity("FB", Resolution.Daily);
|
||||
AddEquity("DIS", Resolution.Daily);
|
||||
AddEquity("CSCO", Resolution.Daily);
|
||||
AddEquity("CRM", Resolution.Daily);
|
||||
AddEquity("C", Resolution.Daily);
|
||||
AddEquity("BAC", Resolution.Daily);
|
||||
AddEquity("BABA", Resolution.Daily);
|
||||
AddEquity("AAPL", Resolution.Daily);
|
||||
|
||||
Schedule.On(DateRules.MonthStart(spy), TimeRules.Noon, () =>
|
||||
{
|
||||
foreach (var symbol in Securities.Keys)
|
||||
{
|
||||
SetHoldings(symbol, 0.10);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <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", "35"},
|
||||
{"Average Win", "0.07%"},
|
||||
{"Average Loss", "-0.07%"},
|
||||
{"Compounding Annual Return", "-68.407%"},
|
||||
{"Drawdown", "32.400%"},
|
||||
{"Expectancy", "-0.309"},
|
||||
{"Net Profit", "-25.901%"},
|
||||
{"Sharpe Ratio", "-1.503"},
|
||||
{"Probabilistic Sharpe Ratio", "2.878%"},
|
||||
{"Loss Rate", "64%"},
|
||||
{"Win Rate", "36%"},
|
||||
{"Profit-Loss Ratio", "0.90"},
|
||||
{"Alpha", "-0.7"},
|
||||
{"Beta", "-0.238"},
|
||||
{"Annual Standard Deviation", "0.386"},
|
||||
{"Annual Variance", "0.149"},
|
||||
{"Information Ratio", "-0.11"},
|
||||
{"Tracking Error", "0.712"},
|
||||
{"Treynor Ratio", "2.442"},
|
||||
{"Total Fees", "$38.99"},
|
||||
{"Estimated Strategy Capacity", "$19000000.00"},
|
||||
{"Fitness Score", "0.003"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-2.021"},
|
||||
{"Return Over Maximum Drawdown", "-2.113"},
|
||||
{"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", "76d8164a3c0d4a7d45e94367c4ba5be1"}
|
||||
};
|
||||
}
|
||||
}
|
||||
111
Algorithm.CSharp/CapacityTests/MonthlyRebalanceHourly.cs
Normal file
111
Algorithm.CSharp/CapacityTests/MonthlyRebalanceHourly.cs
Normal file
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* 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.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Rebalances ultra-liquid stocks monthly, testing
|
||||
/// bursts of orders centered around the start of the month at Hourly resolution
|
||||
/// </summary>
|
||||
public class MonthlyRebalanceHourly : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2019, 12, 31);
|
||||
SetEndDate(2020, 4, 5);
|
||||
SetCash(100000);
|
||||
|
||||
var spy = AddEquity("SPY", Resolution.Hour).Symbol;
|
||||
AddEquity("GE", Resolution.Hour);
|
||||
AddEquity("FB", Resolution.Hour);
|
||||
AddEquity("DIS", Resolution.Hour);
|
||||
AddEquity("CSCO", Resolution.Hour);
|
||||
AddEquity("CRM", Resolution.Hour);
|
||||
AddEquity("C", Resolution.Hour);
|
||||
AddEquity("BAC", Resolution.Hour);
|
||||
AddEquity("BABA", Resolution.Hour);
|
||||
AddEquity("AAPL", Resolution.Hour);
|
||||
|
||||
Schedule.On(DateRules.MonthStart(spy), TimeRules.Noon, () =>
|
||||
{
|
||||
foreach (var symbol in Securities.Keys)
|
||||
{
|
||||
SetHoldings(symbol, 0.10);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <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", "35"},
|
||||
{"Average Win", "0.05%"},
|
||||
{"Average Loss", "-0.10%"},
|
||||
{"Compounding Annual Return", "-72.444%"},
|
||||
{"Drawdown", "36.500%"},
|
||||
{"Expectancy", "-0.449"},
|
||||
{"Net Profit", "-28.406%"},
|
||||
{"Sharpe Ratio", "-1.369"},
|
||||
{"Probabilistic Sharpe Ratio", "4.398%"},
|
||||
{"Loss Rate", "64%"},
|
||||
{"Win Rate", "36%"},
|
||||
{"Profit-Loss Ratio", "0.51"},
|
||||
{"Alpha", "-0.175"},
|
||||
{"Beta", "0.892"},
|
||||
{"Annual Standard Deviation", "0.503"},
|
||||
{"Annual Variance", "0.253"},
|
||||
{"Information Ratio", "-0.822"},
|
||||
{"Tracking Error", "0.138"},
|
||||
{"Treynor Ratio", "-0.772"},
|
||||
{"Total Fees", "$38.83"},
|
||||
{"Estimated Strategy Capacity", "$6000000.00"},
|
||||
{"Fitness Score", "0.004"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-2.033"},
|
||||
{"Return Over Maximum Drawdown", "-2.079"},
|
||||
{"Portfolio Turnover", "0.018"},
|
||||
{"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", "1de9bcf6cda0945af6ba1f74c4dcb22c"}
|
||||
};
|
||||
}
|
||||
}
|
||||
112
Algorithm.CSharp/CapacityTests/SplitTestingStrategy.cs
Normal file
112
Algorithm.CSharp/CapacityTests/SplitTestingStrategy.cs
Normal file
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* 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>
|
||||
/// Tests that splits do not cause the algorithm to report capacity estimates
|
||||
/// above or below the actual capacity due to splits. The stock HTGM is illiquid,
|
||||
/// trading only $1.2 Million per day on average with sparse trade frequencies.
|
||||
/// </summary>
|
||||
public class SplitTestingStrategy : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _htgm;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 11, 1);
|
||||
SetEndDate(2020, 12, 5);
|
||||
SetCash(100000);
|
||||
|
||||
var htgm = AddEquity("HTGM", Resolution.Hour);
|
||||
htgm.SetDataNormalizationMode(DataNormalizationMode.Raw);
|
||||
_htgm = htgm.Symbol;
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
SetHoldings(_htgm, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
SetHoldings(_htgm, -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 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", "162"},
|
||||
{"Average Win", "0.10%"},
|
||||
{"Average Loss", "-0.35%"},
|
||||
{"Compounding Annual Return", "-94.432%"},
|
||||
{"Drawdown", "30.400%"},
|
||||
{"Expectancy", "-0.564"},
|
||||
{"Net Profit", "-23.412%"},
|
||||
{"Sharpe Ratio", "-1.041"},
|
||||
{"Probabilistic Sharpe Ratio", "12.971%"},
|
||||
{"Loss Rate", "66%"},
|
||||
{"Win Rate", "34%"},
|
||||
{"Profit-Loss Ratio", "0.29"},
|
||||
{"Alpha", "-4.827"},
|
||||
{"Beta", "1.43"},
|
||||
{"Annual Standard Deviation", "0.876"},
|
||||
{"Annual Variance", "0.767"},
|
||||
{"Information Ratio", "-4.288"},
|
||||
{"Tracking Error", "0.851"},
|
||||
{"Treynor Ratio", "-0.637"},
|
||||
{"Total Fees", "$2655.91"},
|
||||
{"Estimated Strategy Capacity", "$11000.00"},
|
||||
{"Fitness Score", "0.052"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-2.2"},
|
||||
{"Return Over Maximum Drawdown", "-3.481"},
|
||||
{"Portfolio Turnover", "0.307"},
|
||||
{"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", "54f571c11525656e9b383e235e77002e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
103
Algorithm.CSharp/CapacityTests/SpyBondPortfolioRebalance.cs
Normal file
103
Algorithm.CSharp/CapacityTests/SpyBondPortfolioRebalance.cs
Normal file
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Rebalances between SPY and BND. Tests capacity of the weakest link, which in this
|
||||
/// case is BND, dragging down the capacity estimate.
|
||||
/// </summary>
|
||||
public class SpyBondPortfolioRebalance : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _spy;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2020, 1, 1);
|
||||
SetEndDate(2020, 3, 31);
|
||||
SetCash(10000);
|
||||
|
||||
_spy = AddEquity("SPY", Resolution.Hour).Symbol;
|
||||
var bnd = AddEquity("BND", Resolution.Hour).Symbol;
|
||||
|
||||
Schedule.On(DateRules.EveryDay(_spy), TimeRules.AfterMarketOpen(_spy, 1, false), () =>
|
||||
{
|
||||
SetHoldings(_spy, 0.5m);
|
||||
SetHoldings(bnd, 0.5m);
|
||||
});
|
||||
}
|
||||
|
||||
/// <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", "21"},
|
||||
{"Average Win", "0.02%"},
|
||||
{"Average Loss", "-0.03%"},
|
||||
{"Compounding Annual Return", "-33.564%"},
|
||||
{"Drawdown", "19.700%"},
|
||||
{"Expectancy", "-0.140"},
|
||||
{"Net Profit", "-9.655%"},
|
||||
{"Sharpe Ratio", "-0.99"},
|
||||
{"Probabilistic Sharpe Ratio", "13.754%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.72"},
|
||||
{"Alpha", "-0.022"},
|
||||
{"Beta", "0.538"},
|
||||
{"Annual Standard Deviation", "0.309"},
|
||||
{"Annual Variance", "0.096"},
|
||||
{"Information Ratio", "0.826"},
|
||||
{"Tracking Error", "0.269"},
|
||||
{"Treynor Ratio", "-0.569"},
|
||||
{"Total Fees", "$21.00"},
|
||||
{"Estimated Strategy Capacity", "$1100000.00"},
|
||||
{"Fitness Score", "0.005"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-1.524"},
|
||||
{"Return Over Maximum Drawdown", "-1.688"},
|
||||
{"Portfolio Turnover", "0.02"},
|
||||
{"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", "95a130426900aaf227a08a5d1c617b2b"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -95,6 +95,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0.5"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -114,7 +115,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1456907343"}
|
||||
{"OrderListHash", "6ea6184a2a8d0d69e552ad866933bfb6"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +181,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.149"},
|
||||
{"Treynor Ratio", "-1.405"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$42000000.00"},
|
||||
{"Fitness Score", "0.076"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -200,7 +201,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1465929889"}
|
||||
{"OrderListHash", "edd9e9ffc8a1cdfb7a1e6ae601e61b12"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Demonstration of how to chain a coarse and fine universe selection with an option chain universe selection model
|
||||
/// that will add and remove an <see cref="OptionChainUniverse"/> for each symbol selected on fine
|
||||
/// </summary>
|
||||
public class CoarseFineOptionUniverseChainRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
// initialize our changes to nothing
|
||||
private SecurityChanges _changes = SecurityChanges.None;
|
||||
private int _optionCount;
|
||||
private Symbol _lastEquityAdded;
|
||||
private Symbol _aapl;
|
||||
private Symbol _twx;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
_twx = QuantConnect.Symbol.Create("TWX", SecurityType.Equity, Market.USA);
|
||||
_aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
|
||||
UniverseSettings.Resolution = Resolution.Minute;
|
||||
|
||||
SetStartDate(2014, 06, 05);
|
||||
SetEndDate(2014, 06, 06);
|
||||
|
||||
var selectionUniverse = AddUniverse(enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl },
|
||||
enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl });
|
||||
|
||||
AddUniverseOptions(selectionUniverse, universe =>
|
||||
{
|
||||
if (universe.Underlying == null)
|
||||
{
|
||||
throw new Exception("Underlying data point is null! This shouldn't happen, each OptionChainUniverse handles and should provide this");
|
||||
}
|
||||
return universe.IncludeWeeklys()
|
||||
.FrontMonth()
|
||||
.Contracts(universe.Take(5));
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
// if we have no changes, do nothing
|
||||
if (_changes == SecurityChanges.None ||
|
||||
_changes.AddedSecurities.Any(security => security.Price == 0))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// liquidate removed securities
|
||||
foreach (var security in _changes.RemovedSecurities)
|
||||
{
|
||||
if (security.Invested)
|
||||
{
|
||||
Liquidate(security.Symbol);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var security in _changes.AddedSecurities)
|
||||
{
|
||||
if (!security.Symbol.HasUnderlying)
|
||||
{
|
||||
_lastEquityAdded = security.Symbol;
|
||||
}
|
||||
else
|
||||
{
|
||||
// options added should all match prev added security
|
||||
if (security.Symbol.Underlying != _lastEquityAdded)
|
||||
{
|
||||
throw new Exception($"Unexpected symbol added {security.Symbol}");
|
||||
}
|
||||
|
||||
_optionCount++;
|
||||
}
|
||||
|
||||
SetHoldings(security.Symbol, 0.05m);
|
||||
|
||||
var config = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(security.Symbol).ToList();
|
||||
|
||||
if (!config.Any())
|
||||
{
|
||||
throw new Exception($"Was expecting configurations for {security.Symbol}");
|
||||
}
|
||||
if (config.Any(dataConfig => dataConfig.DataNormalizationMode != DataNormalizationMode.Raw))
|
||||
{
|
||||
throw new Exception($"Was expecting DataNormalizationMode.Raw configurations for {security.Symbol}");
|
||||
}
|
||||
}
|
||||
_changes = SecurityChanges.None;
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
_changes += changes;
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
var config = SubscriptionManager.Subscriptions.ToList();
|
||||
if (config.Any(dataConfig => dataConfig.Symbol == _twx || dataConfig.Symbol.Underlying == _twx))
|
||||
{
|
||||
throw new Exception($"Was NOT expecting any configurations for {_twx} or it's options, since coarse/fine should have deselected it");
|
||||
}
|
||||
|
||||
if (_optionCount == 0)
|
||||
{
|
||||
throw new Exception("Option universe chain did not add any option!");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "13"},
|
||||
{"Average Win", "0.65%"},
|
||||
{"Average Loss", "-0.05%"},
|
||||
{"Compounding Annual Return", "3216040423556140000000000%"},
|
||||
{"Drawdown", "0.500%"},
|
||||
{"Expectancy", "1.393"},
|
||||
{"Net Profit", "32.840%"},
|
||||
{"Sharpe Ratio", "7.14272222483913E+15"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "83%"},
|
||||
{"Win Rate", "17%"},
|
||||
{"Profit-Loss Ratio", "13.36"},
|
||||
{"Alpha", "2.59468989671647E+16"},
|
||||
{"Beta", "67.661"},
|
||||
{"Annual Standard Deviation", "3.633"},
|
||||
{"Annual Variance", "13.196"},
|
||||
{"Information Ratio", "7.24987266907741E+15"},
|
||||
{"Tracking Error", "3.579"},
|
||||
{"Treynor Ratio", "383485597312030"},
|
||||
{"Total Fees", "$13.00"},
|
||||
{"Estimated Strategy Capacity", "$3000000.00"},
|
||||
{"Fitness Score", "0.232"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0.232"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "12470afd9a74ad9c9802361f6f092777"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.126"},
|
||||
{"Treynor Ratio", "-0.607"},
|
||||
{"Total Fees", "$11.63"},
|
||||
{"Estimated Strategy Capacity", "$46000000.00"},
|
||||
{"Fitness Score", "0.013"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -155,7 +156,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1623759093"}
|
||||
{"OrderListHash", "3d1ae61492b34c39115b76757510c058"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,6 +114,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.096"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -133,7 +134,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "371857150"}
|
||||
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,6 +120,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.105"},
|
||||
{"Treynor Ratio", "1.667"},
|
||||
{"Total Fees", "$2.91"},
|
||||
{"Estimated Strategy Capacity", "$670000000.00"},
|
||||
{"Fitness Score", "0.141"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -139,7 +140,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1959413055"}
|
||||
{"OrderListHash", "718d73fbddccb63aeacbf4659938b4b8"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,6 +91,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.101"},
|
||||
{"Treynor Ratio", "5.409"},
|
||||
{"Total Fees", "$67.00"},
|
||||
{"Estimated Strategy Capacity", "$3200000.00"},
|
||||
{"Fitness Score", "0.501"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -110,7 +111,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-28636839"}
|
||||
{"OrderListHash", "ba44309886ea8ff515ef593a24456c47"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,6 +85,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.009"},
|
||||
{"Treynor Ratio", "1.575"},
|
||||
{"Total Fees", "$22.77"},
|
||||
{"Estimated Strategy Capacity", "$22000000.00"},
|
||||
{"Fitness Score", "0.999"},
|
||||
{"Kelly Criterion Estimate", "38.64"},
|
||||
{"Kelly Criterion Probability Value", "0.229"},
|
||||
@@ -104,7 +105,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "54.5455%"},
|
||||
{"Rolling Averaged Population Direction", "59.8056%"},
|
||||
{"Rolling Averaged Population Magnitude", "59.8056%"},
|
||||
{"OrderListHash", "-1225025518"}
|
||||
{"OrderListHash", "e0f388bf9e88b34388c866150b292573"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +94,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"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"},
|
||||
@@ -113,7 +114,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "54.5455%"},
|
||||
{"Rolling Averaged Population Direction", "59.8056%"},
|
||||
{"Rolling Averaged Population Magnitude", "59.8056%"},
|
||||
{"OrderListHash", "501060991"}
|
||||
{"OrderListHash", "07eb3e2c199575b547459a534057eb5e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,6 +164,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.441"},
|
||||
{"Treynor Ratio", "-0.008"},
|
||||
{"Total Fees", "$20.35"},
|
||||
{"Estimated Strategy Capacity", "$19000000.00"},
|
||||
{"Fitness Score", "0.138"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -183,7 +184,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1453269600"}
|
||||
{"OrderListHash", "7c841ca58a4385f42236838e5bf0c382"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,6 +190,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.176"},
|
||||
{"Treynor Ratio", "-1.46"},
|
||||
{"Total Fees", "$7.82"},
|
||||
{"Estimated Strategy Capacity", "$12000000.00"},
|
||||
{"Fitness Score", "0.1"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -209,7 +210,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-611289773"}
|
||||
{"OrderListHash", "71984e154883ece4aef1d71bafbfccaf"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,8 +144,9 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Annual Variance", "0.027"},
|
||||
{"Information Ratio", "-0.391"},
|
||||
{"Tracking Error", "0.239"},
|
||||
{"Treynor Ratio", "-1.416"},
|
||||
{"Treynor Ratio", "-1.435"},
|
||||
{"Total Fees", "$755.29"},
|
||||
{"Estimated Strategy Capacity", "$1100000000.00"},
|
||||
{"Fitness Score", "0.024"},
|
||||
{"Kelly Criterion Estimate", "-0.84"},
|
||||
{"Kelly Criterion Probability Value", "0.53"},
|
||||
@@ -165,7 +166,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "48.2217%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1370210213"}
|
||||
{"OrderListHash", "95f34359f25a7a7a2725f0343a75a105"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +38,10 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
// Find more symbols here: http://quantconnect.com/data
|
||||
AddSecurity(SecurityType.Equity, "SPY", Resolution.Second);
|
||||
|
||||
// Disabling the benchmark / setting to a fixed value
|
||||
// SetBenchmark(time => 0);
|
||||
|
||||
// Set the benchmark to AAPL US Equity
|
||||
SetBenchmark("AAPL");
|
||||
}
|
||||
|
||||
@@ -95,6 +99,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.168"},
|
||||
{"Treynor Ratio", "2.38"},
|
||||
{"Total Fees", "$3.26"},
|
||||
{"Estimated Strategy Capacity", "$300000000.00"},
|
||||
{"Fitness Score", "0.245"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -114,7 +119,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "2069976135"}
|
||||
{"OrderListHash", "9cd604d2c1e3c273697e2ff2cc7faef1"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,6 +96,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0.988"},
|
||||
{"Total Fees", "$7.78"},
|
||||
{"Estimated Strategy Capacity", "$8700000.00"},
|
||||
{"Fitness Score", "0.031"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -115,7 +116,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "519536519"}
|
||||
{"OrderListHash", "be3334e4aeb9dd7cca4ecc07419d0f95"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
139
Algorithm.CSharp/CustomBuyingPowerModelAlgorithm.cs
Normal file
139
Algorithm.CSharp/CustomBuyingPowerModelAlgorithm.cs
Normal file
@@ -0,0 +1,139 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Demonstration of using custom buying power model in backtesting.
|
||||
/// QuantConnect allows you to model all orders as deeply and accurately as you need.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="trading and orders" />
|
||||
/// <meta name="tag" content="transaction fees and slippage" />
|
||||
/// <meta name="tag" content="custom buying power models" />
|
||||
public class CustomBuyingPowerModelAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _spy;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 10, 01);
|
||||
SetEndDate(2013, 10, 31);
|
||||
var security = AddEquity("SPY", Resolution.Hour);
|
||||
_spy = security.Symbol;
|
||||
|
||||
// set the buying power model
|
||||
security.SetBuyingPowerModel(new CustomBuyingPowerModel());
|
||||
}
|
||||
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var quantity = CalculateOrderQuantity(_spy, 1m);
|
||||
if (quantity % 100 != 0)
|
||||
{
|
||||
throw new Exception($"CustomBuyingPowerModel only allow quantity that is multiple of 100 and {quantity} was found");
|
||||
}
|
||||
|
||||
// We normally get insufficient buying power model, but the
|
||||
// CustomBuyingPowerModel always says that there is sufficient buying power for the orders
|
||||
MarketOrder(_spy, quantity * 10);
|
||||
}
|
||||
|
||||
public class CustomBuyingPowerModel : BuyingPowerModel
|
||||
{
|
||||
public override GetMaximumOrderQuantityResult GetMaximumOrderQuantityForTargetBuyingPower(
|
||||
GetMaximumOrderQuantityForTargetBuyingPowerParameters parameters)
|
||||
{
|
||||
var quantity = base.GetMaximumOrderQuantityForTargetBuyingPower(parameters).Quantity;
|
||||
quantity = Math.Floor(quantity / 100) * 100;
|
||||
return new GetMaximumOrderQuantityResult(quantity);
|
||||
}
|
||||
|
||||
public override HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerForOrder(
|
||||
HasSufficientBuyingPowerForOrderParameters parameters)
|
||||
{
|
||||
return new HasSufficientBuyingPowerForOrderResult(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "5672.520%"},
|
||||
{"Drawdown", "22.500%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "40.601%"},
|
||||
{"Sharpe Ratio", "40.201"},
|
||||
{"Probabilistic Sharpe Ratio", "77.339%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "41.848"},
|
||||
{"Beta", "9.224"},
|
||||
{"Annual Standard Deviation", "1.164"},
|
||||
{"Annual Variance", "1.355"},
|
||||
{"Information Ratio", "44.459"},
|
||||
{"Tracking Error", "1.04"},
|
||||
{"Treynor Ratio", "5.073"},
|
||||
{"Total Fees", "$30.00"},
|
||||
{"Estimated Strategy Capacity", "$20000000.00"},
|
||||
{"Fitness Score", "0.418"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "113.05"},
|
||||
{"Return Over Maximum Drawdown", "442.81"},
|
||||
{"Portfolio Turnover", "0.418"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "b88362c462e9ab2942cbcb8dfddc6ce0"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// OnEndOfDay Event Handler - At the end of each trading day we fire this code.
|
||||
/// To avoid flooding, we recommend running your plotting at the end of each day.
|
||||
/// </summary>
|
||||
public override void OnEndOfDay()
|
||||
public override void OnEndOfDay(Symbol symbol)
|
||||
{
|
||||
//Log the end of day prices:
|
||||
Plot("Trade Plot", "Price", _lastPrice);
|
||||
|
||||
@@ -119,6 +119,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.112"},
|
||||
{"Treynor Ratio", "-6.121"},
|
||||
{"Total Fees", "$3.50"},
|
||||
{"Estimated Strategy Capacity", "$48000000.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -138,7 +139,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "559673838"}
|
||||
{"OrderListHash", "6b05339bfcb5bd93bfd66e32a1d2181a"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,6 +124,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.112"},
|
||||
{"Treynor Ratio", "-6.121"},
|
||||
{"Total Fees", "$3.50"},
|
||||
{"Estimated Strategy Capacity", "$48000000.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -143,7 +144,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "559673838"}
|
||||
{"OrderListHash", "6b05339bfcb5bd93bfd66e32a1d2181a"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,6 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.19"},
|
||||
{"Treynor Ratio", "2.159"},
|
||||
{"Total Fees", "$1.00"},
|
||||
{"Estimated Strategy Capacity", "$58000000.00"},
|
||||
{"Fitness Score", "0.1"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -150,7 +151,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1531253381"}
|
||||
{"OrderListHash", "214f38f9084bc350c93010aa2fb69822"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,7 +58,9 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
//Weather used as a tradable asset, like stocks, futures etc.
|
||||
if (data.Close != 0)
|
||||
{
|
||||
Order("BTC", (Portfolio.MarginRemaining / Math.Abs(data.Close + 1)));
|
||||
// It's only OK to use SetHoldings with crypto when using custom data. When trading with built-in crypto data,
|
||||
// use the cashbook. Reference https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/BasicTemplateCryptoAlgorithm.py
|
||||
SetHoldings("BTC", 1);
|
||||
}
|
||||
Console.WriteLine("Buying BTC 'Shares': BTC: " + data.Close);
|
||||
}
|
||||
@@ -117,7 +119,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
//return "http://my-ftp-server.com/futures-data-" + date.ToString("Ymd") + ".zip";
|
||||
// OR simply return a fixed small data file. Large files will slow down your backtest
|
||||
return new SubscriptionDataSource("https://www.quandl.com/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc", SubscriptionTransportMedium.RemoteFile);
|
||||
return new SubscriptionDataSource("https://www.quantconnect.com/api/v2/proxy/quandl/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc&api_key=WyAazVXnq7ATy_fefTqm", SubscriptionTransportMedium.RemoteFile);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -154,6 +156,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
string[] data = line.Split(',');
|
||||
coin.Time = DateTime.Parse(data[0], CultureInfo.InvariantCulture);
|
||||
coin.EndTime = coin.Time.AddDays(1);
|
||||
coin.Open = Convert.ToDecimal(data[1], CultureInfo.InvariantCulture);
|
||||
coin.High = Convert.ToDecimal(data[2], CultureInfo.InvariantCulture);
|
||||
coin.Low = Convert.ToDecimal(data[3], CultureInfo.InvariantCulture);
|
||||
|
||||
@@ -61,7 +61,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// "Nifty" type below and fired into this event handler.
|
||||
/// </summary>
|
||||
/// <param name="data">One(1) Nifty Object, streamed into our algorithm synchronised in time with our other data streams</param>
|
||||
public void OnData(Slice data)
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (data.ContainsKey("USDINR"))
|
||||
{
|
||||
@@ -77,7 +77,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
|
||||
_today.NiftyPrice = Convert.ToDouble(data["NIFTY"].Close);
|
||||
if (_today.Date == data["NIFTY"].EndTime)
|
||||
if (_today.Date == data["NIFTY"].Time)
|
||||
{
|
||||
_prices.Add(_today);
|
||||
|
||||
@@ -91,7 +91,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
var quantity = (int)(Portfolio.MarginRemaining * 0.9m / data["NIFTY"].Close);
|
||||
var highestNifty = (from pair in _prices select pair.NiftyPrice).Max();
|
||||
var lowestNifty = (from pair in _prices select pair.NiftyPrice).Min();
|
||||
|
||||
|
||||
if (Time.DayOfWeek == DayOfWeek.Wednesday) //prices.Count >= minimumCorrelationHistory &&
|
||||
{
|
||||
//List<double> niftyPrices = (from pair in prices select pair.NiftyPrice).ToList();
|
||||
@@ -121,7 +121,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// End of a trading day event handler. This method is called at the end of the algorithm day (or multiple times if trading multiple assets).
|
||||
/// </summary>
|
||||
/// <remarks>Method is called 10 minutes before closing to allow user to close out position.</remarks>
|
||||
public override void OnEndOfDay()
|
||||
public override void OnEndOfDay(Symbol symbol)
|
||||
{
|
||||
Plot("Nifty Closing Price", _today.NiftyPrice);
|
||||
}
|
||||
@@ -181,6 +181,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
//2011-09-13 7792.9 7799.9 7722.65 7748.7 116534670 6107.78
|
||||
var data = line.Split(',');
|
||||
index.Time = DateTime.Parse(data[0], CultureInfo.InvariantCulture);
|
||||
index.EndTime = index.Time.AddDays(1);
|
||||
index.Open = Convert.ToDecimal(data[1], CultureInfo.InvariantCulture);
|
||||
index.High = Convert.ToDecimal(data[2], CultureInfo.InvariantCulture);
|
||||
index.Low = Convert.ToDecimal(data[3], CultureInfo.InvariantCulture);
|
||||
@@ -247,6 +248,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
var data = line.Split(',');
|
||||
currency.Time = DateTime.Parse(data[0], CultureInfo.InvariantCulture);
|
||||
currency.EndTime = currency.Time.AddDays(1);
|
||||
currency.Close = Convert.ToDecimal(data[1], CultureInfo.InvariantCulture);
|
||||
currency.Symbol = "USDINR";
|
||||
currency.Value = currency.Close;
|
||||
|
||||
262
Algorithm.CSharp/CustomDataPropertiesRegressionAlgorithm.cs
Normal file
262
Algorithm.CSharp/CustomDataPropertiesRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,262 @@
|
||||
/*
|
||||
* 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.Globalization;
|
||||
using Newtonsoft.Json;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression test to demonstrate setting custom Symbol Properties and Market Hours for a custom data import
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="custom data" />
|
||||
/// <meta name="tag" content="crypto" />
|
||||
/// <meta name="tag" content="regression test" />
|
||||
public class CustomDataPropertiesRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private string _ticker = "BTC";
|
||||
private Security _bitcoin;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2011, 9, 13);
|
||||
SetEndDate(2015, 12, 01);
|
||||
|
||||
//Set the cash for the strategy:
|
||||
SetCash(100000);
|
||||
|
||||
// Define our custom data properties and exchange hours
|
||||
var properties = new SymbolProperties("Bitcoin", "USD", 1, 0.01m, 0.01m, _ticker);
|
||||
var exchangeHours = SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork);
|
||||
|
||||
// Add the custom data to our algorithm with our custom properties and exchange hours
|
||||
_bitcoin = AddData<Bitcoin>(_ticker, properties, exchangeHours);
|
||||
|
||||
//Verify our symbol properties were changed and loaded into this security
|
||||
if (_bitcoin.SymbolProperties != properties)
|
||||
{
|
||||
throw new Exception("Failed to set and retrieve custom SymbolProperties for BTC");
|
||||
}
|
||||
|
||||
//Verify our exchange hours were changed and loaded into this security
|
||||
if (_bitcoin.Exchange.Hours != exchangeHours)
|
||||
{
|
||||
throw new Exception("Failed to set and retrieve custom ExchangeHours for BTC");
|
||||
}
|
||||
|
||||
// For regression purposes on AddData overloads, this call is simply to ensure Lean can accept this
|
||||
// with default params and is not routed to a breaking function.
|
||||
AddData<Bitcoin>("BTCUSD");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event Handler for Bitcoin Data Events: These Bitcoin objects are created from our
|
||||
/// "Bitcoin" type below and fired into this event handler.
|
||||
/// </summary>
|
||||
/// <param name="data">One(1) Bitcoin Object, streamed into our algorithm synchronized in time with our other data streams</param>
|
||||
public void OnData(Bitcoin data)
|
||||
{
|
||||
//If we don't have any bitcoin "SHARES" -- invest"
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
//Bitcoin used as a tradable asset, like stocks, futures etc.
|
||||
if (data.Close != 0)
|
||||
{
|
||||
//Access custom data symbols using <ticker>.<custom-type>
|
||||
Order("BTC.Bitcoin", Portfolio.MarginRemaining / Math.Abs(data.Close + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
// Reset our Symbol property value, for testing purposes.
|
||||
SymbolPropertiesDatabase.SetEntry(Market.USA, MarketHoursDatabase.GetDatabaseSymbolKey(_bitcoin.Symbol), SecurityType.Base,
|
||||
SymbolProperties.GetDefault("USD"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
public bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "157.498%"},
|
||||
{"Drawdown", "84.800%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "5319.081%"},
|
||||
{"Sharpe Ratio", "2.086"},
|
||||
{"Probabilistic Sharpe Ratio", "69.456%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "1.736"},
|
||||
{"Beta", "0.136"},
|
||||
{"Annual Standard Deviation", "0.84"},
|
||||
{"Annual Variance", "0.706"},
|
||||
{"Information Ratio", "1.925"},
|
||||
{"Tracking Error", "0.846"},
|
||||
{"Treynor Ratio", "12.904"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "2.269"},
|
||||
{"Return Over Maximum Drawdown", "1.858"},
|
||||
{"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", "0d80bb47bd16b5bc6989a4c1c7aa8349"}
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Custom Data Type: Bitcoin data from Quandl - http://www.quandl.com/help/api-for-bitcoin-data
|
||||
/// </summary>
|
||||
public class Bitcoin : BaseData
|
||||
{
|
||||
[JsonProperty("timestamp")]
|
||||
public int Timestamp = 0;
|
||||
[JsonProperty("open")]
|
||||
public decimal Open = 0;
|
||||
[JsonProperty("high")]
|
||||
public decimal High = 0;
|
||||
[JsonProperty("low")]
|
||||
public decimal Low = 0;
|
||||
[JsonProperty("last")]
|
||||
public decimal Close = 0;
|
||||
[JsonProperty("bid")]
|
||||
public decimal Bid = 0;
|
||||
[JsonProperty("ask")]
|
||||
public decimal Ask = 0;
|
||||
[JsonProperty("vwap")]
|
||||
public decimal WeightedPrice = 0;
|
||||
[JsonProperty("volume")]
|
||||
public decimal VolumeBTC = 0;
|
||||
public decimal VolumeUSD = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 1. DEFAULT CONSTRUCTOR: Custom data types need a default constructor.
|
||||
/// We search for a default constructor so please provide one here. It won't be used for data, just to generate the "Factory".
|
||||
/// </summary>
|
||||
public Bitcoin()
|
||||
{
|
||||
Symbol = "BTC";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 2. RETURN THE STRING URL SOURCE LOCATION FOR YOUR DATA:
|
||||
/// This is a powerful and dynamic select source file method. If you have a large dataset, 10+mb we recommend you break it into smaller files. E.g. One zip per year.
|
||||
/// We can accept raw text or ZIP files. We read the file extension to determine if it is a zip file.
|
||||
/// </summary>
|
||||
/// <param name="config">Configuration object</param>
|
||||
/// <param name="date">Date of this source file</param>
|
||||
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
|
||||
/// <returns>String URL of source file.</returns>
|
||||
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
|
||||
{
|
||||
if (isLiveMode)
|
||||
{
|
||||
return new SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.Rest);
|
||||
}
|
||||
|
||||
//return "http://my-ftp-server.com/futures-data-" + date.ToString("Ymd") + ".zip";
|
||||
// OR simply return a fixed small data file. Large files will slow down your backtest
|
||||
return new SubscriptionDataSource("https://www.quantconnect.com/api/v2/proxy/quandl/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc&api_key=WyAazVXnq7ATy_fefTqm", SubscriptionTransportMedium.RemoteFile);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 3. READER METHOD: Read 1 line from data source and convert it into Object.
|
||||
/// Each line of the CSV File is presented in here. The backend downloads your file, loads it into memory and then line by line
|
||||
/// feeds it into your algorithm
|
||||
/// </summary>
|
||||
/// <param name="line">string line from the data source file submitted above</param>
|
||||
/// <param name="config">Subscription data, symbol name, data type</param>
|
||||
/// <param name="date">Current date we're requesting. This allows you to break up the data source into daily files.</param>
|
||||
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
|
||||
/// <returns>New Bitcoin Object which extends BaseData.</returns>
|
||||
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
|
||||
{
|
||||
var coin = new Bitcoin();
|
||||
if (isLiveMode)
|
||||
{
|
||||
//Example Line Format:
|
||||
//{"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"}
|
||||
try
|
||||
{
|
||||
coin = JsonConvert.DeserializeObject<Bitcoin>(line);
|
||||
coin.EndTime = DateTime.UtcNow.ConvertFromUtc(config.ExchangeTimeZone);
|
||||
coin.Value = coin.Close;
|
||||
}
|
||||
catch { /* Do nothing, possible error in json decoding */ }
|
||||
return coin;
|
||||
}
|
||||
|
||||
//Example Line Format:
|
||||
//Date Open High Low Close Volume (BTC) Volume (Currency) Weighted Price
|
||||
//2011-09-13 5.8 6.0 5.65 5.97 58.37138238, 346.0973893944 5.929230648356
|
||||
try
|
||||
{
|
||||
string[] data = line.Split(',');
|
||||
coin.Time = DateTime.Parse(data[0], CultureInfo.InvariantCulture);
|
||||
coin.EndTime = coin.Time.AddDays(1);
|
||||
coin.Open = Convert.ToDecimal(data[1], CultureInfo.InvariantCulture);
|
||||
coin.High = Convert.ToDecimal(data[2], CultureInfo.InvariantCulture);
|
||||
coin.Low = Convert.ToDecimal(data[3], CultureInfo.InvariantCulture);
|
||||
coin.Close = Convert.ToDecimal(data[4], CultureInfo.InvariantCulture);
|
||||
coin.VolumeBTC = Convert.ToDecimal(data[5], CultureInfo.InvariantCulture);
|
||||
coin.VolumeUSD = Convert.ToDecimal(data[6], CultureInfo.InvariantCulture);
|
||||
coin.WeightedPrice = Convert.ToDecimal(data[7], CultureInfo.InvariantCulture);
|
||||
coin.Value = coin.Close;
|
||||
}
|
||||
catch { /* Do nothing, skip first title row */ }
|
||||
|
||||
return coin;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -84,28 +84,29 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "155.262%"},
|
||||
{"Compounding Annual Return", "157.497%"},
|
||||
{"Drawdown", "84.800%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "5123.170%"},
|
||||
{"Sharpe Ratio", "2.066"},
|
||||
{"Probabilistic Sharpe Ratio", "68.832%"},
|
||||
{"Net Profit", "5319.007%"},
|
||||
{"Sharpe Ratio", "2.086"},
|
||||
{"Probabilistic Sharpe Ratio", "69.456%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "1.732"},
|
||||
{"Beta", "0.037"},
|
||||
{"Annual Standard Deviation", "0.841"},
|
||||
{"Annual Variance", "0.707"},
|
||||
{"Information Ratio", "1.902"},
|
||||
{"Tracking Error", "0.848"},
|
||||
{"Treynor Ratio", "46.996"},
|
||||
{"Alpha", "1.736"},
|
||||
{"Beta", "0.136"},
|
||||
{"Annual Standard Deviation", "0.84"},
|
||||
{"Annual Variance", "0.706"},
|
||||
{"Information Ratio", "1.925"},
|
||||
{"Tracking Error", "0.846"},
|
||||
{"Treynor Ratio", "12.903"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "2.238"},
|
||||
{"Return Over Maximum Drawdown", "1.832"},
|
||||
{"Sortino Ratio", "2.269"},
|
||||
{"Return Over Maximum Drawdown", "1.858"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -120,7 +121,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-541549381"}
|
||||
{"OrderListHash", "50faa37f15732bf5c24ad1eeaa335bc7"}
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
@@ -212,6 +213,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
string[] data = line.Split(',');
|
||||
coin.Time = DateTime.Parse(data[0], CultureInfo.InvariantCulture);
|
||||
coin.EndTime = coin.Time.AddDays(1);
|
||||
coin.Open = Convert.ToDecimal(data[1], CultureInfo.InvariantCulture);
|
||||
coin.High = Convert.ToDecimal(data[2], CultureInfo.InvariantCulture);
|
||||
coin.Low = Convert.ToDecimal(data[3], CultureInfo.InvariantCulture);
|
||||
@@ -227,4 +229,4 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -141,6 +141,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.726"},
|
||||
{"Treynor Ratio", "0.142"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0.127"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -160,7 +161,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1014157203"}
|
||||
{"OrderListHash", "1c319ae4b15416184a247bb47b31aabc"}
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -26,11 +26,12 @@ using QuantConnect.Securities;
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Demonstration of using custom fee, slippage and fill models for modelling transactions in backtesting.
|
||||
/// Demonstration of using custom fee, slippage, fill, and buying power models for modelling transactions in backtesting.
|
||||
/// QuantConnect allows you to model all orders as deeply and accurately as you need.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="trading and orders" />
|
||||
/// <meta name="tag" content="transaction fees and slippage" />
|
||||
/// <meta name="tag" content="custom buying power models" />
|
||||
/// <meta name="tag" content="custom transaction models" />
|
||||
/// <meta name="tag" content="custom slippage models" />
|
||||
/// <meta name="tag" content="custom fee models" />
|
||||
@@ -50,6 +51,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
_security.SetFeeModel(new CustomFeeModel(this));
|
||||
_security.SetFillModel(new CustomFillModel(this));
|
||||
_security.SetSlippageModel(new CustomSlippageModel(this));
|
||||
_security.SetBuyingPowerModel(new CustomBuyingPowerModel(this));
|
||||
}
|
||||
|
||||
public void OnData(TradeBars data)
|
||||
@@ -60,13 +62,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
if (Time.Day > 10 && _security.Holdings.Quantity <= 0)
|
||||
{
|
||||
var quantity = CalculateOrderQuantity(_spy, .5m);
|
||||
Log("MarketOrder: " + quantity);
|
||||
Log($"MarketOrder: {quantity}");
|
||||
MarketOrder(_spy, quantity, asynchronous: true); // async needed for partial fill market orders
|
||||
}
|
||||
else if (Time.Day > 20 && _security.Holdings.Quantity >= 0)
|
||||
{
|
||||
var quantity = CalculateOrderQuantity(_spy, -.5m);
|
||||
Log("MarketOrder: " + quantity);
|
||||
Log($"MarketOrder: {quantity}");
|
||||
MarketOrder(_spy, quantity, asynchronous: true); // async needed for partial fill market orders
|
||||
}
|
||||
}
|
||||
@@ -109,7 +111,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
fill.Status = OrderStatus.PartiallyFilled;
|
||||
}
|
||||
|
||||
_algorithm.Log("CustomFillModel: " + fill);
|
||||
_algorithm.Log($"CustomFillModel: {fill}");
|
||||
|
||||
return fill;
|
||||
}
|
||||
@@ -131,7 +133,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
1m,
|
||||
parameters.Security.Price*parameters.Order.AbsoluteQuantity*0.00001m);
|
||||
|
||||
_algorithm.Log("CustomFeeModel: " + fee);
|
||||
_algorithm.Log($"CustomFeeModel: {fee}");
|
||||
return new OrderFee(new CashAmount(fee, "USD"));
|
||||
}
|
||||
}
|
||||
@@ -150,11 +152,31 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
// custom slippage math
|
||||
var slippage = asset.Price*0.0001m*(decimal) Math.Log10(2*(double) order.AbsoluteQuantity);
|
||||
|
||||
_algorithm.Log("CustomSlippageModel: " + slippage);
|
||||
_algorithm.Log($"CustomSlippageModel: {slippage}");
|
||||
return slippage;
|
||||
}
|
||||
}
|
||||
|
||||
public class CustomBuyingPowerModel : BuyingPowerModel
|
||||
{
|
||||
private readonly QCAlgorithm _algorithm;
|
||||
|
||||
public CustomBuyingPowerModel(QCAlgorithm algorithm)
|
||||
{
|
||||
_algorithm = algorithm;
|
||||
}
|
||||
|
||||
public override HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerForOrder(
|
||||
HasSufficientBuyingPowerForOrderParameters parameters)
|
||||
{
|
||||
// custom behavior: this model will assume that there is always enough buying power
|
||||
var hasSufficientBuyingPowerForOrderResult = new HasSufficientBuyingPowerForOrderResult(true);
|
||||
_algorithm.Log($"CustomBuyingPowerModel: {hasSufficientBuyingPowerForOrderResult.IsSufficient}");
|
||||
|
||||
return hasSufficientBuyingPowerForOrderResult;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
||||
/// </summary>
|
||||
@@ -190,6 +212,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.118"},
|
||||
{"Treynor Ratio", "-0.591"},
|
||||
{"Total Fees", "$62.24"},
|
||||
{"Estimated Strategy Capacity", "$49000000.00"},
|
||||
{"Fitness Score", "0.147"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -209,7 +232,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "852026186"}
|
||||
{"OrderListHash", "71c17655bd0731eb25433727526e95ba"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,6 +103,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.251"},
|
||||
{"Treynor Ratio", "9.323"},
|
||||
{"Total Fees", "$3.26"},
|
||||
{"Estimated Strategy Capacity", "$890000000.00"},
|
||||
{"Fitness Score", "0.201"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -122,7 +123,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1268340653"}
|
||||
{"OrderListHash", "82fee25cd17100c53bb173834ab5f0b2"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,6 +193,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.211"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -212,7 +213,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "371857150"}
|
||||
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,6 +118,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.183"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -137,7 +138,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "371857150"}
|
||||
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,6 +118,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.212"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -137,7 +138,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "371857150"}
|
||||
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
@@ -16,7 +16,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using NodaTime;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Interfaces;
|
||||
@@ -45,7 +44,26 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
for (int i = 0; i < _symbols.Length; i++)
|
||||
{
|
||||
var symbol = _symbols[i];
|
||||
var history = History<QuoteBar>(symbol, 10, Resolution.Daily);
|
||||
IEnumerable<BaseData> history;
|
||||
if (symbol.SecurityType == SecurityType.Equity)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
history = History<QuoteBar>(symbol, 10, Resolution.Daily).Select(bar => bar as BaseData);
|
||||
throw new Exception("We were expecting an argument exception to be thrown. Equity does not have daily QuoteBars!");
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// expected
|
||||
}
|
||||
history = History<TradeBar>(symbol, 10, Resolution.Daily).Select(bar => bar as BaseData);
|
||||
}
|
||||
else
|
||||
{
|
||||
history = History<QuoteBar>(symbol, 10, Resolution.Daily)
|
||||
.Select(bar => bar as BaseData);
|
||||
}
|
||||
|
||||
var duplications = history
|
||||
.GroupBy(k => k.Time)
|
||||
@@ -93,6 +111,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -112,7 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "371857150"}
|
||||
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +136,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -155,7 +156,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "371857150"}
|
||||
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,25 +100,26 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Drawdown", "1.300%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.634%"},
|
||||
{"Sharpe Ratio", "2.476"},
|
||||
{"Probabilistic Sharpe Ratio", "92.194%"},
|
||||
{"Sharpe Ratio", "2.495"},
|
||||
{"Probabilistic Sharpe Ratio", "92.298%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.006"},
|
||||
{"Beta", "0.158"},
|
||||
{"Annual Standard Deviation", "0.032"},
|
||||
{"Annual Standard Deviation", "0.033"},
|
||||
{"Annual Variance", "0.001"},
|
||||
{"Information Ratio", "-4.89"},
|
||||
{"Information Ratio", "-4.942"},
|
||||
{"Tracking Error", "0.08"},
|
||||
{"Treynor Ratio", "0.509"},
|
||||
{"Treynor Ratio", "0.517"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Estimated Strategy Capacity", "$270000000.00"},
|
||||
{"Fitness Score", "0.019"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "1.362"},
|
||||
{"Return Over Maximum Drawdown", "9.699"},
|
||||
{"Portfolio Turnover", "0.022"},
|
||||
{"Portfolio Turnover", "0.023"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -132,7 +133,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1252326142"}
|
||||
{"OrderListHash", "00d6dc8775da38f7f79defad06de240a"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
SetEndDate(2007, 05, 25); //Set End Date
|
||||
SetCash(100000); //Set Strategy Cash
|
||||
// Find more symbols here: http://quantconnect.com/data
|
||||
AddSecurity(SecurityType.Equity, "AAA", Resolution.Daily);
|
||||
AddSecurity(SecurityType.Equity, "AAA.1", Resolution.Daily);
|
||||
AddSecurity(SecurityType.Equity, "SPY", Resolution.Daily);
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
_dataCount += data.Bars.Count;
|
||||
if (Transactions.OrdersCount == 0)
|
||||
{
|
||||
SetHoldings("AAA", 1);
|
||||
SetHoldings("AAA.1", 1);
|
||||
Debug("Purchased Stock");
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
// the slice can also contain delisting data: data.Delistings in a dictionary string->Delisting
|
||||
|
||||
var aaa = Securities["AAA"];
|
||||
var aaa = Securities["AAA.1"];
|
||||
if (aaa.IsDelisted && aaa.IsTradable)
|
||||
{
|
||||
throw new Exception("Delisted security must NOT be tradable");
|
||||
@@ -160,6 +160,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.155"},
|
||||
{"Treynor Ratio", "1.589"},
|
||||
{"Total Fees", "$55.05"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0.002"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -179,7 +180,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-2022527947"}
|
||||
{"OrderListHash", "61f4d3c109fc4b6b9eb14d2e4eec4843"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
149
Algorithm.CSharp/DelistingFutureOptionRegressionAlgorithm.cs
Normal file
149
Algorithm.CSharp/DelistingFutureOptionRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,149 @@
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression algorithm reproducing issue #5160 where delisting order would be cancelled because it was placed at the market close on the delisting day
|
||||
/// </summary>
|
||||
public class DelistingFutureOptionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private bool _traded;
|
||||
private int _lastMonth;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2012, 1, 1);
|
||||
SetEndDate(2013, 1, 1);
|
||||
SetCash(10000000);
|
||||
|
||||
var dc = AddFuture(Futures.Dairy.ClassIIIMilk, Resolution.Minute, Market.CME);
|
||||
dc.SetFilter(1, 120);
|
||||
|
||||
AddFutureOption(dc.Symbol, universe => universe.Strikes(-2, 2));
|
||||
_lastMonth = -1;
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (Time.Month != _lastMonth)
|
||||
{
|
||||
_lastMonth = Time.Month;
|
||||
var investedSymbols = Securities.Values
|
||||
.Where(security => security.Invested)
|
||||
.Select(security => security.Symbol)
|
||||
.ToList();
|
||||
|
||||
var delistedSecurity = investedSymbols.Where(symbol => symbol.ID.Date.AddDays(1) < Time).ToList();
|
||||
if (delistedSecurity.Count > 0)
|
||||
{
|
||||
throw new Exception($"[{UtcTime}] We hold a delisted securities: {string.Join(",", delistedSecurity)}");
|
||||
}
|
||||
Log($"Holdings({Time}): {string.Join(",", investedSymbols)}");
|
||||
}
|
||||
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var chain in data.OptionChains.Values)
|
||||
{
|
||||
foreach (var contractsValue in chain.Contracts.Values)
|
||||
{
|
||||
MarketOrder(contractsValue.Symbol, 1);
|
||||
_traded = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (!_traded)
|
||||
{
|
||||
throw new Exception("We expected some FOP trading to happen");
|
||||
}
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
throw new Exception("We shouldn't be invested anymore");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "16"},
|
||||
{"Average Win", "0.01%"},
|
||||
{"Average Loss", "-0.02%"},
|
||||
{"Compounding Annual Return", "-0.111%"},
|
||||
{"Drawdown", "0.100%"},
|
||||
{"Expectancy", "-0.679"},
|
||||
{"Net Profit", "-0.112%"},
|
||||
{"Sharpe Ratio", "-1.052"},
|
||||
{"Probabilistic Sharpe Ratio", "0.000%"},
|
||||
{"Loss Rate", "80%"},
|
||||
{"Win Rate", "20%"},
|
||||
{"Profit-Loss Ratio", "0.61"},
|
||||
{"Alpha", "-0.001"},
|
||||
{"Beta", "-0.001"},
|
||||
{"Annual Standard Deviation", "0.001"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-1.187"},
|
||||
{"Tracking Error", "0.115"},
|
||||
{"Treynor Ratio", "1.545"},
|
||||
{"Total Fees", "$37.00"},
|
||||
{"Estimated Strategy Capacity", "$400000.00"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.128"},
|
||||
{"Return Over Maximum Drawdown", "-0.995"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "de309ab56d2fcd80ff03df2802d9feda"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -186,6 +186,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.204"},
|
||||
{"Treynor Ratio", "-8.165"},
|
||||
{"Total Fees", "$46.75"},
|
||||
{"Estimated Strategy Capacity", "$670000000.00"},
|
||||
{"Fitness Score", "0.002"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -205,7 +206,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-807056289"}
|
||||
{"OrderListHash", "7c4fcd79dd817a9cd3bf44525eaed96c"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,12 +187,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "6441"},
|
||||
{"Average Win", "0.07%"},
|
||||
{"Average Loss", "-0.07%"},
|
||||
{"Compounding Annual Return", "13.284%"},
|
||||
{"Compounding Annual Return", "13.331%"},
|
||||
{"Drawdown", "10.700%"},
|
||||
{"Expectancy", "0.061"},
|
||||
{"Net Profit", "13.284%"},
|
||||
{"Sharpe Ratio", "0.96"},
|
||||
{"Probabilistic Sharpe Ratio", "46.111%"},
|
||||
{"Net Profit", "13.331%"},
|
||||
{"Sharpe Ratio", "0.963"},
|
||||
{"Probabilistic Sharpe Ratio", "46.232%"},
|
||||
{"Loss Rate", "46%"},
|
||||
{"Win Rate", "54%"},
|
||||
{"Profit-Loss Ratio", "0.97"},
|
||||
@@ -200,15 +200,16 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Beta", "-0.066"},
|
||||
{"Annual Standard Deviation", "0.121"},
|
||||
{"Annual Variance", "0.015"},
|
||||
{"Information Ratio", "0.004"},
|
||||
{"Information Ratio", "0.006"},
|
||||
{"Tracking Error", "0.171"},
|
||||
{"Treynor Ratio", "-1.754"},
|
||||
{"Total Fees", "$8669.33"},
|
||||
{"Treynor Ratio", "-1.761"},
|
||||
{"Total Fees", "$8669.41"},
|
||||
{"Estimated Strategy Capacity", "$320000.00"},
|
||||
{"Fitness Score", "0.675"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "1.124"},
|
||||
{"Return Over Maximum Drawdown", "1.242"},
|
||||
{"Sortino Ratio", "1.127"},
|
||||
{"Return Over Maximum Drawdown", "1.246"},
|
||||
{"Portfolio Turnover", "1.64"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -223,7 +224,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "-1120327913"}
|
||||
{"OrderListHash", "0b6746b5759ecd45ab21360fd40858bb"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,12 +160,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "5059"},
|
||||
{"Average Win", "0.08%"},
|
||||
{"Average Loss", "-0.08%"},
|
||||
{"Compounding Annual Return", "14.901%"},
|
||||
{"Compounding Annual Return", "14.950%"},
|
||||
{"Drawdown", "10.600%"},
|
||||
{"Expectancy", "0.075"},
|
||||
{"Net Profit", "14.901%"},
|
||||
{"Sharpe Ratio", "1.068"},
|
||||
{"Probabilistic Sharpe Ratio", "50.201%"},
|
||||
{"Net Profit", "14.950%"},
|
||||
{"Sharpe Ratio", "1.072"},
|
||||
{"Probabilistic Sharpe Ratio", "50.327%"},
|
||||
{"Loss Rate", "45%"},
|
||||
{"Win Rate", "55%"},
|
||||
{"Profit-Loss Ratio", "0.97"},
|
||||
@@ -173,15 +173,16 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Beta", "-0.066"},
|
||||
{"Annual Standard Deviation", "0.121"},
|
||||
{"Annual Variance", "0.015"},
|
||||
{"Information Ratio", "0.08"},
|
||||
{"Information Ratio", "0.083"},
|
||||
{"Tracking Error", "0.171"},
|
||||
{"Treynor Ratio", "-1.963"},
|
||||
{"Total Fees", "$6806.57"},
|
||||
{"Treynor Ratio", "-1.971"},
|
||||
{"Total Fees", "$6806.67"},
|
||||
{"Estimated Strategy Capacity", "$320000.00"},
|
||||
{"Fitness Score", "0.694"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "1.261"},
|
||||
{"Return Over Maximum Drawdown", "1.404"},
|
||||
{"Sortino Ratio", "1.265"},
|
||||
{"Return Over Maximum Drawdown", "1.409"},
|
||||
{"Portfolio Turnover", "1.296"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -196,7 +197,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "974523768"}
|
||||
{"OrderListHash", "a7a893a17a5afa7c2f73a444a7aea507"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,6 +110,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.193"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -129,7 +130,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "371857150"}
|
||||
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,13 +90,14 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$14.91"},
|
||||
{"Total Fees", "$14.92"},
|
||||
{"Estimated Strategy Capacity", "$85000.00"},
|
||||
{"Fitness Score", "0.258"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-27.251"},
|
||||
{"Portfolio Turnover", "0.515"},
|
||||
{"Return Over Maximum Drawdown", "-27.228"},
|
||||
{"Portfolio Turnover", "0.516"},
|
||||
{"Total Insights Generated", "1"},
|
||||
{"Total Insights Closed", "1"},
|
||||
{"Total Insights Analysis Completed", "1"},
|
||||
@@ -110,7 +111,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "221046152"}
|
||||
{"OrderListHash", "21ac8e4179b36d9658f0080868c0e552"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,6 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.29"},
|
||||
{"Treynor Ratio", "4.005"},
|
||||
{"Total Fees", "$18.28"},
|
||||
{"Estimated Strategy Capacity", "$500000000.00"},
|
||||
{"Fitness Score", "0.052"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -150,7 +151,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1300818910"}
|
||||
{"OrderListHash", "17245c38f1b192d2041ca1f3e88250be"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user