Compare commits

..

7 Commits

Author SHA1 Message Date
Jared Broad
4151c40b39 Shuffle init load 2019-07-28 18:26:02 -07:00
Jared Broad
0f942149a0 Testing shuffling worker thread to algorithmSystemHandlers 2019-07-28 15:54:17 -07:00
Jared Broad
e86155c117 Shuffle init to set environment path inline 2019-07-28 15:12:54 -07:00
Jared Broad
1e8fdba3d9 Revert to master 2019-07-28 14:32:04 -07:00
Jared Broad
66a3f2e1d2 Move worker thread creation to launcher before job creation 2019-07-28 12:54:17 -07:00
Jared Broad
5a2adf2065 Remove lock, additional benchmarking 2019-07-28 10:57:22 -07:00
Jared Broad
2dd94f3687 Optimize python load times 2019-07-28 10:33:37 -07:00
3267 changed files with 209674 additions and 365655 deletions

View File

@@ -1,6 +1,4 @@
packages/*
.git/*
.github/*
.vs/*
.nuget/*
Tests/*
*/packages/*
*/.git/*
*/.vs/*
*/.nuget/*

View File

@@ -1,13 +0,0 @@
root = true
[*]
charset = utf-8
indent_size = 4
indent_style = space
insert_final_newline = true
[*.{js,yml,json,config,csproj}]
indent_size = 2
[*.sh]
end_of_line = lf

4
.github/funding.yml vendored
View File

@@ -1,4 +0,0 @@
# These are supported funding model platforms
github: quantconnect
#custom: ['https://github.com/sponsors/QuantConnect']

View File

@@ -24,8 +24,6 @@
#### Types of changes
<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] Refactor (non-breaking change which improves implementation)
- [ ] Performance (non-breaking change which improves performance. Please add associated performance test and results)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] Non-functional change (xml comments/documentation/etc)
@@ -39,4 +37,4 @@
- [ ] All new and existing tests passed.
- [ ] My branch follows the naming convention `bug-<issue#>-<description>` or `feature-<issue#>-<description>`
<!--- Template inspired by https://www.talater.com/open-source-templates/#/page/99 -->
<!--- Template inspired by https://www.talater.com/open-source-templates/#/page/99 -->

View File

@@ -1,30 +0,0 @@
name: Build & Test Lean
on:
push:
branches: ['*']
tags: ['*']
pull_request:
branches: [master]
jobs:
build:
runs-on: ubuntu-20.04
container:
image: quantconnect/lean:foundation
steps:
- uses: actions/checkout@v2
- name: Build
run: dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
- name: Run Tests
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter TestCategory!=TravisExclude -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\)
- name: Generate & Publish python stubs
if: startsWith(github.ref, 'refs/tags/')
run: |
chmod +x ci_build_stubs.sh
./ci_build_stubs.sh -t -g -p
env:
PYPI_API_TOKEN: ${{ secrets.PYPI_API_TOKEN }}

View File

@@ -1,22 +0,0 @@
name: Regression Tests
on:
push:
branches: ['*']
tags: ['*']
pull_request:
branches: [master]
jobs:
build:
runs-on: ubuntu-20.04
container:
image: quantconnect/lean:foundation
steps:
- uses: actions/checkout@v2
- name: Build
run: dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
- name: Run Tests
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter TestCategory=RegressionTests -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\) TestRunParameters.Parameter\(name=\"reduced-disk-size\", value=\"true\"\)

15
.gitignore vendored
View File

@@ -34,9 +34,6 @@
# QC Cloud Setup Bash Files
*.sh
# Include docker launch scripts for Mac/Linux
!run_docker.sh
!research/run_docker_notebook.sh
# QC Config Files:
# config.json
@@ -144,7 +141,6 @@ $tf/
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings
*.DotSettings.user
# JustCode is a .NET coding addin-in
@@ -170,9 +166,6 @@ AutoTest.Net/
# Installshield output folder
[Ee]xpress/
# JetBrains Rider
.idea/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
@@ -196,7 +189,6 @@ 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.
@@ -205,7 +197,6 @@ publish/
#!**/packages/repositories.config
# ignore sln level nuget
.nuget/
!.nuget/NuGet.config
# Windows Azure Build Output
csx/
@@ -271,9 +262,3 @@ Launcher/Plugins/*
/ApiPython/quantconnect.egg-info/*
QuantConnect.Lean.sln.DotSettings*
#User notebook files
Research/Notebooks
#Docker result files
Results/

View File

@@ -1,10 +0,0 @@
<?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>

View File

@@ -1,23 +1,21 @@
sudo: required
language: csharp
mono: none
dotnet: 5.0
os: linux
dist: focal
mono:
- 5.8.0
solution: QuantConnect.Lean.sln
before_install:
- export PATH="$HOME/miniconda3/bin:$PATH"
- 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
- wget https://cdn.quantconnect.com/miniconda/Miniconda3-4.3.31-Linux-x86_64.sh
- bash Miniconda3-4.3.31-Linux-x86_64.sh -b
- rm -rf Miniconda3-4.3.31-Linux-x86_64.sh
- sudo ln -s $HOME/miniconda3/lib/libpython3.6m.so /usr/lib/libpython3.6m.so
- conda update -y python conda pip
- conda install -y python=3.6.8
- conda install -y numpy=1.18.1
- conda install -y pandas=0.25.3
- conda install -y cython=0.29.15
- conda install -y scipy=1.4.1
- conda install -y wrapt=1.12.1
- conda install -y cython pandas scipy
install:
- nuget restore QuantConnect.Lean.sln
- nuget install NUnit.Runners -Version 2.6.4 -OutputDirectory testrunner
script:
- dotnet nuget add source $TRAVIS_BUILD_DIR/LocalPackages
- dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
- dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter TestCategory!=TravisExclude -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\)
- msbuild /p:Configuration=Release /p:VbcToolExe=vbnc.exe QuantConnect.Lean.sln
- mono ./testrunner/NUnit.Runners.2.6.4/tools/nunit-console.exe ./Tests/bin/Release/QuantConnect.Tests.dll --exclude:TravisExclude --labels
after_success:
- coveralls

View File

@@ -1,73 +0,0 @@
<h1>Local Development with Visual Studio</h1>
This document contains information regarding ways to use Visual Studio to work with the Lean engine, this includes a couple options that make lean easy to develop on any machine:
- Using Lean CLI -> A great tool for working with your algorithms locally, while still being able to deploy to the cloud and have access to Lean data. It is also able to run algorithms locally through our official docker images **Recommended for algorithm development.
- Locally installing all dependencies to run Lean with Visual Studio on your OS.
<br />
<h1>Setup</h1>
<h2>Option 1: Lean CLI</h2>
To use Lean CLI follow the instructions for installation and tutorial for usage in our [documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli).
<br />
<h2>Option 2: Install Locally</h2>
1. Install [.Net 5](https://dotnet.microsoft.com/download) for the project
2. (Optional) Get [Python 3.6.8](https://www.python.org/downloads/release/python-368/) for running Python algorithms
- Follow Python instructions [here](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#installing-python-36) for your platform
3. Get [Visual Studio](https://visualstudio.microsoft.com/vs/)
4. Get Lean into VS
- Download the repo or clone it using: _git clone [https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)_
- Open the project file with VS (QuantConnect.Lean.sln)
Your environment is prepared and ready to run lean
<br />
<h1>How to use Lean</h1>
This section will cover configuring, launching and debugging lean. This is only applicable to option 2 from above. This does not apply to Lean CLI, please refer to [CLI documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli)
<br />
<h2>Configuration</h2>
We need to be sure that our Lean configuration at **.\Launcher\config.json** is properly set.
Your configuration file should look something like this for the following languages:
<h3>Python:</h3>
"algorithm-type-name": "**AlgorithmName**",
"algorithm-language": "Python",
"algorithm-location": "../../../Algorithm.Python/**AlgorithmName**.py",
<h3>C#:</h3>
"algorithm-type-name": "**AlgorithmName**",
"algorithm-language": "CSharp",
"algorithm-location": "QuantConnect.Algorithm.CSharp.dll",
<br />
<h2>Launching Lean</h2>
Now that lean is configured we can launch. Use Visual Studio's run option, Make sure QuantConnect.Lean.Launcher is selected as the launch project. Any breakpoints in Lean C# will be triggered.
<br />
<h1>Common Issues</h1>
Here we will cover some common issues with setting this up. Feel free to contribute to this section!

47
.vscode/launch.json vendored
View File

@@ -1,47 +0,0 @@
{
/*
VS Code Launch configurations for the LEAN engine
Launch:
Builds the project with dotnet 5 and then launches the program using coreclr; supports debugging.
In order to use this you need dotnet 5 on your system path, As well as the C# extension from the
marketplace.
Attach to Python:
Will attempt to attach to LEAN running locally using PTVSD. Requires that the process is
actively running and config is set: "debugging": true, "debugging-method": "PTVSD",
Requires Python extension from the marketplace. Currently only works with algorithms in
Algorithm.Python directory. This is because we map that directory to our build directory
that contains the py file at runtime. If using another location change "localRoot" value
to the directory in use.
*/
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/Launcher/bin/Debug/QuantConnect.Lean.Launcher.dll",
"args": [
"--config",
"${workspaceFolder}/Launcher/config.json"
],
"cwd": "${workspaceFolder}/Launcher/bin/Debug/",
"stopAtEntry": false,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
{
"name": "Attach to Python",
"type": "python",
"request": "attach",
"port": 5678,
"pathMappings":[{
"localRoot": "${workspaceFolder}",
"remoteRoot": "${workspaceFolder}"
}]
}
]
}

127
.vscode/readme.md vendored
View File

@@ -1,127 +0,0 @@
<h1>Local Development & Docker Integration with Visual Studio Code</h1>
This document contains information regarding ways to use Visual Studio Code to work with the Lean engine, this includes a couple options that make lean easy to develop on any machine:
- Using Lean CLI -> A great tool for working with your algorithms locally, while still being able to deploy to the cloud and have access to Lean data. It is also able to run algorithms locally through our official docker images **Recommended for algorithm development.
- Locally installing all dependencies to run Lean with Visual Studio Code on your OS.
<br />
<h1>Setup</h1>
<h2>Option 1: Lean CLI</h2>
To use Lean CLI follow the instructions for installation and tutorial for usage in our [documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli)
<br />
<h2>Option 2: Install Dependencies Locally</h2>
1. Install [.Net 5](https://dotnet.microsoft.com/download) for the project
2. (Optional) Get [Python 3.6.8](https://www.python.org/downloads/release/python-368/) for running Python algorithms
- Follow Python instructions [here](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#installing-python-36) for your platform
3. Get [Visual Studio Code](https://code.visualstudio.com/download)
- Get the Extension [C#](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp) for C# Debugging
- Get the Extension [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) for Python Debugging
4. Get Lean into VS Code
- Download the repo or clone it using: _git clone [https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)_
- Open the folder using VS Code
Your environment is prepared and ready to run lean
<br />
<h1>How to use Lean</h1>
This section will cover configuring, building, launching and debugging lean. This is only applicable to option 2 from above. This does not apply to Lean CLI, please refer to [CLI documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli)
<br />
<h2>Configuration</h2>
We need to be sure that our Lean configuration at **.\Launcher\config.json** is properly set.
Your configuration file should look something like this for the following languages:
<h3>Python:</h3>
"algorithm-type-name": "**AlgorithmName**",
"algorithm-language": "Python",
"algorithm-location": "../../../Algorithm.Python/**AlgorithmName**.py",
<h3>C#:</h3>
"algorithm-type-name": "**AlgorithmName**",
"algorithm-language": "CSharp",
"algorithm-location": "QuantConnect.Algorithm.CSharp.dll",
<br />
<h2>Building</h2>
Before running Lean, we must build the project. Currently the VS Code task will automatically build before launching. But find more information below about how to trigger building manually.
In VS Code run build task (Ctrl+Shift+B or "Terminal" dropdown); there are a few options:
- __Build__ - basic build task, just builds Lean once
- __Rebuild__ - rebuild task, completely rebuilds the project. Use if having issues with debugging symbols being loaded for your algorithms.
- __Autobuilder__ - Starts a script that builds then waits for files to change and rebuilds appropriately
- __Clean__ - deletes out all project build files
<br />
<h2>Launching Lean</h2>
Now that lean is configured and built we can launch Lean. Under "Run & Debug" use the launch option "Launch". This will start Lean with C# debugging. Any breakpoints in Lean C# will be triggered.
<br />
<h2>Debugging Python</h2>
Python algorithms require a little extra work in order to be able to debug them. Follow the steps below to get Python debugging working.
<br />
<h3>Modifying the Configuration</h3>
First in order to debug a Python algorithm in VS Code we must make the following change to our configuration (Launcher\config.json) under the comment debugging configuration:
"debugging": true,
"debugging-method": "PTVSD",
In setting this we are telling Lean to expect a debugger connection using Python Tools for Visual Studio Debugger. Once this is set Lean will stop upon initialization and await a connection to the debugger via port 5678.
<br />
<h3>Using VS Code Launch Options to Connect</h3>
Now that Lean is configured for the python debugger we can make use of the programmed launch options to connect to Lean during runtime.
Start Lean using the "Launch" option covered above. Once Lean starts you should see the messages in figure 2 If the message is displayed, use the launch option “Attach to Python”. Then press run, VS Code will now enter and debug any breakpoints you have set in your python algorithm.
<br />
_Figure 2: Python Debugger Messages_
```
20200715 17:12:06.546 Trace:: PythonInitializer.Initialize(): ended
20200715 17:12:06.547 Trace:: DebuggerHelper.Initialize(): python initialization done
20200715 17:12:06.547 Trace:: DebuggerHelper.Initialize(): starting...
20200715 17:12:06.548 Trace:: DebuggerHelper.Initialize(): waiting for debugger to attach at localhost:5678...
```
<br />
<h1>Common Issues</h1>
Here we will cover some common issues with setting this up. This section will expand as we get user feedback!
- Autocomplete and reference finding with omnisharp can sometimes bug, if this occurs use the command palette to restart omnisharp. (Ctrl+Shift+P "OmniSharp: Restart OmniSharp")
- Any error messages about building in VSCode that point to comments in JSON. Either select **ignore** or follow steps described [here](https://stackoverflow.com/questions/47834825/in-vs-code-disable-error-comments-are-not-permitted-in-json) to remove the errors entirely.

55
.vscode/tasks.json vendored
View File

@@ -1,55 +0,0 @@
{
/*
VS Code Tasks for the LEAN engine
In order to use the build tasks you need msbuild on your system path.
*/
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "dotnet",
"args": [
"build",
"/p:Configuration=Debug",
"/p:DebugType=portable",
"/p:WarningLevel=1"
],
"group": "build",
"presentation": {
"reveal": "silent"
},
"problemMatcher": "$msCompile"
},
{
"label": "rebuild",
"type": "shell",
"command": "dotnet",
"args": [
"build",
"--no-incremental",
"/p:Configuration=Debug",
"/p:DebugType=portable",
"/p:WarningLevel=1"
],
"group": "build",
"presentation": {
"reveal": "silent"
},
"problemMatcher": "$msCompile"
},
{
"label": "clean",
"type": "shell",
"command": "dotnet",
"args": [
"clean",
],
"group": "build",
"presentation": {
"reveal": "silent"
},
"problemMatcher": "$msCompile"
}
]
}

View File

@@ -1,121 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Test algorithm using <see cref="AccumulativeInsightPortfolioConstructionModel"/> and <see cref="ConstantAlphaModel"/>
/// generating a constant <see cref="Insight"/> with a 0.25 confidence
/// </summary>
public class AccumulativeInsightPortfolioRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
// Set requested data resolution
UniverseSettings.Resolution = Resolution.Minute;
SetStartDate(2013, 10, 07); //Set Start Date
SetEndDate(2013, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
// set algorithm framework models
SetUniverseSelection(new ManualUniverseSelectionModel(QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA)));
SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromMinutes(20), 0.025, 0.25));
SetPortfolioConstruction(new AccumulativeInsightPortfolioConstructionModel());
SetExecution(new ImmediateExecutionModel());
}
public override void OnEndOfAlgorithm()
{
if (// holdings value should be 0.03 - to avoid price fluctuation issue we compare with 0.06 and 0.01
Portfolio.TotalHoldingsValue > Portfolio.TotalPortfolioValue * 0.06m
||
Portfolio.TotalHoldingsValue < Portfolio.TotalPortfolioValue * 0.01m)
{
throw new Exception($"Unexpected Total Holdings Value: {Portfolio.TotalHoldingsValue}");
}
}
/// <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", "199"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-12.611%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-0.585"},
{"Net Profit", "-0.172%"},
{"Sharpe Ratio", "-10.169"},
{"Probabilistic Sharpe Ratio", "12.075%"},
{"Loss Rate", "78%"},
{"Win Rate", "22%"},
{"Profit-Loss Ratio", "0.87"},
{"Alpha", "-0.149"},
{"Beta", "0.035"},
{"Annual Standard Deviation", "0.008"},
{"Annual Variance", "0"},
{"Information Ratio", "-9.603"},
{"Tracking Error", "0.215"},
{"Treynor Ratio", "-2.264"},
{"Total Fees", "$199.00"},
{"Estimated Strategy Capacity", "$26000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "-22.493"},
{"Return Over Maximum Drawdown", "-77.93"},
{"Portfolio Turnover", "1.211"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
{"Total Insights Analysis Completed", "99"},
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "3c4c4085810cc5ecdb927d3647b9bbf3"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -110,48 +110,38 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "9"},
{"Average Win", "0.86%"},
{"Average Loss", "-0.27%"},
{"Compounding Annual Return", "184.364%"},
{"Drawdown", "1.700%"},
{"Expectancy", "1.781"},
{"Net Profit", "1.442%"},
{"Sharpe Ratio", "4.017"},
{"Probabilistic Sharpe Ratio", "59.636%"},
{"Total Trades", "6"},
{"Average Win", "0.91%"},
{"Average Loss", "-0.23%"},
{"Compounding Annual Return", "214.278%"},
{"Drawdown", "1.600%"},
{"Expectancy", "2.248"},
{"Net Profit", "1.581%"},
{"Sharpe Ratio", "2.803"},
{"Loss Rate", "33%"},
{"Win Rate", "67%"},
{"Profit-Loss Ratio", "3.17"},
{"Alpha", "1.53"},
{"Beta", "-0.292"},
{"Annual Standard Deviation", "0.279"},
{"Annual Variance", "0.078"},
{"Information Ratio", "-0.743"},
{"Tracking Error", "0.372"},
{"Treynor Ratio", "-3.845"},
{"Total Fees", "$14.78"},
{"Estimated Strategy Capacity", "$47000000.00"},
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
{"Fitness Score", "0.408"},
{"Kelly Criterion Estimate", "16.559"},
{"Kelly Criterion Probability Value", "0.316"},
{"Sortino Ratio", "12.447"},
{"Return Over Maximum Drawdown", "106.327"},
{"Portfolio Turnover", "0.411"},
{"Profit-Loss Ratio", "3.87"},
{"Alpha", "0"},
{"Beta", "59.491"},
{"Annual Standard Deviation", "0.244"},
{"Annual Variance", "0.06"},
{"Information Ratio", "2.756"},
{"Tracking Error", "0.244"},
{"Treynor Ratio", "0.012"},
{"Total Fees", "$10.88"},
{"Total Insights Generated", "3"},
{"Total Insights Closed", "3"},
{"Total Insights Analysis Completed", "3"},
{"Long Insight Count", "0"},
{"Short Insight Count", "3"},
{"Long/Short Ratio", "0%"},
{"Estimated Monthly Alpha Value", "$20784418.6104"},
{"Total Accumulated Estimated Alpha Value", "$3579538.7607"},
{"Mean Population Estimated Insight Value", "$1193179.5869"},
{"Estimated Monthly Alpha Value", "$13262182.1037"},
{"Total Accumulated Estimated Alpha Value", "$2284042.4734"},
{"Mean Population Estimated Insight Value", "$761347.4911"},
{"Mean Population Direction", "100%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "100%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "9da9afe1e9137638a55db1676adc2be1"}
{"Rolling Averaged Population Magnitude", "0%"}
};
}
}

View File

@@ -1,134 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm reproducing GH issue #5748 where in some cases an option underlying symbol was not being
/// removed from all universes it was hold
/// </summary>
public class AddAndRemoveOptionContractRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _contract;
private bool _hasRemoved;
public override void Initialize()
{
SetStartDate(2014, 06, 06);
SetEndDate(2014, 06, 09);
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero;
var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
_contract = OptionChainProvider.GetOptionContractList(aapl, Time)
.OrderBy(symbol => symbol.ID.Symbol)
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American);
AddOptionContract(_contract);
}
public override void OnData(Slice slice)
{
if (slice.HasData)
{
if (!_hasRemoved)
{
RemoveOptionContract(_contract);
RemoveSecurity(_contract.Underlying);
_hasRemoved = true;
}
else
{
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
}
}
}
public override void OnEndOfAlgorithm()
{
if (!_hasRemoved)
{
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -1,212 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.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"},
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
{"Fitness Score", "1"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "3.199"},
{"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"}
};
}
}

View File

@@ -1,271 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
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))
{
var optionContract = Securities[option];
var marginModel = optionContract.BuyingPowerModel as FuturesOptionsMarginModel;
if (marginModel.InitialIntradayMarginRequirement == 0
|| marginModel.InitialOvernightMarginRequirement == 0
|| marginModel.MaintenanceIntradayMarginRequirement == 0
|| marginModel.MaintenanceOvernightMarginRequirement == 0)
{
throw new Exception("Unexpected margin requirements");
}
if (marginModel.GetInitialMarginRequirement(optionContract, 1) == 0)
{
throw new Exception("Unexpected Initial Margin requirement");
}
if (marginModel.GetMaintenanceMargin(optionContract) != 0)
{
throw new Exception("Unexpected Maintenance Margin requirement");
}
MarketOrder(option, 1);
_invested = true;
optionInvested = true;
if (marginModel.GetMaintenanceMargin(optionContract) == 0)
{
throw new Exception("Unexpected Maintenance Margin requirement");
}
}
if (!futureInvested && data.ContainsKey(future))
{
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", "$41000.00"},
{"Lowest Capacity Asset", "ES 31C3JQTOYO9T0|ES XCZJLC9NOB29"},
{"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"}
};
}
}

View File

@@ -1,166 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.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.011"},
{"Annual Standard Deviation", "0.006"},
{"Annual Variance", "0"},
{"Information Ratio", "-3.385"},
{"Tracking Error", "0.058"},
{"Treynor Ratio", "2.117"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$45000000.00"},
{"Lowest Capacity Asset", "AOL R735QTJ8XC9X"},
{"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"}
};
}
}

View File

@@ -1,218 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.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.024"},
{"Beta", "-0.171"},
{"Annual Standard Deviation", "0.006"},
{"Annual Variance", "0"},
{"Information Ratio", "-11.082"},
{"Tracking Error", "0.043"},
{"Treynor Ratio", "0.291"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$2800000.00"},
{"Lowest Capacity Asset", "AOL VRKS95ENLBYE|AOL R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"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"}
};
}
}

View File

@@ -40,8 +40,8 @@ namespace QuantConnect.Algorithm.CSharp
private int _expectedContractIndex;
private readonly List<Symbol> _expectedContracts = new List<Symbol>
{
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00750000"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00747500"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00750000"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00752500")
};
@@ -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(Securities.Keys.ToHashSet()))
if (_expectedSecurities.AreDifferent(LinqExtensions.ToHashSet(Securities.Keys)))
{
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(UniverseManager.Keys.ToHashSet()))
if (_expectedUniverses.AreDifferent(LinqExtensions.ToHashSet(UniverseManager.Keys)))
{
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(data.Keys.ToHashSet()))
if (_expectedData.AreDifferent(LinqExtensions.ToHashSet(data.Keys)))
{
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(_expectedContracts.ToHashSet()))
.AreDifferent(LinqExtensions.ToHashSet(_expectedContracts)))
{
throw new Exception("Expected removed securities to equal expected contracts added");
}
@@ -212,14 +212,13 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "6"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Average Loss", "-0.21%"},
{"Compounding Annual Return", "-98.595%"},
{"Drawdown", "0.600%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.631%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
@@ -229,29 +228,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$6.00"},
{"Estimated Strategy Capacity", "$2000.00"},
{"Lowest Capacity Asset", "GOOCV 305RBQ2BZBZT2|GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "0"},
{"Return Over Maximum Drawdown", "0"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1e7b3e90918777b9dbf46353a96f3329"}
{"Total Fees", "$6.00"}
};
}
}

View File

@@ -74,8 +74,8 @@ namespace QuantConnect.Algorithm.CSharp
}
else if (Time.DayOfWeek == DayOfWeek.Thursday)
{
RemoveSecurity(_aig);
RemoveSecurity(_bac);
RemoveSecurity(_aig);
lastAction = Time;
}
}
@@ -112,47 +112,24 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "5"},
{"Average Win", "0.46%"},
{"Average Win", "0.49%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "296.356%"},
{"Compounding Annual Return", "305.340%"},
{"Drawdown", "1.400%"},
{"Expectancy", "0"},
{"Net Profit", "1.776%"},
{"Sharpe Ratio", "13.013"},
{"Probabilistic Sharpe Ratio", "80.409%"},
{"Net Profit", "1.805%"},
{"Sharpe Ratio", "6.475"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.68"},
{"Beta", "0.707"},
{"Annual Standard Deviation", "0.16"},
{"Annual Variance", "0.026"},
{"Information Ratio", "1.378"},
{"Tracking Error", "0.072"},
{"Treynor Ratio", "2.946"},
{"Total Fees", "$28.30"},
{"Estimated Strategy Capacity", "$4700000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Fitness Score", "0.374"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "372.086"},
{"Portfolio Turnover", "0.374"},
{"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", "ac3f4dfcdeb98b488b715412ad2d6c4f"}
{"Alpha", "0.003"},
{"Beta", "82.247"},
{"Annual Standard Deviation", "0.141"},
{"Annual Variance", "0.02"},
{"Information Ratio", "6.401"},
{"Tracking Error", "0.141"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$26.40"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -67,45 +67,35 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "3"},
{"Average Win", "1.02%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "296.066%"},
{"Compounding Annual Return", "289.117%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Net Profit", "1.775%"},
{"Sharpe Ratio", "9.373"},
{"Probabilistic Sharpe Ratio", "68.302%"},
{"Net Profit", "1.752%"},
{"Sharpe Ratio", "4.52"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.105"},
{"Beta", "1.021"},
{"Annual Standard Deviation", "0.227"},
{"Annual Variance", "0.052"},
{"Information Ratio", "25.083"},
{"Tracking Error", "0.006"},
{"Treynor Ratio", "2.086"},
{"Total Fees", "$10.33"},
{"Estimated Strategy Capacity", "$38000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.747"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "107.013"},
{"Portfolio Turnover", "0.747"},
{"Alpha", "0.007"},
{"Beta", "80.237"},
{"Annual Standard Deviation", "0.197"},
{"Annual Variance", "0.039"},
{"Information Ratio", "4.466"},
{"Tracking Error", "0.197"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$9.77"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
{"Total Insights Analysis Completed", "99"},
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "af3a9c98c190d1b6b36fad184e796b0b"}
{"Estimated Monthly Alpha Value", "$158418.3850"},
{"Total Accumulated Estimated Alpha Value", "$25522.9620"},
{"Mean Population Estimated Insight Value", "$257.8077"},
{"Mean Population Direction", "54.5455%"},
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -83,48 +83,38 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "11"},
{"Total Trades", "10"},
{"Average Win", "0%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-14.217%"},
{"Compounding Annual Return", "-14.943%"},
{"Drawdown", "3.300%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.168%"},
{"Sharpe Ratio", "-0.126"},
{"Probabilistic Sharpe Ratio", "45.081%"},
{"Net Profit", "-0.177%"},
{"Sharpe Ratio", "-0.136"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-2.896"},
{"Beta", "0.551"},
{"Annual Standard Deviation", "0.385"},
{"Annual Variance", "0.148"},
{"Information Ratio", "-13.66"},
{"Tracking Error", "0.382"},
{"Treynor Ratio", "-0.088"},
{"Total Fees", "$23.21"},
{"Estimated Strategy Capacity", "$340000000.00"},
{"Lowest Capacity Asset", "FB V6OIPNZEM8V9"},
{"Fitness Score", "0.147"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "1"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-4.352"},
{"Portfolio Turnover", "0.269"},
{"Alpha", "0"},
{"Beta", "-4.084"},
{"Annual Standard Deviation", "0.332"},
{"Annual Variance", "0.11"},
{"Information Ratio", "-0.169"},
{"Tracking Error", "0.332"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$13.98"},
{"Total Insights Generated", "15"},
{"Total Insights Closed", "12"},
{"Total Insights Analysis Completed", "12"},
{"Long Insight Count", "15"},
{"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", "a7a0983c8413ff241e7d223438f3d508"}
{"Estimated Monthly Alpha Value", "$33015795.7342"},
{"Total Accumulated Estimated Alpha Value", "$4585527.1853"},
{"Mean Population Estimated Insight Value", "$382127.2654"},
{"Mean Population Direction", "66.6667%"},
{"Mean Population Magnitude", "66.6667%"},
{"Rolling Averaged Population Direction", "34.3681%"},
{"Rolling Averaged Population Magnitude", "34.3681%"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -37,10 +37,6 @@ namespace QuantConnect.Algorithm.CSharp
// Set requested data resolution
UniverseSettings.Resolution = Resolution.Daily;
// Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
// Commented so regression algorithm is more sensitive
//Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;
SetStartDate(2014, 03, 24);
SetEndDate(2014, 04, 07);
SetCash(100000);
@@ -94,48 +90,38 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "27"},
{"Average Win", "0.01%"},
{"Total Trades", "23"},
{"Average Win", "0.00%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-75.320%"},
{"Compounding Annual Return", "-75.360%"},
{"Drawdown", "5.800%"},
{"Expectancy", "-0.731"},
{"Net Profit", "-5.588%"},
{"Sharpe Ratio", "-3.272"},
{"Probabilistic Sharpe Ratio", "5.825%"},
{"Loss Rate", "86%"},
{"Win Rate", "14%"},
{"Profit-Loss Ratio", "0.89"},
{"Alpha", "-0.594"},
{"Beta", "0.707"},
{"Annual Standard Deviation", "0.203"},
{"Annual Variance", "0.041"},
{"Information Ratio", "-2.929"},
{"Tracking Error", "0.193"},
{"Treynor Ratio", "-0.942"},
{"Total Fees", "$37.25"},
{"Estimated Strategy Capacity", "$520000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.004"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "1"},
{"Sortino Ratio", "-4.469"},
{"Return Over Maximum Drawdown", "-13.057"},
{"Portfolio Turnover", "0.084"},
{"Expectancy", "-0.859"},
{"Net Profit", "-5.594%"},
{"Sharpe Ratio", "-5.582"},
{"Loss Rate", "92%"},
{"Win Rate", "8%"},
{"Profit-Loss Ratio", "0.70"},
{"Alpha", "-1.454"},
{"Beta", "15.578"},
{"Annual Standard Deviation", "0.212"},
{"Annual Variance", "0.045"},
{"Information Ratio", "-5.664"},
{"Tracking Error", "0.212"},
{"Treynor Ratio", "-0.076"},
{"Total Fees", "$25.92"},
{"Total Insights Generated", "33"},
{"Total Insights Closed", "30"},
{"Total Insights Analysis Completed", "30"},
{"Long Insight Count", "33"},
{"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", "f837879b96f5e565b60fd040299d2123"}
{"Estimated Monthly Alpha Value", "$-7788114"},
{"Total Accumulated Estimated Alpha Value", "$-3937325"},
{"Mean Population Estimated Insight Value", "$-131244.2"},
{"Mean Population Direction", "46.6667%"},
{"Mean Population Magnitude", "46.6667%"},
{"Rolling Averaged Population Direction", "61.4247%"},
{"Rolling Averaged Population Magnitude", "61.4247%"}
};
}
}

View File

@@ -1,205 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Configuration;
using QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Interfaces;
using QuantConnect.Util;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm to test volume adjusted behavior
/// </summary>
public class AdjustedVolumeRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _aapl;
private const string Ticker = "AAPL";
private FactorFile _factorFile;
private readonly IEnumerator<decimal> _expectedAdjustedVolume = new List<decimal> { 6164842, 3044047, 3680347, 3468303, 2169943, 2652523,
1499707, 1518215, 1655219, 1510487 }.GetEnumerator();
private readonly IEnumerator<decimal> _expectedAdjustedAskSize = new List<decimal> { 215600, 5600, 25200, 8400, 5600, 5600, 2800,
8400, 14000, 2800 }.GetEnumerator();
private readonly IEnumerator<decimal> _expectedAdjustedBidSize = new List<decimal> { 2800, 11200, 2800, 2800, 2800, 5600, 11200,
8400, 30800, 2800 }.GetEnumerator();
public override void Initialize()
{
SetStartDate(2014, 6, 5); //Set Start Date
SetEndDate(2014, 6, 5); //Set End Date
UniverseSettings.DataNormalizationMode = DataNormalizationMode.SplitAdjusted;
_aapl = AddEquity(Ticker, Resolution.Minute).Symbol;
var dataProvider =
Composer.Instance.GetExportedValueByTypeName<IDataProvider>(Config.Get("data-provider",
"DefaultDataProvider"));
var mapFileProvider = new LocalDiskMapFileProvider();
mapFileProvider.Initialize(dataProvider);
var factorFileProvider = new LocalDiskFactorFileProvider();
factorFileProvider.Initialize(mapFileProvider, dataProvider);
_factorFile = factorFileProvider.Get(_aapl);
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
SetHoldings(_aapl, 1);
}
if (data.Splits.ContainsKey(_aapl))
{
Log(data.Splits[_aapl].ToString());
}
if (data.Bars.ContainsKey(_aapl))
{
var aaplData = data.Bars[_aapl];
// Assert our volume matches what we expect
if (_expectedAdjustedVolume.MoveNext() && _expectedAdjustedVolume.Current != aaplData.Volume)
{
// Our values don't match lets try and give a reason why
var dayFactor = _factorFile.GetSplitFactor(aaplData.Time);
var probableAdjustedVolume = aaplData.Volume / dayFactor;
if (_expectedAdjustedVolume.Current == probableAdjustedVolume)
{
throw new ArgumentException($"Volume was incorrect; but manually adjusted value is correct." +
$" Adjustment by multiplying volume by {1 / dayFactor} is not occurring.");
}
else
{
throw new ArgumentException($"Volume was incorrect; even when adjusted manually by" +
$" multiplying volume by {1 / dayFactor}. Data may have changed.");
}
}
}
if (data.QuoteBars.ContainsKey(_aapl))
{
var aaplQuoteData = data.QuoteBars[_aapl];
// Assert our askSize matches what we expect
if (_expectedAdjustedAskSize.MoveNext() && _expectedAdjustedAskSize.Current != aaplQuoteData.LastAskSize)
{
// Our values don't match lets try and give a reason why
var dayFactor = _factorFile.GetSplitFactor(aaplQuoteData.Time);
var probableAdjustedAskSize = aaplQuoteData.LastAskSize / dayFactor;
if (_expectedAdjustedAskSize.Current == probableAdjustedAskSize)
{
throw new ArgumentException($"Ask size was incorrect; but manually adjusted value is correct." +
$" Adjustment by multiplying size by {1 / dayFactor} is not occurring.");
}
else
{
throw new ArgumentException($"Ask size was incorrect; even when adjusted manually by" +
$" multiplying size by {1 / dayFactor}. Data may have changed.");
}
}
// Assert our bidSize matches what we expect
if (_expectedAdjustedBidSize.MoveNext() && _expectedAdjustedBidSize.Current != aaplQuoteData.LastBidSize)
{
// Our values don't match lets try and give a reason why
var dayFactor = _factorFile.GetSplitFactor(aaplQuoteData.Time);
var probableAdjustedBidSize = aaplQuoteData.LastBidSize / dayFactor;
if (_expectedAdjustedBidSize.Current == probableAdjustedBidSize)
{
throw new ArgumentException($"Bid size was incorrect; but manually adjusted value is correct." +
$" Adjustment by multiplying size by {1 / dayFactor} is not occurring.");
}
else
{
throw new ArgumentException($"Bid size was incorrect; even when adjusted manually by" +
$" multiplying size by {1 / dayFactor}. Data may have changed.");
}
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$21.60"},
{"Estimated Strategy Capacity", "$42000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "0"},
{"Return Over Maximum Drawdown", "0"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "18e41dded4f8cee548ee02b03ffb0814"}
};
}
}

View File

@@ -1,238 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.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.OrderBy(symbol => symbol))
{
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", "19.147%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0.192%"},
{"Sharpe Ratio", "31.331"},
{"Probabilistic Sharpe Ratio", "88.448%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.138"},
{"Beta", "0.04"},
{"Annual Standard Deviation", "0.004"},
{"Annual Variance", "0"},
{"Information Ratio", "4.767"},
{"Tracking Error", "0.077"},
{"Treynor Ratio", "3.223"},
{"Total Fees", "$307.50"},
{"Estimated Strategy Capacity", "$2600000.00"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0.106"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0.106"},
{"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", "0069f402ffcd2d91b9018b81badfab81"}
};
}
}

View File

@@ -19,27 +19,28 @@ 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.Alphas
namespace QuantConnect.Algorithm.CSharp
{
///<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 : QCAlgorithm
/// <summary>
public class MortgageRateVolatilityAlgorithm : QCAlgorithmFramework
{
public override void Initialize()
{
@@ -50,8 +51,8 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
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));
@@ -63,6 +64,8 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
SetRiskManagement(new NullRiskManagementModel());
}
public void OnData(QuandlMortgagePriceColumns data) { }
private class MortgageRateVolatilityAlphaModel : AlphaModel
{
@@ -76,7 +79,7 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
private readonly StandardDeviation _mortgageRateStd;
public MortgageRateVolatilityAlphaModel(
QCAlgorithm algorithm,
QCAlgorithmFramework algorithm,
int indicatorPeriod = 15,
double insightMagnitude = 0.0005,
int deviations = 2,
@@ -99,7 +102,7 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
WarmUpIndicators(algorithm);
}
public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
public override IEnumerable<Insight> Update(QCAlgorithmFramework algorithm, Slice data)
{
var insights = new List<Insight>();
@@ -138,7 +141,7 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
return insights;
}
private void WarmUpIndicators(QCAlgorithm algorithm)
private void WarmUpIndicators(QCAlgorithmFramework algorithm)
{
// Make a history call and update the indicators
algorithm.History(new[] { _mortgageRate }, _indicatorPeriod, _resolution).PushThrough(bar =>

View File

@@ -1,125 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.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", "52"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "0.096%"},
{"Drawdown", "0.100%"},
{"Expectancy", "3.321"},
{"Net Profit", "0.089%"},
{"Sharpe Ratio", "0.868"},
{"Probabilistic Sharpe Ratio", "44.482%"},
{"Loss Rate", "24%"},
{"Win Rate", "76%"},
{"Profit-Loss Ratio", "4.67"},
{"Alpha", "0.001"},
{"Beta", "-0"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.148"},
{"Tracking Error", "0.101"},
{"Treynor Ratio", "-4.168"},
{"Total Fees", "$52.00"},
{"Estimated Strategy Capacity", "$32000000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "1.266"},
{"Return Over Maximum Drawdown", "1.622"},
{"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", "cf43585a8d1781f04b53a4f1ee3380cb"}
};
}
}

View File

@@ -1,195 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Algorithm which tests indicator warm up using different data types, related to GH issue 4205
/// </summary>
public class AutomaticIndicatorWarmupDataTypeRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _symbol;
public override void Initialize()
{
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
EnableAutomaticIndicatorWarmUp = true;
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 09);
var SP500 = QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME);
_symbol = FutureChainProvider.GetFutureContractList(SP500, StartDate).First();
// Test case: custom IndicatorBase<QuoteBar> indicator using Future unsubscribed symbol
var indicator1 = new CustomIndicator();
AssertIndicatorState(indicator1, isReady: false);
WarmUpIndicator(_symbol, indicator1);
AssertIndicatorState(indicator1, isReady: true);
// Test case: SimpleMovingAverage<IndicatorDataPoint> using Future unsubscribed symbol (should use TradeBar)
var sma1 = new SimpleMovingAverage(10);
AssertIndicatorState(sma1, isReady: false);
WarmUpIndicator(_symbol, sma1);
AssertIndicatorState(sma1, isReady: true);
// Test case: SimpleMovingAverage<IndicatorDataPoint> using Equity unsubscribed symbol
var spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
var sma = new SimpleMovingAverage(10);
AssertIndicatorState(sma, isReady: false);
WarmUpIndicator(spy, sma);
AssertIndicatorState(sma, isReady: true);
// We add the symbol
AddFutureContract(_symbol);
AddEquity("SPY");
// force spy for use Raw data mode so that it matches the used when unsubscribed which uses the universe settings
SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(spy).SetDataNormalizationMode(DataNormalizationMode.Raw);
// Test case: custom IndicatorBase<QuoteBar> indicator using Future subscribed symbol
var indicator = new CustomIndicator();
var consolidator = CreateConsolidator(TimeSpan.FromMinutes(1), typeof(QuoteBar));
RegisterIndicator(_symbol, indicator, consolidator);
AssertIndicatorState(indicator, isReady: false);
WarmUpIndicator(_symbol, indicator);
AssertIndicatorState(indicator, isReady: true);
// Test case: SimpleMovingAverage<IndicatorDataPoint> using Future Subscribed symbol (should use TradeBar)
var sma11 = new SimpleMovingAverage(10);
AssertIndicatorState(sma11, isReady: false);
WarmUpIndicator(_symbol, sma11);
AssertIndicatorState(sma11, isReady: true);
if (!sma11.Current.Equals(sma1.Current))
{
throw new Exception("Expected SMAs warmed up before and after adding the Future to the algorithm to have the same current value. " +
"The result of 'WarmUpIndicator' shouldn't change if the symbol is or isn't subscribed");
}
// Test case: SimpleMovingAverage<IndicatorDataPoint> using Equity unsubscribed symbol
var smaSpy = new SimpleMovingAverage(10);
AssertIndicatorState(smaSpy, isReady: false);
WarmUpIndicator(spy, smaSpy);
AssertIndicatorState(smaSpy, isReady: true);
if (!smaSpy.Current.Equals(sma.Current))
{
throw new Exception("Expected SMAs warmed up before and after adding the Equity to the algorithm to have the same current value. " +
"The result of 'WarmUpIndicator' shouldn't change if the symbol is or isn't subscribed");
}
}
private void AssertIndicatorState(IIndicator indicator, bool isReady)
{
if (indicator.IsReady != isReady)
{
throw new Exception($"Expected indicator state, expected {isReady} but was {indicator.IsReady}");
}
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
SetHoldings(_symbol, 0.5);
}
}
private class CustomIndicator : IndicatorBase<QuoteBar>, IIndicatorWarmUpPeriodProvider
{
private bool _isReady;
public int WarmUpPeriod => 1;
public override bool IsReady => _isReady;
public CustomIndicator() : base("Pepe")
{ }
protected override decimal ComputeNextValue(QuoteBar input)
{
_isReady = true;
return input.Ask.High;
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-99.999%"},
{"Drawdown", "16.100%"},
{"Expectancy", "0"},
{"Net Profit", "-6.366%"},
{"Sharpe Ratio", "1.194"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "5.56"},
{"Beta", "-71.105"},
{"Annual Standard Deviation", "0.434"},
{"Annual Variance", "0.188"},
{"Information Ratio", "1.016"},
{"Tracking Error", "0.44"},
{"Treynor Ratio", "-0.007"},
{"Total Fees", "$20.35"},
{"Estimated Strategy Capacity", "$19000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.138"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-1.727"},
{"Return Over Maximum Drawdown", "-12.061"},
{"Portfolio Turnover", "4.916"},
{"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", "7c841ca58a4385f42236838e5bf0c382"}
};
}
}

View File

@@ -1,157 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Algorithm which reproduces GH issue 3861, where in some cases 2 consolidators were added when
/// using the automatic indicator warmup feature
/// </summary>
public class AutomaticIndicatorWarmupRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spy;
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);
EnableAutomaticIndicatorWarmUp = true;
// Test case 1
_spy = AddEquity("SPY").Symbol;
var sma = SMA(_spy, 10);
if (!sma.IsReady)
{
throw new Exception("Expected SMA to be warmed up");
}
// Test case 2
var indicator = new CustomIndicator(10);
RegisterIndicator(_spy, indicator, Resolution.Minute, (Func<IBaseData, decimal>) null);
if (indicator.IsReady)
{
throw new Exception("Expected CustomIndicator Not to be warmed up");
}
WarmUpIndicator(_spy, indicator);
if (!indicator.IsReady)
{
throw new Exception("Expected CustomIndicator to be warmed up");
}
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
var subscription = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_spy).First(config => config.TickType == TickType.Trade);
// we expect 1 consolidator per indicator
if (subscription.Consolidators.Count != 2)
{
throw new Exception($"Unexpected consolidator count for subscription: {subscription.Consolidators.Count}");
}
SetHoldings(_spy, 1);
}
}
private class CustomIndicator : SimpleMovingAverage
{
private IndicatorDataPoint _previous;
public CustomIndicator(int period) : base(period)
{
}
protected override decimal ComputeNextValue(IReadOnlyWindow<IndicatorDataPoint> window, IndicatorDataPoint input)
{
if (_previous != null && input.EndTime == _previous.EndTime)
{
throw new Exception($"Unexpected indicator double data point call: {_previous}");
}
_previous = input;
return base.ComputeNextValue(window, input);
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "271.453%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Net Profit", "1.692%"},
{"Sharpe Ratio", "8.888"},
{"Probabilistic Sharpe Ratio", "67.609%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.005"},
{"Beta", "0.996"},
{"Annual Standard Deviation", "0.222"},
{"Annual Variance", "0.049"},
{"Information Ratio", "-14.565"},
{"Tracking Error", "0.001"},
{"Treynor Ratio", "1.978"},
{"Total Fees", "$3.44"},
{"Estimated Strategy Capacity", "$56000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.248"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "93.728"},
{"Portfolio Turnover", "0.248"},
{"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", "9e4bfd2eb0b81ee5bc1b197a87ccedbe"}
};
}
}

View File

@@ -1,345 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.Fills;
using QuantConnect.Securities;
using QuantConnect.Securities.Option;
using System;
using System.Collections.Generic;
using System.Linq;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regression algorithm tests the order processing of the backtesting brokerage.
/// We open an equity position that should fill in two parts, on two different bars.
/// We open a long option position and let it expire so we can exercise the position.
/// To check the orders we use OnOrderEvent and throw exceptions if verification fails.
/// </summary>
/// <meta name="tag" content="backtesting brokerage" />
/// <meta name="tag" content="regression test" />
/// <meta name="tag" content="options" />
class BacktestingBrokerageRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Security _security;
private Symbol _spy;
private OrderTicket _equityBuy;
private Option _option;
private Symbol _optionSymbol;
private OrderTicket _optionBuy;
private bool _optionBought = false;
private bool _equityBought = false;
private decimal _optionStrikePrice;
/// <summary>
/// Initialize the algorithm
/// </summary>
public override void Initialize()
{
SetCash(100000);
SetStartDate(2015, 12, 24);
SetEndDate(2015, 12, 28);
// Get our equity
_security = AddEquity("SPY", Resolution.Hour);
_security.SetFillModel(new PartialMarketFillModel(2));
_spy = _security.Symbol;
// Get our option
_option = AddOption("GOOG");
_option.SetFilter(u => u.IncludeWeeklys()
.Strikes(-2, +2)
.Expiration(TimeSpan.Zero, TimeSpan.FromDays(10)));
_optionSymbol = _option.Symbol;
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!_equityBought && data.ContainsKey(_spy))
{
//Buy our Equity.
//Quantity is rounded down to an even number since it will be split in two equal halves
var quantity = Math.Floor(CalculateOrderQuantity(_spy, .1m) / 2) * 2;
_equityBuy = MarketOrder(_spy, quantity, asynchronous: true);
_equityBought = true;
}
if (!_optionBought)
{
// Buy our option
OptionChain chain;
if (data.OptionChains.TryGetValue(_optionSymbol, out chain))
{
// Find the second call strike under market price expiring today
var contracts = (
from optionContract in chain.OrderByDescending(x => x.Strike)
where optionContract.Right == OptionRight.Call
where optionContract.Expiry == Time.Date
where optionContract.Strike < chain.Underlying.Price
select optionContract
).Take(2);
if (contracts.Any())
{
var optionToBuy = contracts.FirstOrDefault();
_optionStrikePrice = optionToBuy.Strike;
_optionBuy = MarketOrder(optionToBuy.Symbol, 1);
_optionBought = true;
}
}
}
}
/// <summary>
/// All order events get pushed through this function
/// </summary>
/// <param name="orderEvent">OrderEvent object that contains all the information about the event</param>
public override void OnOrderEvent(OrderEvent orderEvent)
{
// Get the order from our transactions
var order = Transactions.GetOrderById(orderEvent.OrderId);
// Based on the type verify the order
switch (order.Type)
{
case OrderType.Market:
VerifyMarketOrder(order, orderEvent);
break;
case OrderType.OptionExercise:
VerifyOptionExercise(order, orderEvent);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// To verify Market orders is process correctly
/// </summary>
/// <param name="order">Order object to analyze</param>
public void VerifyMarketOrder(Order order, OrderEvent orderEvent)
{
switch (order.Status)
{
case OrderStatus.Submitted:
break;
// All PartiallyFilled orders should have a LastFillTime
case OrderStatus.PartiallyFilled:
if (order.LastFillTime == null)
{
throw new Exception("LastFillTime should not be null");
}
if (order.Quantity / 2 != orderEvent.FillQuantity)
{
throw new Exception("Order size should be half");
}
break;
// All filled equity orders should have filled after creation because of our fill model!
case OrderStatus.Filled:
if (order.SecurityType == SecurityType.Equity && order.CreatedTime == order.LastFillTime)
{
throw new Exception("Order should not finish during the CreatedTime bar");
}
break;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// To verify OptionExercise orders is process correctly
/// </summary>
/// <param name="order">Order object to analyze</param>
public void VerifyOptionExercise(Order order, OrderEvent orderEvent)
{
// If the option price isn't the same as the strike price, its incorrect
if (order.Price != _optionStrikePrice)
{
throw new Exception("OptionExercise order price should be strike price!!");
}
if (orderEvent.Quantity != -1)
{
throw new Exception("OrderEvent Quantity should be -1");
}
}
/// <summary>
/// Runs after algorithm, used to check our portfolio and orders
/// </summary>
public override void OnEndOfAlgorithm()
{
if (!Portfolio.ContainsKey(_optionBuy.Symbol) || !Portfolio.ContainsKey(_optionBuy.Symbol.Underlying) || !Portfolio.ContainsKey(_equityBuy.Symbol))
{
throw new Exception("Portfolio does not contain the Symbols we purchased");
}
//Check option holding, should not be invested since it expired, profit should be -400
var optionHolding = Portfolio[_optionBuy.Symbol];
if (optionHolding.Invested || optionHolding.Profit != -400)
{
throw new Exception("Options holding does not match expected outcome");
}
//Check the option underlying symbol since we should have bought it at exercise
//Quantity should be 100, AveragePrice should be option strike price
var optionExerciseHolding = Portfolio[_optionBuy.Symbol.Underlying];
if (!optionExerciseHolding.Invested || optionExerciseHolding.Quantity != 100 || optionExerciseHolding.AveragePrice != _optionBuy.Symbol.ID.StrikePrice)
{
throw new Exception("Equity holding for exercised option does not match expected outcome");
}
//Check equity holding, should be invested, profit should be
//Quantity should be 52, AveragePrice should be ticket AverageFillPrice
var equityHolding = Portfolio[_equityBuy.Symbol];
if (!equityHolding.Invested || equityHolding.Quantity != 52 || equityHolding.AveragePrice != _equityBuy.AverageFillPrice)
{
throw new Exception("Equity holding does not match expected outcome");
}
}
/// <summary>
/// PartialMarketFillModel that allows the user to set the number of fills and restricts
/// the fill to only one per bar.
/// </summary>
private class PartialMarketFillModel : ImmediateFillModel
{
private readonly decimal _percent;
private readonly Dictionary<long, decimal> _absoluteRemainingByOrderId = new Dictionary<long, decimal>();
/// <param name="numberOfFills"></param>
public PartialMarketFillModel(int numberOfFills = 1)
{
_percent = 1m / numberOfFills;
}
/// <summary>
/// Performs partial market fills once per time step
/// </summary>
/// <param name="asset">The security being ordered</param>
/// <param name="order">The order</param>
/// <returns>The order fill</returns>
public override OrderEvent MarketFill(Security asset, MarketOrder order)
{
var currentUtcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
// Only fill once a time slice
if (order.LastFillTime != null && currentUtcTime <= order.LastFillTime)
{
return new OrderEvent(order, currentUtcTime, OrderFee.Zero);
}
decimal absoluteRemaining;
if (!_absoluteRemainingByOrderId.TryGetValue(order.Id, out absoluteRemaining))
{
absoluteRemaining = order.AbsoluteQuantity;
_absoluteRemainingByOrderId.Add(order.Id, order.AbsoluteQuantity);
}
var fill = base.MarketFill(asset, order);
var absoluteFillQuantity = (int)(Math.Min(absoluteRemaining, (int)(_percent * order.Quantity)));
fill.FillQuantity = Math.Sign(order.Quantity) * absoluteFillQuantity;
if (absoluteRemaining == absoluteFillQuantity)
{
fill.Status = OrderStatus.Filled;
_absoluteRemainingByOrderId.Remove(order.Id);
}
else
{
absoluteRemaining = absoluteRemaining - absoluteFillQuantity;
_absoluteRemainingByOrderId[order.Id] = absoluteRemaining;
fill.Status = OrderStatus.PartiallyFilled;
}
return fill;
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "-0.40%"},
{"Compounding Annual Return", "-22.717%"},
{"Drawdown", "0.400%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.329%"},
{"Sharpe Ratio", "-11.083"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.003"},
{"Beta", "0.097"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "9.742"},
{"Tracking Error", "0.021"},
{"Treynor Ratio", "-0.26"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0.212"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-73.334"},
{"Portfolio Turnover", "0.425"},
{"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", "7f99e1a8ce4675a1e8bbe1ba45967ccd"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -71,45 +71,22 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "11.000%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Net Profit", "-7.328%"},
{"Sharpe Ratio", "-12.15"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$85000.00"},
{"Lowest Capacity Asset", "BTCEUR XJ"},
{"Fitness Score", "0.506"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-14.148"},
{"Portfolio Turnover", "1.073"},
{"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", "18dc611407abec4ea47092e71f33f983"}
{"Alpha", "-17.811"},
{"Beta", "1239.638"},
{"Annual Standard Deviation", "0.762"},
{"Annual Variance", "0.581"},
{"Information Ratio", "-12.169"},
{"Tracking Error", "0.761"},
{"Treynor Ratio", "-0.007"},
{"Total Fees", "$0.00"}
};
}
}

View File

@@ -80,45 +80,22 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "271.453%"},
{"Compounding Annual Return", "263.153%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Net Profit", "1.692%"},
{"Sharpe Ratio", "8.888"},
{"Probabilistic Sharpe Ratio", "67.609%"},
{"Net Profit", "1.663%"},
{"Sharpe Ratio", "4.41"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.005"},
{"Beta", "0.996"},
{"Annual Standard Deviation", "0.222"},
{"Annual Variance", "0.049"},
{"Information Ratio", "-14.565"},
{"Tracking Error", "0.001"},
{"Treynor Ratio", "1.978"},
{"Total Fees", "$3.44"},
{"Estimated Strategy Capacity", "$56000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.248"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "93.728"},
{"Portfolio Turnover", "0.248"},
{"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", "9e4bfd2eb0b81ee5bc1b197a87ccedbe"}
{"Alpha", "0.007"},
{"Beta", "76.118"},
{"Annual Standard Deviation", "0.192"},
{"Annual Variance", "0.037"},
{"Information Ratio", "4.354"},
{"Tracking Error", "0.192"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$3.26"}
};
}
}

View File

@@ -1,53 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Data.UniverseSelection;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Basic template algorithm which showcases <see cref="ConstituentsUniverse"/> simple use case
/// </summary>
public class BasicTemplateConstituentUniverseAlgorithm : QCAlgorithm
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);
// by default will use algorithms UniverseSettings
AddUniverse(Universe.Constituent.Steel());
// we specify the UniverseSettings it should use
AddUniverse(Universe.Constituent.AggressiveGrowth(
new UniverseSettings(Resolution.Hour,
2,
false,
false,
UniverseSettings.MinimumTimeInUniverse)));
SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(1)));
SetExecution(new ImmediateExecutionModel());
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
}
}
}

View File

@@ -205,46 +205,23 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "10"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Average Loss", "-0.13%"},
{"Compounding Annual Return", "-99.979%"},
{"Drawdown", "3.500%"},
{"Expectancy", "-1"},
{"Net Profit", "-2.288%"},
{"Sharpe Ratio", "-11.335"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$85.34"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTCEUR XJ"},
{"Fitness Score", "0.5"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-43.943"},
{"Portfolio Turnover", "1.028"},
{"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", "1bf1a6d9dd921982b72a6178f9e50e68"}
{"Alpha", "-5.739"},
{"Beta", "413.859"},
{"Annual Standard Deviation", "0.254"},
{"Annual Variance", "0.065"},
{"Information Ratio", "-11.39"},
{"Tracking Error", "0.254"},
{"Treynor Ratio", "-0.007"},
{"Total Fees", "$85.34"}
};
}
}

View File

@@ -71,45 +71,22 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "246.546%"},
{"Drawdown", "1.200%"},
{"Compounding Annual Return", "246.000%"},
{"Drawdown", "1.100%"},
{"Expectancy", "0"},
{"Net Profit", "3.464%"},
{"Sharpe Ratio", "9.933"},
{"Probabilistic Sharpe Ratio", "82.470%"},
{"Net Profit", "3.459%"},
{"Sharpe Ratio", "6.033"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.957"},
{"Beta", "-0.125"},
{"Annual Standard Deviation", "0.164"},
{"Annual Variance", "0.027"},
{"Information Ratio", "-4.577"},
{"Tracking Error", "0.225"},
{"Treynor Ratio", "-13.006"},
{"Total Fees", "$3.45"},
{"Estimated Strategy Capacity", "$970000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.112"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "53.951"},
{"Return Over Maximum Drawdown", "209.464"},
{"Portfolio Turnover", "0.112"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"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", "33d01821923c397f999cfb2e5b5928ad"}
{"Alpha", "0.696"},
{"Beta", "17.597"},
{"Annual Standard Deviation", "0.16"},
{"Annual Variance", "0.026"},
{"Information Ratio", "5.939"},
{"Tracking Error", "0.16"},
{"Treynor Ratio", "0.055"},
{"Total Fees", "$3.26"}
};
}
}

View File

@@ -53,15 +53,7 @@ namespace QuantConnect.Algorithm.CSharp
// set algorithm framework models
SetUniverseSelection(new ManualUniverseSelectionModel(QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA)));
SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromMinutes(20), 0.025, null));
// We can define who often the EWPCM will rebalance if no new insight is submitted using:
// Resolution Enum:
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel(Resolution.Daily));
// TimeSpan
// SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel(TimeSpan.FromDays(2)));
// A Func<DateTime, DateTime>. In this case, we can use the pre-defined func at Expiry helper class
// SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel(Expiry.EndOfWeek));
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
SetExecution(new ImmediateExecutionModel());
SetRiskManagement(new MaximumDrawdownPercentPerSecurity(0.01m));
}
@@ -91,46 +83,37 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "-1.01%"},
{"Compounding Annual Return", "261.134%"},
{"Drawdown", "2.200%"},
{"Average Loss", "-1.03%"},
{"Compounding Annual Return", "245.167%"},
{"Drawdown", "2.300%"},
{"Expectancy", "-1"},
{"Net Profit", "1.655%"},
{"Sharpe Ratio", "8.505"},
{"Probabilistic Sharpe Ratio", "66.840%"},
{"Net Profit", "1.597%"},
{"Sharpe Ratio", "4.169"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.091"},
{"Beta", "1.006"},
{"Annual Standard Deviation", "0.224"},
{"Annual Variance", "0.05"},
{"Information Ratio", "-33.445"},
{"Tracking Error", "0.002"},
{"Treynor Ratio", "1.893"},
{"Total Fees", "$10.32"},
{"Estimated Strategy Capacity", "$27000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Alpha", "0.007"},
{"Beta", "73.191"},
{"Annual Standard Deviation", "0.195"},
{"Annual Variance", "0.038"},
{"Information Ratio", "4.113"},
{"Tracking Error", "0.195"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$9.77"},
{"Fitness Score", "0.747"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "85.095"},
{"Portfolio Turnover", "0.747"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
{"Total Insights Analysis Completed", "99"},
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "ad2216297c759d8e5aef48ff065f8919"}
{"Estimated Monthly Alpha Value", "$158418.3850"},
{"Total Accumulated Estimated Alpha Value", "$25522.9620"},
{"Mean Population Estimated Insight Value", "$257.8077"},
{"Mean Population Direction", "54.5455%"},
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -20,7 +20,6 @@ using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
namespace QuantConnect.Algorithm.CSharp
{
@@ -34,15 +33,13 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="futures" />
public class BasicTemplateFuturesAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _contractSymbol;
// S&P 500 EMini futures
private const string RootSP500 = Futures.Indices.SP500EMini;
public Symbol SP500 = QuantConnect.Symbol.Create(RootSP500, SecurityType.Future, Market.CME);
public Symbol SP500 = QuantConnect.Symbol.Create(RootSP500, SecurityType.Future, Market.USA);
// Gold futures
private const string RootGold = Futures.Metals.Gold;
public Symbol Gold = QuantConnect.Symbol.Create(RootGold, SecurityType.Future, Market.COMEX);
public Symbol Gold = QuantConnect.Symbol.Create(RootGold, SecurityType.Future, Market.USA);
/// <summary>
/// Initialize your algorithm and add desired assets.
@@ -57,10 +54,8 @@ namespace QuantConnect.Algorithm.CSharp
var futureGold = AddFuture(RootGold);
// set our expiry filter for this futures chain
// SetFilter method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
futureGold.SetFilter(0, 182);
futureGold.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
var benchmark = AddEquity("SPY");
SetBenchmark(benchmark.Symbol);
@@ -86,8 +81,7 @@ namespace QuantConnect.Algorithm.CSharp
// if found, trade it
if (contract != null)
{
_contractSymbol = contract.Symbol;
MarketOrder(_contractSymbol, 1);
MarketOrder(contract.Symbol, 1);
}
}
}
@@ -97,21 +91,6 @@ namespace QuantConnect.Algorithm.CSharp
}
}
public override void OnEndOfAlgorithm()
{
// Get the margin requirements
var buyingPowerModel = Securities[_contractSymbol].BuyingPowerModel;
var futureMarginModel = buyingPowerModel as FutureMarginModel;
if (buyingPowerModel == null)
{
throw new Exception($"Invalid buying power model. Found: {buyingPowerModel.GetType().Name}. Expected: {nameof(FutureMarginModel)}");
}
var initialOvernight = futureMarginModel.InitialOvernightMarginRequirement;
var maintenanceOvernight = futureMarginModel.MaintenanceOvernightMarginRequirement;
var initialIntraday = futureMarginModel.InitialIntradayMarginRequirement;
var maintenanceIntraday = futureMarginModel.MaintenanceIntradayMarginRequirement;
}
/// <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>
@@ -134,41 +113,19 @@ namespace QuantConnect.Algorithm.CSharp
{"Drawdown", "13.500%"},
{"Expectancy", "-0.818"},
{"Net Profit", "-13.517%"},
{"Sharpe Ratio", "-2.678"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Sharpe Ratio", "-29.354"},
{"Loss Rate", "89%"},
{"Win Rate", "11%"},
{"Profit-Loss Ratio", "0.69"},
{"Alpha", "4.469"},
{"Beta", "-0.961"},
{"Annual Standard Deviation", "0.373"},
{"Annual Variance", "0.139"},
{"Information Ratio", "-13.191"},
{"Tracking Error", "0.507"},
{"Treynor Ratio", "1.04"},
{"Alpha", "-7.746"},
{"Beta", "-0.859"},
{"Annual Standard Deviation", "0.305"},
{"Annual Variance", "0.093"},
{"Information Ratio", "-24.985"},
{"Tracking Error", "0.414"},
{"Treynor Ratio", "10.413"},
{"Total Fees", "$15207.00"},
{"Estimated Strategy Capacity", "$8000.00"},
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
{"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"}
{"Fitness Score", "0.033"}
};
}
}

View File

@@ -33,7 +33,7 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateFuturesConsolidationAlgorithm : QCAlgorithm
{
private const string RootSP500 = Futures.Indices.SP500EMini;
public Symbol SP500 = QuantConnect.Symbol.Create(RootSP500, SecurityType.Future, Market.CME);
public Symbol SP500 = QuantConnect.Symbol.Create(RootSP500, SecurityType.Future, Market.USA);
private HashSet<Symbol> _futureContracts = new HashSet<Symbol>();
public override void Initialize()
@@ -43,11 +43,7 @@ namespace QuantConnect.Algorithm.CSharp
SetCash(1000000);
var futureSP500 = AddFuture(RootSP500);
// set our expiry filter for this future chain
// SetFilter method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
futureSP500.SetFilter(0, 182);
// futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
SetBenchmark(x => 0);
}

View File

@@ -53,12 +53,12 @@ namespace QuantConnect.Algorithm.CSharp
var newYorkTime = utcTime.ConvertFromUtc(TimeZones.NewYork);
if (newYorkTime.Date < new DateTime(2013, 10, 09))
{
yield return QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME);
yield return QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.USA);
}
if (newYorkTime.Date >= new DateTime(2013, 10, 09))
{
yield return QuantConnect.Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX);
yield return QuantConnect.Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.USA);
}
}
@@ -142,27 +142,18 @@ namespace QuantConnect.Algorithm.CSharp
{"Drawdown", "5.000%"},
{"Expectancy", "0"},
{"Net Profit", "-3.312%"},
{"Sharpe Ratio", "-7.795"},
{"Probabilistic Sharpe Ratio", "0.164%"},
{"Sharpe Ratio", "-16.986"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-1.362"},
{"Beta", "0.257"},
{"Annual Standard Deviation", "0.109"},
{"Annual Variance", "0.012"},
{"Information Ratio", "-14.947"},
{"Tracking Error", "0.19"},
{"Treynor Ratio", "-3.309"},
{"Alpha", "-0.828"},
{"Beta", "-77.873"},
{"Annual Standard Deviation", "0.099"},
{"Annual Variance", "0.01"},
{"Information Ratio", "-17.076"},
{"Tracking Error", "0.099"},
{"Treynor Ratio", "0.022"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$52000000.00"},
{"Lowest Capacity Asset", "GC VL5E74HP3EE5"},
{"Fitness Score", "0.009"},
{"Kelly Criterion Estimate", "-112.972"},
{"Kelly Criterion Probability Value", "0.671"},
{"Sortino Ratio", "-8.425"},
{"Return Over Maximum Drawdown", "-35.219"},
{"Portfolio Turnover", "0.548"},
{"Total Insights Generated", "6"},
{"Total Insights Closed", "5"},
{"Total Insights Analysis Completed", "5"},
@@ -175,8 +166,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "18ffd3a774c68da83d867e3b09e3e05d"}
{"Rolling Averaged Population Magnitude", "0%"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -20,8 +20,6 @@ using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
@@ -34,7 +32,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="history and warm up" />
/// <meta name="tag" content="history" />
/// <meta name="tag" content="futures" />
public class BasicTemplateFuturesHistoryAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
public class BasicTemplateFuturesHistoryAlgorithm : QCAlgorithm
{
// S&P 500 EMini futures
private string [] roots = new []
@@ -43,8 +41,6 @@ namespace QuantConnect.Algorithm.CSharp
Futures.Metals.Gold,
};
private int _successCount = 0;
public override void Initialize()
{
SetStartDate(2013, 10, 8);
@@ -58,26 +54,6 @@ namespace QuantConnect.Algorithm.CSharp
}
SetBenchmark(d => 1000000);
Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromHours(1)), MakeHistoryCall);
}
private void MakeHistoryCall()
{
var history = History(10, Resolution.Minute);
if (history.Count() < 10)
{
throw new Exception($"Empty history at {Time}");
}
_successCount++;
}
public override void OnEndOfAlgorithm()
{
if (_successCount < 49)
{
throw new Exception($"Scheduled Event did not assert history call as many times as expected: {_successCount}/49");
}
}
/// <summary>
@@ -92,12 +68,12 @@ namespace QuantConnect.Algorithm.CSharp
{
foreach (var contract in chain.Value)
{
Log($"{contract.Symbol.Value}," +
$"Bid={contract.BidPrice.ToStringInvariant()} " +
$"Ask={contract.AskPrice.ToStringInvariant()} " +
$"Last={contract.LastPrice.ToStringInvariant()} " +
$"OI={contract.OpenInterest.ToStringInvariant()}"
);
Log(String.Format("{0},Bid={1} Ask={2} Last={3} OI={4}",
contract.Symbol.Value,
contract.BidPrice,
contract.AskPrice,
contract.LastPrice,
contract.OpenInterest));
}
}
}
@@ -124,64 +100,5 @@ namespace QuantConnect.Algorithm.CSharp
{
Log(orderEvent.ToString());
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}
}

View File

@@ -1,158 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using QuantConnect.Data;
using System.Collections.Generic;
using QuantConnect.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.908"},
{"Beta", "0.468"},
{"Annual Standard Deviation", "0.139"},
{"Annual Variance", "0.019"},
{"Information Ratio", "-9.003"},
{"Tracking Error", "0.142"},
{"Treynor Ratio", "-1.251"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$14000000.00"},
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
{"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"}
};
}
}

View File

@@ -1,180 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using QuantConnect.Data;
using System.Collections.Generic;
using QuantConnect.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"}
};
}
}

View File

@@ -1,141 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Data;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Basic template India algorithm simply initializes the date range and cash. This is a skeleton
/// framework you can use for designing an algorithm.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="using quantconnect" />
/// <meta name="tag" content="trading and orders" />
public class BasicTemplateIndiaAlgorithm : QCAlgorithm
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2003, 10, 07); //Set Start Date
SetEndDate(2003, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
// Find more symbols here: http://quantconnect.com/data
// Equities Resolutions: Tick, Second, Minute, Hour, Daily.
AddEquity("UNIONBANK", Resolution.Second, Market.India);
//Set Order Prperties as per the requirements for order placement
DefaultOrderProperties = new ZerodhaOrderProperties(exchange: "nse");
//override default productType value set in config.json if needed - order specific productType value
//DefaultOrderProperties = new ZerodhaOrderProperties(exchange: "nse",ZerodhaOrderProperties.KiteProductType.CNC);
// General Debug statement for acknowledgement
Debug("Intialization Done");
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
var marketTicket = MarketOrder("UNIONBANK", 1);
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Status.IsFill())
{
Debug($"Purchased Complete: {orderEvent.Symbol}");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "-1.01%"},
{"Compounding Annual Return", "261.134%"},
{"Drawdown", "2.200%"},
{"Expectancy", "-1"},
{"Net Profit", "1.655%"},
{"Sharpe Ratio", "8.505"},
{"Probabilistic Sharpe Ratio", "66.840%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.091"},
{"Beta", "1.006"},
{"Annual Standard Deviation", "0.224"},
{"Annual Variance", "0.05"},
{"Information Ratio", "-33.445"},
{"Tracking Error", "0.002"},
{"Treynor Ratio", "1.893"},
{"Total Fees", "$10.32"},
{"Estimated Strategy Capacity", "$27000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.747"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "85.095"},
{"Portfolio Turnover", "0.747"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
{"Total Insights Analysis Completed", "99"},
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "ad2216297c759d8e5aef48ff065f8919"}
};
}
}

View File

@@ -56,12 +56,9 @@ namespace QuantConnect.Algorithm.CSharp
// setting up S&P 500 EMini futures
var futureSP500 = AddFuture(Futures.Indices.SP500EMini);
_futureSymbol = futureSP500.Symbol;
// set our expiry filter for this futures chain
// SetFilter method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
futureSP500.SetFilter(10, 182);
// futureSP500.SetFilter(TimeSpan.FromDays(10), TimeSpan.FromDays(182));
futureSP500.SetFilter(TimeSpan.FromDays(10), TimeSpan.FromDays(182));
// setting up Dow Jones ETF Options
var option = AddOption("DIA");
@@ -69,11 +66,8 @@ namespace QuantConnect.Algorithm.CSharp
option.PriceModel = OptionPriceModels.BinomialCoxRossRubinstein();
// option.EnableGreekApproximation = true;
// set our strike/expiry filter for this option chain
// SetFilter method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
option.SetFilter(-2, +2, 0, 180);
// option.SetFilter(-2, +2, TimeSpan.Zero, TimeSpan.FromDays(180));
// set our expiry filter for this option chain
option.SetFilter(-2, +2, TimeSpan.Zero, TimeSpan.FromDays(180));
// specifying zero benchmark
SetBenchmark(date => 0m);
@@ -137,26 +131,26 @@ namespace QuantConnect.Algorithm.CSharp
if (_barCount % 20 == 1)
{
Log($"P/L:{Portfolio.TotalUnrealisedProfit.ToStringInvariant("0.00")}, " +
$"Fees:{Portfolio.TotalFees.ToStringInvariant("0.00")}, " +
$"Profit:{Portfolio.TotalProfit.ToStringInvariant("0.00")}, " +
$"Eq:{Portfolio.TotalPortfolioValue.ToStringInvariant("0.00")}, " +
$"Holdings:{Portfolio.TotalHoldingsValue.ToStringInvariant("0.00")}, " +
$"Vol: {Portfolio.TotalSaleVolume.ToStringInvariant("0.00")}, " +
$"Margin: {Portfolio.TotalMarginUsed.ToStringInvariant("0.00")}"
);
Log(String.Format("P/L:{0:0.00}, Fees:{1:0.00}, Profit:{2:0.00}, Eq:{3:0.00}, Holdings:{4:0.00}, Vol: {5:0.00}, Margin: {6:0.00}",
Portfolio.TotalUnrealisedProfit,
Portfolio.TotalFees,
Portfolio.TotalProfit,
Portfolio.TotalPortfolioValue,
Portfolio.TotalHoldingsValue,
Portfolio.TotalSaleVolume,
Portfolio.TotalMarginUsed));
foreach (var holding in Securities.Values.OrderByDescending(x => x.Holdings.AbsoluteQuantity))
{
Log($" - {holding.Symbol.Value}, " +
$"Avg Prc:{holding.Holdings.AveragePrice.ToStringInvariant("0.00")}, " +
$"Qty:{holding.Holdings.Quantity.ToStringInvariant("0.00")}, " +
$"Mkt Prc:{holding.Holdings.Price.ToStringInvariant("0.00")}, " +
$"Mkt Val:{holding.Holdings.HoldingsValue.ToStringInvariant("0.00")}, " +
$"Unreal P/L: {holding.Holdings.UnrealizedProfit.ToStringInvariant("0.00")}, " +
$"Fees: {holding.Holdings.TotalFees.ToStringInvariant("0.00")}, " +
$"Vol: {holding.Holdings.TotalSaleVolume.ToStringInvariant("0.00")}"
);
Log(String.Format(" - {0}, Avg Prc:{1:0.00}, Qty:{2:0.00}, Mkt Prc:{3:0.00}, Mkt Val:{4:0.00}, Unreal P/L: {5:0.00}, Fees: {6:0.00}, Vol: {7:0.00}",
holding.Symbol.Value,
holding.Holdings.AveragePrice,
holding.Holdings.Quantity,
holding.Holdings.Price,
holding.Holdings.HoldingsValue,
holding.Holdings.UnrealizedProfit,
holding.Holdings.TotalFees,
holding.Holdings.TotalSaleVolume));
}
}
@@ -167,20 +161,21 @@ namespace QuantConnect.Algorithm.CSharp
var underlying = Securities[chain.Key.Underlying];
foreach (var contract in chain.Value)
{
Log($"{Time.ToStringInvariant()} {contract.Symbol.Value}," +
$"B={contract.BidPrice.ToStringInvariant()} " +
$"A={contract.AskPrice.ToStringInvariant()} " +
$"L={contract.LastPrice.ToStringInvariant()} " +
$"OI={contract.OpenInterest.ToStringInvariant()} " +
$"σ={underlying.VolatilityModel.Volatility:0.00} " +
$"NPV={contract.TheoreticalPrice.ToStringInvariant("0.00")} " +
$"Δ={contract.Greeks.Delta.ToStringInvariant("0.00")} " +
$"Γ={contract.Greeks.Gamma.ToStringInvariant("0.00")} " +
$"ν={contract.Greeks.Vega.ToStringInvariant("0.00")} " +
$"ρ={contract.Greeks.Rho.ToStringInvariant("0.00")} " +
$"Θ={(contract.Greeks.Theta / 365.0m).ToStringInvariant("0.00")} " +
$"IV={contract.ImpliedVolatility.ToStringInvariant("0.00")}"
);
Log(String.Format(@"{0} {1},B={2} A={3} L={4} OI={5} σ={6:0.00} NPV={7:0.00} Δ={8:0.00} Γ={9:0.00} ν={10:0.00} ρ={11:0.00} Θ={12:0.00} IV={13:0.00}",
Time.ToString(),
contract.Symbol.Value,
contract.BidPrice,
contract.AskPrice,
contract.LastPrice,
contract.OpenInterest,
underlying.VolatilityModel.Volatility,
contract.TheoreticalPrice,
contract.Greeks.Delta,
contract.Greeks.Gamma,
contract.Greeks.Vega,
contract.Greeks.Rho,
contract.Greeks.Theta / 365.0m,
contract.ImpliedVolatility));
}
}
@@ -188,12 +183,13 @@ namespace QuantConnect.Algorithm.CSharp
{
foreach (var contract in chain.Value)
{
Log($"{contract.Symbol.Value}, {Time}, " +
$"B={contract.BidPrice} " +
$"A={contract.AskPrice} " +
$"L={contract.LastPrice} " +
$"OI={contract.OpenInterest}"
);
Log(String.Format("{0}, {1}, B={2} A={3} L={4} OI={5}",
contract.Symbol.Value,
Time,
contract.BidPrice,
contract.AskPrice,
contract.LastPrice,
contract.OpenInterest));
}
}
}
@@ -205,7 +201,7 @@ namespace QuantConnect.Algorithm.CSharp
foreach (var kpv in slice.Bars)
{
Log($"---> Bar: {Time}, {kpv.Key.Value}, {kpv.Value.Close.ToStringInvariant("0.0000")}");
Log($"---> Bar: {Time}, {kpv.Key.Value}, {kpv.Value.Close:0.0000}");
}
}

View File

@@ -1,151 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Data.Market;
using System.Collections.Generic;
using QuantConnect.Securities.Option;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Basic template algorithm trading a Call Butterfly option equity strategy
/// </summary>
/// <meta name="tag" content="options" />
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="using quantconnect" />
/// <meta name="tag" content="trading and orders" />
public class BasicTemplateOptionEquityStrategyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected Symbol _optionSymbol;
public override void Initialize()
{
SetStartDate(2015, 12, 24);
SetEndDate(2015, 12, 24);
var equity = AddEquity("GOOG", leverage: 4);
var option = AddOption(equity.Symbol);
_optionSymbol = option.Symbol;
// set our strike/expiry filter for this option chain
option.SetFilter(u => u.Strikes(-2, +2)
// Expiration method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
.Expiration(0, 180));
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
OptionChain chain;
if (IsMarketOpen(_optionSymbol) && slice.OptionChains.TryGetValue(_optionSymbol, out chain))
{
var callContracts = chain.Where(contract => contract.Right == OptionRight.Call)
.GroupBy(x => x.Expiry)
.OrderBy(grouping => grouping.Key)
.First()
.OrderBy(x => x.Strike)
.ToList();
var expiry = callContracts[0].Expiry;
var lowerStrike = callContracts[0].Strike;
var middleStrike = callContracts[1].Strike;
var higherStrike = callContracts[2].Strike;
var optionStrategy = OptionStrategies.CallButterfly(_optionSymbol, higherStrike, middleStrike, lowerStrike, expiry);
Order(optionStrategy, 10);
}
}
}
/// <summary>
/// Order fill event handler. On an order fill update the resulting information is passed to this method.
/// </summary>
/// <param name="orderEvent">Order event details containing details of the evemts</param>
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
public override void OnOrderEvent(OrderEvent orderEvent)
{
Log($"{orderEvent}");
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally => true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$10.00"},
{"Estimated Strategy Capacity", "$84000.00"},
{"Lowest Capacity Asset", "GOOCV W78ZERHAOVVQ|GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "0"},
{"Return Over Maximum Drawdown", "0"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "82c29cc9db9a300074d6ff136253f4ac"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -48,10 +48,7 @@ namespace QuantConnect.Algorithm.CSharp
_optionSymbol = option.Symbol;
// set our strike/expiry filter for this option chain
// SetFilter method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
option.SetFilter(-2, +2, 0, 180);
// option.SetFilter(-2, +2, TimeSpan.Zero, TimeSpan.FromDays(180));
option.SetFilter(-2, +2, TimeSpan.Zero, TimeSpan.FromDays(180));
// Adding this to reproduce GH issue #2314
SetWarmup(TimeSpan.FromMinutes(1));
@@ -116,14 +113,13 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "778"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Average Loss", "-0.02%"},
{"Compounding Annual Return", "-100%"},
{"Drawdown", "6.900%"},
{"Expectancy", "-1"},
{"Net Profit", "-6.860%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
@@ -133,29 +129,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$778.00"},
{"Estimated Strategy Capacity", "$1000.00"},
{"Lowest Capacity Asset", "GOOCV W78ZFMEBBB2E|GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "0"},
{"Return Over Maximum Drawdown", "0"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "6a88f302b7f29a2c59e4b1e978161da1"}
{"Total Fees", "$778.00"}
};
}
}

View File

@@ -41,10 +41,7 @@ namespace QuantConnect.Algorithm.CSharp
_optionSymbol = option.Symbol;
// set our strike/expiry filter for this option chain
// SetFilter method accepts TimeSpan objects or integer for days.
// The following statements yields the same filtering criteria
option.SetFilter(-2, +2, 0, 10);
// option.SetFilter(-2, +2, TimeSpan.Zero, TimeSpan.FromDays(10));
option.SetFilter(-2, +2, TimeSpan.Zero, TimeSpan.FromDays(10));
// use the underlying equity as the benchmark
SetBenchmark("GOOG");

View File

@@ -35,7 +35,8 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateOptionsAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "GOOG";
public Symbol OptionSymbol;
public readonly Symbol Underlying = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Equity, Market.USA);
public readonly Symbol OptionSymbol = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Option, Market.USA);
public override void Initialize()
{
@@ -45,14 +46,10 @@ namespace QuantConnect.Algorithm.CSharp
var equity = AddEquity(UnderlyingTicker);
var option = AddOption(UnderlyingTicker);
OptionSymbol = option.Symbol;
// set our strike/expiry filter for this option chain
option.SetFilter(u => u.Strikes(-2, +2)
// Expiration method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
.Expiration(0, 180));
// .Expiration(TimeSpan.Zero, TimeSpan.FromDays(180)));
.Expiration(TimeSpan.Zero, TimeSpan.FromDays(180)));
// use the underlying equity as the benchmark
SetBenchmark(equity.Symbol);
@@ -113,14 +110,13 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Average Loss", "-0.28%"},
{"Compounding Annual Return", "-78.282%"},
{"Drawdown", "0.300%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.282%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
@@ -130,29 +126,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$1300000.00"},
{"Lowest Capacity Asset", "GOOCV 30AKMEIPOSS1Y|GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "0"},
{"Return Over Maximum Drawdown", "0"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "9d9f9248ee8fe30d87ff0a6f6fea5112"}
{"Total Fees", "$2.00"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -15,11 +15,9 @@
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
@@ -33,26 +31,27 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="options" />
/// <meta name="tag" content="filter selection" />
public class BasicTemplateOptionsFilterUniverseAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
public class BasicTemplateOptionsFilterUniverseAlgorithm : QCAlgorithm
{
private const string UnderlyingTicker = "GOOG";
public Symbol OptionSymbol;
public readonly Symbol Underlying = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Equity, Market.USA);
public readonly Symbol OptionSymbol = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Option, Market.USA);
public override void Initialize()
{
SetStartDate(2015, 12, 24);
SetEndDate(2015, 12, 24);
SetCash(100000);
SetCash(10000);
var equity = AddEquity(UnderlyingTicker);
var option = AddOption(UnderlyingTicker);
OptionSymbol = option.Symbol;
// Set our custom universe filter, Expires today, is a call, and is within 10 dollars of the current price
option.SetFilter(universe => from symbol in universe.WeeklysOnly().Expiration(0, 1)
// set our custom filter for this option chain
option.SetFilter(universe => from symbol in universe
.WeeklysOnly()
.Expiration(TimeSpan.Zero, TimeSpan.FromDays(10))
where symbol.ID.OptionRight != OptionRight.Put &&
-10 < universe.Underlying.Price - symbol.ID.StrikePrice &&
universe.Underlying.Price - symbol.ID.StrikePrice < 10
universe.Underlying.Price - symbol.ID.StrikePrice < 60
select symbol);
// use the underlying equity as the benchmark
@@ -66,13 +65,14 @@ namespace QuantConnect.Algorithm.CSharp
OptionChain chain;
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
{
// Get the first ITM call expiring today
// find the second call strike under market price expiring today
var contract = (
from optionContract in chain.OrderByDescending(x => x.Strike)
where optionContract.Right == OptionRight.Call
where optionContract.Expiry == Time.Date
where optionContract.Strike < chain.Underlying.Price
select optionContract
).FirstOrDefault();
).Skip(2).FirstOrDefault();
if (contract != null)
{
@@ -86,64 +86,5 @@ namespace QuantConnect.Algorithm.CSharp
{
Log(orderEvent.ToString());
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "0"},
{"Return Over Maximum Drawdown", "0"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "92d8a50efe230524512404dab66b19dd"}
};
}
}

View File

@@ -80,10 +80,7 @@ namespace QuantConnect.Algorithm.CSharp
{
return filter
.Strikes(+1, +1)
// Expiration method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
.Expiration(0, 7)
//.Expiration(TimeSpan.Zero, TimeSpan.FromDays(7))
.Expiration(TimeSpan.Zero, TimeSpan.FromDays(7))
.WeeklysOnly()
.PutsOnly()
.OnlyApplyFilterAtMarketOpen();
@@ -142,47 +139,37 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "4"},
{"Average Win", "0%"},
{"Average Win", "0.14%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Compounding Annual Return", "71.396%"},
{"Drawdown", "0.700%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Net Profit", "0.271%"},
{"Sharpe Ratio", "9.165"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$3.00"},
{"Estimated Strategy Capacity", "$74000.00"},
{"Lowest Capacity Asset", "AAPL 2ZQGWTSSZ0WLI|AAPL R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0.327"},
{"Kelly Criterion Probability Value", "1"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Beta", "24.746"},
{"Annual Standard Deviation", "0.025"},
{"Annual Variance", "0.001"},
{"Information Ratio", "8.883"},
{"Tracking Error", "0.025"},
{"Treynor Ratio", "0.009"},
{"Total Fees", "$4.00"},
{"Total Insights Generated", "26"},
{"Total Insights Closed", "24"},
{"Total Insights Analysis Completed", "24"},
{"Long Insight Count", "26"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$31.01809"},
{"Estimated Monthly Alpha Value", "$28.43325"},
{"Total Accumulated Estimated Alpha Value", "$1.89555"},
{"Mean Population Estimated Insight Value", "$0.07898125"},
{"Mean Population Direction", "50%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "50.0482%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "ce06ddfa4b2ffeb666a8910ac8836992"}
{"Rolling Averaged Population Magnitude", "0%"}
};
}
}

View File

@@ -39,11 +39,8 @@ namespace QuantConnect.Algorithm.CSharp
SetCash(1000000);
var option = AddOption("GOOG");
// add the initial contract filter
// SetFilter method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
option.SetFilter(-2, +2, 0, 180);
// option.SetFilter(-2, +2, TimeSpan.Zero, TimeSpan.FromDays(180));
// add the initial contract filter
option.SetFilter(-2, +2, TimeSpan.Zero, TimeSpan.FromDays(180));
// set the pricing model for Greeks and volatility
// find more pricing models https://www.quantconnect.com/lean/documentation/topic27704.html
@@ -68,20 +65,20 @@ namespace QuantConnect.Algorithm.CSharp
var underlying = Securities[chain.Key.Underlying];
foreach (var contract in chain.Value)
{
Log($"{contract.Symbol.Value}," +
$"Bid={contract.BidPrice.ToStringInvariant()} " +
$"Ask={contract.AskPrice.ToStringInvariant()} " +
$"Last={contract.LastPrice.ToStringInvariant()} " +
$"OI={contract.OpenInterest.ToStringInvariant()} " +
$"σ={underlying.VolatilityModel.Volatility.ToStringInvariant("0.000")} " +
$"NPV={contract.TheoreticalPrice.ToStringInvariant("0.000")} " +
$"Δ={contract.Greeks.Delta.ToStringInvariant("0.000")} " +
$"Γ={contract.Greeks.Gamma.ToStringInvariant("0.000")} " +
$"ν={contract.Greeks.Vega.ToStringInvariant("0.000")} " +
$"ρ={contract.Greeks.Rho.ToStringInvariant("0.00")} " +
$"Θ={(contract.Greeks.Theta / 365.0m).ToStringInvariant("0.00")} " +
$"IV={contract.ImpliedVolatility.ToStringInvariant("0.000")}"
);
Log(String.Format(@"{0},Bid={1} Ask={2} Last={3} OI={4} σ={5:0.000} NPV={6:0.000} Δ={7:0.000} Γ={8:0.000} ν={9:0.000} ρ={10:0.00} Θ={11:0.00} IV={12:0.000}",
contract.Symbol.Value,
contract.BidPrice,
contract.AskPrice,
contract.LastPrice,
contract.OpenInterest,
underlying.VolatilityModel.Volatility,
contract.TheoreticalPrice,
contract.Greeks.Delta,
contract.Greeks.Gamma,
contract.Greeks.Vega,
contract.Greeks.Rho,
contract.Greeks.Theta / 365.0m,
contract.ImpliedVolatility));
}
}
}

View File

@@ -28,11 +28,11 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
_symbol = AddEquity("SPY").Symbol;
}
public override void OnEndOfDay(Symbol symbol)
public override void OnEndOfDay()
{
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;

View File

@@ -37,10 +37,6 @@ namespace QuantConnect.Algorithm.CSharp
// Set requested data resolution
UniverseSettings.Resolution = Resolution.Minute;
// Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
// Commented so regression algorithm is more sensitive
//Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;
SetStartDate(2013, 10, 07); //Set Start Date
SetEndDate(2013, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
@@ -78,48 +74,38 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "20"},
{"Total Trades", "21"},
{"Average Win", "0%"},
{"Average Loss", "-0.13%"},
{"Compounding Annual Return", "62.435%"},
{"Drawdown", "1.100%"},
{"Average Loss", "-0.38%"},
{"Compounding Annual Return", "-82.823%"},
{"Drawdown", "4.300%"},
{"Expectancy", "-1"},
{"Net Profit", "0.667%"},
{"Sharpe Ratio", "3.507"},
{"Probabilistic Sharpe Ratio", "59.181%"},
{"Net Profit", "-2.384%"},
{"Sharpe Ratio", "-6.465"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.384"},
{"Beta", "0.564"},
{"Annual Standard Deviation", "0.116"},
{"Annual Variance", "0.013"},
{"Information Ratio", "-10.791"},
{"Tracking Error", "0.092"},
{"Treynor Ratio", "0.718"},
{"Total Fees", "$46.20"},
{"Estimated Strategy Capacity", "$2300000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Fitness Score", "0.645"},
{"Kelly Criterion Estimate", "13.787"},
{"Kelly Criterion Probability Value", "0.231"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "65.642"},
{"Portfolio Turnover", "0.645"},
{"Total Insights Generated", "13"},
{"Total Insights Closed", "10"},
{"Total Insights Analysis Completed", "10"},
{"Alpha", "0"},
{"Beta", "-87.084"},
{"Annual Standard Deviation", "0.155"},
{"Annual Variance", "0.024"},
{"Information Ratio", "-6.536"},
{"Tracking Error", "0.155"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$72.41"},
{"Total Insights Generated", "14"},
{"Total Insights Closed", "11"},
{"Total Insights Analysis Completed", "11"},
{"Long Insight Count", "6"},
{"Short Insight Count", "7"},
{"Long/Short Ratio", "85.71%"},
{"Estimated Monthly Alpha Value", "$52003.0716"},
{"Total Accumulated Estimated Alpha Value", "$8956.0846"},
{"Mean Population Estimated Insight Value", "$895.6085"},
{"Mean Population Direction", "70%"},
{"Mean Population Magnitude", "70%"},
{"Rolling Averaged Population Direction", "94.5154%"},
{"Rolling Averaged Population Magnitude", "94.5154%"},
{"OrderListHash", "0945ff7a39bb8f8a07b3dcc817c070aa"}
{"Short Insight Count", "4"},
{"Long/Short Ratio", "150.0%"},
{"Estimated Monthly Alpha Value", "$-85612.32"},
{"Total Accumulated Estimated Alpha Value", "$-14744.34"},
{"Mean Population Estimated Insight Value", "$-1340.395"},
{"Mean Population Direction", "27.2727%"},
{"Mean Population Magnitude", "27.2727%"},
{"Rolling Averaged Population Direction", "5.8237%"},
{"Rolling Averaged Population Magnitude", "5.8237%"}
};
}
}

View File

@@ -108,9 +108,8 @@ namespace QuantConnect.Algorithm.CSharp
{
// return a message describing why we're not allowing this order
message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "InsufficientRemainingCapital",
$"Account must maintain a minimum of ${_minimumAccountBalance.ToStringInvariant()} USD at all times. " +
$"Order ID: {order.Id.ToStringInvariant()}"
);
string.Format("Account must maintain a minimum of ${0} USD at all times. Order ID: {1}", _minimumAccountBalance, order.Id)
);
return false;
}
return true;

View File

@@ -130,45 +130,22 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "5.600%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Net Profit", "-4.431%"},
{"Sharpe Ratio", "-23.129"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$370000.00"},
{"Lowest Capacity Asset", "ETHUSD XJ"},
{"Fitness Score", "0.501"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-30.158"},
{"Portfolio Turnover", "1.033"},
{"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", "aea2e321d17414c1f3c6fa2491f10c88"}
{"Alpha", "-8.364"},
{"Beta", "395.811"},
{"Annual Standard Deviation", "0.243"},
{"Annual Variance", "0.059"},
{"Information Ratio", "-23.216"},
{"Tracking Error", "0.243"},
{"Treynor Ratio", "-0.014"},
{"Total Fees", "$0.00"}
};
}
}

View File

@@ -1,102 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.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"}
};
}
}

View File

@@ -1,147 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.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"}
};
}
}

View File

@@ -1,231 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.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"}
};
}
}

View File

@@ -1,117 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.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"}
};
}
}

View File

@@ -1,123 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.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"}
};
}
}

View File

@@ -1,117 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.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"}
};
}
}

View File

@@ -1,143 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.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"}
};
}
}

View File

@@ -1,118 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.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"}
};
}
}

View File

@@ -1,118 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.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"}
};
}
}

View File

@@ -1,111 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.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"}
};
}
}

View File

@@ -1,111 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.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"}
};
}
}

View File

@@ -1,112 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.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"}
};
}
}

View File

@@ -1,103 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.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"}
};
}
}

View File

@@ -81,7 +81,8 @@ namespace QuantConnect.Algorithm.CSharp
algorithm.DateRules.MonthStart(benchmark.Symbol),
algorithm.TimeRules.AfterMarketOpen(benchmark.Symbol),
datetime => SelectPair(algorithm, datetime),
algorithm.UniverseSettings);
algorithm.UniverseSettings,
algorithm.SecurityInitializer);
}
/// <summary>

View File

@@ -75,48 +75,25 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "251"},
{"Total Trades", "167"},
{"Average Win", "0.01%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-37.465%"},
{"Drawdown", "0.300%"},
{"Expectancy", "-0.285"},
{"Net Profit", "-0.257%"},
{"Sharpe Ratio", "-40.568"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "66%"},
{"Win Rate", "34%"},
{"Profit-Loss Ratio", "1.08"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0.006"},
{"Compounding Annual Return", "-16.316%"},
{"Drawdown", "0.100%"},
{"Expectancy", "-0.121"},
{"Net Profit", "-0.081%"},
{"Sharpe Ratio", "-87.066"},
{"Loss Rate", "49%"},
{"Win Rate", "51%"},
{"Profit-Loss Ratio", "0.74"},
{"Alpha", "-0.116"},
{"Beta", "-0.092"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-40.568"},
{"Tracking Error", "0.006"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$660000.00"},
{"Lowest Capacity Asset", "DE30EUR 8I"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-23.868"},
{"Return Over Maximum Drawdown", "-170.818"},
{"Portfolio Turnover", "12.673"},
{"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", "6745cf313aa3ef780d052ca3ba933c6c"}
{"Information Ratio", "2.962"},
{"Tracking Error", "0.014"},
{"Treynor Ratio", "1.116"},
{"Total Fees", "$0.00"}
};
}
}

View File

@@ -74,14 +74,14 @@ namespace QuantConnect.Algorithm.CSharp
};
}
// sort the data by market capitalization and take the top 'NumberOfSymbolsFine'
// sort the data by P/E ratio and take the top 'NumberOfSymbolsFine'
public IEnumerable<Symbol> FineSelectionFunction(IEnumerable<FineFundamental> fine)
{
// sort descending by market capitalization
var sortedByMarketCap = fine.OrderByDescending(x => x.MarketCap);
// sort descending by P/E ratio
var sortedByPeRatio = fine.OrderByDescending(x => x.ValuationRatios.PERatio);
// take the top entries from our sorted collection
var topFine = sortedByMarketCap.Take(NumberOfSymbolsFine);
var topFine = sortedByPeRatio.Take(NumberOfSymbolsFine);
// we need to return only the symbol objects
return topFine.Select(x => x.Symbol);
@@ -162,47 +162,24 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "1.16%"},
{"Average Win", "1.39%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "32.505%"},
{"Compounding Annual Return", "40.038%"},
{"Drawdown", "1.400%"},
{"Expectancy", "0"},
{"Net Profit", "1.163%"},
{"Sharpe Ratio", "2.876"},
{"Probabilistic Sharpe Ratio", "64.984%"},
{"Net Profit", "1.394%"},
{"Sharpe Ratio", "3.081"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.237"},
{"Beta", "-0.188"},
{"Annual Standard Deviation", "0.089"},
{"Annual Variance", "0.008"},
{"Information Ratio", "2.409"},
{"Tracking Error", "0.148"},
{"Treynor Ratio", "-1.358"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$49000000.00"},
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
{"Fitness Score", "0.076"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "27.328"},
{"Return Over Maximum Drawdown", "24.002"},
{"Portfolio Turnover", "0.076"},
{"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", "159887a90516df8ba8e8d35b9c30b227"}
{"Alpha", "-0.033"},
{"Beta", "19.023"},
{"Annual Standard Deviation", "0.096"},
{"Annual Variance", "0.009"},
{"Information Ratio", "2.904"},
{"Tracking Error", "0.096"},
{"Treynor Ratio", "0.016"},
{"Total Fees", "$2.00"}
};
}
}

View File

@@ -1,191 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.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", "79228162514264337593543950335%"},
{"Drawdown", "0.500%"},
{"Expectancy", "1.393"},
{"Net Profit", "149.699%"},
{"Sharpe Ratio", "4.743312616499238E+27"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "83%"},
{"Win Rate", "17%"},
{"Profit-Loss Ratio", "13.36"},
{"Alpha", "7.922816251426434E+28"},
{"Beta", "304.581"},
{"Annual Standard Deviation", "16.703"},
{"Annual Variance", "278.995"},
{"Information Ratio", "4.75893717482582E+27"},
{"Tracking Error", "16.648"},
{"Treynor Ratio", "2.6012216611301735E+26"},
{"Total Fees", "$13.20"},
{"Estimated Strategy Capacity", "$3000000.00"},
{"Lowest Capacity Asset", "AOL VRKS95ENLBYE|AOL R735QTJ8XC9X"},
{"Fitness Score", "0.18"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0.18"},
{"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", "2a6319d0d474f976e653dd1ebc42caac"}
};
}
}

View File

@@ -116,48 +116,25 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "12"},
{"Average Win", "0.55%"},
{"Average Loss", "-0.26%"},
{"Compounding Annual Return", "16.717%"},
{"Drawdown", "1.700%"},
{"Expectancy", "0.850"},
{"Net Profit", "0.637%"},
{"Sharpe Ratio", "1.131"},
{"Probabilistic Sharpe Ratio", "50.538%"},
{"Loss Rate", "40%"},
{"Win Rate", "60%"},
{"Profit-Loss Ratio", "2.08"},
{"Alpha", "0.186"},
{"Beta", "0.465"},
{"Annual Standard Deviation", "0.123"},
{"Total Trades", "11"},
{"Average Win", "0.51%"},
{"Average Loss", "-0.33%"},
{"Compounding Annual Return", "-31.051%"},
{"Drawdown", "2.700%"},
{"Expectancy", "0.263"},
{"Net Profit", "-1.516%"},
{"Sharpe Ratio", "-2.526"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "1.53"},
{"Alpha", "-0.556"},
{"Beta", "14.058"},
{"Annual Standard Deviation", "0.124"},
{"Annual Variance", "0.015"},
{"Information Ratio", "1.908"},
{"Tracking Error", "0.126"},
{"Treynor Ratio", "0.299"},
{"Total Fees", "$27.94"},
{"Estimated Strategy Capacity", "$200000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.28"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "3"},
{"Return Over Maximum Drawdown", "9.559"},
{"Portfolio Turnover", "0.308"},
{"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", "de456413f89396bd6f920686219ed0a5"}
{"Information Ratio", "-2.666"},
{"Tracking Error", "0.124"},
{"Treynor Ratio", "-0.022"},
{"Total Fees", "$11.63"}
};
}
}

View File

@@ -102,7 +102,6 @@ namespace QuantConnect.Algorithm.CSharp
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
@@ -110,32 +109,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.388"},
{"Tracking Error", "0.096"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
{"Total Fees", "$0.00"}
};
}
}

View File

@@ -1,147 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Test algorithm that reproduces GH issues 3410 and 3409.
/// Coarse universe selection should start from the algorithm start date.
/// Data returned by history requests performed from the selection method should be up to date.
/// </summary>
public class CoarseSelectionTimeRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spy;
private decimal _historyCoarseSpyPrice;
/// <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(2014, 03, 25);
SetEndDate(2014, 04, 01);
_spy = AddEquity("SPY", Resolution.Daily).Symbol;
UniverseSettings.Resolution = Resolution.Daily;
AddUniverse(CoarseSelectionFunction);
}
public IEnumerable<Symbol> CoarseSelectionFunction(IEnumerable<CoarseFundamental> coarse)
{
var sortedByDollarVolume = coarse.OrderByDescending(x => x.DollarVolume);
var top = sortedByDollarVolume
.Where(fundamental => fundamental.Symbol != _spy) // ignore spy
.Take(1);
_historyCoarseSpyPrice = History(_spy, 1).First().Close;
return top.Select(x => x.Symbol);
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (data.Count != 2)
{
throw new Exception($"Unexpected data count: {data.Count}");
}
if (ActiveSecurities.Count != 2)
{
throw new Exception($"Unexpected ActiveSecurities count: {ActiveSecurities.Count}");
}
// the price obtained by the previous coarse selection should be the same as the current price
if (_historyCoarseSpyPrice != 0 && _historyCoarseSpyPrice != Securities[_spy].Price)
{
throw new Exception($"Unexpected SPY price: {_historyCoarseSpyPrice}");
}
_historyCoarseSpyPrice = 0;
if (!Portfolio.Invested)
{
SetHoldings(_spy, 1);
Debug("Purchased Stock");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "57.657%"},
{"Drawdown", "1.000%"},
{"Expectancy", "0"},
{"Net Profit", "1.003%"},
{"Sharpe Ratio", "5.024"},
{"Probabilistic Sharpe Ratio", "68.421%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.312"},
{"Beta", "0.27"},
{"Annual Standard Deviation", "0.087"},
{"Annual Variance", "0.008"},
{"Information Ratio", "-0.242"},
{"Tracking Error", "0.105"},
{"Treynor Ratio", "1.616"},
{"Total Fees", "$3.08"},
{"Estimated Strategy Capacity", "$720000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.141"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "10.385"},
{"Return Over Maximum Drawdown", "58.709"},
{"Portfolio Turnover", "0.143"},
{"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", "50145c3c1d58b09f38ec1b77cfe69eae"}
};
}
}

View File

@@ -73,32 +73,23 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "7"},
{"Average Win", "0.01%"},
{"Average Loss", "-0.40%"},
{"Compounding Annual Return", "1143.086%"},
{"Drawdown", "1.800%"},
{"Expectancy", "-0.319"},
{"Net Profit", "3.275%"},
{"Sharpe Ratio", "23.495"},
{"Probabilistic Sharpe Ratio", "80.494%"},
{"Average Loss", "-0.38%"},
{"Compounding Annual Return", "1192.794%"},
{"Drawdown", "1.700%"},
{"Expectancy", "-0.323"},
{"Net Profit", "3.326%"},
{"Sharpe Ratio", "6.635"},
{"Loss Rate", "33%"},
{"Win Rate", "67%"},
{"Profit-Loss Ratio", "0.02"},
{"Alpha", "4.366"},
{"Beta", "1.255"},
{"Annual Standard Deviation", "0.292"},
{"Annual Variance", "0.085"},
{"Information Ratio", "47.955"},
{"Tracking Error", "0.102"},
{"Treynor Ratio", "5.461"},
{"Total Fees", "$71.37"},
{"Estimated Strategy Capacity", "$3500000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Fitness Score", "0.501"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "148.07"},
{"Return Over Maximum Drawdown", "1487.238"},
{"Portfolio Turnover", "0.501"},
{"Profit-Loss Ratio", "0.01"},
{"Alpha", "0"},
{"Beta", "152.178"},
{"Annual Standard Deviation", "0.253"},
{"Annual Variance", "0.064"},
{"Information Ratio", "6.594"},
{"Tracking Error", "0.253"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$67.00"},
{"Total Insights Generated", "2"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -111,8 +102,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "5a171f804d47cd27f84aaef791da8594"}
{"Rolling Averaged Population Magnitude", "0%"}
};
}
}

View File

@@ -66,47 +66,37 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "7"},
{"Average Win", "1.01%"},
{"Average Loss", "-1.01%"},
{"Compounding Annual Return", "210.936%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0.339"},
{"Net Profit", "1.461%"},
{"Sharpe Ratio", "7.289"},
{"Probabilistic Sharpe Ratio", "65.077%"},
{"Average Win", "1.00%"},
{"Average Loss", "-1.03%"},
{"Compounding Annual Return", "190.425%"},
{"Drawdown", "2.300%"},
{"Expectancy", "0.314"},
{"Net Profit", "1.372%"},
{"Sharpe Ratio", "3.771"},
{"Loss Rate", "33%"},
{"Win Rate", "67%"},
{"Profit-Loss Ratio", "1.01"},
{"Alpha", "-0.349"},
{"Beta", "0.968"},
{"Annual Standard Deviation", "0.216"},
{"Annual Variance", "0.046"},
{"Information Ratio", "-47.59"},
{"Tracking Error", "0.009"},
{"Treynor Ratio", "1.623"},
{"Total Fees", "$24.07"},
{"Estimated Strategy Capacity", "$23000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.999"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "69.017"},
{"Portfolio Turnover", "1.242"},
{"Profit-Loss Ratio", "0.97"},
{"Alpha", "0.007"},
{"Beta", "62.953"},
{"Annual Standard Deviation", "0.186"},
{"Annual Variance", "0.035"},
{"Information Ratio", "3.713"},
{"Tracking Error", "0.186"},
{"Treynor Ratio", "0.011"},
{"Total Fees", "$22.77"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
{"Total Insights Analysis Completed", "99"},
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "d8d556bcf963ba50f85cea387c55922b"}
{"Estimated Monthly Alpha Value", "$158418.3850"},
{"Total Accumulated Estimated Alpha Value", "$25522.9620"},
{"Mean Population Estimated Insight Value", "$257.8077"},
{"Mean Population Direction", "54.5455%"},
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"}
};
}
}

View File

@@ -1,125 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Test algorithm using <see cref="ConfidenceWeightedPortfolioConstructionModel"/> and <see cref="ConstantAlphaModel"/>
/// generating a constant <see cref="Insight"/> with a 0.25 confidence
/// </summary>
public class ConfidenceWeightedFrameworkAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
// Set requested data resolution
UniverseSettings.Resolution = Resolution.Minute;
// Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
// Commented so regression algorithm is more sensitive
//Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;
SetStartDate(2013, 10, 07); //Set Start Date
SetEndDate(2013, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
// set algorithm framework models
SetUniverseSelection(new ManualUniverseSelectionModel(QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA)));
SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromMinutes(20), 0.025, 0.25));
SetPortfolioConstruction(new ConfidenceWeightedPortfolioConstructionModel());
SetExecution(new ImmediateExecutionModel());
}
public override void OnEndOfAlgorithm()
{
if (// holdings value should be 0.25 - to avoid price fluctuation issue we compare with 0.28 and 0.23
Portfolio.TotalHoldingsValue > Portfolio.TotalPortfolioValue * 0.28m
||
Portfolio.TotalHoldingsValue < Portfolio.TotalPortfolioValue * 0.23m)
{
throw new Exception($"Unexpected Total Holdings Value: {Portfolio.TotalHoldingsValue}");
}
}
/// <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", "17"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "37.229%"},
{"Drawdown", "0.600%"},
{"Expectancy", "-1"},
{"Net Profit", "0.405%"},
{"Sharpe Ratio", "5.424"},
{"Probabilistic Sharpe Ratio", "66.818%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.191"},
{"Beta", "0.247"},
{"Annual Standard Deviation", "0.055"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-10.052"},
{"Tracking Error", "0.168"},
{"Treynor Ratio", "1.207"},
{"Total Fees", "$17.00"},
{"Estimated Strategy Capacity", "$45000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.067"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "65.855"},
{"Portfolio Turnover", "0.067"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
{"Total Insights Analysis Completed", "99"},
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "8a8c913e5ad4ea956a345c84430649c2"}
};
}
}

View File

@@ -1,191 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm reproducing data type bugs in the Consolidate API. Related to GH 4205.
/// </summary>
public class ConsolidateRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private List<int> _consolidationCount;
private int _customDataConsolidator;
private Symbol _symbol;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 09);
var SP500 = QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME);
_symbol = FutureChainProvider.GetFutureContractList(SP500, StartDate).First();
AddFutureContract(_symbol);
_consolidationCount = new List<int> { 0, 0, 0, 0, 0, 0, 0, 0 };
var sma = new SimpleMovingAverage(10);
Consolidate<QuoteBar>(_symbol, time => new CalendarInfo(time.RoundDown(TimeSpan.FromDays(1)), TimeSpan.FromDays(1)),
bar => UpdateQuoteBar(sma, bar, 0));
var sma2 = new SimpleMovingAverage(10);
Consolidate<QuoteBar>(_symbol, TimeSpan.FromDays(1), bar => UpdateQuoteBar(sma2, bar, 1));
var sma3 = new SimpleMovingAverage(10);
Consolidate(_symbol, Resolution.Daily, TickType.Quote, (Action<QuoteBar>)(bar => UpdateQuoteBar(sma3, bar, 2)));
var sma4 = new SimpleMovingAverage(10);
Consolidate(_symbol, TimeSpan.FromDays(1), bar => UpdateTradeBar(sma4, bar, 3));
var sma5 = new SimpleMovingAverage(10);
Consolidate<TradeBar>(_symbol, TimeSpan.FromDays(1), bar => UpdateTradeBar(sma5, bar, 4));
// custom data
var sma6 = new SimpleMovingAverage(10);
var symbol = AddData<CustomDataRegressionAlgorithm.Bitcoin>("BTC", Resolution.Minute).Symbol;
Consolidate<TradeBar>(symbol, TimeSpan.FromDays(1), bar => _customDataConsolidator++);
try
{
Consolidate<QuoteBar>(symbol, TimeSpan.FromDays(1), bar => { UpdateQuoteBar(sma6, bar, -1); });
throw new Exception($"Expected {nameof(ArgumentException)} to be thrown");
}
catch (ArgumentException)
{
// will try to use BaseDataConsolidator for which input is TradeBars not QuoteBars
}
// Test using abstract T types, through defining a 'BaseData' handler
var sma7 = new SimpleMovingAverage(10);
Consolidate(_symbol, Resolution.Daily, null, (Action<BaseData>)(bar => UpdateBar(sma7, bar, 5)));
var sma8 = new SimpleMovingAverage(10);
Consolidate(_symbol, TimeSpan.FromDays(1), null, (Action<BaseData>)(bar => UpdateBar(sma8, bar, 6)));
var sma9 = new SimpleMovingAverage(10);
Consolidate(_symbol, TimeSpan.FromDays(1), (Action<BaseData>)(bar => UpdateBar(sma9, bar, 7)));
}
private void UpdateBar(SimpleMovingAverage sma, BaseData tradeBar, int position)
{
if (!(tradeBar is TradeBar))
{
throw new Exception("Expected a TradeBar");
}
_consolidationCount[position]++;
sma.Update(tradeBar.EndTime, tradeBar.Value);
}
private void UpdateTradeBar(SimpleMovingAverage sma, TradeBar tradeBar, int position)
{
_consolidationCount[position]++;
sma.Update(tradeBar.EndTime, tradeBar.High);
}
private void UpdateQuoteBar(SimpleMovingAverage sma, QuoteBar quoteBar, int position)
{
_consolidationCount[position]++;
sma.Update(quoteBar.EndTime, quoteBar.High);
}
public override void OnEndOfAlgorithm()
{
if (_consolidationCount.Any(i => i != 3) || _customDataConsolidator == 0)
{
throw new Exception("Unexpected consolidation count");
}
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
SetHoldings(_symbol, 0.5);
}
}
/// <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", "-99.999%"},
{"Drawdown", "16.100%"},
{"Expectancy", "0"},
{"Net Profit", "-6.366%"},
{"Sharpe Ratio", "1.194"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "5.56"},
{"Beta", "-71.105"},
{"Annual Standard Deviation", "0.434"},
{"Annual Variance", "0.188"},
{"Information Ratio", "1.016"},
{"Tracking Error", "0.44"},
{"Treynor Ratio", "-0.007"},
{"Total Fees", "$20.35"},
{"Estimated Strategy Capacity", "$19000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.138"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-1.727"},
{"Return Over Maximum Drawdown", "-12.061"},
{"Portfolio Turnover", "4.916"},
{"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", "7c841ca58a4385f42236838e5bf0c382"}
};
}
}

View File

@@ -13,12 +13,14 @@
* limitations under the License.
*/
using QuantConnect.Data.UniverseSelection;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Demonstration of how to estimate constituents of QC500 index based on the company fundamentals
/// The algorithm creates a default tradable and liquid universe containing 500 US equities
/// which are chosen at the first trading day of each month.
/// The algorithm creates a default tradable and liquid universe containing 500 US equities
/// which are chosen at the first trading day of each month.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="universes" />

View File

@@ -1,161 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using QuantConnect.Data.UniverseSelection;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Algorithm used to generate daily data on disk for the different <see cref="ConstituentsUniverse"/>.
/// How to use me? search for 'CHANGE ME'
/// 1- change the universe name
/// 2- change the desired start and end date to generate
/// 3- define the universe selection to use
/// Data will be generated in:
/// 'Globals.DataFolder\SecurityType\Market\universes\Resolution\{UniverseName}\{dates:yyyyMMdd}.csv'
/// </summary>
/// <remarks>The data produced by this algorithm is the one used by the
/// <see cref="ConstituentsUniverseRegressionAlgorithm"/></remarks>
/// <remarks>In the cloud, users can implement their own <see cref="ConstituentsUniverseData"/>
/// (not using <see cref="SubscriptionTransportMedium.LocalFile"/>) that can fetch the files
/// generated from this algorithm</remarks>
public class ConstituentsUniverseDataGeneratorAlgorithm : QCAlgorithm
{
private readonly HashSet<Symbol> _currentSelection = new HashSet<Symbol>();
private DateTime _currentDateTime = DateTime.MinValue;
private readonly string _rootDataPath = Globals.DataFolder;
private string _dataPath;
private bool _skippedFirst;
// Configuration properties: Only these are supported for now (Don't change me)
private readonly SecurityType _securityType = SecurityType.Equity;
private readonly string _market = Market.USA;
private readonly Resolution _resolution = Resolution.Daily;
// CHANGE ME
private readonly string _universeName = "qctest";
public override void Initialize()
{
// CHANGE ME
SetStartDate(2013, 10, 07); // Set Start Date
SetEndDate(2013, 10, 11); // Set End Date
SetCash(100000); // Set Strategy Cash
UniverseSettings.Resolution = Resolution.Daily;
_dataPath = Path.Combine(_rootDataPath,
_securityType.SecurityTypeToLower(),
_market,
"universes",
_resolution.ResolutionToLower(),
_universeName);
Directory.CreateDirectory(_dataPath);
// CHANGE ME
int step = 0;
AddUniverse(coarse =>
{
step++;
switch (step)
{
case 1:
case 2:
return new[]
{
QuantConnect.Symbol.Create("QQQ", SecurityType.Equity, Market.USA),
QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA)
};
case 3:
return Enumerable.Empty<Symbol>();
case 4:
case 5:
return new[]
{
QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA),
QuantConnect.Symbol.Create("FB", SecurityType.Equity, Market.USA)
};
default:
throw new Exception("Unexpected step count");
}
});
Schedule.On(DateRules.EveryDay(), TimeRules.At(23, 0), SaveConstituentsUniverseDataToDisk);
}
private void SaveConstituentsUniverseDataToDisk()
{
if (_skippedFirst && Time > _currentDateTime)
{
if (Time.DayOfWeek == DayOfWeek.Sunday
|| Time.DayOfWeek == DayOfWeek.Monday)
{
// we generate files from Tue to Saturday using current selected securities
return;
}
// files are for Mon to Friday
_currentDateTime = Time.Date.AddDays(-1);
var path = Path.Combine(_dataPath, $"{_currentDateTime:yyyyMMdd}.csv");
File.Delete(path);
if (_currentSelection.Count == 0)
{
using (StreamWriter constituentsUniverseFile = new StreamWriter(path, append:true))
{
constituentsUniverseFile.WriteLine(
$"{QuantConnect.Symbol.None.Value},{QuantConnect.Symbol.None.ID.ToString()}");
}
}
else
{
foreach (var symbol in _currentSelection)
{
using (StreamWriter constituentsUniverseFile = new StreamWriter(path, append: true))
{
constituentsUniverseFile.WriteLine($"{symbol.Value},{symbol.ID.ToString()}");
}
}
}
}
_skippedFirst = true;
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var added in changes.AddedSecurities)
{
Log($"AddedSecurities {added}");
if (_currentSelection.Contains(added.Symbol))
{
throw new Exception("Added symbol already selected");
}
_currentSelection.Add(added.Symbol);
}
foreach (var removed in changes.RemovedSecurities)
{
Log($"RemovedSecurities {removed}");
if (!_currentSelection.Contains(removed.Symbol))
{
throw new Exception("Removing symbol already deselected");
}
_currentSelection.Remove(removed.Symbol);
}
}
}
}

View File

@@ -1,217 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Test algorithm using a <see cref="ConstituentsUniverse"/> with test data
/// </summary>
public class ConstituentsUniverseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private readonly Symbol _appl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
private readonly Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
private readonly Symbol _qqq = QuantConnect.Symbol.Create("QQQ", SecurityType.Equity, Market.USA);
private readonly Symbol _fb = QuantConnect.Symbol.Create("FB", SecurityType.Equity, Market.USA);
private int _step;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 07); //Set Start Date
SetEndDate(2013, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
UniverseSettings.Resolution = Resolution.Daily;
var customUniverseSymbol = new Symbol(SecurityIdentifier.GenerateConstituentIdentifier(
"constituents-universe-qctest",
SecurityType.Equity,
Market.USA),
"constituents-universe-qctest");
AddUniverse(new ConstituentsUniverse(customUniverseSymbol, UniverseSettings));
}
/// <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)
{
_step++;
if (_step == 1)
{
if (!data.ContainsKey(_qqq)
|| !data.ContainsKey(_appl))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 2)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
// AAPL will be deselected by the ConstituentsUniverse
// but it shouldn't be removed since we hold it
SetHoldings(_appl, 0.5);
}
else if (_step == 2)
{
if (!data.ContainsKey(_appl))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 1)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
// AAPL should now be released
// note: takes one extra loop because the order is executed on market open
Liquidate();
}
else if (_step == 3)
{
if (!data.ContainsKey(_fb)
|| !data.ContainsKey(_spy)
|| !data.ContainsKey(_appl))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 3)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
}
else if (_step == 4)
{
if (!data.ContainsKey(_fb)
|| !data.ContainsKey(_spy))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 2)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
}
else if (_step == 5)
{
if (!data.ContainsKey(_fb)
|| !data.ContainsKey(_spy))
{
throw new Exception($"Unexpected symbols found, step: {_step}");
}
if (data.Count != 2)
{
throw new Exception($"Unexpected data count, step: {_step}");
}
}
}
public override void OnEndOfAlgorithm()
{
if (_step != 5)
{
throw new Exception($"Unexpected step count: {_step}");
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var added in changes.AddedSecurities)
{
Log($"AddedSecurities {added}");
}
foreach (var removed in changes.RemovedSecurities)
{
Log($"RemovedSecurities {removed} {_step}");
// we are currently notifying the removal of AAPl twice,
// when deselected and when finally removed (since it stayed pending)
if (removed.Symbol == _appl && _step != 1 && _step != 2
|| removed.Symbol == _qqq && _step != 1)
{
throw new Exception($"Unexpected removal step count: {_step}");
}
}
}
/// <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.54%"},
{"Compounding Annual Return", "-32.671%"},
{"Drawdown", "0.900%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.540%"},
{"Sharpe Ratio", "-3.168"},
{"Probabilistic Sharpe Ratio", "23.963%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.456"},
{"Beta", "0.157"},
{"Annual Standard Deviation", "0.075"},
{"Annual Variance", "0.006"},
{"Information Ratio", "-9.176"},
{"Tracking Error", "0.178"},
{"Treynor Ratio", "-1.514"},
{"Total Fees", "$32.32"},
{"Estimated Strategy Capacity", "$95000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.1"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-36.199"},
{"Portfolio Turnover", "0.2"},
{"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", "3b9c93151bf191a82529e6e915961356"}
};
}
}

View File

@@ -128,46 +128,36 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "85"},
{"Average Win", "4.85%"},
{"Average Loss", "-4.22%"},
{"Compounding Annual Return", "-3.124%"},
{"Drawdown", "53.000%"},
{"Average Loss", "-4.21%"},
{"Compounding Annual Return", "-3.105%"},
{"Drawdown", "52.900%"},
{"Expectancy", "-0.053"},
{"Net Profit", "-29.486%"},
{"Sharpe Ratio", "-0.078"},
{"Probabilistic Sharpe Ratio", "0.004%"},
{"Net Profit", "-29.335%"},
{"Sharpe Ratio", "-0.084"},
{"Loss Rate", "56%"},
{"Win Rate", "44%"},
{"Profit-Loss Ratio", "1.15"},
{"Alpha", "-0.013"},
{"Beta", "0.007"},
{"Annual Standard Deviation", "0.163"},
{"Annual Variance", "0.027"},
{"Information Ratio", "-0.393"},
{"Tracking Error", "0.238"},
{"Treynor Ratio", "-1.72"},
{"Total Fees", "$796.82"},
{"Estimated Strategy Capacity", "$1200000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.024"},
{"Kelly Criterion Estimate", "-0.9"},
{"Kelly Criterion Probability Value", "0.532"},
{"Sortino Ratio", "-0.228"},
{"Return Over Maximum Drawdown", "-0.058"},
{"Portfolio Turnover", "0.05"},
{"Alpha", "0.046"},
{"Beta", "-3.04"},
{"Annual Standard Deviation", "0.181"},
{"Annual Variance", "0.033"},
{"Information Ratio", "-0.194"},
{"Tracking Error", "0.181"},
{"Treynor Ratio", "0.005"},
{"Total Fees", "$755.20"},
{"Total Insights Generated", "85"},
{"Total Insights Closed", "85"},
{"Total Insights Analysis Completed", "85"},
{"Long Insight Count", "42"},
{"Short Insight Count", "43"},
{"Long/Short Ratio", "97.67%"},
{"Estimated Monthly Alpha Value", "$-719932.6"},
{"Total Accumulated Estimated Alpha Value", "$-96427970"},
{"Mean Population Estimated Insight Value", "$-1134447"},
{"Mean Population Direction", "51.7647%"},
{"Estimated Monthly Alpha Value", "$-607698.1"},
{"Total Accumulated Estimated Alpha Value", "$-81395260"},
{"Mean Population Estimated Insight Value", "$-957591.3"},
{"Mean Population Direction", "50.5882%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "48.2217%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "177fb7f308a252864365442a30dd9eeb"}
{"Rolling Averaged Population Direction", "46.5677%"},
{"Rolling Averaged Population Magnitude", "0%"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -13,10 +13,7 @@
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
@@ -25,7 +22,7 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="benchmarks" />
public class CustomBenchmarkAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
public class CustomBenchmarkAlgorithm : QCAlgorithm
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
@@ -38,11 +35,7 @@ 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");
SetBenchmark("SPY");
}
/// <summary>
@@ -56,71 +49,6 @@ namespace QuantConnect.Algorithm.CSharp
SetHoldings("SPY", 1);
Debug("Purchased Stock");
}
Symbol symbol;
if (SymbolCache.TryGetSymbol("AAPL", out symbol))
{
throw new Exception("Benchmark Symbol is not expected to be added to the Symbol cache");
}
}
/// <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", "272.157%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Net Profit", "1.694%"},
{"Sharpe Ratio", "8.897"},
{"Probabilistic Sharpe Ratio", "67.609%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.144"},
{"Beta", "0.842"},
{"Annual Standard Deviation", "0.222"},
{"Annual Variance", "0.049"},
{"Information Ratio", "5.987"},
{"Tracking Error", "0.165"},
{"Treynor Ratio", "2.347"},
{"Total Fees", "$3.45"},
{"Estimated Strategy Capacity", "$310000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.246"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "9.761"},
{"Return Over Maximum Drawdown", "107.509"},
{"Portfolio Turnover", "0.249"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "e10039d74166b161f3ea2851a5e85843"}
};
}
}
}

View File

@@ -1,123 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Reproduces Lean GH issue 3572: benchmark _would_ use custom data versus equity
/// when both were present
/// </summary>
public class CustomBenchmarkRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
/// <summary>
/// Algorithm initialization
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);
AddEquity("AAPL", Resolution.Hour);
AddData<DummyCustomData>("AAPL");
// set benchmark will use equity AAPL as benchmark
SetBenchmark("AAPL");
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
SetHoldings("AAPL", 1);
Debug("Purchased Stock");
}
}
private class DummyCustomData : BaseData
{
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
return new SubscriptionDataSource("NonExistingFile", SubscriptionTransportMedium.LocalFile);
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "34.768%"},
{"Drawdown", "2.300%"},
{"Expectancy", "0"},
{"Net Profit", "0.382%"},
{"Sharpe Ratio", "5.488"},
{"Probabilistic Sharpe Ratio", "60.047%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.001"},
{"Beta", "0.997"},
{"Annual Standard Deviation", "0.179"},
{"Annual Variance", "0.032"},
{"Information Ratio", "-7.724"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0.986"},
{"Total Fees", "$32.11"},
{"Estimated Strategy Capacity", "$66000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.029"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-2.336"},
{"Return Over Maximum Drawdown", "-8.991"},
{"Portfolio Turnover", "0.251"},
{"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", "9ce7252112d0ad7be0704297f7d48a88"}
};
}
}

View File

@@ -61,7 +61,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <param name="message">Message object</param>
public void Handle(BrokerageMessageEvent message)
{
var toLog = $"{_algo.Time.ToStringInvariant("o")} Event: {message.Message}";
var toLog = _algo.Time.ToString("o") + " Event: " + message.Message;
_algo.Debug(toLog);
_algo.Log(toLog);
}

View File

@@ -1,144 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Interfaces;
using QuantConnect.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)
{
// if portfolio doesn't have enough buying power:
// parameters.Insufficient()
// this model never allows a lack of funds get in the way of buying securities
return parameters.Sufficient();
}
}
/// <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", "4775.196%"},
{"Drawdown", "21.600%"},
{"Expectancy", "0"},
{"Net Profit", "38.619%"},
{"Sharpe Ratio", "33.779"},
{"Probabilistic Sharpe Ratio", "77.029%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "32.812"},
{"Beta", "8.756"},
{"Annual Standard Deviation", "1.11"},
{"Annual Variance", "1.231"},
{"Information Ratio", "37.501"},
{"Tracking Error", "0.985"},
{"Treynor Ratio", "4.281"},
{"Total Fees", "$30.00"},
{"Estimated Strategy Capacity", "$22000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.395"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "98.148"},
{"Return Over Maximum Drawdown", "384.626"},
{"Portfolio Turnover", "0.395"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"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", "3df007afa8125770e8f1a49263af90a2"}
};
}
}

View File

@@ -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(Symbol symbol)
public override void OnEndOfDay()
{
//Log the end of day prices:
Plot("Trade Plot", "Price", _lastPrice);

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -58,13 +58,11 @@ namespace QuantConnect.Algorithm.CSharp
//Weather used as a tradable asset, like stocks, futures etc.
if (data.Close != 0)
{
// 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);
Order("BTC", (Portfolio.MarginRemaining / Math.Abs(data.Close + 1)));
}
Console.WriteLine("Buying BTC 'Shares': BTC: " + data.Close);
}
Console.WriteLine("Time: " + Time.ToStringInvariant("T") + " " + Time.ToStringInvariant("T") + data.Close.ToStringInvariant());
Console.WriteLine("Time: " + Time.ToLongDateString() + " " + Time.ToLongTimeString() + data.Close.ToString());
}
/// <summary>
@@ -119,7 +117,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.quantconnect.com/api/v2/proxy/quandl/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc&api_key=WyAazVXnq7ATy_fefTqm", SubscriptionTransportMedium.RemoteFile);
return new SubscriptionDataSource("https://www.quandl.com/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc", SubscriptionTransportMedium.RemoteFile);
}
/// <summary>
@@ -156,7 +154,6 @@ 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);
@@ -172,4 +169,4 @@ namespace QuantConnect.Algorithm.CSharp
}
}
}
}
}

View File

@@ -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 override void OnData(Slice data)
public 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"].Time)
if (_today.Date == data["NIFTY"].EndTime)
{
_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(Symbol symbol)
public override void OnEndOfDay()
{
Plot("Nifty Closing Price", _today.NiftyPrice);
}
@@ -181,7 +181,6 @@ 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);
@@ -248,7 +247,6 @@ 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;

View File

@@ -1,263 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.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.142"},
{"Annual Standard Deviation", "0.84"},
{"Annual Variance", "0.706"},
{"Information Ratio", "1.925"},
{"Tracking Error", "0.846"},
{"Treynor Ratio", "12.334"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTC.Bitcoin 2S"},
{"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;
}
}
}
}

View File

@@ -60,8 +60,7 @@ namespace QuantConnect.Algorithm.CSharp
//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));
Order("BTC", Portfolio.MarginRemaining / Math.Abs(data.Close + 1));
}
}
}
@@ -84,45 +83,22 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "157.497%"},
{"Compounding Annual Return", "155.365%"},
{"Drawdown", "84.800%"},
{"Expectancy", "0"},
{"Net Profit", "5319.007%"},
{"Sharpe Ratio", "2.086"},
{"Probabilistic Sharpe Ratio", "69.456%"},
{"Net Profit", "5123.170%"},
{"Sharpe Ratio", "1.2"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.736"},
{"Beta", "0.142"},
{"Alpha", "-0.008"},
{"Beta", "73.725"},
{"Annual Standard Deviation", "0.84"},
{"Annual Variance", "0.706"},
{"Information Ratio", "1.925"},
{"Tracking Error", "0.846"},
{"Treynor Ratio", "12.333"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTC.Bitcoin 2S"},
{"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", "50faa37f15732bf5c24ad1eeaa335bc7"}
{"Information Ratio", "1.183"},
{"Tracking Error", "0.84"},
{"Treynor Ratio", "0.014"},
{"Total Fees", "$0.00"}
};
/// <summary>
@@ -214,7 +190,6 @@ 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);

View File

@@ -128,7 +128,7 @@ namespace QuantConnect.Algorithm.CSharp
{
Time = DateTime.ParseExact(csv[0], "yyyyMMdd", null),
Symbol = Symbol.Create(csv[1], SecurityType.Equity, Market.USA),
TopGainersRank = Parse.Int(csv[2])
TopGainersRank = int.Parse(csv[2])
};
}

View File

@@ -1,219 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm demonstrating use of map files with custom data
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="custom data" />
/// <meta name="tag" content="regression test" />
/// <meta name="tag" content="rename event" />
/// <meta name="tag" content="map" />
/// <meta name="tag" content="mapping" />
/// <meta name="tag" content="map files" />
public class CustomDataUsingMapFileRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _symbol;
private bool _initialMapping;
private bool _executionMapping;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 06, 27);
SetEndDate(2013, 07, 02);
var foxa = QuantConnect.Symbol.Create("FOXA", SecurityType.Equity, Market.USA);
_symbol = AddData<CustomDataUsingMapping>(foxa).Symbol;
foreach (var config in SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_symbol))
{
if (config.Resolution != Resolution.Minute)
{
throw new Exception("Expected resolution to be set to Minute");
}
}
}
/// <summary>
/// Checks to see if the stock has been renamed, and places an order once the symbol has changed
/// </summary>
public override void OnData(Slice slice)
{
if (slice.SymbolChangedEvents.ContainsKey(_symbol))
{
var mappingEvent = slice.SymbolChangedEvents.Single(x => x.Key.SecurityType == SecurityType.Base).Value;
Log($"{Time} - Ticker changed from: {mappingEvent.OldSymbol} to {mappingEvent.NewSymbol}");
if (Time.Date == new DateTime(2013, 06, 27))
{
// we should Not receive the initial mapping event
if (mappingEvent.NewSymbol != "NWSA"
|| mappingEvent.OldSymbol != "FOXA")
{
throw new Exception($"Unexpected mapping event {mappingEvent}");
}
_initialMapping = true;
}
else if (Time.Date == new DateTime(2013, 06, 29))
{
if (mappingEvent.NewSymbol != "FOXA"
|| mappingEvent.OldSymbol != "NWSA")
{
throw new Exception($"Unexpected mapping event {mappingEvent}");
}
_executionMapping = true;
SetHoldings(_symbol, 1);
}
}
}
/// <summary>
/// Final step of the algorithm
/// </summary>
public override void OnEndOfAlgorithm()
{
if (_initialMapping)
{
throw new Exception("The ticker generated the initial rename event");
}
if (!_executionMapping)
{
throw new Exception("The ticker did not rename throughout the course of its life even though it should have");
}
}
/// <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", "-99.907%"},
{"Drawdown", "11.000%"},
{"Expectancy", "0"},
{"Net Profit", "-10.343%"},
{"Sharpe Ratio", "-1.554"},
{"Probabilistic Sharpe Ratio", "0.001%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.91"},
{"Beta", "-5.602"},
{"Annual Standard Deviation", "0.643"},
{"Annual Variance", "0.413"},
{"Information Ratio", "-1.378"},
{"Tracking Error", "0.736"},
{"Treynor Ratio", "0.178"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "NWSA.CustomDataUsingMapping T3MO1488O0H0"},
{"Fitness Score", "0.127"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-9.481"},
{"Portfolio Turnover", "0.249"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "d4cf2839e74df7fa436e30f44be4cb57"}
};
/// <summary>
/// Test example custom data showing how to enable the use of mapping.
/// Implemented as a wrapper of existing NWSA->FOXA equity
/// </summary>
private class CustomDataUsingMapping : TradeBar
{
/// <summary>
/// Indicates if there is support for mapping
/// </summary>
/// <returns>True indicates mapping should be done</returns>
public override bool RequiresMapping()
{
return true;
}
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
return base.GetSource(new SubscriptionDataConfig(config,
typeof(CustomDataUsingMapping),
// create a new symbol as equity so we find the existing data files
Symbol.Create(config.MappedSymbol, SecurityType.Equity, config.Market)),
date,
isLiveMode);
}
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
return ParseEquity(config, line, date);
}
/// <summary>
/// Gets the default resolution for this data and security type
/// </summary>
/// <remarks>This is a method and not a property so that python
/// custom data types can override it</remarks>
public override Resolution DefaultResolution()
{
return Resolution.Minute;
}
/// <summary>
/// Gets the supported resolution for this data and security type
/// </summary>
/// <remarks>This is a method and not a property so that python
/// custom data types can override it</remarks>
public override List<Resolution> SupportedResolutions()
{
return new List<Resolution> { Resolution.Minute };
}
}
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -26,12 +26,11 @@ using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Demonstration of using custom fee, slippage, fill, and buying power models for modelling transactions in backtesting.
/// Demonstration of using custom fee, slippage and fill 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" />
@@ -51,7 +50,6 @@ 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)
@@ -62,13 +60,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
}
}
@@ -111,7 +109,7 @@ namespace QuantConnect.Algorithm.CSharp
fill.Status = OrderStatus.PartiallyFilled;
}
_algorithm.Log($"CustomFillModel: {fill}");
_algorithm.Log("CustomFillModel: " + fill);
return fill;
}
@@ -133,7 +131,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"));
}
}
@@ -152,31 +150,11 @@ 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>
@@ -195,45 +173,22 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "62"},
{"Average Win", "0.11%"},
{"Average Loss", "-0.06%"},
{"Compounding Annual Return", "-7.236%"},
{"Compounding Annual Return", "-7.582%"},
{"Drawdown", "2.400%"},
{"Expectancy", "-0.187"},
{"Net Profit", "-0.629%"},
{"Sharpe Ratio", "-1.475"},
{"Probabilistic Sharpe Ratio", "23.597%"},
{"Expectancy", "-0.193"},
{"Net Profit", "-0.660%"},
{"Sharpe Ratio", "-1.563"},
{"Loss Rate", "70%"},
{"Win Rate", "30%"},
{"Profit-Loss Ratio", "1.73"},
{"Alpha", "-0.136"},
{"Beta", "0.126"},
{"Annual Standard Deviation", "0.047"},
{"Profit-Loss Ratio", "1.71"},
{"Alpha", "-0.174"},
{"Beta", "5.695"},
{"Annual Standard Deviation", "0.046"},
{"Annual Variance", "0.002"},
{"Information Ratio", "-5.094"},
{"Tracking Error", "0.118"},
{"Treynor Ratio", "-0.547"},
{"Total Fees", "$62.25"},
{"Estimated Strategy Capacity", "$52000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.16"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-2.59"},
{"Return Over Maximum Drawdown", "-3.337"},
{"Portfolio Turnover", "2.562"},
{"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", "1118fb362bfe261323a6b496d50bddde"}
{"Information Ratio", "-1.959"},
{"Tracking Error", "0.046"},
{"Treynor Ratio", "-0.013"},
{"Total Fees", "$62.24"}
};
}
}

View File

@@ -1,108 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Orders.Fills;
using QuantConnect.Securities;
using System;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Basic template algorithm that implements a fill model with partial fills
/// </summary>
/// <meta name="tag" content="transaction fees and slippage" />
/// <meta name="tag" content="custom fill models" />
public class CustomPartialFillModelAlgorithm : QCAlgorithm
{
private Symbol _spy;
private SecurityHolding _holdings;
public override void Initialize()
{
SetStartDate(2019, 1, 1);
SetEndDate(2019, 3, 1);
var equity = AddEquity("SPY", Resolution.Hour);
_spy = equity.Symbol;
_holdings = equity.Holdings;
// Set the fill model
equity.SetFillModel(new CustomPartialFillModel(this));
}
public override void OnData(Slice data)
{
var openOrders = Transactions.GetOpenOrders(_spy);
if (openOrders.Count != 0) return;
if (Time.Day > 10 && _holdings.Quantity <= 0)
{
MarketOrder(_spy, 100, true);
}
else if (Time.Day > 20 && _holdings.Quantity >= 0)
{
MarketOrder(_spy, -100, true);
}
}
/// <summary>
/// Implements a custom fill model that inherit from FillModel. Override the MarketFill method to simulate partially fill orders
/// </summary>
internal class CustomPartialFillModel : FillModel
{
private readonly QCAlgorithm _algorithm;
private readonly Dictionary<int, decimal> _absoluteRemainingByOrderId;
public CustomPartialFillModel(QCAlgorithm algorithm)
: base()
{
_algorithm = algorithm;
_absoluteRemainingByOrderId = new Dictionary<int, decimal>();
}
public override OrderEvent MarketFill(Security asset, MarketOrder order)
{
decimal absoluteRemaining;
if (!_absoluteRemainingByOrderId.TryGetValue(order.Id, out absoluteRemaining))
{
absoluteRemaining = order.AbsoluteQuantity;
}
// Create the object
var fill = base.MarketFill(asset, order);
// Set this fill amount
fill.FillQuantity = Math.Sign(order.Quantity) * 10;
if (absoluteRemaining == fill.FillQuantity)
{
fill.Status = OrderStatus.Filled;
_absoluteRemainingByOrderId.Remove(order.Id);
}
else
{
fill.Status = OrderStatus.PartiallyFilled;
_absoluteRemainingByOrderId[order.Id] = absoluteRemaining - fill.FillQuantity;
var price = fill.FillPrice;
_algorithm.Debug($"{_algorithm.Time} - Partial Fill - Remaining {absoluteRemaining} Price - {price}");
}
return fill;
}
}
}
}

View File

@@ -1,130 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Test algorithm that verifies that securities added through
/// <see cref="QCAlgorithm.AddEquity"/> API and universe selection
/// both start sending data at the same time
/// </summary>
public class CustomUniverseSelectionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);
AddEquity("AAPL", Resolution.Daily);
UniverseSettings.Resolution = Resolution.Daily;
AddUniverse(SecurityType.Equity,
"SecondUniverse",
Resolution.Daily,
Market.USA,
UniverseSettings,
time => new[] { "SPY" });
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (data.Count != 2)
{
throw new Exception($"Unexpected data count: {data.Count}");
}
if (ActiveSecurities.Count != 2)
{
throw new Exception($"Unexpected ActiveSecurities count: {ActiveSecurities.Count}");
}
if (!Portfolio.Invested)
{
SetHoldings(Securities.Keys.First(symbol => symbol.Value == "SPY"), 1);
Debug("Purchased Stock");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "240.939%"},
{"Drawdown", "1.200%"},
{"Expectancy", "0"},
{"Net Profit", "1.694%"},
{"Sharpe Ratio", "6.988"},
{"Probabilistic Sharpe Ratio", "68.188%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.172"},
{"Beta", "0.14"},
{"Annual Standard Deviation", "0.196"},
{"Annual Variance", "0.038"},
{"Information Ratio", "-0.118"},
{"Tracking Error", "0.256"},
{"Treynor Ratio", "9.783"},
{"Total Fees", "$3.45"},
{"Estimated Strategy Capacity", "$970000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.201"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "204.701"},
{"Portfolio Turnover", "0.201"},
{"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", "33d01821923c397f999cfb2e5b5928ad"}
};
}
}

View File

@@ -1,220 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm with a custom universe and benchmark, both using the same security.
/// </summary>
public class CustomUniverseWithBenchmarkRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const int ExpectedLeverage = 2;
private Symbol _spy;
private decimal _previousBenchmarkValue;
private DateTime _previousTime;
private decimal _previousSecurityValue;
private bool _universeSelected;
private bool _onDataWasCalled;
private int _benchmarkPriceDidNotChange;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 4);
SetEndDate(2013, 10, 11);
// Hour resolution
_spy = AddEquity("SPY", Resolution.Hour).Symbol;
// Minute resolution
AddUniverse("my-universe", x =>
{
if(x.Day % 2 == 0)
{
_universeSelected = true;
return new List<string> {"SPY"};
}
_universeSelected = false;
return Enumerable.Empty<string>();
}
);
// internal daily resolution
SetBenchmark("SPY");
Symbol symbol;
if (!SymbolCache.TryGetSymbol("SPY", out symbol)
|| !ReferenceEquals(_spy, symbol))
{
throw new Exception("We expected 'SPY' to be added to the Symbol cache," +
" since the algorithm is also using it");
}
}
/// <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)
{
var security = Securities[_spy];
_onDataWasCalled = true;
var bar = data.Bars.Values.Single();
if (_universeSelected)
{
if (bar.IsFillForward
|| bar.Period != TimeSpan.FromMinutes(1))
{
// bar should always be the Minute resolution one here
throw new Exception("Unexpected Bar error");
}
if (_previousTime.Date == data.Time.Date
&& (data.Time - _previousTime) != TimeSpan.FromMinutes(1))
{
throw new Exception("For the same date expected data updates every 1 minute");
}
}
else
{
if (data.Time.Minute == 0
&& _previousSecurityValue == security.Price)
{
throw new Exception($"Security Price error. Price should change every new hour");
}
if (data.Time.Minute != 0
&& _previousSecurityValue != security.Price)
{
throw new Exception($"Security Price error. Price should not change every minute");
}
}
_previousSecurityValue = security.Price;
// assert benchmark updates only on date change
var currentValue = Benchmark.Evaluate(data.Time);
if (_previousTime.Hour == data.Time.Hour)
{
if (currentValue != _previousBenchmarkValue)
{
throw new Exception($"Benchmark value error - expected: {_previousBenchmarkValue} {_previousTime}, actual: {currentValue} {data.Time}. " +
"Benchmark value should only change when there is a change in hours");
}
}
else
{
if (data.Time.Minute == 0)
{
if (currentValue == _previousBenchmarkValue)
{
_benchmarkPriceDidNotChange++;
// there are two consecutive equal data points so we give it some room
if (_benchmarkPriceDidNotChange > 1)
{
throw new Exception($"Benchmark value error - expected a new value, current {currentValue} {data.Time}" +
"Benchmark value should change when there is a change in hours");
}
}
else
{
_benchmarkPriceDidNotChange = 0;
}
}
}
_previousBenchmarkValue = currentValue;
_previousTime = data.Time;
// assert algorithm security is the correct one - not the internal one
if (security.Leverage != ExpectedLeverage)
{
throw new Exception($"Leverage error - expected: {ExpectedLeverage}, actual: {security.Leverage}");
}
}
public override void OnEndOfAlgorithm()
{
if (!_onDataWasCalled)
{
throw new Exception("OnData was not called");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.564"},
{"Tracking Error", "0.214"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

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