Compare commits

..

117 Commits
14385 ... 14830

Author SHA1 Message Date
Martin-Molinero
fcee43b56e Update readme.md 2022-11-17 14:38:14 -03:00
Martin-Molinero
7898e74148 Update readme.md 2022-11-17 13:50:31 -03:00
Louis Szeto
b34cea4458 Calculate Option Greeks with Implied Volatility (#6720)
* Using IV to calculate Greeks, and remove single-step stochastic approximation

* Correct calculation for theta, vega, rho

* Add calculation from Black Calculator and peer review

* Address peer review and added unit test

* Update some tests and correct vega/eho

* Fix Unit Test and Improve Comments

Fixes `IndexOptionCallITMGreeksExpiryRegressionAlgorithm` since `Vega` was really non-zero.

* Fix regression test and add IV calculation

* refactor and bug fixing on peer review

* refactor and bug fixing on peer review

* for rerun test

* add warning on IV estimation not coveraged and edit speed unit test to not exceed 2s per 1000 iteration

* update logging

* update logging and description

* Add default option pricing models and unit tests

* address review

* Added Fed interest rate as risk-free rate with unit tests and set as default for option greeks calculation, added regression algorithms, addressed peer review

* refactor structure of interest rate

* Skip Saturday and Sunday

* regression test fix

* peer review

* Fixes Interest Rate Provider Logic

* Minor tweaks

* Fix start date

* Minor test tweak

* Update interest rates

* Fix unit tests

* Add minor log

Co-authored-by: Alexandre Catarino <AlexCatarino@users.noreply.github.com>
Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-11-17 13:35:42 -03:00
Jhonathan Abreu
e9edb8ac29 Fix IndicatorExtensions for Python indicators (#6748)
* Fix using python custom indicators with extensions

* Minor changes to the algorithm

* Address PR comments
2022-11-16 18:36:46 -03:00
Jhonathan Abreu
33c57bbde4 Use selector on indicator warm up (#6746) 2022-11-15 19:59:59 -03:00
Jhonathan Abreu
94b9b13530 Make PlotIndicator able to receive IndicatorBase (#6745)
* Make PlotIndicator able to receive IndicatorBase

* Minor changes
2022-11-15 11:49:55 -03:00
Jhonathan Abreu
682b9aa760 Restrict index and cash-settled options exercise in IB brokerage (#6744)
* Limit exercise in IB brokerage for limit and cash-settled options

* Add regression algorithm

* Assert that index option is automatically exercised in regression algorithm
2022-11-15 11:03:43 -03:00
Jhonathan Abreu
98c6023748 Forbid european options exercise before expiry (#6734)
* Forbid european options exercise before expiry

* Minor tweaks

* Minor tweaks to tests
2022-11-11 19:32:44 -03:00
Martin-Molinero
dacc679d42 Wolverine brokerage setup (#6733)
* Wolverine LEAN integration

* Wolverine Lean integration - adjusting comments and restrict to Equity only

* fix 0.005$ per share fee

* remove PostOnly from Wolverine as its not needed

* AccountType.Margin and also removed check for USD only currency

* fix Market Wolverine -> USA

* change config

* Minor tweaks

Co-authored-by: Mark Virchenko <mark.virchenko@redduck.io>
2022-11-10 17:59:36 -03:00
Jhonathan Abreu
3e76716b07 Fix ppply options filter on market open only when using OnlyApplyFilterAtMarketOpen (#6731) 2022-11-10 12:46:09 -03:00
Jhonathan Abreu
55b09a1ea6 Data monitor (#6725)
* Data monitor (FIRST TEST)

* Calculate data request frequency in data monitor

* Detecting universe data usage in data monitor

* Json data monitor report generation

* Data monitor refactor

* Log and store data monitor report

* Data monitor report tests

* Clean up

* Clean up

* Address changes request

* Address changes request

* Wire data monitor only for backtest, not for live or research

* Minor tweaks

* Some minor tweaks

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-11-09 17:38:34 -03:00
Martin-Molinero
5539e27905 Fix tradier default config (#6727)
- Tradier brokerage is no longer a history provider, after refactor https://github.com/QuantConnect/Lean.Brokerages.Tradier/pull/7
2022-11-08 15:55:15 -03:00
Martin-Molinero
42ed7cf2a7 Update readme.md 2022-11-08 12:17:56 -03:00
Martin-Molinero
62d1321d74 Object Store Limit Validation (#6726)
- Minor object store limit validation on saving a new entry
2022-11-08 11:51:16 -03:00
Derek Melchin
0fa2ea19bc Reset trailing stop model highwater mark upon security liquidation (#6724)
* Fix trailing stop reset

* Add regression algorithm
2022-11-07 17:46:46 -03:00
Martin-Molinero
e155f620e1 Update readme.md 2022-11-03 11:23:15 -03:00
Alexandre Catarino
897e16c484 Changes SuperTrend Indicator Type from TradeBarIndicator to BarIndicator (#6717) 2022-11-01 10:19:13 -03:00
Martin-Molinero
6477b40661 Fix Options Strategies Names (#6715)
- Minor fix for options strategies names. Update regression algorithm
  order hash due to tag
2022-10-31 15:17:07 -03:00
Derek Melchin
5bfe2491c3 Add Sortino indicator (#6696)
* Add sortino indicator and helper indicators

* Address review

* Address review
2022-10-28 18:12:33 -03:00
Martin-Molinero
03f1bacd3f Update readme.md 2022-10-25 17:23:55 -03:00
Martin-Molinero
9849a11933 Update readme.md 2022-10-25 14:22:41 -03:00
Martin-Molinero
8e6dd5a338 Update readme.md 2022-10-25 12:45:15 -03:00
Martin-Molinero
2738c0f006 Refactor multi IDQH frontier (#6709)
* Refactor multi IDQH frontier

- Fix for multi IDQH frontier support, specially for IB + QC
- Adding new CompositeTimeProvide. Adding unit tests

* Adjust solution to fix new data available event
2022-10-25 11:59:21 -03:00
Martin-Molinero
a0c4d7b741 Update readme.md 2022-10-24 12:02:49 -03:00
Martin-Molinero
7095dc1559 Update gateway to 1019 (#6706)
- Update gateway to latest 1019
- Fix bug in IB data subscription limit, not applying when using
  multiple data queue handlers
2022-10-24 12:01:13 -03:00
Jhonathan Abreu
2d7afa798a Make NDAX use the same fill model as the other crypto brokerages (#6705) 2022-10-21 16:42:42 -03:00
Martin-Molinero
b8bcc4796f Create directory & replace link (#6704) 2022-10-21 15:55:10 -03:00
Martin-Molinero
0fc9555121 Update readme.md 2022-10-21 15:22:35 -03:00
Martin-Molinero
45e13bb35b Memory Related Performance improvements (#6700)
* Memory Related Performance improvements

- Make sure we cleanup & dipose of python related objects during pandas
  data generation.
- Disable memoizing enumerable use while creating pandas data frames,
  since we do not require it
- Reduce unrequired object creations
- Replace concurrentCollections for ordinary locks

* Decimal parsing typo fix
2022-10-21 15:11:18 -03:00
Martin-Molinero
5773d29419 Research Libraries Fixes (#6702)
- Replace old conda libc for OS version
- Remove unrequired LD_LIBRARY_PATH added for a mono issue at https://github.com/QuantConnect/Lean/pull/5380
2022-10-21 15:09:44 -03:00
Jhonathan Abreu
8f3bdcfe6c Fix adding Python additional paths in research (#6699)
* Add python additional paths for research

* Delegate adding additional paths to pythonpath to PythonInitializer

* Add new way to keep algorithm location at the beginning of pythonpath

* Add switch to disable BeginAllowThreads in PythonInitializer

* Add switch to disable BeginAllowThreads in PythonInitializer

* Address changes request
2022-10-21 12:11:10 -03:00
Alexandre Catarino
736e5d1fe0 Adds Support to Visual Studio Code Dev Container (#6680)
* Adds Support to Visual Studio Code Dev Container

Adds support and documentation to VSCode Dev Container.

* Address Peer Review

- Adds Dockerfile to install QuantConnect Stubs to enable Python autocomplete.
- Adds settings.json to enable Python autocomplete and LF line ending.
- Removes autobuilder task.
- Fixes Research Laucher

* Launcher and Task Impromevents

Fixes line endings issue
Fixes Launcher to point to right config.json file
Improve readme formatting

* Simplify Jupyter Notebook Deployment
2022-10-19 16:41:57 -03:00
Alexandre Catarino
c5e5de3416 Fixes Index Option Assignment Simulation (#6697)
Cash settlements do not open a position for the underlying, so we don't need to calculate the cost of closing the position.
2022-10-19 10:45:55 -03:00
Martin-Molinero
39735941ec FillForward delisting handling (#6692)
- In some rare cases the FillForwardEnumerator was missing to register
  the delisting date of an asset because it was the first data it got.
  Adding unit test reproducing issue
2022-10-14 20:29:40 -03:00
Martin-Molinero
fc6835cace Normalize time in universe behavior (#6693)
* Normalize time in universe behavior

- Normalize Option & Future chain universe behavior regarding their
  assets time in universe. They will now respect the universe settings
  time in universe value. Adding new regression algorithms asserting the
  behavior

* Address reviews & cleanup
2022-10-14 15:13:59 -03:00
Derek Melchin
dba0fd0824 Update description (#6691) 2022-10-13 20:21:52 -03:00
Martin-Molinero
a0fd2b193f Option greeks improvements (#6690)
- Update QLNet library to latest version from 6/2019 -> 11/2021
- Fix evaluation date which was using settlement date. Adding unit tests
  reproducing issue
2022-10-13 20:00:17 -03:00
Martin-Molinero
0fa471f4e5 Resource related improvements (#6683)
- Add resource controls logs
- Make sure the OS CPU performance counter thread is only created when
  desired, not in research
2022-10-12 17:25:56 -03:00
Martin-Molinero
b899aa4767 Make UserDefinedUniverse thread safe (#6682)
- Make UserDefinedUniverse thread safe. Adding regression test
2022-10-12 15:06:01 -03:00
Martin-Molinero
fed1b6e780 Add pyvinecopulib to foundation (#6679)
- Adding pyvinecopulib to foundation. Adding unit test
2022-10-11 16:30:57 -03:00
Martin-Molinero
f528c39700 Foundation update (#6677)
- Add new python packages to foundation images. Adding tests
2022-10-10 20:03:33 -03:00
Jhonathan Abreu
6a0fdd63a8 Add algorithm directory before any additional paths to pythonpath (#6674) 2022-10-06 20:04:47 -03:00
Alexandre Catarino
ca4187290b Normalize Algorithm EndDate Initilization (#6672)
Use `SetEndDate` to set `EndDate` in `QCAlgorithm` constructor. It will ensure that the `EndDate` is independent of the time the algorithm is executed if `SetEndDate` is not called in `Initilaize`.

Some users don't implement `SetEndDate` to run the algorithm to the latest datapoint, but this is not true if we run the algorithm during the day as the latest datapoint will be 24 hours before the execution time while there is data until the current day midnight.
2022-10-05 20:20:16 -03:00
Jhonathan Abreu
a0491a9b74 python-additional-paths config file setting (#6667)
* Add python-additional-paths setting in config file

* Configure python additional paths in JobQueue instead of PythonInitializer
2022-09-30 16:52:17 -03:00
Alexandre Catarino
abeb841a0c Adds Additional Condition to Parse SecurityIdentifier Properties (#6658)
* Adds Additional Condition to Parse SecurityIdentifier Properties

A string can pass the previous conditions and create an invalid `SecurityIdentifier` (e.g. "Sharpe ration").  If it is invalid, the Market is not supported (e.g. "378").

* Adds Unit Test to Pandas Indexing

* Log Only Once if TryParseProperties Cannot Parse

Use cache to increase speed and remove redundant logging
2022-09-29 10:13:45 -03:00
Martin-Molinero
783805ccf9 Allow running start from python (#6662)
* Allow running start from python

- Allow running start.py from python as well as IPython, so C# can be
  called. Adding unit test

* Address review
2022-09-28 12:57:47 -03:00
Alexandre Catarino
848d812bf2 Fixes Buying Power Model Selection for Cash Account (#6652)
`DefaultBrokerageModel` was selecting `CashBuyingPowerModel` for securities not supported by this model as it only supports Crypto and Forex.
2022-09-26 12:50:08 -03:00
Derek Melchin
96b07e6916 Add PyObject overload to ETFConstituentsUniverseSelectionModel (#6616) 2022-09-26 12:47:25 -03:00
Martin-Molinero
7796868da7 Fix research image typo (#6650)
Fix research image typo
2022-09-22 10:58:23 -03:00
Martin-Molinero
108bfa6c0a Enable debugging worker threads (#6647)
- Enable debugging worker threads in python
2022-09-21 16:29:37 -03:00
Martin-Molinero
7f44c3d605 Update readme.md 2022-09-19 19:34:02 -03:00
Martin-Molinero
59eae963be Fix order cancel using order ticket (#6640)
- If cancel request failed, allow user to retry. Adding unit test
  reproducing the issue
2022-09-19 18:36:51 -03:00
Louis Szeto
c48979e986 Remove alpha stream from docker image (#6638) 2022-09-19 17:48:07 -03:00
Martin-Molinero
e54fe3ae95 Pin clr loader version (#6641) 2022-09-19 17:04:24 -03:00
Martin-Molinero
ee685ea045 Add new python libraries to foundation (#6629) 2022-09-19 13:20:54 -03:00
Ryan Russell
11f13be75b docs(VixDualThrustAlpha): readability improvements (#6632)
* docs(VIXDualThrustAlpha): `determine` fixup

Signed-off-by: Ryan Russell <git@ryanrussell.org>

* docs(VixDualThrustAlpha): `unsubscribe` fixup

Signed-off-by: Ryan Russell <git@ryanrussell.org>

Signed-off-by: Ryan Russell <git@ryanrussell.org>
2022-09-19 13:17:18 -03:00
Ryan Russell
188506b5da docs(ShareClassMeanReversionAlpha): dollar-neutral fixup (#6631)
Signed-off-by: Ryan Russell <git@ryanrussell.org>

Signed-off-by: Ryan Russell <git@ryanrussell.org>
2022-09-19 13:17:10 -03:00
Ryan Russell
ca83e8443f docs(BasicTemplateIndiaIndexAlgorithm): readability fixups (#6633)
* docs(BasicTemplateIndia): `Prperties` -> `Properties`

Signed-off-by: Ryan Russell <git@ryanrussell.org>

* docs: `Intialization` -> `Initialization`

Signed-off-by: Ryan Russell <git@ryanrussell.org>

Signed-off-by: Ryan Russell <git@ryanrussell.org>
2022-09-19 13:16:54 -03:00
Ryan Russell
ac0cdb20f5 docs: formatted readability fix (#6627)
Signed-off-by: Ryan Russell <git@ryanrussell.org>

Signed-off-by: Ryan Russell <git@ryanrussell.org>
2022-09-16 17:32:44 -03:00
Ryan Russell
a131a4849a docs: automatic readability fixes (#6626)
Signed-off-by: Ryan Russell <git@ryanrussell.org>

Signed-off-by: Ryan Russell <git@ryanrussell.org>
2022-09-16 17:32:28 -03:00
Jhonathan Abreu
31b603593d Get history for a specific bar type in Python (#6611)
* Get history of a given bar type in python

* Separate GetDataFrame in sub methods to avoid dynamic type resolution

* Housekeeping and unit tests update

* Use all requests in python type method history method

* Address changes request

* Reverted some requested changes
2022-09-13 10:26:47 -03:00
Jhonathan Abreu
f62f110b1b Handle non-unique multi-index error in history dataframe creation (#6617)
* Handle non-unique multi-index error for Ticks in data frame creation

* Update unit tests

* Update unit tests and add comments

* Add regression algorithm
2022-09-08 19:40:57 -03:00
Derek Melchin
ede2991823 Add ETF universe selection model and example algos (#6604)
* Add ETF universe selection model and example algos

* Address review

* address peer review
2022-09-07 21:32:51 -03:00
Martin-Molinero
3b65f4b9a1 Fix micro crude oil future expiration (#6614)
* Fix micro crude oil future expiration

- Fix micro crude oil future expiration. Adding unit test

* Add MicroCL for ExpiriesPriorMonth
2022-09-07 21:06:28 -03:00
Alexandre Catarino
f755b91158 Fixes PythonData.EndTime (#6602)
* Fixes PythonData.EndTime

The `EndTime` property of `PythonData` didn't override the base implementation in `BaseData`. Therefore `EndTime` was always set as `Time`.

Fixes Regression Tests
- The C# version of `Bitcoin` class needs to implement `EndTime`-
- Fixes regression tests

* Minor tweaks and rebase

- Add support for python data types just setting EndTime. Adding unit
  tests for PythonData
- Fix for DynamicData EndTime property being fetched. Updating unit
  tests

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-09-07 14:53:05 -03:00
Martin-Molinero
7d1cd79618 Fix warmup live time zone (#6612)
- Fix live trading warmup timezone issue. Adding unit test
- Adding useful configuration values to main config.json
2022-09-02 18:30:46 -03:00
Martin-Molinero
a0ba23a7f0 Update readme.md 2022-09-02 17:24:35 -03:00
Jhonathan Abreu
4415468d96 Update CME futures market hours (#6607)
* Update CME futures market hours

* Update regression algorithms stats

* Update regression algorithms stats

* Update expected values in unit tests

* Additional mhdb updates

* Update mhdb
2022-09-02 12:33:50 -03:00
Louis Szeto
dff92ac85e Fix BlackLittermanPortfolioConstructionModel (#6603)
* Remove redundant dimension that throw error

* Fix bug

* Fix bug

* Add dimension test

* Fix test and bug

* Fix python bug

* Address peer review

* Update python workflow

* Update python and test
2022-09-01 16:43:23 -03:00
Martin-Molinero
dc4a903727 Fix ObjectStore limits enforcement (#6609)
- Fix object store limits enforcement. Adding unit tests
2022-09-01 13:52:11 -03:00
Martin-Molinero
5e7651f699 Update dotnet interactive (#6608) 2022-09-01 12:43:02 -03:00
Martin-Molinero
fcd48ecdbb Object Store Improvements (#6605)
- Fix for cache behavior, finer grained writting and loading
- Add Keys and Clear to the object store API. Adding tests
2022-08-31 20:50:00 -03:00
Martin-Molinero
8e8aa74fb0 Add project id to algorithm (#6600)
- Add projectId for algorithm usage
2022-08-30 20:56:28 -03:00
Jhonathan Abreu
548a6998e3 Report generation with non-default algorithm settings (#6589)
* Add algorithm settings to backtest results

* Use algorithm result settings in report generation

* Add unit tests

* Housekeeping

* Changes for live result report

* Housekeeping

* Housekeeping

* Housekeeping

* Add unit tests
2022-08-30 19:23:25 -03:00
Jhonathan Abreu
9a062e4b5d Include trades and quotes in tick history request (#6595)
* Include both quotes and trades in Tick history request

* Regression algorithm

* Housekeeping

* Housekeeping
2022-08-30 19:03:11 -03:00
Jhonathan Abreu
82f2aa7a63 Parsing all currencies in a number with currency (#6599)
* Correctly stripping out currency symbol from numbers with currency

* Fixes
2022-08-30 19:02:21 -03:00
Martin-Molinero
46aa62bd0c Improve object store key support (#6598) 2022-08-30 18:18:50 -03:00
Martin-Molinero
250230e79f Global object store (#6594)
* Refactor object store

* Address reviews

* Simplify implementation

- Remove base64 encoding
- Refactor object store api to allow a single path argument

* Fix bug

* Adjust storage controls

* Fix unit tests
2022-08-30 16:40:01 -03:00
Martin-Molinero
0be339d75f Update python install instructions (#6590) 2022-08-26 18:51:32 -03:00
Martin-Molinero
3eb2b94070 Minor logging improvements (#6588)
- Add virtual env name in init log
- Log account type with cashbook
- Consolidate job handlers log. Adding DataProvider
2022-08-26 14:18:28 -03:00
Louis Szeto
b655bd776e Addition of Risk Parity Portfolio Construction Model (#6577)
* /

* Models

* Models

* Partial test

* Complete test and fix bug

* Address peer review

* Address review and fix bugs

* Fix regression result

* Fix regression result
2022-08-26 12:23:31 -03:00
Martin-Molinero
2bc41e0e32 Websocket improvements (#6585)
* Dynamically set wait time on WS error

- Dynamically adjust wait time on websocket error

* Avoid subscribing multiple times to message events

- Avoid websocket subscription multiple times to message events during
  disconnection/connection cycle

* Add Dispose Brokerage WebSocket Subscription Manager
2022-08-26 10:53:28 -03:00
Martin-Molinero
d6d3514ae2 Live warmup resolution check (#6586)
- Add check for live warmup history request, making sure there is at
  least room for a single bar between start and end. Avoid sending
  start==end when rouded down by the resolution causing some history
  providers to fail
2022-08-26 10:50:02 -03:00
Martin-Molinero
575f17c6ec Order command improvements (#6584)
- Create SubmitOrderRequest method in algorithm API to reduce
  duplication of code and responsability.
- Add order command tests for different failure and success cases
- Fix null reference exception in equity fill model, when there is no
  data for an asset.
2022-08-25 15:53:11 -03:00
Jhonathan Abreu
3c6ae2f1e7 Fix report's exposure plot colors and other bugs (#6580)
* Use correct colors in report's exposure plot

* Add 12 month rolling sharpe to report plot

* Housekeeping

* Fix failing unit tests
2022-08-25 12:28:22 -03:00
Martin-Molinero
19f3d8b305 Fix python memory leak (#6579)
* Fix python memory leak

- Fix python memory leak. Adding unit test

* Update pythonnet to 2.0.17
2022-08-24 18:24:07 -03:00
Jhonathan Abreu
475f295ce0 Support market orders for futures and FOPs on extended hours (#6575)
* Allow market orders for futures and FOPs on extended market hours

* Update regression algorithms stats

* Add futures fill model to allow extended market hours

* Add unit tests

* Update regression algorithms stats

* Update regression algorithms stats

* Housekeeping
2022-08-24 11:04:52 -03:00
Martin-Molinero
7fdedbe98f Rename python environments (#6572)
* Rename python environments

* Rename to Foundation-Py/C#-Default
2022-08-23 19:06:19 -03:00
Martin-Molinero
24605c6788 Add missing PY.GIL when shutting down (#6571) 2022-08-23 17:40:20 -03:00
Martin-Molinero
c8a80e361c Update readme.md 2022-08-23 15:53:29 -03:00
Martin-Molinero
dc7b2faa6b Fix launcher potential null reference (#6567)
- Fix launcher potential null reference if the job is null
2022-08-22 19:03:32 -03:00
Ryan Russell
9cd38a388b chore(.NET 6): Update references from dotnet 5 to dotnet 6 #6560 (#6565)
* docs(dotnet6): `dotnet 5` -> `dotnet 6`

Signed-off-by: Ryan Russell <git@ryanrussell.org>

* `.Net 5` -> `.Net 6`

Signed-off-by: Ryan Russell <git@ryanrussell.org>

Signed-off-by: Ryan Russell <git@ryanrussell.org>
2022-08-22 17:51:24 -03:00
Martin-Molinero
04723df362 Fix ARM foundation image (#6566)
- Remove unsupported libraries
2022-08-22 17:50:11 -03:00
Martin-Molinero
3f42101f6d Update to python38 and libraries (#6558)
* Update to python38

- Update to python38
- Update libraries

* Create latest virtual environment. Add CI unit tests

* Further update python packages

* Virtual env fixes

- Refactor python virtual env setup
- Adding CI unit tests for python packages and virtual envs

* Adding more python packages

- Adding NBeats, Ax-platform, Riskfolio-Lib

* Rename pomegranate venv
2022-08-22 13:54:02 -03:00
Jhonathan Abreu
eddd28243b Show backtest and live runtime days in report (#6561)
* Show backtest and live runtime days in report

* Show live or backtest runtime days in report stats

* Housekeeping
2022-08-22 12:12:19 -03:00
Jhonathan Abreu
8e35155c40 Fix IB futures commission fees (#6557)
* Adapted futures commission fees for IB

* Unit tests

* Some cleanup

* Fix exchange fees

* Update regression algorithms stats

* Update unit tests
2022-08-18 18:35:49 -03:00
Ryan Russell
98fa4464ce docs: excersizing -> exercising (#6559)
* docs: `excersizing` -> `exercising`

Signed-off-by: Ryan Russell <git@ryanrussell.org>

* docs: fix `exercising for exercising`

Signed-off-by: Ryan Russell <git@ryanrussell.org>

* docs: `migth` -> `might`

Signed-off-by: Ryan Russell <git@ryanrussell.org>

Signed-off-by: Ryan Russell <git@ryanrussell.org>
2022-08-18 11:00:26 -03:00
Jhonathan Abreu
539011274c Support extended market hours for futures (#6522)
* Support extended market hours in AddFuture()

* Support extended market hours in AddFutureContract()

* Add C# regression algorithm

* Add Python regression algorithm

* Add regression algorithm for future contracts

* Add regression algorithm checking market hour ranges

* Fixed future regression algorithms to use extended market hours

* Fixed future regression algorithms to use extended market hours

* Fixed future regression algorithms to use extended market hours

* Fixed AddFutureOptionContractFromFutureChainRegressionAlgorithm to use extended market hours

* Update future market hours to include extended in market hours database

* Fixed AddFutureOptionContractDataStreamingRegressionAlgorithm to use extended market hours

* Fixed AddFutureOptionContractFromFutureChainRegressionAlgorithm to use extended market hours

* Fixed AddFutureContractWithContinuousRegressionAlgorithm to use extended market hours

* Fixed BasicTemplateContinuousFutureAlgorithm to use extended market hours

* Fixed BasicTemplateFuturesAlgorithm to use extended market hours

* Fix BasicTemplateFuturesDailyAlgorithm to use extended market hours

* Fixed BasicTemplateFuturesFrameworkAlgorithm to use extended market hours

* Fixed BasicTemplateFuturesHistoryAlgorithm to use extended market hours

* Fixed ContinuousBackMonthRawFutureRegressionAlgorithm to use extended market hours

* Fixed ContinuousFutureBackMonthRegressionAlgorithm to use extended market hours

* Fixed ContinuousFutureHistoryRegressionAlgorithm to use extended market hours

* Fixed ContinuousFutureLimitIfTouchedOrderRegressionAlgorithm to use extended market hours

* Fixed ContinuousFutureRegressionAlgorithm to use extended market hours

* Fixed DelistedFutureLiquidateRegressionAlgorithm to use extended market hours

* Fixed AutomaticIndicatorWarmupDataTypeRegressionAlgorithm to use extended market hours

* Fixed ConsolidateRegressionAlgorithm to use extended market hours

* Fixed DelistingFutureOptionRegressionAlgorithm to use extended market hours

* Fixed EqualWeightingPortfolioConstructionModelFutureRegressionAlgorithm to use extended market hours

* Fixed FutureContractsExtendedMarketHoursRegressionAlgorithm to use extended market hours

* Fixed FutureMarketOpenAndCloseRegressionAlgorithm to use extended market hours

* Fixed FutureMarketOpenConsolidatorRegressionAlgorithm to use extended market hours

* Fixed FutureOptionBuySellCallIntradayRegressionAlgorithm to use extended market hours

* Fixed FutureOptionCallITMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionCallITMGreeksExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionCallOTMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionDailyRegressionAlgorithm to use extended market hours

* Fixed FutureOptionHourlyRegressionAlgorithm to use extended market hours

* Fixed FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm to use extended market hours

* Fixed FutureOptionPutITMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionPutOTMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionShortCallITMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionShortCallOTMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionShortPutITMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionShortPutOTMExpiryRegressionAlgorithm to use extended market hours

* Fixed FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm to use extended market hours

* Fixed FuturesExpiredContractRegression to use extended market hours

* Fixed FutureSharingTickerRegressionAlgorithm to use extended market hours

* Fixed HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm to use extended market hours

* Fixed HistoryWithDifferentDataMappingModeRegressionAlgorithm to use extended market hours

* Fixed HistoryWithDifferentDataNormalizationModeRegressionAlgorithm to use extended market hours

* Fixed LimitOrdersAreFilledAfterHoursForFuturesRegressionAlgorithm to use extended market hours

* Fixed OpenInterestFuturesRegressionAlgorithm to use extended market hours

* Fixed RegisterIndicatorRegressionAlgorithm to use extended market hours

* Fixed SetHoldingsFutureRegressionAlgorithm to use extended market hours

* Fixed WarmupFutureRegressionAlgorithm to use extended market hours

* Fixed AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm to use extended market hours

* Fixed AlgorithmHistoryTests to use extended market hours for futures

* Fixed AlgorithmTradingTests to use extended market hours for futures

* Fixed BrokerageSetupHandlerTests to use extended market hours for futures

* Fixed TimeRulesTests to use extended market hours for futures

* Fixed FutureOptionMarginBuyingPowerModelTests to use extended market hours for futures

* Fixed FutureMarginBuyingPowerModelTests to use extended market hours for futures

* Fixed FileSystemDataFeedTests to use extended market hours for futures

* Fixed QuantBookHistoryTests to use extended market hours for futures

* Split BasicTemplateContinuousFutureAlgorithm to have an extended market version

* Fixed FutureMarketOpenAndCloseRegressionAlgorithm to use extended market hours

* Split BasicTemplateFuturesAlgorithm to have an extended market version

* Split BasicTemplateFuturesAlgorithm to have an extended market version

* Split BasicTemplateFuturesFrameworkAlgorithm to have an extended market version

* Split BasicTemplateFuturesHistoryAlgorithm to have an extended market version

* Revert AddFutureContractWithContinuousRegressionAlgorithm

* Revert AddFutureOptionContractDataStreamingRegressionAlgorithm and added data

* Revert AddFutureOptionContractFromFutureChainRegressionAlgorithm

* Revert AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm

* Revert ConsolidateRegressionAlgorithm

* Revert Algorithm.CSharp/ContinuousBackMonthRawFutureRegressionAlgorithm.cs

* Revert ContinuousFutureBackMonthRegressionAlgorithm

* Revert ContinuousFutureHistoryRegressionAlgorithm

* Revert ContinuousFutureLimitIfTouchedOrderRegressionAlgorithm

* Revert ContinuousFutureRegressionAlgorithm

* Revert Algorithm.CSharp/DelistedFutureLiquidateRegressionAlgorithm.cs

* Revert EqualWeightingPortfolioConstructionModelFutureRegressionAlgorithm

* Split FutureMarketOpenAndCloseRegressionAlgorithm to have an extended market version

* Split FutureMarketOpenConsolidatorRegressionAlgorithm to have an extended market version

* Revert FutureOptionBuySellCallIntradayRegressionAlgorithm

* Revert FutureOptionCallITMExpiryRegressionAlgorithm

* Revert FutureOptionDailyRegressionAlgorithm

* Revert FutureOptionPutITMExpiryRegressionAlgorithm

* Revert FutureSharingTickerRegressionAlgorithm

* Revert FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm

* Revert FuturesExpiredContractRegression

* Revert HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm

* Revert HistoryWithDifferentDataMappingModeRegressionAlgorithm

* Revert HistoryWithDifferentDataNormalizationModeRegressionAlgorithm

* Revert OpenInterestFuturesRegressionAlgorithm

* Revert RegisterIndicatorRegressionAlgorithm

* Revert SetHoldingsFutureRegressionAlgorithm

* Revert WarmupFutureRegressionAlgorithm

* Revert AutomaticIndicatorWarmupDataTypeRegressionAlgorithm

* Some cleanup

* Address changes request

* Address changes request

* Add more Class III Milk data to fix DelistingFutureOptionDailyRegressionAlgorithm
2022-08-18 10:56:44 -03:00
Martin-Molinero
6f3208eded Python Virtual Environments Support (#6556)
- Add support to use a python virtual environment if defined in the
  algorithm job. Adding tests
2022-08-17 16:40:52 -03:00
Ryan Russell
62493f8986 docs: algorithm readability improvements (#6554)
docs: `algorthm` -> `algorithm`
2022-08-17 10:39:57 -07:00
Ryan Russell
35afe3da84 docs: portfolio readability fixes (#6553)
* docs: `portolio` -> `portfolio`

Signed-off-by: Ryan Russell <git@ryanrussell.org>

* docs: `porfoltio` -> `portfolio`

Signed-off-by: Ryan Russell <git@ryanrussell.org>

Signed-off-by: Ryan Russell <git@ryanrussell.org>
2022-08-17 10:23:40 -03:00
Jhonathan Abreu
b07680688f Fix FormatException on estimated capacity rendering during report generation (#6551)
* Fix FormatException on non-USD currency capacity in report generator

* Improve currency removal from capacity string

Applied this improvement to OptimizationBacktestJsonConverter.WriteJson

* Address changes request
2022-08-16 11:08:36 -03:00
Ryan Russell
e4647ea146 docs: epected -> expected (#6552)
Signed-off-by: Ryan Russell <git@ryanrussell.org>

Signed-off-by: Ryan Russell <git@ryanrussell.org>
2022-08-16 10:12:30 -03:00
Ryan Russell
052e20cbf4 refactor(Algorithm): readability improvements (#6547)
* refactor(Algorithm): Correct `Intrinino` -> `Intrinio` references

Signed-off-by: Ryan Russell <git@ryanrussell.org>

* refactor(Algorithm): Update `evemts` -> `events`

Signed-off-by: Ryan Russell <git@ryanrussell.org>

* refactor(BubbleAlgorithm): readability improvements

Signed-off-by: Ryan Russell <git@ryanrussell.org>

* refactor(OrderTicketDemoAlgorithm): readability improvements

Signed-off-by: Ryan Russell <git@ryanrussell.org>

Signed-off-by: Ryan Russell <git@ryanrussell.org>
2022-08-15 10:52:07 -03:00
Jhonathan Abreu
771cc11b3a Fix KeyError in report generator due to missing color mappings (#6546)
* Fix KeyError when rendering exposure chart in report with some security types

* Update exposure chart colors and add unit tests

* Updated json test file
2022-08-12 18:52:15 -03:00
Ronit Jain
0d882b8201 Refactor handle lean-cli commands for live deployments (#6527)
* handle multiple command files

* remove default useage

* add tests for verify files are read in order

* add comment

* change reuslt file name

* add comment

* liquidate using given symbol values

* remove redundant

* accept ticker, market, security type to build symbol, to be used by CLI commands

* use null leverage

* symbol can be null if ticker, market, security type values are provided

* reject the default value of security type

* cleanup

* cleanup

* check if status is not invalid

* cleanup

* abstraction to remove duplication

* fix name

* address reviews

* use counter

* add test to validate symbol/ticker agrumnets

* remove hardcoded values
2022-08-12 18:12:33 -03:00
Ryan Russell
95c1f752ac docs: Readability improvements (#6545)
Signed-off-by: Ryan Russell <git@ryanrussell.org>

Signed-off-by: Ryan Russell <git@ryanrussell.org>
2022-08-12 16:56:26 -03:00
Martin-Molinero
37dca9d458 Remove log packet aggregation (#6538)
- Remove log packet aggregation
- Clean up Queue api usage
2022-08-11 19:06:11 -03:00
Jhonathan Abreu
2dd3a0cb94 Fix 'GetParameter()' ambiguous call error when no default parameter is provided (#6541)
* Fix QCAlgorithm.GetParameter() ambiguous call error when no default parameter is provided

* Add unit tests

* Add regression algorithms
2022-08-11 18:45:00 -03:00
Jhonathan Abreu
aa8a3a241b GetParameter number conversion overloads (#6535)
* Add numeric conversion overloads to QCAlgorithm.GetParameter()

* Add unit tests

* Address changes request
2022-08-10 18:15:04 -03:00
Louis Szeto
cfa4a4c1c1 Update readme information in Equity data (#6536)
* Update readme

* Update equity readme

* Add quote info

* Fix typo

* Add back QuoteQuant as pre-2007 vendor

* Fix typo
2022-08-10 18:11:20 -03:00
Ronit Jain
3064c1ed4b update config value (#6537) 2022-08-10 18:10:02 -03:00
Jhonathan Abreu
9e7690754a Forbid tick resolution period-based history requests (#6533)
* Detect implicit tick resolution in period-based history requests and throw

* Add regression algorithms
2022-08-09 18:19:08 -03:00
Jhonathan Abreu
460ef10ff4 Add more info to python runtime error message (#6526) 2022-08-09 17:56:23 -03:00
Jhonathan Abreu
6f70606f3e Allow tick history request without tick subscription (#6534) 2022-08-09 17:51:25 -03:00
Louis Szeto
9eb71e1543 Mean Reversion Portfolio Construction Model (#6519)
* MRP

* Fix bug

* Rename

* Provide virtual `GetPriceRelative` function to override for any variants in future

* SymbolData class within model

* Address peer review

* fix bug

* revise unit test and fix bug in python model

* revise unit test and fix bug in model

* Revise regression statistics

* Revise regression statistics

* Revise regression statistics

* Revise regression statistics

* Revise regression statistics

* Address peer review

* Updated unit tests according to peer review

* Address peer review
2022-08-04 11:20:11 -03:00
Martin-Molinero
3f7d339463 Fix live result Handler null reference (#6521)
- Fix live result handler null reference, that could happen if the
  algorithm explodes mid initialization. Adding unit test
2022-08-03 19:57:03 -03:00
494 changed files with 23783 additions and 5349 deletions

8
.devcontainer/Dockerfile Normal file
View File

@@ -0,0 +1,8 @@
# Use QuantConnect Research as the base
FROM quantconnect/research:latest
# Install dos2unix utility for converting pesky windows formatting when needed
RUN apt-get update && apt-get install -y dos2unix
# Install QuantConnect Stubs for Python Autocomplete
RUN pip install --no-cache-dir quantconnect-stubs

View File

@@ -0,0 +1,34 @@
{
"name": "Lean Development Container",
"workspaceMount": "source=${localWorkspaceFolder},target=/Lean,type=bind",
"workspaceFolder": "/Lean",
// Use devcontainer Dockerfile that is based on Lean foundation image
"build": { "dockerfile": "Dockerfile" },
// Set *default* container specific settings.json values on container create.
"settings": {
"terminal.integrated.profiles.linux": {
"bash": {
"path": "bash",
"icon": "terminal-bash"
}
}
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": ["ms-dotnettools.csharp", "ms-python.python", "ms-python.vscode-pylance", "formulahendry.dotnet-test-explorer", "eamodio.gitlens", "yzhang.markdown-all-in-one"],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Uncomment the next line to run commands after the container is created - for example installing curl.
"postCreateCommand": "dotnet nuget add source /Lean/LocalPackages; dos2unix /Lean/.vscode/launch_research.sh",
// Add mounts to docker container
"mounts": [
// Example data mount from local machine, must use target directory in Config.json
// "source=C:/Users/XXXXXXXXXXXX/Lean/Data,target=/Data,type=bind,consistency=cached"
]
}

View File

@@ -17,10 +17,10 @@ jobs:
- name: install dependencies
run: |
pip3 install papermill clr-loader
pip3 install papermill==2.4.0 clr-loader==0.1.6
- name: install kernel
run: dotnet tool install --global Microsoft.dotnet-interactive --version 1.0.317502
run: dotnet tool install --global Microsoft.dotnet-interactive --version 1.0.340501
- name: Add dotnet tools to Path
run: echo "$HOME/.dotnet/tools" >> $GITHUB_PATH

View File

@@ -0,0 +1,61 @@
name: Python Virtual Environments
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: Python Virtual Environment System Packages
run: python -m venv /lean-testenv --system-site-packages && . /lean-testenv/bin/activate && pip install --no-cache-dir lean==1.0.99 && deactivate
- name: Run Virtual Environment Test System Packages
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonVirtualEnvironmentTests.AssertVirtualEnvironment"
- name: Python Virtual Environment
run: rm -rf /lean-testenv && python -m venv /lean-testenv && . /lean-testenv/bin/activate && pip install --no-cache-dir lean==1.0.99 && deactivate
- name: Run Virtual Environment Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonVirtualEnvironmentTests.AssertVirtualEnvironment"
- name: Run Python Package Tests
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests"
- name: Run Pomegranate Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.PomegranateTest"
- name: Run Tensorforce Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorforceTests"
- name: Run StableBaselines Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.StableBaselinesTest"
- name: Run AxPlatform Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.AxPlatformTest"
- name: Run NeuralTangents Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.NeuralTangentsTest"
- name: Run NBeats Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.NBeatsTest"
- name: Run Tensorly Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorlyTest"
- name: Run Ignite Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.IgniteTest"
- name: Run Hvplot Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.HvplotTest"

View File

@@ -18,7 +18,7 @@ To use Lean CLI follow the instructions for installation and tutorial for usage
<h2>Option 2: Install Locally</h2>
1. Install [.Net 5](https://dotnet.microsoft.com/download) for the project
1. Install [.Net 6](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

6
.vscode/launch.json vendored
View File

@@ -3,8 +3,8 @@
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
Builds the project with dotnet 6 and then launches the program using coreclr; supports debugging.
In order to use this you need dotnet 6 on your system path, As well as the C# extension from the
marketplace.
Attach to Python:
@@ -26,7 +26,7 @@
"program": "${workspaceFolder}/Launcher/bin/Debug/QuantConnect.Lean.Launcher.dll",
"args": [
"--config",
"${workspaceFolder}/Launcher/config.json"
"${workspaceFolder}/Launcher/bin/Debug/config.json"
],
"cwd": "${workspaceFolder}/Launcher/bin/Debug/",
"stopAtEntry": false,

15
.vscode/launch_research.sh vendored Normal file
View File

@@ -0,0 +1,15 @@
# Realpath polyfill, notably absent macOS and some debian distros
absolute_path() {
echo "$(cd "$(dirname "${1}")" && pwd)/$(basename "${1}")"
}
# Get build directory from args position 1, or use default
DEFAULT_BUILD_DIR=../Launcher/bin/Debug/
BUILD_DIR=${1:-$DEFAULT_BUILD_DIR}
BUILD_DIR=$(absolute_path "${BUILD_DIR}")
#Add our build directory to python path for python kernel
export PYTHONPATH="${PYTHONPATH}:${BUILD_DIR}"
# Launch jupyter-lab
jupyter-lab --allow-root --no-browser --notebook-dir=$BUILD_DIR --LabApp.token=''

51
.vscode/readme.md vendored
View File

@@ -4,6 +4,8 @@ This document contains information regarding ways to use Visual Studio Code to w
- 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.
- Using a Lean Dev container -> A docker environment with all dependencies pre-installed to allow seamless Lean development across platforms. Great for open source contributors.
- Locally installing all dependencies to run Lean with Visual Studio Code on your OS.
<br />
@@ -12,32 +14,63 @@ This document contains information regarding ways to use Visual Studio Code to w
<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)
To use Lean CLI follow the instructions for installation and tutorial for usage in our [documentation](https://www.quantconnect.com/docs/v2/lean-cli/key-concepts/getting-started)
<br />
<h2>Option 2: Install Dependencies Locally</h2>
<h2>Option 2: Lean Development Container</h2>
1. Install [.Net 5](https://dotnet.microsoft.com/download) for the project
Before anything we need to ensure a few things have been done for either option:
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
1. Get [Visual Studio Code](https://code.visualstudio.com/download)
- Get [Remote Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) Extension
2. Get [Docker](https://docs.docker.com/get-docker/):
- Follow the instructions for your Operating System
- New to Docker? Try [docker getting-started](https://docs.docker.com/get-started/)
3. Pull Leans latest research image from a terminal
- `docker pull quantconnect/research:latest`
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
5. Open Development Container
- In VS Code, either:
- Select "Reopen in Container" from pop up box.
OR
- Ctrl+Shift+P (Command Palette) and select "Remote-Containers: Rebuild and Reopen in Container"
You should now be in the development container, give VS Code a moment to prepare and you will be ready to go!
If you would like to mount any additional local files to your container, checkout [devcontainer.json "mounts" section](https://containers.dev/implementors/json_reference/) for an example! Upon any mount changes you must rebuild the container using Command Palette as in step 5.
<br />
<h2>Option 3: Install Dependencies Locally</h2>
1. Install [.NET 6](https://dotnet.microsoft.com/en-us/download/dotnet/6.0) for the project
2. (Optional) Get [Python 3.8.13](https://www.python.org/downloads/release/python-3813/) for running Python algorithms
- Follow Python instructions [here](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#installing-python-38) 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)_
- 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
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)
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/key-concepts/getting-started)
<br />
@@ -73,7 +106,6 @@ In VS Code run build task (Ctrl+Shift+B or "Terminal" dropdown); there are a few
- __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 />
@@ -123,5 +155,6 @@ _Figure 2: Python Debugger Messages_
<h1>Common Issues</h1>
Here we will cover some common issues with setting this up. This section will expand as we get user feedback!
- The "project file cannot be loaded" and "nuget packages not found" errors occurs when the project files are open by another process in the host. Closing all applications and/or restarting the computer solve the issue.
- 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.

7
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,7 @@
{
"files.eol": "\n",
"python.analysis.extraPaths": [
"/Lean/Algorithm.Python",
"/opt/miniconda3/lib/python3.8/site-packages"
]
}

12
.vscode/tasks.json vendored
View File

@@ -50,6 +50,18 @@
"reveal": "silent"
},
"problemMatcher": "$msCompile"
},
{
"label": "start research",
"type": "shell",
"dependsOn": ["build"],
"group": "build",
"isBackground": true,
"command" : "${workspaceFolder}/.vscode/launch_research.sh",
"args" : [
"${workspaceFolder}/Launcher/bin/Debug"
],
"problemMatcher": "$msCompile"
}
]
}

View File

@@ -116,7 +116,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 59;
public long DataPoints => 63;
/// <summary>
/// Data Points count of the algorithm history
@@ -131,31 +131,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "-0.03%"},
{"Compounding Annual Return", "-2.503%"},
{"Compounding Annual Return", "-2.594%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.032%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Net Profit", "-0.034%"},
{"Sharpe Ratio", "-7.854"},
{"Probabilistic Sharpe Ratio", "1.216%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Alpha", "-0.022"},
{"Beta", "0.004"},
{"Annual Standard Deviation", "0.003"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.678"},
{"Tracking Error", "0.243"},
{"Treynor Ratio", "0"},
{"Total Fees", "$7.40"},
{"Estimated Strategy Capacity", "$2100000.00"},
{"Information Ratio", "-0.768"},
{"Tracking Error", "0.241"},
{"Treynor Ratio", "-4.689"},
{"Total Fees", "$8.60"},
{"Estimated Strategy Capacity", "$5500000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.419"},
{"Fitness Score", "0.417"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-81.557"},
{"Portfolio Turnover", "0.837"},
{"Return Over Maximum Drawdown", "-81.518"},
{"Portfolio Turnover", "0.834"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -169,7 +169,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "68775c18eb40c1bde212653faec4016e"}
{"OrderListHash", "802a335b5c355e83b8cd2174f053c1b9"}
};
}
}

View File

@@ -41,7 +41,7 @@ namespace QuantConnect.Algorithm.CSharp
public override void Initialize()
{
SetStartDate(2020, 1, 4);
SetEndDate(2020, 1, 6);
SetEndDate(2020, 1, 8);
_es20h20 = AddFutureContract(
QuantConnect.Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 3, 20)),
@@ -51,8 +51,9 @@ namespace QuantConnect.Algorithm.CSharp
QuantConnect.Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)),
Resolution.Minute).Symbol;
// Get option contract lists for 2020/01/05 (Time.AddDays(1)) because Lean has local data for that date
var optionChains = OptionChainProvider.GetOptionContractList(_es20h20, Time.AddDays(1))
.Concat(OptionChainProvider.GetOptionContractList(_es19m20, Time));
.Concat(OptionChainProvider.GetOptionContractList(_es19m20, Time.AddDays(1)));
foreach (var optionContract in optionChains)
{
@@ -163,7 +164,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 210329;
public long DataPoints => 311879;
/// <summary>
/// Data Points count of the algorithm history
@@ -178,31 +179,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "116.059%"},
{"Drawdown", "0.600%"},
{"Compounding Annual Return", "5512.811%"},
{"Drawdown", "1.000%"},
{"Expectancy", "0"},
{"Net Profit", "0.635%"},
{"Sharpe Ratio", "17.16"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Net Profit", "5.333%"},
{"Sharpe Ratio", "64.137"},
{"Probabilistic Sharpe Ratio", "95.977%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "2.25"},
{"Beta", "-1.665"},
{"Annual Standard Deviation", "0.071"},
{"Annual Variance", "0.005"},
{"Information Ratio", "5.319"},
{"Tracking Error", "0.114"},
{"Treynor Ratio", "-0.735"},
{"Total Fees", "$7.40"},
{"Estimated Strategy Capacity", "$24000000.00"},
{"Alpha", "25.72"},
{"Beta", "2.914"},
{"Annual Standard Deviation", "0.423"},
{"Annual Variance", "0.179"},
{"Information Ratio", "66.11"},
{"Tracking Error", "0.403"},
{"Treynor Ratio", "9.315"},
{"Total Fees", "$8.60"},
{"Estimated Strategy Capacity", "$22000000.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", "2.133"},
{"Portfolio Turnover", "2.035"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -216,7 +217,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "35738733ff791eeeaf508faec804cab0"}
{"OrderListHash", "e7021bd385f366771ae00abd3a46a22e"}
};
}
}

View File

@@ -93,7 +93,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 46583;
public long DataPoints => 12164;
/// <summary>
/// Data Points count of the algorithm history
@@ -108,31 +108,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "20"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-47.647%"},
{"Drawdown", "3.200%"},
{"Compounding Annual Return", "386219349.202%"},
{"Drawdown", "5.200%"},
{"Expectancy", "0"},
{"Net Profit", "-0.530%"},
{"Sharpe Ratio", "-8.194"},
{"Net Profit", "11.912%"},
{"Sharpe Ratio", "1604181.92"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-1.345"},
{"Beta", "1.391"},
{"Annual Standard Deviation", "0.06"},
{"Annual Variance", "0.004"},
{"Information Ratio", "-66.031"},
{"Tracking Error", "0.017"},
{"Treynor Ratio", "-0.351"},
{"Total Fees", "$37.00"},
{"Estimated Strategy Capacity", "$3400000.00"},
{"Alpha", "2144881.34"},
{"Beta", "31.223"},
{"Annual Standard Deviation", "1.337"},
{"Annual Variance", "1.788"},
{"Information Ratio", "1657259.526"},
{"Tracking Error", "1.294"},
{"Treynor Ratio", "68696.045"},
{"Total Fees", "$35.70"},
{"Estimated Strategy Capacity", "$2600000.00"},
{"Lowest Capacity Asset", "ES 31C3JQS9D84PW|ES XCZJLC9NOB29"},
{"Fitness Score", "0.5"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-94.467"},
{"Portfolio Turnover", "5.578"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -146,7 +146,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "7fbb8c0a1f5eee780f0b37efafbbdc4b"}
{"OrderListHash", "64221a660525c4259d5bd852eef1299c"}
};
}
}

View File

@@ -43,7 +43,7 @@ namespace QuantConnect.Algorithm.CSharp
public override void Initialize()
{
SetStartDate(2020, 1, 4);
SetEndDate(2020, 1, 6);
SetEndDate(2020, 1, 8);
_es = AddFuture(Futures.Indices.SP500EMini, Resolution.Minute, Market.CME);
_es.SetFilter((futureFilter) =>
@@ -164,8 +164,6 @@ namespace QuantConnect.Algorithm.CSharp
public override void OnEndOfAlgorithm()
{
base.OnEndOfAlgorithm();
if (!_optionFilterRan)
{
throw new InvalidOperationException("Option chain filter was never ran");
@@ -222,7 +220,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 779544;
public long DataPoints => 608437;
/// <summary>
/// Data Points count of the algorithm history
@@ -237,31 +235,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-10.708%"},
{"Drawdown", "0.200%"},
{"Compounding Annual Return", "347.065%"},
{"Drawdown", "0.900%"},
{"Expectancy", "0"},
{"Net Profit", "-0.093%"},
{"Sharpe Ratio", "-10.594"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Net Profit", "1.951%"},
{"Sharpe Ratio", "15.548"},
{"Probabilistic Sharpe Ratio", "95.977%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.261"},
{"Beta", "0.244"},
{"Annual Standard Deviation", "0.01"},
{"Annual Variance", "0"},
{"Information Ratio", "-22.456"},
{"Tracking Error", "0.032"},
{"Treynor Ratio", "-0.454"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$41000.00"},
{"Lowest Capacity Asset", "ES 31C3JQTOYO9T0|ES XCZJLC9NOB29"},
{"Fitness Score", "0.273"},
{"Alpha", "1.885"},
{"Beta", "1.066"},
{"Annual Standard Deviation", "0.155"},
{"Annual Variance", "0.024"},
{"Information Ratio", "13.528"},
{"Tracking Error", "0.142"},
{"Treynor Ratio", "2.258"},
{"Total Fees", "$3.57"},
{"Estimated Strategy Capacity", "$760000.00"},
{"Lowest Capacity Asset", "ES XCZJLDQX2SRO|ES XCZJLC9NOB29"},
{"Fitness Score", "0.403"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-123.159"},
{"Portfolio Turnover", "0.547"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0.403"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -275,7 +273,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "9347e3b610cfa21f7cbd968a0135c8af"}
{"OrderListHash", "738240babf741f1bf79f85ea5026ec4c"}
};
}
}

View File

@@ -0,0 +1,147 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Algorithm asserting that using OnlyApplyFilterAtMarketOpen along with other dynamic filters will make the filters be applied only on market
/// open, regardless of the order of configuration of the filters
/// </summary>
public class AddOptionWithOnMarketOpenOnlyFilterRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2014, 6, 5);
SetEndDate(2014, 6, 10);
// OnlyApplyFilterAtMarketOpen as first filter
AddOption("AAPL", Resolution.Minute).SetFilter(u =>
u.OnlyApplyFilterAtMarketOpen()
.Strikes(-5, 5)
.Expiration(0, 100)
.IncludeWeeklys());
// OnlyApplyFilterAtMarketOpen as last filter
AddOption("TWX", Resolution.Minute).SetFilter(u =>
u.Strikes(-5, 5)
.Expiration(0, 100)
.IncludeWeeklys()
.OnlyApplyFilterAtMarketOpen());
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
// This will be the first call, the underlying securities are added.
if (changes.AddedSecurities.All(s => s.Type != SecurityType.Option))
{
return;
}
var changeOptions = changes.AddedSecurities.Concat(changes.RemovedSecurities)
.Where(s => s.Type == SecurityType.Option);
// Susbtract one minute to get the actual market open. If market open is at 9:30am, this will be invoked at 9:31am
var expectedTime = Time.TimeOfDay - TimeSpan.FromMinutes(1);
var allOptionsWereChangedOnMarketOpen = changeOptions.All(s =>
{
var firstMarketSegment = s.Exchange.Hours.MarketHours[Time.DayOfWeek].Segments
.First(segment => segment.State == MarketHoursState.Market);
return firstMarketSegment.Start == expectedTime;
});
if (!allOptionsWereChangedOnMarketOpen)
{
throw new Exception("Expected options filter to be run only on market open");
}
}
/// <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>
/// Data Points count of all time slices of algorithm
/// </summary>
public long DataPoints => 3338420;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <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", "-10.144"},
{"Tracking Error", "0.033"},
{"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

@@ -31,7 +31,7 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
/// A number of companies publicly trade two different classes of shares
/// in US equity markets. If both assets trade with reasonable volume, then
/// the underlying driving forces of each should be similar or the same. Given
/// this, we can create a relatively dollar-netural long/short portfolio using
/// this, we can create a relatively dollar-neutral long/short portfolio using
/// the dual share classes. Theoretically, any deviation of this portfolio from
/// its mean-value should be corrected, and so the motivating idea is based on
/// mean-reversion. Using a Simple Moving Average indicator, we can

View File

@@ -109,7 +109,7 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
int barsToConsolidate = 1
)
{
// coefficient that used to determinte upper and lower borders of a breakout channel
// coefficient that used to determine upper and lower borders of a breakout channel
_k1 = k1;
_k2 = k2;
@@ -202,7 +202,7 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
SymbolData symbolData;
if (_symbolDataBySymbol.TryGetValue(removed.Symbol, out symbolData))
{
// unsibscribe consolidator from data updates
// unsubscribe consolidator from data updates
algorithm.SubscriptionManager.RemoveConsolidator(removed.Symbol, symbolData.GetConsolidator());
// remove item from dictionary collection

View File

@@ -34,8 +34,8 @@ namespace QuantConnect.Algorithm.CSharp
{
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
EnableAutomaticIndicatorWarmUp = true;
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 09);
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 10);
var SP500 = QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME);
_symbol = FutureChainProvider.GetFutureContractList(SP500, StartDate).First();
@@ -146,7 +146,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 14531;
public long DataPoints => 6426;
/// <summary>
/// Data Points count of the algorithm history
@@ -161,31 +161,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "19.800%"},
{"Compounding Annual Return", "733913.744%"},
{"Drawdown", "15.900%"},
{"Expectancy", "0"},
{"Net Profit", "-10.353%"},
{"Sharpe Ratio", "-1.379"},
{"Net Profit", "6.828%"},
{"Sharpe Ratio", "203744786353.302"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "3.004"},
{"Beta", "5.322"},
{"Annual Standard Deviation", "0.725"},
{"Annual Variance", "0.525"},
{"Information Ratio", "-0.42"},
{"Tracking Error", "0.589"},
{"Treynor Ratio", "-0.188"},
{"Total Fees", "$20.35"},
{"Estimated Strategy Capacity", "$13000000.00"},
{"Alpha", "456382350698.561"},
{"Beta", "9.229"},
{"Annual Standard Deviation", "2.24"},
{"Annual Variance", "5.017"},
{"Information Ratio", "228504036840.953"},
{"Tracking Error", "1.997"},
{"Treynor Ratio", "49450701625.718"},
{"Total Fees", "$23.65"},
{"Estimated Strategy Capacity", "$200000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.125"},
{"Fitness Score", "0.518"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-2.162"},
{"Return Over Maximum Drawdown", "-8.144"},
{"Portfolio Turnover", "3.184"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-7.708"},
{"Portfolio Turnover", "5.277"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -199,7 +199,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "7ff48adafe9676f341e64ac9388d3c2c"}
{"OrderListHash", "dd38e7b94027d20942a5aa9ac31a9a7f"}
};
}
}

View File

@@ -83,7 +83,8 @@ namespace QuantConnect.Algorithm.CSharp
Liquidate();
}
if (_currentContract != null && _currentContract.Symbol != _continuousContract.Mapped)
// We check exchange hours because the contract mapping can call OnData outside of regular hours.
if (_currentContract != null && _currentContract.Symbol != _continuousContract.Mapped && _continuousContract.Exchange.ExchangeOpen)
{
Log($"{Time} - rolling position from {_currentContract.Symbol} to {_continuousContract.Mapped}");
@@ -117,7 +118,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 875590;
public long DataPoints => 284403;
/// <summary>
/// Data Points count of the algorithm history
@@ -132,30 +133,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.02%"},
{"Compounding Annual Return", "-0.032%"},
{"Compounding Annual Return", "-0.033%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.016%"},
{"Net Profit", "-0.017%"},
{"Sharpe Ratio", "-1.173"},
{"Probabilistic Sharpe Ratio", "0.011%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0"},
{"Beta", "0"},
{"Beta", "-0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.753"},
{"Information Ratio", "-2.752"},
{"Tracking Error", "0.082"},
{"Treynor Ratio", "-8.269"},
{"Total Fees", "$3.70"},
{"Treynor Ratio", "1.883"},
{"Total Fees", "$4.30"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.006"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-1.985"},
{"Return Over Maximum Drawdown", "-1.993"},
{"Portfolio Turnover", "0.01"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -170,7 +171,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "d5bb3821a9a78b9fbef422c0f6bb6b4c"}
{"OrderListHash", "1fd4b49e9450800981c6dead2bbca995"}
};
}
}

View File

@@ -0,0 +1,182 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Indicators;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
using Futures = QuantConnect.Securities.Futures;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Basic Continuous Futures Template Algorithm with extended market hours
/// </summary>
public class BasicTemplateContinuousFutureWithExtendedMarketAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Future _continuousContract;
private Security _currentContract;
private SimpleMovingAverage _fast;
private SimpleMovingAverage _slow;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 7, 1);
SetEndDate(2014, 1, 1);
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
dataMappingMode: DataMappingMode.LastTradingDay,
contractDepthOffset: 0,
extendedMarketHours: true
);
_fast = SMA(_continuousContract.Symbol, 3, Resolution.Daily);
_slow = SMA(_continuousContract.Symbol, 10, Resolution.Daily);
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
foreach (var changedEvent in data.SymbolChangedEvents.Values)
{
Debug($"{Time} - SymbolChanged event: {changedEvent}");
if (Time.TimeOfDay != TimeSpan.Zero)
{
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
if (!IsMarketOpen(_continuousContract.Symbol))
{
return;
}
if (!Portfolio.Invested)
{
if(_fast > _slow)
{
_currentContract = Securities[_continuousContract.Mapped];
Buy(_currentContract.Symbol, 1);
}
}
else if(_fast < _slow)
{
Liquidate();
}
if (_currentContract != null && _currentContract.Symbol != _continuousContract.Mapped)
{
Log($"{Time} - rolling position from {_currentContract.Symbol} to {_continuousContract.Mapped}");
var currentPositionSize = _currentContract.Holdings.Quantity;
Liquidate(_currentContract.Symbol);
Buy(_continuousContract.Mapped, currentPositionSize);
_currentContract = Securities[_continuousContract.Mapped];
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
Debug($"{orderEvent}");
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
Debug($"{Time}-{changes}");
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 884815;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <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.02%"},
{"Compounding Annual Return", "-0.033%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.017%"},
{"Sharpe Ratio", "-1.173"},
{"Probabilistic Sharpe Ratio", "0.011%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0"},
{"Beta", "-0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.752"},
{"Tracking Error", "0.082"},
{"Treynor Ratio", "1.883"},
{"Total Fees", "$4.30"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.006"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-1.985"},
{"Portfolio Turnover", "0.01"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "adb237703e65b93da5961c0085109732"}
};
}
}

View File

@@ -59,7 +59,7 @@ namespace QuantConnect.Algorithm.CSharp
// 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
// The following statements yield the same filtering criteria
futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
futureGold.SetFilter(0, 182);
@@ -151,46 +151,46 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 203367;
public long DataPoints => 68645;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 518;
public int AlgorithmHistoryDataPoints => 340;
/// <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", "8186"},
{"Total Trades", "2700"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "13.100%"},
{"Expectancy", "-0.817"},
{"Net Profit", "-13.059%"},
{"Sharpe Ratio", "-22.436"},
{"Compounding Annual Return", "-99.777%"},
{"Drawdown", "4.400%"},
{"Expectancy", "-0.724"},
{"Net Profit", "-4.430%"},
{"Sharpe Ratio", "-31.389"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "89%"},
{"Win Rate", "11%"},
{"Profit-Loss Ratio", "0.69"},
{"Alpha", "1.976"},
{"Beta", "-0.184"},
{"Annual Standard Deviation", "0.045"},
{"Annual Variance", "0.002"},
{"Information Ratio", "-59.896"},
{"Tracking Error", "0.287"},
{"Treynor Ratio", "5.445"},
{"Total Fees", "$15144.10"},
{"Estimated Strategy Capacity", "$130000.00"},
{"Loss Rate", "83%"},
{"Win Rate", "17%"},
{"Profit-Loss Ratio", "0.65"},
{"Alpha", "-3.059"},
{"Beta", "0.128"},
{"Annual Standard Deviation", "0.031"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-81.232"},
{"Tracking Error", "0.212"},
{"Treynor Ratio", "-7.618"},
{"Total Fees", "$6237.00"},
{"Estimated Strategy Capacity", "$14000.00"},
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
{"Fitness Score", "0.028"},
{"Fitness Score", "0.001"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-10.138"},
{"Return Over Maximum Drawdown", "-8.192"},
{"Portfolio Turnover", "299.379"},
{"Sortino Ratio", "-58.725"},
{"Return Over Maximum Drawdown", "-32.073"},
{"Portfolio Turnover", "98.477"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -204,7 +204,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "fbf8650f2a4f433563f37f44c59cfa0d"}
{"OrderListHash", "8f92e1528c6477a156449fd1e86527e7"}
};
}
}

View File

@@ -19,7 +19,9 @@ using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
namespace QuantConnect.Algorithm.CSharp
{
@@ -31,14 +33,16 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="futures" />
public class BasicTemplateFuturesDailyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _contractSymbol;
protected virtual Resolution Resolution => Resolution.Daily;
protected virtual bool ExtendedMarketHours => false;
// S&P 500 EMini futures
private const string RootSP500 = Futures.Indices.SP500EMini;
// Gold futures
private const string RootGold = Futures.Metals.Gold;
private Future _futureSP500;
private Future _futureGold;
/// <summary>
/// Initialize your algorithm and add desired assets.
@@ -49,14 +53,14 @@ namespace QuantConnect.Algorithm.CSharp
SetEndDate(2014, 10, 10);
SetCash(1000000);
var futureSP500 = AddFuture(RootSP500, Resolution);
var futureGold = AddFuture(RootGold, Resolution);
_futureSP500 = AddFuture(RootSP500, Resolution, extendedMarketHours: ExtendedMarketHours);
_futureGold = AddFuture(RootGold, Resolution, extendedMarketHours: ExtendedMarketHours);
// 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);
_futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
_futureGold.SetFilter(0, 182);
}
/// <summary>
@@ -76,16 +80,17 @@ namespace QuantConnect.Algorithm.CSharp
select futuresContract
).FirstOrDefault();
// if found and exchange is open, trade it. Exchange could be closed, for example for a bar after 6:00pm on a friday, when futures
// markets are closed.
if (contract != null && Securities[contract.Symbol].Exchange.ExchangeOpen)
// if found, trade it.
// Also check if exchange is open for regular or extended hours. Since daily data comes at 8PM, this allows us prevent the
// algorithm from trading on friday when there is not after-market.
if (contract != null && Securities[contract.Symbol].Exchange.Hours.IsOpen(Time, true))
{
_contractSymbol = contract.Symbol;
MarketOrder(_contractSymbol, 1);
MarketOrder(contract.Symbol, 1);
}
}
}
else
// Same as above, check for cases like trading on a friday night.
else if (Securities.Values.Where(x => x.Invested).All(x => x.Exchange.Hours.IsOpen(Time, true)))
{
Liquidate();
}
@@ -112,7 +117,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 13559;
public virtual long DataPoints => 11709;
/// <summary>
/// Data Points count of the algorithm history
@@ -124,34 +129,34 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "152"},
{"Total Trades", "118"},
{"Average Win", "0.09%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-0.638%"},
{"Drawdown", "0.600%"},
{"Expectancy", "-0.871"},
{"Net Profit", "-0.643%"},
{"Sharpe Ratio", "-2.323"},
{"Compounding Annual Return", "-0.479%"},
{"Drawdown", "0.500%"},
{"Expectancy", "-0.835"},
{"Net Profit", "-0.483%"},
{"Sharpe Ratio", "-1.938"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "99%"},
{"Win Rate", "1%"},
{"Profit-Loss Ratio", "8.83"},
{"Alpha", "-0.004"},
{"Loss Rate", "98%"},
{"Win Rate", "2%"},
{"Profit-Loss Ratio", "8.76"},
{"Alpha", "-0.003"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.408"},
{"Information Ratio", "-1.397"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "3.612"},
{"Total Fees", "$281.20"},
{"Treynor Ratio", "5.665"},
{"Total Fees", "$263.30"},
{"Estimated Strategy Capacity", "$1000.00"},
{"Lowest Capacity Asset", "ES VRJST036ZY0X"},
{"Fitness Score", "0.013"},
{"Fitness Score", "0.01"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-1.45"},
{"Sortino Ratio", "-1.059"},
{"Return Over Maximum Drawdown", "-0.992"},
{"Portfolio Turnover", "0.04"},
{"Portfolio Turnover", "0.031"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -165,7 +170,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "48bfc4d255420cb589e00cf582554e0a"}
{"OrderListHash", "b75b224669c374dcbacc33f946a1cc7c"}
};
}
}

View File

@@ -31,9 +31,12 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public class BasicTemplateFuturesFrameworkAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected virtual bool ExtendedMarketHours => false;
public override void Initialize()
{
UniverseSettings.Resolution = Resolution.Minute;
UniverseSettings.ExtendedMarketHours = ExtendedMarketHours;
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);
@@ -123,70 +126,70 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
public virtual bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 123378;
public virtual long DataPoints => 43786;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-92.656%"},
{"Drawdown", "5.000%"},
{"Compounding Annual Return", "-81.734%"},
{"Drawdown", "4.100%"},
{"Expectancy", "0"},
{"Net Profit", "-3.312%"},
{"Sharpe Ratio", "-6.305"},
{"Probabilistic Sharpe Ratio", "9.342%"},
{"Net Profit", "-2.169%"},
{"Sharpe Ratio", "-10.195"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-1.465"},
{"Beta", "0.312"},
{"Annual Standard Deviation", "0.134"},
{"Annual Variance", "0.018"},
{"Information Ratio", "-14.77"},
{"Tracking Error", "0.192"},
{"Treynor Ratio", "-2.718"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$52000000.00"},
{"Alpha", "-1.206"},
{"Beta", "0.238"},
{"Annual Standard Deviation", "0.072"},
{"Annual Variance", "0.005"},
{"Information Ratio", "-15.404"},
{"Tracking Error", "0.176"},
{"Treynor Ratio", "-3.077"},
{"Total Fees", "$4.62"},
{"Estimated Strategy Capacity", "$17000000.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"},
{"Long Insight Count", "6"},
{"Fitness Score", "0.006"},
{"Kelly Criterion Estimate", "-50.022"},
{"Kelly Criterion Probability Value", "0.711"},
{"Sortino Ratio", "-9.907"},
{"Return Over Maximum Drawdown", "-50.79"},
{"Portfolio Turnover", "0.54"},
{"Total Insights Generated", "5"},
{"Total Insights Closed", "4"},
{"Total Insights Analysis Completed", "4"},
{"Long Insight Count", "5"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$-96.12923"},
{"Total Accumulated Estimated Alpha Value", "$-15.621"},
{"Mean Population Estimated Insight Value", "$-3.1242"},
{"Mean Population Direction", "0%"},
{"Estimated Monthly Alpha Value", "$-4434.791"},
{"Total Accumulated Estimated Alpha Value", "$-720.6535"},
{"Mean Population Estimated Insight Value", "$-180.1634"},
{"Mean Population Direction", "25%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Direction", "25%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "18ffd3a774c68da83d867e3b09e3e05d"}
{"OrderListHash", "323b899ae80aa839e320806411665ce7"}
};
}
}

View File

@@ -0,0 +1,95 @@
/*
* 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.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Basic template futures framework algorithm uses framework components to define an algorithm
/// that trades futures.
/// </summary>
public class BasicTemplateFuturesFrameworkWithExtendedMarketAlgorithm : BasicTemplateFuturesFrameworkAlgorithm
{
protected override bool ExtendedMarketHours => true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 123753;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-92.667%"},
{"Drawdown", "5.000%"},
{"Expectancy", "0"},
{"Net Profit", "-3.314%"},
{"Sharpe Ratio", "-6.303"},
{"Probabilistic Sharpe Ratio", "9.333%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-1.465"},
{"Beta", "0.312"},
{"Annual Standard Deviation", "0.134"},
{"Annual Variance", "0.018"},
{"Information Ratio", "-14.77"},
{"Tracking Error", "0.192"},
{"Treynor Ratio", "-2.718"},
{"Total Fees", "$4.62"},
{"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.421"},
{"Return Over Maximum Drawdown", "-35.2"},
{"Portfolio Turnover", "0.548"},
{"Total Insights Generated", "6"},
{"Total Insights Closed", "5"},
{"Total Insights Analysis Completed", "5"},
{"Long Insight Count", "6"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$-96.12923"},
{"Total Accumulated Estimated Alpha Value", "$-15.621"},
{"Mean Population Estimated Insight Value", "$-3.1242"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "18ffd3a774c68da83d867e3b09e3e05d"}
};
}
}

View File

@@ -36,6 +36,9 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="futures" />
public class BasicTemplateFuturesHistoryAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected virtual bool ExtendedMarketHours => false;
protected virtual int ExpectedHistoryCallCount => 42;
// S&P 500 EMini futures
private string [] roots = new []
{
@@ -44,7 +47,6 @@ namespace QuantConnect.Algorithm.CSharp
};
private int _successCount = 0;
public override void Initialize()
{
SetStartDate(2013, 10, 8);
@@ -54,7 +56,7 @@ namespace QuantConnect.Algorithm.CSharp
foreach (var root in roots)
{
// set our expiry filter for this futures chain
AddFuture(root, Resolution.Minute).SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
AddFuture(root, Resolution.Minute, extendedMarketHours: ExtendedMarketHours).SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
}
SetBenchmark(d => 1000000);
@@ -74,7 +76,7 @@ namespace QuantConnect.Algorithm.CSharp
public override void OnEndOfAlgorithm()
{
if (_successCount < 49)
if (_successCount < ExpectedHistoryCallCount)
{
throw new Exception($"Scheduled Event did not assert history call as many times as expected: {_successCount}/49");
}
@@ -118,7 +120,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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>
/// <param name="orderEvent">Order event details containing details of the events</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)
{
@@ -128,27 +130,27 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
public virtual bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 133616;
public virtual long DataPoints => 44184;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 5539;
public virtual int AlgorithmHistoryDataPoints => 4818;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},

View File

@@ -0,0 +1,106 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to get access to futures history for a given root symbol with extended market hours.
/// It also shows how you can prefilter contracts easily based on expirations, and inspect the futures
/// chain to pick a specific contract to trade.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="history and warm up" />
/// <meta name="tag" content="history" />
/// <meta name="tag" content="futures" />
public class BasicTemplateFuturesHistoryWithExtendedMarketHoursAlgorithm : BasicTemplateFuturesHistoryAlgorithm
{
protected override bool ExtendedMarketHours => true;
protected override int ExpectedHistoryCallCount => 49;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 134096;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 5539;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "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

@@ -31,14 +31,8 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="futures" />
public class BasicTemplateFuturesHourlyAlgorithm : BasicTemplateFuturesDailyAlgorithm
{
private Symbol _contractSymbol;
protected override Resolution Resolution => Resolution.Hour;
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public override bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
@@ -47,46 +41,41 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 205645;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 0;
public override long DataPoints => 73252;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1982"},
{"Average Win", "0.01%"},
{"Total Trades", "638"},
{"Average Win", "0.02%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-4.581%"},
{"Drawdown", "4.600%"},
{"Expectancy", "-0.910"},
{"Net Profit", "-4.615%"},
{"Sharpe Ratio", "-5.78"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "97%"},
{"Win Rate", "3%"},
{"Profit-Loss Ratio", "2.09"},
{"Alpha", "-0.03"},
{"Beta", "-0.008"},
{"Annual Standard Deviation", "0.005"},
{"Compounding Annual Return", "-1.610%"},
{"Drawdown", "1.600%"},
{"Expectancy", "-0.841"},
{"Net Profit", "-1.622%"},
{"Sharpe Ratio", "-5.105"},
{"Probabilistic Sharpe Ratio", "0.000%"},
{"Loss Rate", "96%"},
{"Win Rate", "4%"},
{"Profit-Loss Ratio", "3.21"},
{"Alpha", "-0.01"},
{"Beta", "-0.003"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.694"},
{"Tracking Error", "0.09"},
{"Treynor Ratio", "4.084"},
{"Total Fees", "$3666.70"},
{"Estimated Strategy Capacity", "$2000.00"},
{"Information Ratio", "-1.473"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "3.179"},
{"Total Fees", "$1456.18"},
{"Estimated Strategy Capacity", "$6000.00"},
{"Lowest Capacity Asset", "ES VP274HSU1AF5"},
{"Fitness Score", "0.131"},
{"Fitness Score", "0.045"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-6.174"},
{"Return Over Maximum Drawdown", "-0.995"},
{"Portfolio Turnover", "0.649"},
{"Sortino Ratio", "-4.326"},
{"Return Over Maximum Drawdown", "-0.994"},
{"Portfolio Turnover", "0.205"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -100,7 +89,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "2402a307b20aee195b77b8478d7ca64d"}
{"OrderListHash", "8842e0b890f721371ebf3c25328dee5b"}
};
}
}

View File

@@ -0,0 +1,210 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to add futures for a given underlying asset.
/// It also shows how you can prefilter contracts easily based on expirations, and how you
/// can inspect the futures chain to pick a specific contract to trade.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="benchmarks" />
/// <meta name="tag" content="futures" />
public class BasicTemplateFuturesWithExtendedMarketAlgorithm : 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);
// Gold futures
private const string RootGold = Futures.Metals.Gold;
public Symbol Gold = QuantConnect.Symbol.Create(RootGold, SecurityType.Future, Market.COMEX);
/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 10);
SetCash(1000000);
var futureSP500 = AddFuture(RootSP500, extendedMarketHours: true);
var futureGold = AddFuture(RootGold, extendedMarketHours: true);
// 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);
var benchmark = AddEquity("SPY");
SetBenchmark(benchmark.Symbol);
var seeder = new FuncSecuritySeeder(GetLastKnownPrices);
SetSecurityInitializer(security => seeder.SeedSecurity(security));
}
/// <summary>
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
/// </summary>
/// <param name="slice">The current slice of data keyed by symbol string</param>
public override void OnData(Slice slice)
{
foreach (var changedEvent in slice.SymbolChangedEvents.Values)
{
Debug($"{Time} - SymbolChanged event: {changedEvent}");
if (Time.TimeOfDay != TimeSpan.Zero)
{
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
if (!Portfolio.Invested)
{
foreach(var chain in slice.FutureChains)
{
// find the front contract expiring no earlier than in 90 days
var contract = (
from futuresContract in chain.Value.OrderBy(x => x.Expiry)
where futuresContract.Expiry > Time.Date.AddDays(90)
select futuresContract
).FirstOrDefault();
// if found, trade it
if (contract != null)
{
_contractSymbol = contract.Symbol;
MarketOrder(_contractSymbol, 1);
}
}
}
else
{
Liquidate();
}
}
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;
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var addedSecurity in changes.AddedSecurities)
{
if (addedSecurity.Symbol.SecurityType == SecurityType.Future
&& !addedSecurity.Symbol.IsCanonical()
&& !addedSecurity.HasData)
{
throw new Exception($"Future contracts did not work up as expected: {addedSecurity.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; } = 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>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 204087;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 340;
/// <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", "8282"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "13.900%"},
{"Expectancy", "-0.824"},
{"Net Profit", "-13.874%"},
{"Sharpe Ratio", "-19.202"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "89%"},
{"Win Rate", "11%"},
{"Profit-Loss Ratio", "0.64"},
{"Alpha", "2.477"},
{"Beta", "-0.215"},
{"Annual Standard Deviation", "0.052"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-58.37"},
{"Tracking Error", "0.295"},
{"Treynor Ratio", "4.66"},
{"Total Fees", "$19131.42"},
{"Estimated Strategy Capacity", "$130000.00"},
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
{"Fitness Score", "0.032"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-9.217"},
{"Return Over Maximum Drawdown", "-7.692"},
{"Portfolio Turnover", "304.869"},
{"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", "85cdd035d7c7a3da178d1c2dff31f1bd"}
};
}
}

View File

@@ -0,0 +1,97 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to add futures with daily resolution and extended market hours.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="benchmarks" />
/// <meta name="tag" content="futures" />
public class BasicTemplateFuturesWithExtendedMarketDailyAlgorithm : BasicTemplateFuturesDailyAlgorithm
{
protected override bool ExtendedMarketHours => true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 13559;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "152"},
{"Average Win", "0.09%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-0.644%"},
{"Drawdown", "0.600%"},
{"Expectancy", "-0.872"},
{"Net Profit", "-0.649%"},
{"Sharpe Ratio", "-2.343"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "99%"},
{"Win Rate", "1%"},
{"Profit-Loss Ratio", "8.76"},
{"Alpha", "-0.004"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.409"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "3.618"},
{"Total Fees", "$338.96"},
{"Estimated Strategy Capacity", "$1000.00"},
{"Lowest Capacity Asset", "ES VRJST036ZY0X"},
{"Fitness Score", "0.013"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-1.464"},
{"Return Over Maximum Drawdown", "-0.992"},
{"Portfolio Turnover", "0.04"},
{"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", "48bfc4d255420cb589e00cf582554e0a"}
};
}
}

View File

@@ -0,0 +1,95 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regressions tests the BasicTemplateFuturesDailyAlgorithm with hour data and extended market hours
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="benchmarks" />
/// <meta name="tag" content="futures" />
public class BasicTemplateFuturesWithExtendedMarketHourlyAlgorithm : BasicTemplateFuturesHourlyAlgorithm
{
protected override bool ExtendedMarketHours => true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 205645;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1982"},
{"Average Win", "0.01%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-4.666%"},
{"Drawdown", "4.700%"},
{"Expectancy", "-0.911"},
{"Net Profit", "-4.700%"},
{"Sharpe Ratio", "-5.792"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "97%"},
{"Win Rate", "3%"},
{"Profit-Loss Ratio", "2.04"},
{"Alpha", "-0.031"},
{"Beta", "-0.008"},
{"Annual Standard Deviation", "0.005"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.701"},
{"Tracking Error", "0.09"},
{"Treynor Ratio", "4.096"},
{"Total Fees", "$4521.78"},
{"Estimated Strategy Capacity", "$2000.00"},
{"Lowest Capacity Asset", "ES VP274HSU1AF5"},
{"Fitness Score", "0.131"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-6.211"},
{"Return Over Maximum Drawdown", "-0.995"},
{"Portfolio Turnover", "0.649"},
{"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", "2402a307b20aee195b77b8478d7ca64d"}
};
}
}

View File

@@ -43,13 +43,13 @@ namespace QuantConnect.Algorithm.CSharp
// Equities Resolutions: Tick, Second, Minute, Hour, Daily.
AddEquity("YESBANK", Resolution.Minute, Market.India);
//Set Order Prperties as per the requirements for order placement
//Set Order Properties as per the requirements for order placement
DefaultOrderProperties = new IndiaOrderProperties(exchange: Exchange.NSE);
//override default productType value set in config.json if needed - order specific productType value
//DefaultOrderProperties = new IndiaOrderProperties(exchange: Exchange.NSE, IndiaOrderProperties.IndiaProductType.CNC);
// General Debug statement for acknowledgement
Debug("Intialization Done");
Debug("Initialization Done");
}
/// <summary>

View File

@@ -52,7 +52,7 @@ namespace QuantConnect.Algorithm.CSharp
//Trade Index based ETF
NiftyETF = AddEquity("JUNIORBEES", Resolution.Minute, Market.India).Symbol;
//Set Order Prperties as per the requirements for order placement
//Set Order Properties as per the requirements for order placement
DefaultOrderProperties = new IndiaOrderProperties(exchange: Exchange.NSE);
_emaSlow = EMA(Nifty, 80);

View File

@@ -31,7 +31,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="trading and orders" />
public class BasicTemplateIntrinioEconomicData : QCAlgorithm
{
// Set your Intrinino user and password.
// Set your Intrinio user and password.
public string _user = "";
public string _password = "";
@@ -55,7 +55,7 @@ namespace QuantConnect.Algorithm.CSharp
SetEndDate(year: 2013, month: 12, day: 31); //Set End Date
SetCash(startingCash: 100000); //Set Strategy Cash
// Set your Intrinino user and password.
// Set your Intrinio user and password.
IntrinioConfig.SetUserAndPassword(_user, _password);
// Set Intrinio config to make 1 call each minute, default is 1 call each 5 seconds.

View File

@@ -212,7 +212,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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>
/// <param name="orderEvent">Order event details containing details of the events</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)
{

View File

@@ -82,7 +82,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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>
/// <param name="orderEvent">Order event details containing details of the events</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)
{
@@ -155,7 +155,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "82c29cc9db9a300074d6ff136253f4ac"}
{"OrderListHash", "0673d23c27fa8dd01da0aace0e866cc3"}
};
}
}

View File

@@ -92,7 +92,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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>
/// <param name="orderEvent">Order event details containing details of the events</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)
{

View File

@@ -87,7 +87,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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>
/// <param name="orderEvent">Order event details containing details of the events</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)
{

View File

@@ -89,7 +89,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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>
/// <param name="orderEvent">Order event details containing details of the events</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)
{

View File

@@ -81,7 +81,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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>
/// <param name="orderEvent">Order event details containing details of the events</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)
{

View File

@@ -89,7 +89,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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>
/// <param name="orderEvent">Order event details containing details of the events</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)
{

View File

@@ -51,7 +51,7 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
// define an indicator that takes the output of the sma and pipes it into our delay indicator
var delayedSma = delay.Of(sma);
// register our new 'delayedSma' for automaic updates on a daily resolution
// register our new 'delayedSma' for automatic updates on a daily resolution
RegisterIndicator(_spy, delayedSma, Resolution.Daily, data => data.Value);
return delayedSma;

View File

@@ -166,7 +166,7 @@ namespace QuantConnect.Algorithm.CSharp
}
}
// Cape Ratio is missing from orignial data
// Cape Ratio is missing from original data
// Most recent cape data is most likely to be missing
else if (_currCape == 0)
{
@@ -246,7 +246,7 @@ namespace QuantConnect.Algorithm.CSharp
}
/// <summary>
/// Reader Method :: using set of arguements we specify read out type. Enumerate
/// Reader Method :: using set of arguments we specify read out type. Enumerate
/// until the end of the data stream or file. E.g. Read CSV file line by line and convert
/// into data types.
/// </summary>

View File

@@ -40,7 +40,7 @@ namespace QuantConnect.Algorithm.CSharp
public override void Initialize()
{
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 09);
SetEndDate(2013, 10, 11);
var SP500 = QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME);
_symbol = FutureChainProvider.GetFutureContractList(SP500, StartDate).First();
@@ -142,7 +142,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 8091;
public long DataPoints => 5450;
/// <summary>
/// Data Points count of the algorithm history
@@ -157,31 +157,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Compounding Annual Return", "87589624.963%"},
{"Drawdown", "15.900%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Net Profit", "16.178%"},
{"Sharpe Ratio", "43229388091.465"},
{"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", "$20.35"},
{"Estimated Strategy Capacity", "$19000000.00"},
{"Alpha", "69177566862.121"},
{"Beta", "8.93"},
{"Annual Standard Deviation", "1.6"},
{"Annual Variance", "2.561"},
{"Information Ratio", "48583550955.512"},
{"Tracking Error", "1.424"},
{"Treynor Ratio", "7746445590.006"},
{"Total Fees", "$23.65"},
{"Estimated Strategy Capacity", "$210000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.138"},
{"Fitness Score", "0.999"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-1.727"},
{"Return Over Maximum Drawdown", "-12.061"},
{"Portfolio Turnover", "4.916"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "6752050.52"},
{"Portfolio Turnover", "2.638"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -195,7 +195,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "7c841ca58a4385f42236838e5bf0c382"}
{"OrderListHash", "dd38e7b94027d20942a5aa9ac31a9a7f"}
};
}
}

View File

@@ -134,7 +134,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 815242;
public long DataPoints => 264153;
/// <summary>
/// Data Points count of the algorithm history
@@ -147,32 +147,32 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "1.20%"},
{"Average Win", "1.50%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "2.387%"},
{"Compounding Annual Return", "2.993%"},
{"Drawdown", "1.600%"},
{"Expectancy", "0"},
{"Net Profit", "1.196%"},
{"Sharpe Ratio", "0.773"},
{"Probabilistic Sharpe Ratio", "40.221%"},
{"Net Profit", "1.496%"},
{"Sharpe Ratio", "0.814"},
{"Probabilistic Sharpe Ratio", "42.511%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.006"},
{"Beta", "0.099"},
{"Annual Standard Deviation", "0.022"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.726"},
{"Alpha", "-0.005"},
{"Beta", "0.114"},
{"Annual Standard Deviation", "0.026"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-2.672"},
{"Tracking Error", "0.076"},
{"Treynor Ratio", "0.169"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$810000000.00"},
{"Treynor Ratio", "0.184"},
{"Total Fees", "$4.30"},
{"Estimated Strategy Capacity", "$2200000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.007"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "0.581"},
{"Return Over Maximum Drawdown", "1.931"},
{"Sortino Ratio", "0.275"},
{"Return Over Maximum Drawdown", "2.603"},
{"Portfolio Turnover", "0.01"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -187,7 +187,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "9689ea5896706b2ce7e8aebd201de3f0"}
{"OrderListHash", "ebeeac4c57ccacef7b458b6160190f5b"}
};
}
}

View File

@@ -106,7 +106,7 @@ namespace QuantConnect.Algorithm.CSharp
else
{
Buy(_continuousContract.Mapped, 1);
}
}
}
if(Time.Month == 1 && Time.Year == 2013)
@@ -150,7 +150,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 875590;
public long DataPoints => 284403;
/// <summary>
/// Data Points count of the algorithm history
@@ -163,32 +163,32 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "1.20%"},
{"Average Win", "1.50%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "2.354%"},
{"Compounding Annual Return", "2.959%"},
{"Drawdown", "1.600%"},
{"Expectancy", "0"},
{"Net Profit", "1.180%"},
{"Sharpe Ratio", "0.763"},
{"Probabilistic Sharpe Ratio", "39.832%"},
{"Net Profit", "1.479%"},
{"Sharpe Ratio", "0.805"},
{"Probabilistic Sharpe Ratio", "42.183%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.006"},
{"Beta", "0.099"},
{"Annual Standard Deviation", "0.022"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.729"},
{"Alpha", "-0.005"},
{"Beta", "0.114"},
{"Annual Standard Deviation", "0.026"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-2.676"},
{"Tracking Error", "0.076"},
{"Treynor Ratio", "0.167"},
{"Total Fees", "$5.55"},
{"Estimated Strategy Capacity", "$67000000.00"},
{"Treynor Ratio", "0.181"},
{"Total Fees", "$6.45"},
{"Estimated Strategy Capacity", "$180000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.01"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "0.511"},
{"Return Over Maximum Drawdown", "1.905"},
{"Sortino Ratio", "0.32"},
{"Return Over Maximum Drawdown", "2.573"},
{"Portfolio Turnover", "0.016"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -203,7 +203,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "468572bbb8256bd47d381757b66da0d0"}
{"OrderListHash", "88e74055be58b3759f493b2c47e4c097"}
};
}
}

View File

@@ -114,7 +114,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 26112;
public virtual long DataPoints => 9949;
/// <summary>
/// Data Points count of the algorithm history
@@ -145,15 +145,15 @@ namespace QuantConnect.Algorithm.CSharp
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$290000000.00"},
{"Total Fees", "$2.15"},
{"Estimated Strategy Capacity", "$3600000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.408"},
{"Fitness Score", "0.414"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0.408"},
{"Portfolio Turnover", "0.414"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -167,7 +167,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "10cf3584cd0131898df3f19d26df0649"}
{"OrderListHash", "1fcd459f69177160b35f7daf96b01a0d"}
};
}
}

View File

@@ -34,6 +34,6 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 40881;
public override long DataPoints => 14915;
}
}

View File

@@ -78,7 +78,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 64065;
public long DataPoints => 19876;
/// <summary>
/// Data Points count of the algorithm history
@@ -93,31 +93,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-98.962%"},
{"Drawdown", "6.200%"},
{"Compounding Annual Return", "-99.258%"},
{"Drawdown", "6.300%"},
{"Expectancy", "0"},
{"Net Profit", "-6.066%"},
{"Sharpe Ratio", "-2.143"},
{"Probabilistic Sharpe Ratio", "32.231%"},
{"Net Profit", "-6.129%"},
{"Sharpe Ratio", "-2.182"},
{"Probabilistic Sharpe Ratio", "5.175%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.237"},
{"Beta", "-0.662"},
{"Annual Standard Deviation", "0.161"},
{"Annual Variance", "0.026"},
{"Information Ratio", "-1.265"},
{"Tracking Error", "0.403"},
{"Treynor Ratio", "0.523"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$710000000.00"},
{"Alpha", "-0.976"},
{"Beta", "-0.022"},
{"Annual Standard Deviation", "0.449"},
{"Annual Variance", "0.202"},
{"Information Ratio", "-2.231"},
{"Tracking Error", "0.513"},
{"Treynor Ratio", "43.626"},
{"Total Fees", "$2.15"},
{"Estimated Strategy Capacity", "$2600000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.018"},
{"Fitness Score", "0.028"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-2.218"},
{"Return Over Maximum Drawdown", "-16.972"},
{"Portfolio Turnover", "0.165"},
{"Sortino Ratio", "-1.662"},
{"Return Over Maximum Drawdown", "-18.253"},
{"Portfolio Turnover", "0.206"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -131,7 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "de931c9003e11617ffc012f9ee41093e"}
{"OrderListHash", "f0e1235ff2d29030e374d966b3e225fa"}
};
}
}

View File

@@ -169,7 +169,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 875590;
public long DataPoints => 284403;
/// <summary>
/// Data Points count of the algorithm history
@@ -182,32 +182,32 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "1.20%"},
{"Average Win", "1.50%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "2.354%"},
{"Compounding Annual Return", "2.959%"},
{"Drawdown", "1.600%"},
{"Expectancy", "0"},
{"Net Profit", "1.180%"},
{"Sharpe Ratio", "0.763"},
{"Probabilistic Sharpe Ratio", "39.832%"},
{"Net Profit", "1.479%"},
{"Sharpe Ratio", "0.805"},
{"Probabilistic Sharpe Ratio", "42.183%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.006"},
{"Beta", "0.099"},
{"Annual Standard Deviation", "0.022"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.729"},
{"Alpha", "-0.005"},
{"Beta", "0.114"},
{"Annual Standard Deviation", "0.026"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-2.676"},
{"Tracking Error", "0.076"},
{"Treynor Ratio", "0.167"},
{"Total Fees", "$5.55"},
{"Estimated Strategy Capacity", "$67000000.00"},
{"Treynor Ratio", "0.181"},
{"Total Fees", "$6.45"},
{"Estimated Strategy Capacity", "$180000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.01"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "0.511"},
{"Return Over Maximum Drawdown", "1.905"},
{"Sortino Ratio", "0.32"},
{"Return Over Maximum Drawdown", "2.573"},
{"Portfolio Turnover", "0.016"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -222,7 +222,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "468572bbb8256bd47d381757b66da0d0"}
{"OrderListHash", "88e74055be58b3759f493b2c47e4c097"}
};
}
}

View File

@@ -73,12 +73,12 @@ namespace QuantConnect.Algorithm.CSharp
|| filledEvent.FillQuantity != ticket.QuantityFilled
|| (0.1m - filledEvent.OrderFee.Value.Amount) != ticket.QuantityFilled)
{
throw new Exception($"Unexpected BaseCurrency porfoltio status. Event {filledEvent}. CashBook: {Portfolio.CashBook}. ");
throw new Exception($"Unexpected BaseCurrency portfolio status. Event {filledEvent}. CashBook: {Portfolio.CashBook}. ");
}
if (Portfolio.CashBook[quoteCurrency].Amount != (initialQuoteCurrency - 0.1m * filledEvent.FillPrice))
{
throw new Exception($"Unexpected QuoteCurrency porfoltio status. Event {filledEvent}. CashBook: {Portfolio.CashBook}. ");
throw new Exception($"Unexpected QuoteCurrency portfolio status. Event {filledEvent}. CashBook: {Portfolio.CashBook}. ");
}
if (Securities[_symbol].Holdings.Quantity != (0.1m - filledEvent.OrderFee.Value.Amount))

View File

@@ -92,6 +92,16 @@ namespace QuantConnect.Algorithm.CSharp
public decimal VolumeBTC = 0;
public decimal VolumeUSD = 0;
/// <summary>
/// The end time of this data. Some data covers spans (trade bars)
/// and as such we want to know the entire time span covered
/// </summary>
/// <remarks>
/// This property is overriden to allow different values for Time and EndTime
/// if they are set in the Reader. In the base implementation EndTime equals Time
/// </remarks>
public override DateTime EndTime { get; set; }
/// <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".

View File

@@ -109,7 +109,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 10489;
public long DataPoints => 10491;
/// <summary>
/// Data Points count of the algorithm history
@@ -124,30 +124,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "157.498%"},
{"Compounding Annual Return", "155.211%"},
{"Drawdown", "84.800%"},
{"Expectancy", "0"},
{"Net Profit", "5319.081%"},
{"Sharpe Ratio", "2.086"},
{"Probabilistic Sharpe Ratio", "69.456%"},
{"Net Profit", "5123.242%"},
{"Sharpe Ratio", "2.067"},
{"Probabilistic Sharpe Ratio", "68.833%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.747"},
{"Beta", "0.047"},
{"Annual Standard Deviation", "0.84"},
{"Annual Variance", "0.706"},
{"Information Ratio", "1.922"},
{"Alpha", "1.732"},
{"Beta", "0.043"},
{"Annual Standard Deviation", "0.841"},
{"Annual Variance", "0.707"},
{"Information Ratio", "1.902"},
{"Tracking Error", "0.848"},
{"Treynor Ratio", "37.47"},
{"Treynor Ratio", "40.467"},
{"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"},
{"Sortino Ratio", "2.236"},
{"Return Over Maximum Drawdown", "1.83"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -190,6 +190,16 @@ namespace QuantConnect.Algorithm.CSharp
public decimal VolumeBTC = 0;
public decimal VolumeUSD = 0;
/// <summary>
/// The end time of this data. Some data covers spans (trade bars)
/// and as such we want to know the entire time span covered
/// </summary>
/// <remarks>
/// This property is overriden to allow different values for Time and EndTime
/// if they are set in the Reader. In the base implementation EndTime equals Time
/// </remarks>
public override DateTime EndTime { get; set; }
/// <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".

View File

@@ -110,7 +110,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 8942;
public long DataPoints => 8943;
/// <summary>
/// Data Points count of the algorithm history
@@ -125,30 +125,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "157.655%"},
{"Compounding Annual Return", "155.365%"},
{"Drawdown", "84.800%"},
{"Expectancy", "0"},
{"Net Profit", "5319.007%"},
{"Sharpe Ratio", "2.123"},
{"Probabilistic Sharpe Ratio", "70.581%"},
{"Net Profit", "5123.170%"},
{"Sharpe Ratio", "2.103"},
{"Probabilistic Sharpe Ratio", "69.967%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.776"},
{"Beta", "0.059"},
{"Alpha", "1.76"},
{"Beta", "0.055"},
{"Annual Standard Deviation", "0.84"},
{"Annual Variance", "0.706"},
{"Information Ratio", "1.962"},
{"Tracking Error", "0.847"},
{"Treynor Ratio", "30.455"},
{"Information Ratio", "1.942"},
{"Tracking Error", "0.848"},
{"Treynor Ratio", "32.317"},
{"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.271"},
{"Return Over Maximum Drawdown", "1.86"},
{"Sortino Ratio", "2.238"},
{"Return Over Maximum Drawdown", "1.832"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -191,6 +191,16 @@ namespace QuantConnect.Algorithm.CSharp
public decimal VolumeBTC = 0;
public decimal VolumeUSD = 0;
/// <summary>
/// The end time of this data. Some data covers spans (trade bars)
/// and as such we want to know the entire time span covered
/// </summary>
/// <remarks>
/// This property is overriden to allow different values for Time and EndTime
/// if they are set in the Reader. In the base implementation EndTime equals Time
/// </remarks>
public override DateTime EndTime { get; set; }
/// <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".

View File

@@ -0,0 +1,126 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using QuantConnect.Data;
using QuantConnect.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm which tests the default option price model
/// </summary>
/// <meta name="tag" content="options" />
public class DefaultOptionPriceModelRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2015, 12, 24);
SetEndDate(2015, 12, 24);
SetCash(100000);
AddEquity("SPY");
AddOption("SPY");
AddIndex("SPX");
AddIndexOption("SPX");
}
public override void OnData(Slice slice)
{
if (slice.OptionChains.Any(kvp => kvp.Value.Any(
contract => contract.Greeks.Delta == 0 &&
contract.Greeks.Gamma == 0 &&
contract.Greeks.Theta == 0 &&
contract.Greeks.Vega == 0 &&
contract.Greeks.Rho == 0)))
{
throw new Exception("All Greeks are zero - Pricing Model is not ready!");
}
}
/// <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>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 13;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <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", "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", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -28,7 +28,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 1637;
public override long DataPoints => 1450;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
@@ -38,30 +38,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "2"},
{"Average Win", "7.78%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "38.034%"},
{"Drawdown", "1.000%"},
{"Compounding Annual Return", "38.033%"},
{"Drawdown", "0.200%"},
{"Expectancy", "0"},
{"Net Profit", "7.779%"},
{"Sharpe Ratio", "2.639"},
{"Probabilistic Sharpe Ratio", "93.699%"},
{"Sharpe Ratio", "3.2"},
{"Probabilistic Sharpe Ratio", "99.459%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.206"},
{"Beta", "0.13"},
{"Annual Standard Deviation", "0.098"},
{"Annual Variance", "0.01"},
{"Information Ratio", "-1.152"},
{"Tracking Error", "0.121"},
{"Treynor Ratio", "1.981"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$62000000000.00"},
{"Alpha", "0.149"},
{"Beta", "0.271"},
{"Annual Standard Deviation", "0.08"},
{"Annual Variance", "0.006"},
{"Information Ratio", "-1.446"},
{"Tracking Error", "0.098"},
{"Treynor Ratio", "0.946"},
{"Total Fees", "$2.15"},
{"Estimated Strategy Capacity", "$60000000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.018"},
{"Fitness Score", "0.019"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "4.641"},
{"Return Over Maximum Drawdown", "39.421"},
{"Sortino Ratio", "28.065"},
{"Return Over Maximum Drawdown", "246.484"},
{"Portfolio Turnover", "0.019"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},

View File

@@ -92,7 +92,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 1224778;
public virtual long DataPoints => 398985;
/// <summary>
/// Data Points count of the algorithm history
@@ -105,32 +105,32 @@ namespace QuantConnect.Algorithm.CSharp
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "1.64%"},
{"Average Win", "1.48%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "7.329%"},
{"Compounding Annual Return", "6.608%"},
{"Drawdown", "1.300%"},
{"Expectancy", "0"},
{"Net Profit", "1.642%"},
{"Sharpe Ratio", "2.36"},
{"Probabilistic Sharpe Ratio", "94.555%"},
{"Net Profit", "1.479%"},
{"Sharpe Ratio", "2.544"},
{"Probabilistic Sharpe Ratio", "96.625%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.006"},
{"Beta", "0.158"},
{"Annual Standard Deviation", "0.03"},
{"Alpha", "0.014"},
{"Beta", "0.175"},
{"Annual Standard Deviation", "0.033"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-4.44"},
{"Information Ratio", "-4.246"},
{"Tracking Error", "0.075"},
{"Treynor Ratio", "0.441"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$170000000.00"},
{"Treynor Ratio", "0.483"},
{"Total Fees", "$2.15"},
{"Estimated Strategy Capacity", "$1800000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.019"},
{"Fitness Score", "0.022"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "1.369"},
{"Return Over Maximum Drawdown", "9.749"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "5.652"},
{"Portfolio Turnover", "0.023"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -145,7 +145,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "4c5e32aedcd5bb67642d1629628fe615"}
{"OrderListHash", "d93bc642994899d48dd9e00232d444bc"}
};
}
}

View File

@@ -14,6 +14,7 @@
*/
using System.Collections.Generic;
using QuantConnect.Orders;
namespace QuantConnect.Algorithm.CSharp
{
@@ -28,7 +29,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 15192;
public override long DataPoints => 13223;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
@@ -42,7 +43,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Drawdown", "0.100%"},
{"Expectancy", "-0.678"},
{"Net Profit", "-0.111%"},
{"Sharpe Ratio", "-0.965"},
{"Sharpe Ratio", "-0.951"},
{"Probabilistic Sharpe Ratio", "0.000%"},
{"Loss Rate", "80%"},
{"Win Rate", "20%"},
@@ -51,17 +52,17 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.073"},
{"Information Ratio", "-1.075"},
{"Tracking Error", "0.107"},
{"Treynor Ratio", "1.349"},
{"Total Fees", "$14.80"},
{"Estimated Strategy Capacity", "$2400000.00"},
{"Treynor Ratio", "1.338"},
{"Total Fees", "$19.76"},
{"Estimated Strategy Capacity", "$2300000.00"},
{"Lowest Capacity Asset", "DC V5E8PHPRCHJ8|DC V5E8P9SH0U0X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.128"},
{"Return Over Maximum Drawdown", "-0.992"},
{"Sortino Ratio", "-0.126"},
{"Return Over Maximum Drawdown", "-0.995"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},

View File

@@ -107,7 +107,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>0
public virtual long DataPoints => 15228955;
public virtual long DataPoints => 5117455;
/// <summary>
/// Data Points count of the algorithm history
@@ -138,14 +138,14 @@ namespace QuantConnect.Algorithm.CSharp
{"Information Ratio", "-1.075"},
{"Tracking Error", "0.107"},
{"Treynor Ratio", "1.353"},
{"Total Fees", "$14.80"},
{"Estimated Strategy Capacity", "$860000000.00"},
{"Lowest Capacity Asset", "DC V5E8P9SH0U0X"},
{"Total Fees", "$19.76"},
{"Estimated Strategy Capacity", "$1300000000.00"},
{"Lowest Capacity Asset", "DC V5E8PHPRCHJ8|DC V5E8P9SH0U0X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.128"},
{"Return Over Maximum Drawdown", "-0.995"},
{"Sortino Ratio", "-0.129"},
{"Return Over Maximum Drawdown", "-0.997"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},

View File

@@ -64,7 +64,7 @@ namespace QuantConnect.Algorithm.CSharp
// define an indicator that takes the output of the sma and pipes it into our delay indicator
var delayedSma = delay.Of(sma);
// register our new 'delayedSma' for automaic updates on a daily resolution
// register our new 'delayedSma' for automatic updates on a daily resolution
RegisterIndicator(_spy, delayedSma, Resolution.Daily, data => data.Value);
return delayedSma;

View File

@@ -23,7 +23,7 @@ using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// In this algortihm we show how you can easily use the universe selection feature to fetch symbols
/// In this algorithm we show how you can easily use the universe selection feature to fetch symbols
/// to be traded using the BaseData custom data system in combination with the AddUniverse{T} method.
/// AddUniverse{T} requires a function that will return the symbols to be traded.
/// </summary>

View File

@@ -24,7 +24,7 @@ using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// In this algortihm we show how you can easily use the universe selection feature to fetch symbols
/// In this algorithm we show how you can easily use the universe selection feature to fetch symbols
/// to be traded using the AddUniverse method. This method accepts a function that will return the
/// desired current set of symbols. Return Universe.Unchanged if no universe changes should be made
/// </summary>

View File

@@ -0,0 +1,122 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Example algorithm of using ETFConstituentsUniverseSelectionModel
/// </summary>
public class ETFConstituentsFrameworkAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2020, 12, 1);
SetEndDate(2020, 12, 7);
SetCash(100000);
UniverseSettings.Resolution = Resolution.Daily;
var symbol = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
AddUniverseSelection(new ETFConstituentsUniverseSelectionModel(symbol, UniverseSettings, ETFConstituentsFilter));
AddAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(1)));
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
}
private IEnumerable<Symbol> ETFConstituentsFilter(IEnumerable<ETFConstituentData> constituents)
{
// Get the 10 securities with the largest weight in the index
return constituents.OrderByDescending(c => c.Weight).Take(8).Select(c => c.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; } = 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>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 565;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <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", "8"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "60.921%"},
{"Drawdown", "0.900%"},
{"Expectancy", "-1"},
{"Net Profit", "0.917%"},
{"Sharpe Ratio", "4.712"},
{"Probabilistic Sharpe Ratio", "67.398%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.62"},
{"Beta", "-0.348"},
{"Annual Standard Deviation", "0.1"},
{"Annual Variance", "0.01"},
{"Information Ratio", "0.399"},
{"Tracking Error", "0.127"},
{"Treynor Ratio", "-1.361"},
{"Total Fees", "$8.02"},
{"Estimated Strategy Capacity", "$350000000.00"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0.159"},
{"Kelly Criterion Estimate", "4.164"},
{"Kelly Criterion Probability Value", "0.444"},
{"Sortino Ratio", "19.028"},
{"Return Over Maximum Drawdown", "70.879"},
{"Portfolio Turnover", "0.16"},
{"Total Insights Generated", "20"},
{"Total Insights Closed", "16"},
{"Total Insights Analysis Completed", "16"},
{"Long Insight Count", "20"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$-875816.5"},
{"Total Accumulated Estimated Alpha Value", "$-210439.3"},
{"Mean Population Estimated Insight Value", "$-13152.45"},
{"Mean Population Direction", "37.5%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "82.1399%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "018dc981190b94fdbae00e75b1bbe2c2"}
};
}
}

View File

@@ -130,7 +130,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 208361;
public long DataPoints => 72192;
/// <summary>
/// Data Points count of the algorithm history
@@ -142,48 +142,48 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "7"},
{"Average Win", "0%"},
{"Average Loss", "-1.40%"},
{"Compounding Annual Return", "-99.829%"},
{"Drawdown", "29.500%"},
{"Expectancy", "-1"},
{"Net Profit", "-7.888%"},
{"Sharpe Ratio", "-0.593"},
{"Probabilistic Sharpe Ratio", "34.346%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-15.391"},
{"Beta", "7.259"},
{"Annual Standard Deviation", "1.679"},
{"Annual Variance", "2.818"},
{"Information Ratio", "-2.032"},
{"Tracking Error", "1.466"},
{"Treynor Ratio", "-0.137"},
{"Total Fees", "$40.70"},
{"Estimated Strategy Capacity", "$4000000.00"},
{"Total Trades", "8"},
{"Average Win", "0.69%"},
{"Average Loss", "-2.47%"},
{"Compounding Annual Return", "-99.966%"},
{"Drawdown", "28.600%"},
{"Expectancy", "-0.680"},
{"Net Profit", "-9.786%"},
{"Sharpe Ratio", "-0.598"},
{"Probabilistic Sharpe Ratio", "30.082%"},
{"Loss Rate", "75%"},
{"Win Rate", "25%"},
{"Profit-Loss Ratio", "0.28"},
{"Alpha", "-15.867"},
{"Beta", "7.498"},
{"Annual Standard Deviation", "1.669"},
{"Annual Variance", "2.787"},
{"Information Ratio", "-2.061"},
{"Tracking Error", "1.447"},
{"Treynor Ratio", "-0.133"},
{"Total Fees", "$52.01"},
{"Estimated Strategy Capacity", "$1800000.00"},
{"Lowest Capacity Asset", "GC VL5E74HP3EE5"},
{"Fitness Score", "0.072"},
{"Kelly Criterion Estimate", "-9.366"},
{"Kelly Criterion Probability Value", "0.607"},
{"Sortino Ratio", "-5.172"},
{"Return Over Maximum Drawdown", "-5.25"},
{"Portfolio Turnover", "4.987"},
{"Fitness Score", "0.213"},
{"Kelly Criterion Estimate", "-24.978"},
{"Kelly Criterion Probability Value", "0.773"},
{"Sortino Ratio", "-0.966"},
{"Return Over Maximum Drawdown", "-5.15"},
{"Portfolio Turnover", "5.36"},
{"Total Insights Generated", "10"},
{"Total Insights Closed", "8"},
{"Total Insights Analysis Completed", "8"},
{"Long Insight Count", "10"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$-78.89231"},
{"Total Accumulated Estimated Alpha Value", "$-12.82"},
{"Mean Population Estimated Insight Value", "$-1.6025"},
{"Mean Population Direction", "25%"},
{"Estimated Monthly Alpha Value", "$13142.3631"},
{"Total Accumulated Estimated Alpha Value", "$2135.634"},
{"Mean Population Estimated Insight Value", "$266.9542"},
{"Mean Population Direction", "50%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "25.058%"},
{"Rolling Averaged Population Direction", "50.0384%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "874fc945335aa8d93f2e3734641f9890"}
{"OrderListHash", "525af9e5e2ca7ebdee6c9deeec326a3e"}
};
}
}

View File

@@ -0,0 +1,191 @@
/*
* 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.Orders;
using QuantConnect.Securities.Option;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting that European options cannot be exercised before expiry
/// </summary>
public class EuropeanOptionsCannotBeExercisedBeforeExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Option _option;
private OptionContract _contract;
private bool _marketOrderDone;
private bool _exerciseBeforeExpiryDone;
private bool _exerciseOnExpiryDone;
public override void Initialize()
{
SetStartDate(2021, 1, 4);
SetEndDate(2021, 2, 1);
SetCash(200000);
var index = AddIndex("SPX", Resolution.Hour, fillDataForward: true);
var indexOption = AddIndexOption(index.Symbol, Resolution.Hour, fillDataForward: true);
indexOption.SetFilter(filterFunc => filterFunc);
_option = indexOption;
}
public override void OnData(Slice slice)
{
if ((_exerciseBeforeExpiryDone && _exerciseOnExpiryDone) || !_option.Exchange.ExchangeOpen)
{
return;
}
if (_contract == null)
{
OptionChain contracts;
if (!slice.OptionChains.TryGetValue(_option.Symbol, out contracts) || !contracts.Any())
{
return;
}
_contract = contracts.First();
}
var expiry = _contract.Expiry.ConvertToUtc(_option.Exchange.TimeZone).Date;
if (!_exerciseBeforeExpiryDone && UtcTime.Date < expiry)
{
if (!_marketOrderDone)
{
if (MarketOrder(_contract.Symbol, 1).Status != OrderStatus.Filled)
{
throw new Exception("Expected market order to fill immediately");
}
_marketOrderDone = true;
}
if (ExerciseOption(_contract.Symbol, 1).Status == OrderStatus.Filled)
{
throw new Exception($"Expected European option to not be exercisable before its expiration date. " +
$"Time: {UtcTime}. Expiry: {_contract.Expiry.ConvertToUtc(_option.Exchange.TimeZone)}");
}
_exerciseBeforeExpiryDone = true;
return;
}
if (!_exerciseOnExpiryDone && UtcTime.Date == expiry)
{
if (ExerciseOption(_contract.Symbol, 1).Status != OrderStatus.Filled)
{
throw new Exception($"Expected European option to be exercisable on its expiration date. " +
$"Time: {UtcTime}. Expiry: {_contract.Expiry.ConvertToUtc(_option.Exchange.TimeZone)}");
}
_exerciseOnExpiryDone = true;
// We already tested everything, so we can stop the algorithm
Quit();
}
}
public override void OnEndOfAlgorithm()
{
if (!_exerciseBeforeExpiryDone || !_exerciseOnExpiryDone)
{
throw new Exception("Expected to try to exercise option before and on expiry");
}
}
/// <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>
/// Data Points count of all time slices of algorithm
/// </summary>
public long DataPoints => 1828;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-4.10%"},
{"Compounding Annual Return", "24.075%"},
{"Drawdown", "1.900%"},
{"Expectancy", "-1"},
{"Net Profit", "0.677%"},
{"Sharpe Ratio", "5.78"},
{"Probabilistic Sharpe Ratio", "89.644%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.95"},
{"Beta", "-0.354"},
{"Annual Standard Deviation", "0.123"},
{"Annual Variance", "0.015"},
{"Information Ratio", "0.211"},
{"Tracking Error", "0.176"},
{"Treynor Ratio", "-2.011"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$1700000.00"},
{"Lowest Capacity Asset", "SPX XL80P3HB5O6M|SPX 31"},
{"Fitness Score", "0.004"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "20.506"},
{"Portfolio Turnover", "0.004"},
{"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", "eddce46e44ac8ebb279bc6aa9af85ece"}
};
}
}

View File

@@ -0,0 +1,162 @@
/*
* 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 System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regression algorithm asserts that futures have data at extended market hours when this is enabled.
/// </summary>
public class FutureContractsExtendedMarketHoursRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Future _es;
private Future _gc;
private bool _esRanOnRegularHours;
private bool _esRanOnExtendedHours;
private bool _gcRanOnRegularHours;
private bool _gcRanOnExtendedHours;
public override void Initialize()
{
SetStartDate(2013, 10, 6);
SetEndDate(2013, 10, 11);
var esFutureSymbol = QuantConnect.Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, new DateTime(2013, 12, 20));
_es = AddFutureContract(esFutureSymbol, Resolution.Hour, fillDataForward: true, extendedMarketHours: true);
var gcFutureSymbol = QuantConnect.Symbol.CreateFuture(Futures.Metals.Gold, Market.COMEX, new DateTime(2013, 10, 29));
_gc = AddFutureContract(gcFutureSymbol, Resolution.Hour, fillDataForward: true, extendedMarketHours: false);
}
public override void OnData(Slice slice)
{
var sliceSymbols = new HashSet<Symbol>(slice.Keys);
sliceSymbols.UnionWith(slice.Bars.Keys);
sliceSymbols.UnionWith(slice.Ticks.Keys);
sliceSymbols.UnionWith(slice.QuoteBars.Keys);
var esIsInRegularHours = _es.Exchange.Hours.IsOpen(Time, false);
var esIsInExtendedHours = !esIsInRegularHours && _es.Exchange.Hours.IsOpen(Time, true);
var sliceHasESData = sliceSymbols.Any(symbol => symbol == _es.Symbol || symbol.Canonical == _es.Symbol);
_esRanOnRegularHours |= esIsInRegularHours && sliceHasESData;
_esRanOnExtendedHours |= esIsInExtendedHours && sliceHasESData;
var gcIsInRegularHours = _gc.Exchange.Hours.IsOpen(Time, false);
var gcIsInExtendedHours = !gcIsInRegularHours && _gc.Exchange.Hours.IsOpen(Time, true);
var sliceHasGCData = sliceSymbols.Any(symbol => symbol == _gc.Symbol || symbol.Canonical == _gc.Symbol);
_gcRanOnRegularHours |= gcIsInRegularHours && sliceHasGCData;
_gcRanOnExtendedHours |= gcIsInExtendedHours && sliceHasGCData;
}
public override void OnEndOfAlgorithm()
{
if (!_esRanOnRegularHours)
{
throw new Exception($"Algorithm should have run on regular hours for {_es.Symbol} future, which enabled extended market hours");
}
if (!_esRanOnExtendedHours)
{
throw new Exception($"Algorithm should have run on extended hours for {_es.Symbol} future, which enabled extended market hours");
}
if (!_gcRanOnRegularHours)
{
throw new Exception($"Algorithm should have run on regular hours for {_gc.Symbol} future, which did not enable extended market hours");
}
if (_gcRanOnExtendedHours)
{
throw new Exception($"Algorithm should have not run on extended hours for {_gc.Symbol} future, which did not enable extended market hours");
}
}
/// <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>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 525;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <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"}
};
}
}

View File

@@ -25,39 +25,43 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public class FutureMarketOpenAndCloseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private static List<DateTime> _afterMarketOpen = new List<DateTime>() {
new DateTime(2022, 02, 01, 16, 30, 0),
new DateTime(2022, 02, 02, 16, 30, 0),
new DateTime(2022, 02, 03, 16, 30, 0),
new DateTime(2022, 02, 04, 16, 30, 0),
new DateTime(2022, 02, 06, 18, 0, 0),
new DateTime(2022, 02, 07, 16, 30, 0),
new DateTime(2022, 02, 08, 16, 30, 0)
protected virtual bool ExtendedMarketHours => false;
protected virtual List<DateTime> AfterMarketOpen => new List<DateTime>() {
new DateTime(2022, 02, 01, 9, 30, 0),
new DateTime(2022, 02, 02, 9, 30, 0),
new DateTime(2022, 02, 03, 9, 30, 0),
new DateTime(2022, 02, 04, 9, 30, 0),
new DateTime(2022, 02, 07, 9, 30, 0),
new DateTime(2022, 02, 08, 9, 30, 0)
};
private static List<DateTime> _beforeMarketClose = new List<DateTime>()
protected virtual List<DateTime> BeforeMarketClose => new List<DateTime>()
{
new DateTime(2022, 02, 01, 16, 15, 0),
new DateTime(2022, 02, 02, 16, 15, 0),
new DateTime(2022, 02, 03, 16, 15, 0),
new DateTime(2022, 02, 04, 16, 15, 0),
new DateTime(2022, 02, 07, 16, 15, 0),
new DateTime(2022, 02, 08, 16, 15, 0)
new DateTime(2022, 02, 01, 17, 0, 0),
new DateTime(2022, 02, 02, 17, 0, 0),
new DateTime(2022, 02, 03, 17, 0, 0),
new DateTime(2022, 02, 04, 17, 0, 0),
new DateTime(2022, 02, 07, 17, 0, 0),
new DateTime(2022, 02, 08, 17, 0, 0)
};
private Queue<DateTime> _afterMarketOpenQueue = new Queue<DateTime>(_afterMarketOpen);
private Queue<DateTime> _beforeMarketCloseQueue = new Queue<DateTime>(_beforeMarketClose);
private Queue<DateTime> _afterMarketOpenQueue;
private Queue<DateTime> _beforeMarketCloseQueue;
public override void Initialize()
{
SetStartDate(2022, 02, 01);
SetEndDate(2022, 02, 08);
var esFuture = AddFuture("ES").Symbol;
var esFuture = AddFuture("ES", extendedMarketHours: ExtendedMarketHours).Symbol;
_afterMarketOpenQueue = new Queue<DateTime>(AfterMarketOpen);
_beforeMarketCloseQueue = new Queue<DateTime>(BeforeMarketClose);
Schedule.On(DateRules.EveryDay(esFuture),
TimeRules.AfterMarketOpen(esFuture),
TimeRules.AfterMarketOpen(esFuture, extendedMarketOpen: ExtendedMarketHours),
EveryDayAfterMarketOpen);
Schedule.On(DateRules.EveryDay(esFuture),
TimeRules.BeforeMarketClose(esFuture),
TimeRules.BeforeMarketClose(esFuture, extendedMarketClose: ExtendedMarketHours),
EveryDayBeforeMarketClose);
}
@@ -91,12 +95,12 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp};
public virtual Language[] Languages { get; } = { Language.CSharp};
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 7;
public virtual long DataPoints => 7;
/// </summary>
/// Data Points count of the algorithm history
@@ -106,7 +110,7 @@ namespace QuantConnect.Algorithm.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>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},

View File

@@ -0,0 +1,106 @@
/*
* 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.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm to check we are getting the correct market open and close times when extended market hours are used
/// </summary>
public class FutureMarketOpenAndCloseWithExtendedMarketRegressionAlgorithm : FutureMarketOpenAndCloseRegressionAlgorithm
{
protected override bool ExtendedMarketHours => true;
protected override List<DateTime> AfterMarketOpen => new List<DateTime>() {
new DateTime(2022, 02, 01, 18, 0, 0), // Tuesday
new DateTime(2022, 02, 02, 18, 0, 0),
new DateTime(2022, 02, 03, 18, 0, 0),
new DateTime(2022, 02, 06, 18, 0, 0),
new DateTime(2022, 02, 07, 18, 0, 0),
new DateTime(2022, 02, 08, 18, 0, 0)
};
protected override List<DateTime> BeforeMarketClose => new List<DateTime>()
{
new DateTime(2022, 02, 01, 17, 0, 0),
new DateTime(2022, 02, 02, 17, 0, 0),
new DateTime(2022, 02, 03, 17, 0, 0),
new DateTime(2022, 02, 04, 17, 0, 0),
new DateTime(2022, 02, 07, 17, 0, 0),
new DateTime(2022, 02, 08, 17, 0, 0)
};
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override Language[] Languages { get; } = { Language.CSharp};
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 7;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "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

@@ -27,44 +27,65 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public class FutureMarketOpenConsolidatorRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private static List<DateTime> _expectedOpens = new List<DateTime>(){
new DateTime(2013, 10, 06, 18, 00, 0),
new DateTime(2013, 10, 07, 16, 30, 0),
new DateTime(2013, 10, 08, 16, 30, 0),
new DateTime(2013, 10, 09, 16, 30, 0),
new DateTime(2013, 10, 10, 16, 30, 0),
new DateTime(2013, 10, 11, 16, 30, 0),
new DateTime(2013, 10, 13, 18, 00, 0),
protected virtual bool ExtendedMarketHours => false;
protected virtual List<DateTime> ExpectedOpens => new List<DateTime>()
{
new DateTime(2013, 10, 07, 9, 30, 0),
new DateTime(2013, 10, 08, 9, 30, 0),
new DateTime(2013, 10, 09, 9, 30, 0),
new DateTime(2013, 10, 10, 9, 30, 0),
new DateTime(2013, 10, 11, 9, 30, 0),
new DateTime(2013, 10, 14, 9, 30, 0),
new DateTime(2013, 10, 14, 9, 30, 0),
};
private static List<DateTime> _expectedCloses = new List<DateTime>(){
new DateTime(2013, 10, 07, 16, 15, 0),
new DateTime(2013, 10, 08, 16, 15, 0),
new DateTime(2013, 10, 09, 16, 15, 0),
new DateTime(2013, 10, 10, 16, 15, 0),
new DateTime(2013, 10, 11, 16, 15, 0),
new DateTime(2013, 10, 14, 16, 15, 0),
new DateTime(2013, 10, 14, 16, 15, 0),
protected virtual List<DateTime> ExpectedCloses => new List<DateTime>()
{
new DateTime(2013, 10, 07, 17, 0, 0),
new DateTime(2013, 10, 08, 17, 0, 0),
new DateTime(2013, 10, 09, 17, 0, 0),
new DateTime(2013, 10, 10, 17, 0, 0),
new DateTime(2013, 10, 11, 17, 0, 0),
new DateTime(2013, 10, 14, 17, 0, 0),
new DateTime(2013, 10, 14, 17, 0, 0),
};
private Queue<DateTime> _expectedOpensQueue = new Queue<DateTime>(_expectedOpens);
private Queue<DateTime> _expectedClosesQueue = new Queue<DateTime>(_expectedCloses);
private Queue<DateTime> _expectedOpensQueue;
private Queue<DateTime> _expectedClosesQueue;
public override void Initialize()
{
SetStartDate(2013, 10, 06);
SetEndDate(2013, 10, 14);
var es = AddSecurity(SecurityType.Future, "ES");
var es = AddSecurity(SecurityType.Future, "ES", extendedMarketHours: ExtendedMarketHours);
_expectedOpensQueue = new Queue<DateTime>(ExpectedOpens);
_expectedClosesQueue = new Queue<DateTime>(ExpectedCloses);
Consolidate<BaseData>(es.Symbol, dataTime =>
{
var start = es.Exchange.Hours.GetPreviousMarketOpen(dataTime, false);
var end = es.Exchange.Hours.GetNextMarketClose(start, false);
var start = es.Exchange.Hours.GetPreviousMarketOpen(dataTime, ExtendedMarketHours);
var end = es.Exchange.Hours.GetNextMarketClose(start, ExtendedMarketHours);
// market might open at 16:30 and close again at 17:00 but we are not interested in using the close so we skip it here
while (end.Date == start.Date)
if (ExtendedMarketHours)
{
end = es.Exchange.Hours.GetNextMarketClose(end, false);
// market might open at 16:30 and close again at 17:00 but we are not interested in using the close so we skip it here
while (end.Date == start.Date)
{
end = es.Exchange.Hours.GetNextMarketClose(end, ExtendedMarketHours);
}
} else
{
// Let's not consider regular market gaps like when market closes at 16:15 and opens again at 16:30
while (true)
{
var potentialEnd = es.Exchange.Hours.GetNextMarketClose(end, ExtendedMarketHours);
if (potentialEnd.Date != end.Date)
{
break;
}
end = potentialEnd;
}
}
var period = end - start;
@@ -92,12 +113,12 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public virtual Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 94112;
public virtual long DataPoints => 29802;
/// </summary>
/// Data Points count of the algorithm history
@@ -107,7 +128,7 @@ namespace QuantConnect.Algorithm.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>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},

View File

@@ -0,0 +1,106 @@
/*
* 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.Consolidators;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm using a consolidator to check GetNextMarketClose() and GetNextMarketOpen()
/// are returning the correct market close and open times, when extended market hours are used
/// </summary>
public class FutureMarketOpenConsolidatorWithExtendedMarketRegressionAlgorithm : FutureMarketOpenConsolidatorRegressionAlgorithm
{
protected override bool ExtendedMarketHours => true;
protected override List<DateTime> ExpectedOpens => new List<DateTime>(){
new DateTime(2013, 10, 06, 18, 0, 0), // Sunday
new DateTime(2013, 10, 07, 18, 0, 0),
new DateTime(2013, 10, 08, 18, 0, 0),
new DateTime(2013, 10, 09, 18, 0, 0),
new DateTime(2013, 10, 10, 18, 0, 0),
new DateTime(2013, 10, 13, 18, 0, 0),
};
protected override List<DateTime> ExpectedCloses => new List<DateTime>(){
new DateTime(2013, 10, 07, 17, 0, 0),
new DateTime(2013, 10, 08, 17, 0, 0),
new DateTime(2013, 10, 09, 17, 0, 0),
new DateTime(2013, 10, 10, 17, 0, 0),
new DateTime(2013, 10, 11, 17, 0, 0),
new DateTime(2013, 10, 14, 17, 0, 0),
};
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 95102;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "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", "-3.108"},
{"Tracking Error", "0.163"},
{"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

@@ -0,0 +1,149 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting the behavior of a zero time in universe setting. Related to GH issue #6653
/// </summary>
public class FutureNoTimeInUniverseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Dictionary<DateTime, Symbol> _seenSymbols = new();
private Symbol _sp500;
/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 10);
UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero;
var futureSP500 = AddFuture(Futures.Indices.SP500EMini);
_sp500 = futureSP500.Symbol;
futureSP500.SetFilter(u =>
{
return u.Where(s =>
{
if (_seenSymbols.ContainsKey(Time) || _seenSymbols.ContainsValue(s))
{
// for each timestamp we select a single symbol which we haven't selected before
return false;
}
_seenSymbols[Time] = s;
return true;
});
});
}
/// <summary>
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
/// </summary>
/// <param name="slice">The current slice of data keyed by symbol string</param>
public override void OnData(Slice slice)
{
var futureContracts = slice.FutureChains.GetValue(_sp500);
if(futureContracts == null)
{
return;
}
var futureSymbols = futureContracts.Select(future => future.Symbol).ToHashSet();
if (futureSymbols.Count > 1)
{
throw new Exception($"At {Time} found {futureSymbols.Count}. Future symbols: [{string.Join(",", futureSymbols)}]");
}
}
/// <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>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 14931;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <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", "-66.775"},
{"Tracking Error", "0.243"},
{"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

@@ -85,10 +85,6 @@ namespace QuantConnect.Algorithm.CSharp
MarketOrder(esOptions[0], 1);
MarketOrder(esOptions[1], -1);
});
Schedule.On(DateRules.Tomorrow, TimeRules.Noon, () =>
{
Liquidate();
});
}
/// <summary>
@@ -116,7 +112,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 939460;
public long DataPoints => 308080;
/// <summary>
/// Data Points count of the algorithm history
@@ -129,33 +125,33 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "6"},
{"Average Win", "2.94%"},
{"Average Loss", "-4.15%"},
{"Compounding Annual Return", "-5.589%"},
{"Drawdown", "5.600%"},
{"Expectancy", "-0.145"},
{"Net Profit", "-2.760%"},
{"Sharpe Ratio", "-0.45"},
{"Probabilistic Sharpe Ratio", "9.306%"},
{"Average Win", "3.37%"},
{"Average Loss", "-4.34%"},
{"Compounding Annual Return", "-4.637%"},
{"Drawdown", "5.200%"},
{"Expectancy", "-0.111"},
{"Net Profit", "-2.284%"},
{"Sharpe Ratio", "-0.413"},
{"Probabilistic Sharpe Ratio", "9.827%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.71"},
{"Alpha", "-0.036"},
{"Beta", "-0.013"},
{"Annual Standard Deviation", "0.08"},
{"Annual Variance", "0.006"},
{"Information Ratio", "-0.149"},
{"Tracking Error", "0.387"},
{"Treynor Ratio", "2.865"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$140000000.00"},
{"Profit-Loss Ratio", "0.78"},
{"Alpha", "-0.03"},
{"Beta", "-0.011"},
{"Annual Standard Deviation", "0.072"},
{"Annual Variance", "0.005"},
{"Information Ratio", "-0.134"},
{"Tracking Error", "0.385"},
{"Treynor Ratio", "2.816"},
{"Total Fees", "$2.84"},
{"Estimated Strategy Capacity", "$120000000.00"},
{"Lowest Capacity Asset", "ES XFH59UPBIJ7O|ES XFH59UK0MYO1"},
{"Fitness Score", "0.017"},
{"Fitness Score", "0.021"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.096"},
{"Return Over Maximum Drawdown", "-0.993"},
{"Portfolio Turnover", "0.043"},
{"Sortino Ratio", "-0.08"},
{"Return Over Maximum Drawdown", "-0.896"},
{"Portfolio Turnover", "0.051"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -169,7 +165,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1f521247474162d17ff94fbaa654385b"}
{"OrderListHash", "6ae724ba0dbcbd1ca49dcfcdf94e0319"}
};
}
}

View File

@@ -200,7 +200,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 644315;
public long DataPoints => 211475;
/// <summary>
/// Data Points count of the algorithm history
@@ -213,33 +213,33 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "1.26%"},
{"Average Loss", "-7.41%"},
{"Compounding Annual Return", "-12.424%"},
{"Drawdown", "6.300%"},
{"Expectancy", "-0.415"},
{"Net Profit", "-6.252%"},
{"Sharpe Ratio", "-1.226"},
{"Probabilistic Sharpe Ratio", "0.002%"},
{"Average Win", "2.28%"},
{"Average Loss", "-6.80%"},
{"Compounding Annual Return", "-9.373%"},
{"Drawdown", "5.300%"},
{"Expectancy", "-0.332"},
{"Net Profit", "-4.676%"},
{"Sharpe Ratio", "-1.002"},
{"Probabilistic Sharpe Ratio", "0.165%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.17"},
{"Alpha", "-0.086"},
{"Profit-Loss Ratio", "0.34"},
{"Alpha", "-0.064"},
{"Beta", "0.003"},
{"Annual Standard Deviation", "0.07"},
{"Annual Variance", "0.005"},
{"Information Ratio", "-0.283"},
{"Tracking Error", "0.379"},
{"Treynor Ratio", "-25.997"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$140000000.00"},
{"Annual Standard Deviation", "0.064"},
{"Annual Variance", "0.004"},
{"Information Ratio", "-0.226"},
{"Tracking Error", "0.378"},
{"Treynor Ratio", "-18.824"},
{"Total Fees", "$1.42"},
{"Estimated Strategy Capacity", "$120000000.00"},
{"Lowest Capacity Asset", "ES XFH59UPBIJ7O|ES XFH59UK0MYO1"},
{"Fitness Score", "0.008"},
{"Fitness Score", "0.017"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.205"},
{"Return Over Maximum Drawdown", "-1.989"},
{"Portfolio Turnover", "0.023"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-1.769"},
{"Portfolio Turnover", "0.027"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -253,7 +253,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "c61ac689d112eab8fde5f2b1f715b7d3"}
{"OrderListHash", "02b16807a77a858047996f15597ff145"}
};
}
}

View File

@@ -50,8 +50,8 @@ namespace QuantConnect.Algorithm.CSharp
// We must set the volatility model on the underlying, since the defaults are
// too strict to calculate greeks with when we only have data for a single day
_es19m20.VolatilityModel = new StandardDeviationOfReturnsVolatilityModel(
60,
Resolution.Minute,
60,
Resolution.Minute,
TimeSpan.FromMinutes(1));
// Select a future option expiring ITM, and adds it to the algorithm.
@@ -165,7 +165,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 644315;
public long DataPoints => 211475;
/// <summary>
/// Data Points count of the algorithm history
@@ -178,33 +178,33 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "8.93%"},
{"Average Loss", "-34.88%"},
{"Compounding Annual Return", "-50.632%"},
{"Drawdown", "29.100%"},
{"Expectancy", "-0.372"},
{"Net Profit", "-29.072%"},
{"Sharpe Ratio", "-0.978"},
{"Probabilistic Sharpe Ratio", "0.012%"},
{"Average Win", "16.44%"},
{"Average Loss", "-35.38%"},
{"Compounding Annual Return", "-44.262%"},
{"Drawdown", "26.200%"},
{"Expectancy", "-0.268"},
{"Net Profit", "-24.757%"},
{"Sharpe Ratio", "-0.932"},
{"Probabilistic Sharpe Ratio", "0.060%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.26"},
{"Alpha", "-0.339"},
{"Beta", "0.017"},
{"Annual Standard Deviation", "0.347"},
{"Annual Variance", "0.12"},
{"Information Ratio", "-0.714"},
{"Tracking Error", "0.505"},
{"Treynor Ratio", "-19.672"},
{"Total Fees", "$9.25"},
{"Estimated Strategy Capacity", "$50000000.00"},
{"Profit-Loss Ratio", "0.46"},
{"Alpha", "-0.292"},
{"Beta", "0.016"},
{"Annual Standard Deviation", "0.313"},
{"Annual Variance", "0.098"},
{"Information Ratio", "-0.649"},
{"Tracking Error", "0.483"},
{"Treynor Ratio", "-17.96"},
{"Total Fees", "$7.10"},
{"Estimated Strategy Capacity", "$24000000.00"},
{"Lowest Capacity Asset", "ES XFH59UPBIJ7O|ES XFH59UK0MYO1"},
{"Fitness Score", "0.055"},
{"Fitness Score", "0.108"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.155"},
{"Return Over Maximum Drawdown", "-1.743"},
{"Portfolio Turnover", "0.152"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-1.692"},
{"Portfolio Turnover", "0.171"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -218,7 +218,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "ed0cbd8487dd45519e5d0225e51ba29c"}
{"OrderListHash", "c1c4c793696f75c528527334563ae8df"}
};
}
}

View File

@@ -71,6 +71,7 @@ namespace QuantConnect.Algorithm.CSharp
throw new Exception($"Contract {_expectedContract} was not found in the chain");
}
// Place order after regular market opens
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
{
MarketOrder(_esOption, 1);
@@ -175,7 +176,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 644315;
public long DataPoints => 211475;
/// <summary>
/// Data Points count of the algorithm history
@@ -189,31 +190,31 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-4.02%"},
{"Compounding Annual Return", "-8.099%"},
{"Drawdown", "4.000%"},
{"Average Loss", "-3.85%"},
{"Compounding Annual Return", "-7.754%"},
{"Drawdown", "4.300%"},
{"Expectancy", "-1"},
{"Net Profit", "-4.027%"},
{"Sharpe Ratio", "-1.175"},
{"Probabilistic Sharpe Ratio", "0.009%"},
{"Net Profit", "-3.851%"},
{"Sharpe Ratio", "-1.023"},
{"Probabilistic Sharpe Ratio", "0.131%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.056"},
{"Beta", "0.002"},
{"Annual Standard Deviation", "0.047"},
{"Annual Variance", "0.002"},
{"Information Ratio", "-0.206"},
{"Tracking Error", "0.376"},
{"Treynor Ratio", "-23.833"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$99000000.00"},
{"Alpha", "-0.053"},
{"Beta", "0.003"},
{"Annual Standard Deviation", "0.052"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-0.198"},
{"Tracking Error", "0.377"},
{"Treynor Ratio", "-19.331"},
{"Total Fees", "$1.42"},
{"Estimated Strategy Capacity", "$180000000.00"},
{"Lowest Capacity Asset", "ES XFH59UPHGV9G|ES XFH59UK0MYO1"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.184"},
{"Return Over Maximum Drawdown", "-2.013"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-1.798"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -228,7 +229,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "498c9958139b70d42ebecc65c4eceeee"}
{"OrderListHash", "29bb2f59fa2ee3dab8ed2aecf6544189"}
};
}
}

View File

@@ -32,7 +32,7 @@ namespace QuantConnect.Algorithm.CSharp
protected OrderTicket Ticket;
protected Symbol DcOption;
protected virtual Resolution Resolution => Resolution.Daily;
public override void Initialize()
{
SetStartDate(2012, 1, 3);
@@ -51,30 +51,30 @@ namespace QuantConnect.Algorithm.CSharp
.Where(x => x.ID.StrikePrice == 17m && x.ID.OptionRight == OptionRight.Call)
.Select(x => AddFutureOptionContract(x, Resolution).Symbol)
.FirstOrDefault();
// Validate it is the expected contract
var expectedContract = QuantConnect.Symbol.CreateOption(dc, Market.CME, OptionStyle.American,
OptionRight.Call, 17m,
new DateTime(2012, 4, 01));
if (DcOption != expectedContract)
{
throw new Exception($"Contract {DcOption} was not the expected contract {expectedContract}");
}
ScheduleBuySell();
}
protected virtual void ScheduleBuySell()
{
// Schedule a purchase of this contract tomorrow at 1AM
Schedule.On(DateRules.Tomorrow, TimeRules.At(1,0,0), () =>
// Schedule a purchase of this contract tomorrow at 10AM when the market is open
Schedule.On(DateRules.Tomorrow, TimeRules.At(10,0,0), () =>
{
Ticket = MarketOrder(DcOption, 1);
});
// Schedule liquidation tomorrow at 6PM
Schedule.On(DateRules.Tomorrow, TimeRules.At(18,0,0), () =>
// Schedule liquidation tomorrow at 2PM when the market is open
Schedule.On(DateRules.Tomorrow, TimeRules.At(14,0,0), () =>
{
Liquidate();
});
@@ -99,7 +99,7 @@ namespace QuantConnect.Algorithm.CSharp
{
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
}
if (Ticket.Status != OrderStatus.Filled)
{
throw new Exception("Future option order failed to fill correctly");
@@ -134,30 +134,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.82%"},
{"Compounding Annual Return", "-66.089%"},
{"Compounding Annual Return", "-66.144%"},
{"Drawdown", "0.800%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.824%"},
{"Sharpe Ratio", "-6.993"},
{"Net Profit", "-0.825%"},
{"Sharpe Ratio", "-6.988"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.466"},
{"Beta", "-7.501"},
{"Annual Standard Deviation", "0.092"},
{"Alpha", "0.467"},
{"Beta", "-7.512"},
{"Annual Standard Deviation", "0.093"},
{"Annual Variance", "0.009"},
{"Information Ratio", "-7.586"},
{"Information Ratio", "-7.581"},
{"Tracking Error", "0.105"},
{"Treynor Ratio", "0.086"},
{"Total Fees", "$3.70"},
{"Total Fees", "$4.94"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "DC V5E8P9VAH3IC|DC V5E8P9SH0U0X"},
{"Fitness Score", "0.006"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-80.233"},
{"Return Over Maximum Drawdown", "-80.18"},
{"Portfolio Turnover", "0.013"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -172,7 +172,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "f00013930ab4c104a6177485d8090b31"}
{"OrderListHash", "dfcf673b46b9054a15babe1b0d734c35"}
};
}
}

View File

@@ -38,9 +38,9 @@ namespace QuantConnect.Algorithm.CSharp
{
Ticket = MarketOrder(DcOption, 1);
});
// Schedule liquidation at 6PM
Schedule.On(DateRules.Today, TimeRules.At(18,0,0), () =>
// Schedule liquidation at 2PM when the market is open
Schedule.On(DateRules.Today, TimeRules.At(14,0,0), () =>
{
Liquidate();
});
@@ -68,7 +68,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 180;
public override long DataPoints => 88;
/// <summary>
/// Data Points count of the algorithm history
@@ -99,15 +99,15 @@ namespace QuantConnect.Algorithm.CSharp
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$3.70"},
{"Total Fees", "$4.94"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "DC V5E8P9VAH3IC|DC V5E8P9SH0U0X"},
{"Fitness Score", "0.01"},
{"Fitness Score", "0.021"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-101.911"},
{"Portfolio Turnover", "0.02"},
{"Return Over Maximum Drawdown", "-135.888"},
{"Portfolio Turnover", "0.043"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -121,7 +121,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "665d06e4f758724b5b9576b14fd18743"}
{"OrderListHash", "aa0827b2e3105a09c7308382ac0512aa"}
};
}
}

View File

@@ -37,10 +37,13 @@ namespace QuantConnect.Algorithm.CSharp
public override void Initialize()
{
// Required for FOPs to use extended hours, until GH #6491 is addressed
UniverseSettings.ExtendedMarketHours = true;
SetStartDate(2020, 1, 4);
SetEndDate(2020, 1, 6);
var goldFutures = AddFuture("GC", Resolution.Minute, Market.COMEX);
var goldFutures = AddFuture("GC", Resolution.Minute, Market.COMEX, extendedMarketHours: true);
goldFutures.SetFilter(0, 365);
AddFutureOption(goldFutures.Symbol);
@@ -50,7 +53,8 @@ namespace QuantConnect.Algorithm.CSharp
{
foreach (var symbol in data.QuoteBars.Keys)
{
if (_expectedSymbols.ContainsKey(symbol))
// Check that we are in regular hours, we can place a market order (on extended hours, limit orders should be used)
if (_expectedSymbols.ContainsKey(symbol) && IsInRegularHours(symbol))
{
var invested = _expectedSymbols[symbol];
if (!invested)
@@ -76,6 +80,11 @@ namespace QuantConnect.Algorithm.CSharp
}
}
private bool IsInRegularHours(Symbol symbol)
{
return Securities[symbol].Exchange.ExchangeOpen;
}
private static Symbol CreateOption(DateTime expiry, OptionRight optionRight, decimal strikePrice)
{
return QuantConnect.Symbol.CreateOption(
@@ -115,31 +124,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "4"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-5.605%"},
{"Drawdown", "3.500%"},
{"Compounding Annual Return", "-25.338%"},
{"Drawdown", "0.200%"},
{"Expectancy", "0"},
{"Net Profit", "-0.047%"},
{"Sharpe Ratio", "-10.898"},
{"Net Profit", "-0.240%"},
{"Sharpe Ratio", "-9.692"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.135"},
{"Beta", "0.124"},
{"Annual Standard Deviation", "0.005"},
{"Annual Variance", "0"},
{"Information Ratio", "-17.984"},
{"Tracking Error", "0.038"},
{"Treynor Ratio", "-0.467"},
{"Total Fees", "$7.40"},
{"Estimated Strategy Capacity", "$25000000.00"},
{"Alpha", "0.127"},
{"Beta", "-0.629"},
{"Annual Standard Deviation", "0.027"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-12.58"},
{"Tracking Error", "0.07"},
{"Treynor Ratio", "0.415"},
{"Total Fees", "$9.88"},
{"Estimated Strategy Capacity", "$31000000.00"},
{"Lowest Capacity Asset", "OG 31BFX0QKBVPGG|GC XE1Y0ZJ8NQ8T"},
{"Fitness Score", "0.012"},
{"Fitness Score", "0.013"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-126.806"},
{"Portfolio Turnover", "0.025"},
{"Return Over Maximum Drawdown", "-112.343"},
{"Portfolio Turnover", "0.026"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -153,7 +162,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "979e3995c0dbedc46eaf3705e0438bf5"}
{"OrderListHash", "ebde540d026c0bf7055caf5bf2eeded5"}
};
}
}

View File

@@ -201,7 +201,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 644315;
public long DataPoints => 211475;
/// <summary>
/// Data Points count of the algorithm history
@@ -214,33 +214,33 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "4.18%"},
{"Average Loss", "-8.26%"},
{"Compounding Annual Return", "-8.884%"},
{"Drawdown", "4.400%"},
{"Expectancy", "-0.247"},
{"Net Profit", "-4.427%"},
{"Sharpe Ratio", "-1.283"},
{"Probabilistic Sharpe Ratio", "0.001%"},
{"Average Win", "3.13%"},
{"Average Loss", "-8.06%"},
{"Compounding Annual Return", "-10.371%"},
{"Drawdown", "5.200%"},
{"Expectancy", "-0.306"},
{"Net Profit", "-5.189%"},
{"Sharpe Ratio", "-1.353"},
{"Probabilistic Sharpe Ratio", "0.000%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.51"},
{"Alpha", "-0.061"},
{"Profit-Loss Ratio", "0.39"},
{"Alpha", "-0.072"},
{"Beta", "0.002"},
{"Annual Standard Deviation", "0.048"},
{"Annual Variance", "0.002"},
{"Information Ratio", "-0.221"},
{"Tracking Error", "0.376"},
{"Treynor Ratio", "-28.081"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$170000000.00"},
{"Annual Standard Deviation", "0.053"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-0.248"},
{"Tracking Error", "0.377"},
{"Treynor Ratio", "-31.761"},
{"Total Fees", "$1.42"},
{"Estimated Strategy Capacity", "$79000000.00"},
{"Lowest Capacity Asset", "ES 31EL5FAOOQON8|ES XFH59UK0MYO1"},
{"Fitness Score", "0.008"},
{"Fitness Score", "0.009"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.225"},
{"Return Over Maximum Drawdown", "-2.009"},
{"Portfolio Turnover", "0.023"},
{"Sortino Ratio", "-0.264"},
{"Return Over Maximum Drawdown", "-2.001"},
{"Portfolio Turnover", "0.027"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -254,7 +254,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1d90a4ed7fc218fe364435359358b2d5"}
{"OrderListHash", "621491b86f9d0e1a6abf4a882f73a38b"}
};
}
}

View File

@@ -174,7 +174,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 644315;
public long DataPoints => 211475;
/// <summary>
/// Data Points count of the algorithm history
@@ -188,31 +188,31 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-5.11%"},
{"Compounding Annual Return", "-10.226%"},
{"Drawdown", "5.100%"},
{"Average Loss", "-5.25%"},
{"Compounding Annual Return", "-10.492%"},
{"Drawdown", "5.300%"},
{"Expectancy", "-1"},
{"Net Profit", "-5.114%"},
{"Sharpe Ratio", "-1.164"},
{"Probabilistic Sharpe Ratio", "0.009%"},
{"Net Profit", "-5.251%"},
{"Sharpe Ratio", "-1.289"},
{"Probabilistic Sharpe Ratio", "0.001%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.07"},
{"Alpha", "-0.072"},
{"Beta", "0.003"},
{"Annual Standard Deviation", "0.06"},
{"Annual Variance", "0.004"},
{"Information Ratio", "-0.243"},
{"Tracking Error", "0.378"},
{"Treynor Ratio", "-23.592"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$180000000.00"},
{"Annual Standard Deviation", "0.056"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-0.249"},
{"Tracking Error", "0.377"},
{"Treynor Ratio", "-28.519"},
{"Total Fees", "$1.42"},
{"Estimated Strategy Capacity", "$290000000.00"},
{"Lowest Capacity Asset", "ES 31EL5FBZBMXES|ES XFH59UK0MYO1"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.182"},
{"Return Over Maximum Drawdown", "-2.002"},
{"Sortino Ratio", "-0.23"},
{"Return Over Maximum Drawdown", "-2"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -227,7 +227,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "76a3f4adc886f92b2f996d7e45e77dad"}
{"OrderListHash", "05dcd0b935d8206ca42ffc325fec4302"}
};
}
}

View File

@@ -185,7 +185,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 644315;
public long DataPoints => 211475;
/// <summary>
/// Data Points count of the algorithm history
@@ -198,33 +198,33 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "10.05%"},
{"Average Loss", "-5.60%"},
{"Compounding Annual Return", "8.148%"},
{"Drawdown", "0.500%"},
{"Expectancy", "0.397"},
{"Net Profit", "3.886%"},
{"Sharpe Ratio", "1.088"},
{"Probabilistic Sharpe Ratio", "53.421%"},
{"Average Win", "10.24%"},
{"Average Loss", "-6.46%"},
{"Compounding Annual Return", "6.498%"},
{"Drawdown", "0.900%"},
{"Expectancy", "0.292"},
{"Net Profit", "3.111%"},
{"Sharpe Ratio", "0.935"},
{"Probabilistic Sharpe Ratio", "45.614%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "1.79"},
{"Alpha", "0.057"},
{"Profit-Loss Ratio", "1.58"},
{"Alpha", "0.046"},
{"Beta", "-0.003"},
{"Annual Standard Deviation", "0.053"},
{"Annual Variance", "0.003"},
{"Information Ratio", "0.094"},
{"Tracking Error", "0.379"},
{"Treynor Ratio", "-20.601"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$150000000.00"},
{"Annual Standard Deviation", "0.049"},
{"Annual Variance", "0.002"},
{"Information Ratio", "0.064"},
{"Tracking Error", "0.378"},
{"Treynor Ratio", "-16.913"},
{"Total Fees", "$1.42"},
{"Estimated Strategy Capacity", "$13000000.00"},
{"Lowest Capacity Asset", "ES XFH59UP5K75W|ES XFH59UK0MYO1"},
{"Fitness Score", "0.02"},
{"Fitness Score", "0.024"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "17.34"},
{"Portfolio Turnover", "0.02"},
{"Return Over Maximum Drawdown", "7.532"},
{"Portfolio Turnover", "0.025"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -238,7 +238,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "5358f87044d3f8dc5d67cb7362b12cea"}
{"OrderListHash", "bf5fe7396dd65efe92326817647d2350"}
};
}
}

View File

@@ -168,7 +168,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 644315;
public long DataPoints => 211475;
/// <summary>
/// Data Points count of the algorithm history
@@ -181,32 +181,32 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "1.81%"},
{"Average Win", "1.74%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "3.756%"},
{"Drawdown", "0.000%"},
{"Compounding Annual Return", "3.600%"},
{"Drawdown", "0.300%"},
{"Expectancy", "0"},
{"Net Profit", "1.811%"},
{"Sharpe Ratio", "1.183"},
{"Probabilistic Sharpe Ratio", "60.811%"},
{"Net Profit", "1.736%"},
{"Sharpe Ratio", "1.008"},
{"Probabilistic Sharpe Ratio", "49.736%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.026"},
{"Alpha", "0.025"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.022"},
{"Annual Variance", "0"},
{"Information Ratio", "0.012"},
{"Annual Standard Deviation", "0.025"},
{"Annual Variance", "0.001"},
{"Information Ratio", "0.009"},
{"Tracking Error", "0.375"},
{"Treynor Ratio", "-23.475"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$39000000.00"},
{"Treynor Ratio", "-18.666"},
{"Total Fees", "$1.42"},
{"Estimated Strategy Capacity", "$100000000.00"},
{"Lowest Capacity Asset", "ES XFH59UPNF7B8|ES XFH59UK0MYO1"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "95.594"},
{"Return Over Maximum Drawdown", "11.26"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -221,7 +221,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "3e2637348e4985e9398811e0a9ba62ff"}
{"OrderListHash", "5c9cb56b3d08ac28a51d146ef6be7669"}
};
}
}

View File

@@ -182,7 +182,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 644315;
public long DataPoints => 211475;
/// <summary>
/// Data Points count of the algorithm history
@@ -195,33 +195,33 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "10.19%"},
{"Average Loss", "-8.02%"},
{"Compounding Annual Return", "2.790%"},
{"Drawdown", "0.500%"},
{"Expectancy", "0.135"},
{"Net Profit", "1.348%"},
{"Sharpe Ratio", "0.862"},
{"Probabilistic Sharpe Ratio", "42.945%"},
{"Average Win", "10.89%"},
{"Average Loss", "-7.10%"},
{"Compounding Annual Return", "6.286%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0.267"},
{"Net Profit", "3.011%"},
{"Sharpe Ratio", "1.642"},
{"Probabilistic Sharpe Ratio", "85.803%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "1.27"},
{"Alpha", "0.02"},
{"Profit-Loss Ratio", "1.53"},
{"Alpha", "0.044"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.023"},
{"Annual Standard Deviation", "0.026"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-0.006"},
{"Information Ratio", "0.058"},
{"Tracking Error", "0.375"},
{"Treynor Ratio", "-15.363"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$100000000.00"},
{"Treynor Ratio", "-54.73"},
{"Total Fees", "$1.42"},
{"Estimated Strategy Capacity", "$12000000.00"},
{"Lowest Capacity Asset", "ES 31EL5FAOUP0P0|ES XFH59UK0MYO1"},
{"Fitness Score", "0.021"},
{"Fitness Score", "0.026"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "5.859"},
{"Portfolio Turnover", "0.022"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0.026"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -235,7 +235,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "e8b27b23cb2bc65318696257af42b82e"}
{"OrderListHash", "cdf689416d6e6e04739cbaa7fb2f8b80"}
};
}
}

View File

@@ -167,7 +167,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 644315;
public long DataPoints => 211475;
/// <summary>
/// Data Points count of the algorithm history
@@ -180,32 +180,32 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "3.29%"},
{"Average Win", "3.42%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "6.869%"},
{"Compounding Annual Return", "7.162%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0"},
{"Net Profit", "3.286%"},
{"Sharpe Ratio", "1.205"},
{"Probabilistic Sharpe Ratio", "61.483%"},
{"Net Profit", "3.424%"},
{"Sharpe Ratio", "1.371"},
{"Probabilistic Sharpe Ratio", "73.287%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.048"},
{"Alpha", "0.05"},
{"Beta", "-0.002"},
{"Annual Standard Deviation", "0.04"},
{"Annual Variance", "0.002"},
{"Information Ratio", "0.07"},
{"Annual Standard Deviation", "0.036"},
{"Annual Variance", "0.001"},
{"Information Ratio", "0.075"},
{"Tracking Error", "0.377"},
{"Treynor Ratio", "-24.023"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$40000000.00"},
{"Treynor Ratio", "-30.322"},
{"Total Fees", "$1.42"},
{"Estimated Strategy Capacity", "$110000000.00"},
{"Lowest Capacity Asset", "ES 31EL5FAJQ6SBO|ES XFH59UK0MYO1"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "150.849"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -220,7 +220,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "9213af45c30119e0a53c3b57d3c553de"}
{"OrderListHash", "5895d7c6447d4b1487e4705bc32b50a6"}
};
}
}

View File

@@ -80,7 +80,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 135885;
public long DataPoints => 44671;
/// <summary>
/// Data Points count of the algorithm history
@@ -95,31 +95,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-98.645%"},
{"Drawdown", "5.400%"},
{"Compounding Annual Return", "-99.356%"},
{"Drawdown", "4.500%"},
{"Expectancy", "0"},
{"Net Profit", "-3.474%"},
{"Sharpe Ratio", "-68.954"},
{"Net Profit", "-3.675%"},
{"Sharpe Ratio", "-15.427"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-1.896"},
{"Beta", "0.058"},
{"Annual Standard Deviation", "0.014"},
{"Annual Variance", "0"},
{"Information Ratio", "-75.062"},
{"Tracking Error", "0.229"},
{"Treynor Ratio", "-16.736"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$93000000.00"},
{"Alpha", "3.273"},
{"Beta", "-0.263"},
{"Annual Standard Deviation", "0.064"},
{"Annual Variance", "0.004"},
{"Information Ratio", "-56.095"},
{"Tracking Error", "0.306"},
{"Treynor Ratio", "3.744"},
{"Total Fees", "$2.47"},
{"Estimated Strategy Capacity", "$19000000.00"},
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
{"Fitness Score", "0.005"},
{"Fitness Score", "0.007"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-10.938"},
{"Return Over Maximum Drawdown", "-25.528"},
{"Portfolio Turnover", "0.445"},
{"Sortino Ratio", "-10.333"},
{"Return Over Maximum Drawdown", "-53.15"},
{"Portfolio Turnover", "0.665"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -133,7 +133,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "c627a8c7156e3ab378f2ab13d21b5737"}
{"OrderListHash", "fea761e839af44276dd9c4bdca1ef7bb"}
};
}
}

View File

@@ -178,7 +178,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 645061;
public long DataPoints => 212221;
/// <summary>
/// Data Points count of the algorithm history
@@ -191,33 +191,33 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "10.15%"},
{"Average Loss", "-11.34%"},
{"Compounding Annual Return", "-2.573%"},
{"Drawdown", "2.300%"},
{"Expectancy", "-0.052"},
{"Net Profit", "-2.341%"},
{"Sharpe Ratio", "-0.867"},
{"Probabilistic Sharpe Ratio", "0.001%"},
{"Average Win", "10.36%"},
{"Average Loss", "-10.99%"},
{"Compounding Annual Return", "-1.942%"},
{"Drawdown", "2.000%"},
{"Expectancy", "-0.028"},
{"Net Profit", "-1.766%"},
{"Sharpe Ratio", "-0.763"},
{"Probabilistic Sharpe Ratio", "0.020%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.90"},
{"Profit-Loss Ratio", "0.94"},
{"Alpha", "-0.014"},
{"Beta", "0.001"},
{"Annual Standard Deviation", "0.016"},
{"Annual Standard Deviation", "0.017"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.603"},
{"Information Ratio", "-0.602"},
{"Tracking Error", "0.291"},
{"Treynor Ratio", "-13.292"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$45000000.00"},
{"Treynor Ratio", "-11.14"},
{"Total Fees", "$3.57"},
{"Estimated Strategy Capacity", "$16000000.00"},
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
{"Fitness Score", "0.005"},
{"Fitness Score", "0.009"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.181"},
{"Return Over Maximum Drawdown", "-1.1"},
{"Portfolio Turnover", "0.013"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-0.977"},
{"Portfolio Turnover", "0.014"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -231,7 +231,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "67d8ad460ff796937ee252c3e4340e62"}
{"OrderListHash", "271484857fd3dbf4e4a332485bcfa773"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -89,7 +89,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 420232;
public long DataPoints => 136444;
/// <summary>
/// Data Points count of the algorithm history

View File

@@ -0,0 +1,172 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regression algorithm asserts that futures have data at extended market hours when this is enabled.
/// </summary>
public class FuturesExtendedMarketHoursRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Future _es;
private Future _gc;
private bool _esRanOnRegularHours;
private bool _esRanOnExtendedHours;
private bool _gcRanOnRegularHours;
private bool _gcRanOnExtendedHours;
public override void Initialize()
{
SetStartDate(2013, 10, 6);
SetEndDate(2013, 10, 11);
_es = AddFuture(Futures.Indices.SP500EMini, Resolution.Hour, fillDataForward: true, extendedMarketHours: true);
_es.SetFilter(0, 180);
_gc = AddFuture(Futures.Metals.Gold, Resolution.Hour, fillDataForward: true, extendedMarketHours: false);
_gc.SetFilter(0, 180);
}
public override void OnData(Slice slice)
{
var sliceSymbols = new HashSet<Symbol>(slice.Keys);
sliceSymbols.UnionWith(slice.Bars.Keys);
sliceSymbols.UnionWith(slice.Ticks.Keys);
sliceSymbols.UnionWith(slice.QuoteBars.Keys);
var esIsInRegularHours = _es.Exchange.Hours.IsOpen(Time, false);
var esIsInExtendedHours = !esIsInRegularHours && _es.Exchange.Hours.IsOpen(Time, true);
var sliceHasESData = sliceSymbols.Any(symbol => symbol == _es.Symbol || symbol.Canonical == _es.Symbol);
_esRanOnRegularHours |= esIsInRegularHours && sliceHasESData;
_esRanOnExtendedHours |= esIsInExtendedHours && sliceHasESData;
var gcIsInRegularHours = _gc.Exchange.Hours.IsOpen(Time, false);
var gcIsInExtendedHours = !gcIsInRegularHours && _gc.Exchange.Hours.IsOpen(Time, true);
var sliceHasGCData = sliceSymbols.Any(symbol => symbol == _gc.Symbol || symbol.Canonical == _gc.Symbol);
_gcRanOnRegularHours |= gcIsInRegularHours && sliceHasGCData;
_gcRanOnExtendedHours |= gcIsInExtendedHours && sliceHasGCData;
var currentTimeIsRegularHours = (Time.TimeOfDay >= new TimeSpan(9, 30, 0) && Time.TimeOfDay < new TimeSpan(16, 15, 0)) ||
(Time.TimeOfDay >= new TimeSpan(16, 30, 0) && Time.TimeOfDay < new TimeSpan(17, 0, 0));
var currentTimeIsExtendedHours = !currentTimeIsRegularHours
&& (Time.TimeOfDay < new TimeSpan(9, 30, 0) || Time.TimeOfDay >= new TimeSpan(18, 0, 0));
if (esIsInRegularHours != currentTimeIsRegularHours || esIsInExtendedHours != currentTimeIsExtendedHours)
{
throw new Exception($"At {Time}, {_es.Symbol} is either in regular hours but current time is in extended hours, or viceversa");
}
}
public override void OnEndOfAlgorithm()
{
if (!_esRanOnRegularHours)
{
throw new Exception($"Algorithm should have run on regular hours for {_es.Symbol} future, which enabled extended market hours");
}
if (!_esRanOnExtendedHours)
{
throw new Exception($"Algorithm should have run on extended hours for {_es.Symbol} future, which enabled extended market hours");
}
if (!_gcRanOnRegularHours)
{
throw new Exception($"Algorithm should have run on regular hours for {_gc.Symbol} future, which did not enable extended market hours");
}
if (_gcRanOnExtendedHours)
{
throw new Exception($"Algorithm should have not run on extended hours for {_gc.Symbol} future, which did not enable extended market hours");
}
}
/// <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>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 3387;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <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"}
};
}
}

View File

@@ -0,0 +1,132 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm for testing parameterized regression algorithms get valid parameters.
/// </summary>
public class GetParameterRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2013, 10, 07);
CheckParameter((string)null, GetParameter("non-existing"), "GetParameter(\"non-existing\")");
CheckParameter("100", GetParameter("non-existing", "100"), "GetParameter(\"non-existing\", \"100\")");
CheckParameter(100, GetParameter("non-existing", 100), "GetParameter(\"non-existing\", 100)");
CheckParameter(100d, GetParameter("non-existing", 100d), "GetParameter(\"non-existing\", 100d)");
CheckParameter(100m, GetParameter("non-existing", 100m), "GetParameter(\"non-existing\", 100m)");
CheckParameter("10", GetParameter("ema-fast"), "GetParameter(\"ema-fast\")");
CheckParameter(10, GetParameter("ema-fast", 100), "GetParameter(\"ema-fast\", 100)");
CheckParameter(10d, GetParameter("ema-fast", 100d), "GetParameter(\"ema-fast\", 100d)");
CheckParameter(10m, GetParameter("ema-fast", 100m), "GetParameter(\"ema-fast\", 100m)");
Quit();
}
private void CheckParameter<T, P>(T expected, P actual, string call)
{
if (expected == null && actual != null)
{
throw new Exception($"{call} should have returned null but returned {actual} ({actual.GetType()})");
}
if (expected != null && actual == null)
{
throw new Exception($"{call} should have returned {expected} ({expected.GetType()}) but returned null");
}
if (expected != null && actual != null && (expected.GetType() != actual.GetType() || !expected.Equals(actual)))
{
throw new Exception($"{call} should have returned {expected} ({expected.GetType()}) but returned {actual} ({actual.GetType()})");
}
}
/// <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>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 0;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <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", "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", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -0,0 +1,121 @@
/*
* 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 asserting that tick history request includes both trade and quote data
/// </summary>
public class HistoryTickRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _symbol;
public override void Initialize()
{
SetStartDate(2013, 10, 11);
SetEndDate(2013, 10, 11);
_symbol = AddEquity("SPY", Resolution.Tick).Symbol;
}
public override void OnEndOfAlgorithm()
{
var history = History<Tick>(_symbol, StartDate, EndDate, Resolution.Tick);
var quotes = history.Where(x => x.TickType == TickType.Quote).ToList();
var trades = history.Where(x => x.TickType == TickType.Trade).ToList();
if (quotes.Count == 0 || trades.Count == 0)
{
throw new Exception("Expected to find at least one tick of each type (quote and trade)");
}
}
/// <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>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 2741747;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 2741732;
/// <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", "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", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -129,12 +129,12 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1337;
public long DataPoints => 1187;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 449;
public int AlgorithmHistoryDataPoints => 366;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm

View File

@@ -101,12 +101,12 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1337;
public long DataPoints => 1187;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 600;
public int AlgorithmHistoryDataPoints => 488;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm

View File

@@ -93,12 +93,12 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1387;
public long DataPoints => 1246;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 772;
public int AlgorithmHistoryDataPoints => 668;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm

View File

@@ -13,16 +13,13 @@
* limitations under the License.
*/
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Securities.Option;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Securities.Option;
using QuantConnect.Securities.Volatility;
namespace QuantConnect.Algorithm.CSharp
{
@@ -90,6 +87,7 @@ namespace QuantConnect.Algorithm.CSharp
var lambda = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Lambda).ToList();
var rho = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Rho).ToList();
var theta = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Theta).ToList();
var impliedVol = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.ImpliedVolatility).ToList();
var vega = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Vega).ToList();
// The commented out test cases all return zero.
@@ -116,9 +114,8 @@ namespace QuantConnect.Algorithm.CSharp
{
throw new AggregateException("Option contract Theta was equal to zero");
}
// The strike is far away from the underlying asset's price, and we're very close to expiry.
// Zero is an expected value here.
if (vega.Any(v => v != 0))
// Vega will equal 0 if the quote price and IV are way too off, causing the price is not sensitive to volatility change
if (vega.Zip(impliedVol, (v, iv) => (v, iv)).Any(x => x.v == 0 && x.iv < 10))
{
throw new AggregateException("Option contract Vega was equal to zero");
}

View File

@@ -0,0 +1,204 @@
/*
* 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.Market;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities.Option;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting that InteractiveBrokers brokerage model does not support index options exercise
/// </summary>
public class InteractiveBrokersBrokerageDisablesIndexOptionsExerciseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Option _option;
private OptionContract _contract;
private bool _marketOrderDone;
private bool _triedExercise;
private bool _automaticallyExercised;
private decimal _initialCash = 200000;
public override void Initialize()
{
SetStartDate(2021, 1, 4);
SetEndDate(2021, 1, 30);
SetCash(_initialCash);
SetBrokerageModel(new InteractiveBrokersBrokerageModel());
var index = AddIndex("SPX", Resolution.Hour, fillDataForward: true);
var indexOption = AddIndexOption(index.Symbol, Resolution.Hour, fillDataForward: true);
indexOption.SetFilter(filterFunc => filterFunc.CallsOnly());
_option = indexOption;
}
public override void OnData(Slice slice)
{
if (_triedExercise || !_option.Exchange.ExchangeOpen)
{
return;
}
if (_contract == null)
{
OptionChain contracts;
if (!slice.OptionChains.TryGetValue(_option.Symbol, out contracts) || !contracts.Any())
{
return;
}
_contract = contracts.First();
}
var expiry = _contract.Expiry.ConvertToUtc(_option.Exchange.TimeZone).Date;
if (UtcTime.Date < expiry && !_marketOrderDone)
{
if (MarketOrder(_contract.Symbol, 1).Status != OrderStatus.Filled)
{
throw new Exception("Expected market order to fill immediately");
}
_marketOrderDone = true;
return;
}
if (!_triedExercise && UtcTime.Date == expiry)
{
if (ExerciseOption(_contract.Symbol, 1).Status == OrderStatus.Filled)
{
throw new Exception($"Expected index option to not be exercisable on its expiration date. " +
$"Time: {UtcTime}. Expiry: {_contract.Expiry.ConvertToUtc(_option.Exchange.TimeZone)}");
}
_triedExercise = true;
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
// The manual exercise failed and we are not placing any other orders, so this is the automatic exercise
if (orderEvent.Status == OrderStatus.Filled &&
_marketOrderDone &&
_triedExercise &&
UtcTime.Date >= _contract.Expiry.ConvertToUtc(_option.Exchange.TimeZone).Date)
{
var profit = Portfolio.TotalPortfolioValue - _initialCash;
if (profit < 0)
{
throw new Exception($"Expected profit to be positive. Actual: {profit}");
}
_automaticallyExercised = true;
}
}
public override void OnEndOfAlgorithm()
{
if (!_triedExercise)
{
throw new Exception("Expected to try to exercise index option before and on expiry");
}
if (!_automaticallyExercised || Portfolio.Cash <= _initialCash)
{
throw new Exception("Expected index option to have ben automatically exercised on expiry and to have received cash");
}
}
/// <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>
/// Data Points count of all time slices of algorithm
/// </summary>
public long DataPoints => 2009;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-4.10%"},
{"Compounding Annual Return", "10.046%"},
{"Drawdown", "1.900%"},
{"Expectancy", "-1"},
{"Net Profit", "0.676%"},
{"Sharpe Ratio", "3.284"},
{"Probabilistic Sharpe Ratio", "86.292%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0.081"},
{"Annual Variance", "0.007"},
{"Information Ratio", "3.284"},
{"Tracking Error", "0.081"},
{"Treynor Ratio", "0"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$1700000.00"},
{"Lowest Capacity Asset", "SPX XL80P3HB5O6M|SPX 31"},
{"Fitness Score", "0.001"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "0.632"},
{"Return Over Maximum Drawdown", "6.244"},
{"Portfolio Turnover", "0.002"},
{"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", "a585462f5f7f9b901f253d66edb31316"}
};
}
}

View File

@@ -27,7 +27,7 @@ namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm for testing limit orders are filled after hours for futures.
/// It also asserts that market and market-on-open orders are not allowed for futures outside of regular market hours
/// It also asserts that market-on-open orders are not allowed for futures outside of regular market hours
/// </summary>
public class LimitOrdersAreFilledAfterHoursForFuturesRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
@@ -45,9 +45,10 @@ namespace QuantConnect.Algorithm.CSharp
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
dataMappingMode: DataMappingMode.LastTradingDay,
contractDepthOffset: 0
contractDepthOffset: 0,
extendedMarketHours: true
);
_futureContract = AddFutureContract(FutureChainProvider.GetFutureContractList(_continuousContract.Symbol, Time).First());
_futureContract = AddFutureContract(FutureChainProvider.GetFutureContractList(_continuousContract.Symbol, Time).First(), extendedMarketHours: true);
}
public override void OnWarmupFinished()
@@ -58,13 +59,6 @@ namespace QuantConnect.Algorithm.CSharp
throw new Exception("We should be outside regular market hours");
}
// Market order should not be allowed for futures outside of regular market hours
var futureContractMarketOrder = MarketOrder(_futureContract.Symbol, 1);
if (futureContractMarketOrder.Status != OrderStatus.Invalid)
{
throw new Exception($"Market order should not be allowed for futures outside of regular market hours");
}
// Market on open order should not be allowed for futures outside of regular market hours
var futureContractMarketOnOpenOrder = MarketOnOpenOrder(_futureContract.Symbol, 1);
if (futureContractMarketOnOpenOrder.Status != OrderStatus.Invalid)
@@ -119,7 +113,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 81526;
public long DataPoints => 82366;
/// <summary>
/// Data Points count of the algorithm history
@@ -134,10 +128,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "121.062%"},
{"Compounding Annual Return", "120.870%"},
{"Drawdown", "3.700%"},
{"Expectancy", "0"},
{"Net Profit", "1.093%"},
{"Net Profit", "1.091%"},
{"Sharpe Ratio", "4.285"},
{"Probabilistic Sharpe Ratio", "58.720%"},
{"Loss Rate", "0%"},
@@ -147,17 +141,17 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "1.285"},
{"Annual Standard Deviation", "0.314"},
{"Annual Variance", "0.098"},
{"Information Ratio", "15.223"},
{"Information Ratio", "15.222"},
{"Tracking Error", "0.077"},
{"Treynor Ratio", "1.046"},
{"Total Fees", "$3.70"},
{"Total Fees", "$4.30"},
{"Estimated Strategy Capacity", "$39000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.327"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "7.193"},
{"Return Over Maximum Drawdown", "23.933"},
{"Sortino Ratio", "7.175"},
{"Return Over Maximum Drawdown", "23.875"},
{"Portfolio Turnover", "0.334"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -114,6 +114,16 @@ namespace QuantConnect.Algorithm.CSharp
public decimal VolumeBTC = 0;
public decimal VolumeUSD = 0;
/// <summary>
/// The end time of this data. Some data covers spans (trade bars)
/// and as such we want to know the entire time span covered
/// </summary>
/// <remarks>
/// This property is overriden to allow different values for Time and EndTime
/// if they are set in the Reader. In the base implementation EndTime equals Time
/// </remarks>
public override DateTime EndTime { get; set; }
/// <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".
@@ -193,4 +203,4 @@ namespace QuantConnect.Algorithm.CSharp
}
}
}
}
}

View File

@@ -0,0 +1,149 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using System.Collections.Generic;
using QuantConnect.Securities.Future;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting that market orders are supported on extended market hours for futures.
/// </summary>
public class MarketOrdersAreSupportedOnExtendedHoursForFuturesRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Future _continuousContract;
private Future _futureContract;
public override void Initialize()
{
SetStartDate(2013, 10, 6);
SetEndDate(2013, 10, 10);
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
dataMappingMode: DataMappingMode.LastTradingDay,
contractDepthOffset: 0,
extendedMarketHours: true
);
_futureContract = AddFutureContract(FutureChainProvider.GetFutureContractList(_continuousContract.Symbol, Time).First(),
extendedMarketHours: true);
}
public override void OnData(Slice slice)
{
if (Time.TimeOfDay.Hours > 18 && !Portfolio.Invested)
{
var futureContractMarketOrder = MarketOrder(_futureContract.Symbol, 1);
var continuousContractMarketOrder = MarketOrder(_continuousContract.Mapped, 1);
if (futureContractMarketOrder.Status == OrderStatus.Invalid || continuousContractMarketOrder.Status == OrderStatus.Invalid)
{
throw new Exception($"Market orders should be allowed for futures outside of regular market hours");
}
}
}
public override void OnEndOfAlgorithm()
{
if (Transactions.GetOrders().Any(order => order.Status != OrderStatus.Filled ))
{
throw new Exception("Not all orders were filled");
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
// 13:30 and 21:00 UTC are 9:30 and 17 New york, which are the regular market hours litimits for this security
if (orderEvent.Status == OrderStatus.Filled && !Securities[orderEvent.Symbol].Exchange.DateTimeIsOpen(orderEvent.UtcTime) &&
(orderEvent.UtcTime.TimeOfDay >= new TimeSpan(13, 30, 0) && orderEvent.UtcTime.TimeOfDay < new TimeSpan(21, 0, 0)))
{
throw new Exception($"Order should have been filled during extended market hours");
}
}
/// <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>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 82366;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <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", "113.036%"},
{"Drawdown", "3.700%"},
{"Expectancy", "0"},
{"Net Profit", "1.041%"},
{"Sharpe Ratio", "4.286"},
{"Probabilistic Sharpe Ratio", "58.720%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.133"},
{"Beta", "1.285"},
{"Annual Standard Deviation", "0.314"},
{"Annual Variance", "0.098"},
{"Information Ratio", "15.206"},
{"Tracking Error", "0.078"},
{"Treynor Ratio", "1.046"},
{"Total Fees", "$4.30"},
{"Estimated Strategy Capacity", "$12000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.325"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "6.46"},
{"Return Over Maximum Drawdown", "21.495"},
{"Portfolio Turnover", "0.335"},
{"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", "e5f9bd8f1fe5684eab176db3e67ec772"}
};
}
}

View File

@@ -0,0 +1,117 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http, //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using QuantConnect.Algorithm;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Interfaces;
namespace QuantConnect.DataLibrary.Tests
{
/// <summary>
/// Example algorithm of using MeanReversionPortfolioConstructionModel
/// </summary>
public class MeanReversionPortfolioAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2020, 9, 1);
SetEndDate(2021, 2, 28);
SetCash(100000);
SetSecurityInitializer(security => security.SetMarketPrice(GetLastKnownPrice(security)));
foreach (var ticker in new List<string>{"SPY", "AAPL"})
{
AddEquity(ticker, Resolution.Daily);
}
AddAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(1)));
SetPortfolioConstruction(new MeanReversionPortfolioConstructionModel());
}
/// <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>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1115;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 47;
/// <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", "71"},
{"Average Win", "2.31%"},
{"Average Loss", "-0.29%"},
{"Compounding Annual Return", "19.882%"},
{"Drawdown", "12.300%"},
{"Expectancy", "2.098"},
{"Net Profit", "9.303%"},
{"Sharpe Ratio", "0.642"},
{"Probabilistic Sharpe Ratio", "36.783%"},
{"Loss Rate", "66%"},
{"Win Rate", "34%"},
{"Profit-Loss Ratio", "8.04"},
{"Alpha", "-0.022"},
{"Beta", "1.299"},
{"Annual Standard Deviation", "0.246"},
{"Annual Variance", "0.06"},
{"Information Ratio", "0.12"},
{"Tracking Error", "0.163"},
{"Treynor Ratio", "0.122"},
{"Total Fees", "$130.72"},
{"Estimated Strategy Capacity", "$370000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.144"},
{"Kelly Criterion Estimate", "-0.659"},
{"Kelly Criterion Probability Value", "0.566"},
{"Sortino Ratio", "0.916"},
{"Return Over Maximum Drawdown", "1.618"},
{"Portfolio Turnover", "0.21"},
{"Total Insights Generated", "248"},
{"Total Insights Closed", "244"},
{"Total Insights Analysis Completed", "244"},
{"Long Insight Count", "248"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$678641.0425"},
{"Total Accumulated Estimated Alpha Value", "$4053937.6722"},
{"Mean Population Estimated Insight Value", "$16614.4987"},
{"Mean Population Direction", "39.3443%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "37.8719%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "b6dca94ebb3d821f72457389a7cac298"}
};
}
}

View File

@@ -92,7 +92,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 7080848;
public long DataPoints => 2561853;
/// <summary>
/// Data Points count of the algorithm history
@@ -105,17 +105,17 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "4"},
{"Average Win", "0.00%"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "0.003%"},
{"Drawdown", "0%"},
{"Expectancy", "0.351"},
{"Compounding Annual Return", "-0.020%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Net Profit", "0.000%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "1.70"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
@@ -123,14 +123,14 @@ namespace QuantConnect.Algorithm.CSharp
{"Information Ratio", "-57.739"},
{"Tracking Error", "0.178"},
{"Treynor Ratio", "0"},
{"Total Fees", "$7.40"},
{"Total Fees", "$9.88"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
{"Fitness Score", "0.017"},
{"Lowest Capacity Asset", "GC VMRHKN2NLWV1"},
{"Fitness Score", "0.008"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-121.652"},
{"Portfolio Turnover", "0.017"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -145,7 +145,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "75477a2d1f470d97bdbc5689712c54bf"}
{"OrderListHash", "7cd0ac939e3b54130734e111180e99ae"}
};
}
}

View File

@@ -99,7 +99,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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>
/// <param name="orderEvent">Order event details containing details of the events</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)
{

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