Compare commits

...

151 Commits
14151 ... 14751

Author SHA1 Message Date
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
Martin-Molinero
3f2bcc1784 Add missing CancellationTokenSource dispose (#6512)
- Add missing CancellationTokenSource disposals to avoid memory leaks
2022-08-01 11:12:01 -03:00
Martin-Molinero
30d137e9cc Track CPU usage (#6520)
- Track CPU usage, useful for debugging
2022-08-01 11:10:52 -03:00
Martin-Molinero
ab9ad75c93 Update readme.md 2022-07-29 15:52:57 -03:00
Jhonathan Abreu
1440842d87 Fix LocalMarketHours.GetMarketClose for extended market hours (#6516)
* Fix LocalMarketHours.GetMarketClose to get the actual next market close time with extended market hours

The method was not properly considering gaps between regular hours close and extended market open

* Revert some changes to fix errors
2022-07-29 12:31:10 -03:00
Martin-Molinero
2df01c4d2e Update readme.md 2022-07-28 20:54:04 -03:00
Martin-Molinero
82aab246a8 Update readme.md 2022-07-28 20:43:32 -03:00
Martin-Molinero
f665d693b7 Update readme.md 2022-07-28 20:30:15 -03:00
Martin-Molinero
ef531e09bd Add Lean commands (#6513)
* Add Lean commands

- Add Lean commands to common project

* Address reviews

- Address reviews, refactor command interfaces and classes

* Rename FileCommandQueueHandler to FileCommandHandler
2022-07-28 16:44:40 -03:00
Jhonathan Abreu
3db470de52 Add fill forward and extended market parameters to QuantBook's history methods (#6515) 2022-07-28 15:29:15 -03:00
Martin-Molinero
a43bdaf1c7 Fix crypto hash leak (#6511)
- Fix crypto sha256 memory leak
- Minor improvements to reduce improve performance
2022-07-26 20:00:23 -03:00
Martin-Molinero
e0f483c46b Fix ARM IB gateway java version check (#6509)
- Fix for ARM IB gateway java version check.
  See https://github.com/QuantConnect/lean-cli/issues/114
2022-07-26 10:35:47 -03:00
Martin-Molinero
8093df31cc Update readme.md 2022-07-25 20:11:25 -03:00
Ronit Jain
9df9d76081 get value from config, default to local (#6502) 2022-07-22 11:08:46 -03:00
Jhonathan Abreu
ad844e9411 Fix checking market open for post market segments (#6500)
* Consider post-market segments when getting market open

* Consider post-market segments when getting market open

* Fixes and more unit tests
2022-07-22 10:57:01 -03:00
Derek Melchin
e7e9153fbf Update indicator source links (#6501) 2022-07-21 17:50:14 -03:00
Martin-Molinero
24627f5efa Fix optimization json converter (#6499)
- Fix optimization json converter, not handling correctly different
  account currencies. Updating unit test to reproduce issue
2022-07-21 17:43:14 -03:00
Martin-Molinero
440282c138 Update compare_benchmarks.py 2022-07-20 20:04:33 -03:00
Martin-Molinero
3d3f04abbc Update python autocomplete readme (#6498)
- Updating the python autocomplete readme to suggest adding
 `from AlgorithmImports import *`
2022-07-20 18:40:52 -03:00
Martin-Molinero
0a64462e50 Add performance gh action (#6497)
* Add performance gh action

- Add new performance github action, running python and csharp benchmark
  algorithms
- Adjusting algorithms length so they are not too long or too short

* Checkout master branch benchmark reference
2022-07-20 18:15:38 -03:00
Martin-Molinero
c43f472503 Fill model will use internal configurations (#6494)
- Fill model will take into account internal configurations, this is
  specially relevant for continuous future mapped contracts. Updating
  regression algorithms and unit tests.
- Allowing internal configurations to update trade builder information
2022-07-19 19:00:35 -03:00
Jhonathan Abreu
6c93af96a1 Disable MOO orders for futures out of regular market hours (#6480)
* Remove suppport for market orders and MOO orders for futures

* Add regression algorithm to assert that limit orders are filled on after hours for futures

* Remove suppport for market orders and MOO orders for futures in DefaultBrokerageModel

* Update regression algorithms stats

* Fixed regression algorithm and clean up

* Add unit tests

* Fix regression algorithms

* Address changes request
2022-07-19 16:18:06 -03:00
Martin-Molinero
b3cb24a16f Update readme.md 2022-07-19 14:39:14 -03:00
Jhonathan Abreu
38f7e72dbe Add delisted futures and FOP regression algorithms with daily resolution (#6493)
* Add regression algorithms for delisted futures with daily resolution

* Add regression algorithms for delisted futures options with daily resolution

* Updated documentation
2022-07-18 17:53:43 -03:00
Martin-Molinero
a9073396bd Add WarmUpResolution pass through (#6487)
- Add new WarmUpResoltuion pass through version for friendly
user experience. Adding unit test
2022-07-18 13:47:04 -03:00
Martin-Molinero
b7df632294 Correctly handle Polygon authentication sequence (#6485)
- Correctly handler Polygon data queue handler authentication sequence
2022-07-18 13:40:21 -03:00
Martin-Molinero
38772a5a89 Do not apply split during live warmup (#6488)
- Do not apply split during live warmup. Adding unit tests asserting the
  behavior for live dividends and splits during warmup and non warmup
2022-07-15 18:17:26 -03:00
Martin-Molinero
7540af454c Warmup resolution respected (#6467)
* Respect warmup resolution given

- The data feed will respect the warmup resolution given and override
  the resolution used by the algorithm when adding a subscription.
  Updating regression algorithm to keep previous statistics. Adding new
  regression algorithm asserting the desired behavior

* Testing improvements

- Add more unit tests and regresion test
- Add missing data for crypto
- Fix bug with FFed data crossing after the end time of the warmup
  request

* Add more Warmup resolution regression algorithms

- Adding more warmup resolution regression algorithms, using
  Settings.WarmupResolution and an option selection case

* Add more warmup regression tests

- Adding more warmup regression tests.
- Will no longer skip universe selection subscriptions from warmup
  resolution enforcement. Updating regression algorithms data points

* Fix bug with data rounding

- Fix data rounding bug when warmup resolution is set to a different
  value than the original configuration. Updating regression algorithms
  to assert the expected behavior

* Address reviews

- Revert regression algorithms changes to use Resolution during warmup.
  Updating their stats.
- Adding new regression algorithms asserting the behavior warming up
  using a timespan and no warmup resolution
- Fix bug where data used to warmup the 'normal' enumerator will make it
  through into the warmup time span. Updating tests

* Address reviews

- Add missing comments, explaning warmup algorithms time span
  calculations.
- Revert changes in existing `WarmupOptionTimeSpanRegressionAlgorithm`
  to reduce diff to minimum
- Adding new warmup unit tests asseting algorithm warmup start time, for
  different combinations of bar count, timespan, resolution
2022-07-15 13:05:06 -03:00
Derek Melchin
cd06e87493 Update data normalization mode comments (#6486)
* Update Data Normalization Mode enum descriptions

* Extend descriptions
2022-07-15 11:10:52 -03:00
Ricardo Andrés Marino Rojas
5200a9e593 Add ReadBacktestOrders() and ReadLiveOrders() methods (#6329)
* First commit

* Any change

* Add more unit tests

* Nit changes

* Changes requested

* Fix bugs and requested changes

* Requested changes

* More changes

* Check ongoing backtest orders

* Read ongoing backtest does not fail

* nit change

* Fixes for standarized API orders response

- Fixes for a standarized API read orders reponse

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-07-14 16:02:58 -03:00
Martin-Molinero
07aa5625e1 Avoid division by zero error in backtesting result handler (#6484)
* Minor improvements

- Avoid division by zero error in backtesting result handler. Race
  condition where the SetAlgorithm implementation would still be running
  and we try to loop through the update method
- Improvement nullreference exception message
- Cleanup resolution to timespan extension method

* Address reviews

- Cleanup data config fill forward conditional statement for tick
  resolution
2022-07-14 12:54:55 -03:00
Martin-Molinero
31fc7ac236 Do not generate Equity Quote Daily data (#6483)
- Fix for so the random data generator does not try to create daily
  equity quote data
2022-07-14 10:20:34 -03:00
Martin-Molinero
e6f8a7535e Fix live future and option universe selection daily resolution (#6482)
* Fix live future and option universe selection daily resolution

- Adding unit test reproducing issue for option and future universe
  chain using daily resolution, since was rounding down in UTC TZ the
  date might not change and it would re emit the same data point

* Address reviews

- Add more test cases
- Adding locks around RegisteredSecurityDataTypesProvider to allow it to
  be used by multiple threads at the same time without exploding
2022-07-13 19:10:13 -03:00
Martin-Molinero
778d436b94 Removed mapped futures contract is non tradable (#6479)
* Minor fixes for mapped futures contract

- Future security was never able to be non tradable
- Skip remove future contracts from live holdings. Adding unit test
  reproducing issue and regression algorithm

* Fix removal of continuous futures

- The canonical continuous future would leave behind an OpenInterest
  subscription when removed because of a different in the way the
  configurations were built, this will now be centralized in a single
  method. Adding unit tests reproducing issue
- FillForwarding setting of the continuous future was not being
  respected. Updating algorithm reproducing the issue to assert the
  behavior failing in master

* Address reviews

- Minor refactors addressing reviews
2022-07-13 15:36:24 -03:00
Martin-Molinero
36ddf1c618 Update config.json 2022-07-13 15:33:48 -03:00
Martin-Molinero
632833caaa Minor live related testing changes (#6481)
- The history provider manager will log the underlying instances it's using.
- Allow brokerage test suites to reuse the algorithm stubs class
2022-07-13 15:26:45 -03:00
Martin-Molinero
6200988ad5 Fix result handler live holdings (#6478)
* Fix result handler live holdings

- Live result handler live holdings will include future assets
  associated with continuous futures. Adding unit tests

* Fixed for live holdings price rounding

- Live holdings will use the SPDB minimum price variation for rounding.
  Adding unit tests
2022-07-12 18:31:35 -03:00
Martin-Molinero
826f2cbbf9 Minor refactor messaging handler (#6472) 2022-07-11 16:24:26 -03:00
Jared
e54cc3e948 Update readme.md 2022-07-08 11:32:05 -07:00
Louis Szeto
413a084254 Add Price in CoarseFundamental (#6464)
* Update CoarseFundamental.cs

* Fix typo

* Add virtual/override
2022-07-06 13:28:57 -03:00
Martin-Molinero
8c0b60cd2f Refactor work queue scheduling (#6465)
- Remove thread in charge of sorting and updating the queues weight.
  This will be handled by each worker thread instead. Avoid cases where
  the work count is so high that the sorting thread in master would not
  be able to update all the weights, causing data to be enqueued beyond
  the max prefetch limit. Adding benchmark algorithm reproducing issue
2022-07-06 12:13:32 -03:00
Martin-Molinero
64f0a9e0a2 Fix for ApiDataProvider (#6461)
- Avoid race condition while downloading data.
- Reused http client for downloads
2022-07-05 18:43:58 -03:00
Martin-Molinero
3f407cd80f Smaller live warmup history requests (#6455)
- Smaller live warmup history requests, will keep track of the last point
  we got from the file based enumerator and start our history enumeration from this point
2022-07-05 13:15:23 -03:00
Jhonathan Abreu
5758b65099 Added configuration parameters to Python QCAlgorithm.History() method that takes custom data source type (#6448)
* Add new Python QCAlgorithm.History() method with all parameters and type

* Add regression algorithms

* Using all parameters in History()

* Use private methods to reuse History() code

* Use private methods to reuse History() code

* Add unit tests for QCAlgorithm.Python.History()

* Add unit tests for QCAlgorithm.Python.History()

* Add unit tests for QCAlgorithm.Python.History()

* Add unit tests for QCAlgorithm.Python.History()

* Add unit tests for QCAlgorithm.Python.History()

* Add unit tests for QCAlgorithm.Python.History()

* Asserting history count
2022-07-05 13:14:08 -03:00
Louis Szeto
c1db23250e Update enum values in comments (#6460) 2022-07-05 10:29:28 -03:00
Martin-Molinero
b426483e1d Rebase org- branches on trunk (#6456)
- Adding github actions to automatically rebase org- branches on trunk
  when master get's a merge
2022-07-01 12:24:03 -03:00
Louis Szeto
30e47f3e8b Add basic template algorithm for Cfd and FutureOption (#6454) 2022-07-01 12:20:45 -03:00
Martin-Molinero
506e3a1c2c Add default value for GetParameter (#6452)
- Allow providing a default value for GetParameter. Updating regression
  test to use it
2022-06-29 18:58:09 -03:00
Alexandre Catarino
ab228e8eca Adds typing Import to AlgorithmImports (#6450) 2022-06-29 15:37:43 -03:00
Martin-Molinero
dc043f8c09 Fix future chain data normalization mode (#6445)
- Similar to the OptionChainUniverse, the future chain universe should
  also add it's contracts using the raw data normalization mode. Adding
  regression algorithm reproducing issue
2022-06-28 15:15:09 -03:00
Martin-Molinero
05bfad729c Fix custom fine universe selection model (#6447)
- For for custom fine universe selection model so it can return
  Universe.Unchanged. Adding regression tests
2022-06-28 15:11:04 -03:00
Martin-Molinero
5c6a779f4d Period consolidator adjusments (#6444)
- Replace logic to convert TimeSpan based PeriodConsolidator into count
  based, by an override of the 'potentialStartTime' in the case we could
  be falling into a look ahead consolidated bar end time
2022-06-27 19:17:20 -03:00
Martin-Molinero
630503bf9c Remove deprecated inspect.getargspec (#6443)
- Remove deprecated python `inspect.getargspec` usage, replace for new
  `getfullargspec`. Adding unit tests reproducing issue
2022-06-27 18:49:46 -03:00
Martin-Molinero
18eec48a3d Avoid PythonNet runtime stash on shutdown (#6441)
* Can't relesase the GIL after shutdown

* Bump version to pythonnet 2.0.16
2022-06-27 13:04:01 -03:00
594 changed files with 28004 additions and 5910 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"
]
}

39
.github/workflows/benchmarks.yml vendored Normal file
View File

@@ -0,0 +1,39 @@
name: Benchmarks
on:
push:
branches: ['*']
tags: ['*']
pull_request:
branches: [master]
jobs:
build:
runs-on: self-hosted
container:
image: quantconnect/lean:foundation
volumes:
- /nas:/Data
steps:
- uses: actions/checkout@v2
- name: Checkout Lean Master
uses: actions/checkout@v2
with:
repository: QuantConnect/Lean
path: LeanMaster
ref: 'master'
- name: Build Lean Master
run: dotnet build --verbosity q /p:Configuration=Release /p:WarningLevel=1 LeanMaster/QuantConnect.Lean.sln
- name: Run Benchmarks Master
run: cp run_benchmarks.py LeanMaster/run_benchmarks.py && cd LeanMaster && python run_benchmarks.py /Data && cd ../
- name: Build
run: dotnet build --verbosity q /p:Configuration=Release /p:WarningLevel=1 QuantConnect.Lean.sln
- name: Run Benchmarks
run: python run_benchmarks.py /Data
- name: Compare Benchmarks
run: python compare_benchmarks.py LeanMaster/benchmark_results.json benchmark_results.json

View File

@@ -0,0 +1,21 @@
name: Rebase Organization Branches
on:
push:
branches:
- 'master'
jobs:
build:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Rebase Organization Branches
run: |
chmod +x rebase_organization_branches.sh
./rebase_organization_branches.sh
env:
QC_GIT_TOKEN: ${{ secrets.QC_GIT_TOKEN }}

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

@@ -0,0 +1,152 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using System.Collections.Generic;
using System.Linq;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regression algorithm tests we can add future option contracts from contracts in the future chain
/// </summary>
public class AddFutureOptionContractFromFutureChainRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private bool _addedOptions;
public override void Initialize()
{
SetStartDate(2020, 1, 4);
SetEndDate(2020, 1, 6);
var es = AddFuture(Futures.Indices.SP500EMini, Resolution.Minute, Market.CME);
es.SetFilter((futureFilter) =>
{
return futureFilter.Expiration(0, 365).ExpirationCycle(new[] { 3, 6 });
});
}
public override void OnData(Slice data)
{
if (!_addedOptions)
{
_addedOptions = true;
foreach (var futuresContracts in data.FutureChains.Values)
{
foreach (var contract in futuresContracts)
{
var option_contract_symbols = OptionChainProvider.GetOptionContractList(contract.Symbol, Time).ToList();
if(option_contract_symbols.Count == 0)
{
continue;
}
foreach (var option_contract_symbol in option_contract_symbols.OrderBy(x => x.ID.Date)
.ThenBy(x => x.ID.StrikePrice)
.ThenBy(x => x.ID.OptionRight).Take(5))
{
AddOptionContract(option_contract_symbol);
}
}
}
}
if (Portfolio.Invested)
{
return;
}
foreach (var chain in data.OptionChains.Values)
{
foreach (var option in chain.Contracts.Keys)
{
MarketOrder(option, 1);
MarketOrder(option.Underlying, 1);
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = 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 => 12164;
/// <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", "20"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "386219349.202%"},
{"Drawdown", "5.200%"},
{"Expectancy", "0"},
{"Net Profit", "11.912%"},
{"Sharpe Ratio", "1604181.92"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"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"},
{"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", "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

@@ -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

@@ -0,0 +1,72 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Orders;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Algorithm demonstrating CFD asset types and requesting history.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="history" />
/// <meta name="tag" content="cfd" />
public class BasicTemplateCfdAlgorithm : QCAlgorithm
{
private Symbol _symbol;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetAccountCurrency("EUR");
SetStartDate(2019, 2, 20);
SetEndDate(2019, 2, 21);
SetCash("EUR", 100000);
_symbol = AddCfd("DE30EUR").Symbol;
// Historical Data
var history = History(_symbol, 60, Resolution.Daily);
Log($"Received {history.Count()} bars from CFD historical data call.");
}
/// <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 slice)
{
// Access Data
if (slice.QuoteBars.ContainsKey(_symbol))
{
var quoteBar = slice.QuoteBars[_symbol];
Log($"{quoteBar.EndTime} :: {quoteBar.Close}");
}
if (!Portfolio.Invested)
SetHoldings(_symbol, 1);
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
Debug($"{Time} {orderEvent.ToString()}");
}
}
}

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
@@ -131,31 +132,31 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-0.007%"},
{"Average Loss", "-0.02%"},
{"Compounding Annual Return", "-0.033%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.004%"},
{"Sharpe Ratio", "-0.369"},
{"Probabilistic Sharpe Ratio", "10.640%"},
{"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.751"},
{"Information Ratio", "-2.752"},
{"Tracking Error", "0.082"},
{"Treynor Ratio", "-0.616"},
{"Total Fees", "$3.70"},
{"Treynor Ratio", "1.883"},
{"Total Fees", "$4.30"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.007"},
{"Fitness Score", "0.006"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-0.738"},
{"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", "bd7fbe57802dfedb36c85609b7234016"}
{"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

@@ -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.Linq;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Algorithm demonstrating FutureOption asset types and requesting history.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="history" />
/// <meta name="tag" content="future option" />
public class BasicTemplateFutureOptionAlgorithm : QCAlgorithm
{
private Symbol _symbol;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2022, 1, 1);
SetEndDate(2022, 2, 1);
SetCash(100000);
var gold_futures = AddFuture(Futures.Metals.Gold, Resolution.Minute);
gold_futures.SetFilter(0, 180);
_symbol = gold_futures.Symbol;
AddFutureOption(_symbol, universe => universe.Strikes(-5, +5)
.CallsOnly()
.BackMonth()
.OnlyApplyFilterAtMarketOpen());
// Historical Data
var history = History(_symbol, 60, Resolution.Daily);
Log($"Received {history.Count()} bars from {_symbol} FutureOption historical data call.");
}
/// <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 slice)
{
// Access Data
foreach(var kvp in slice.OptionChains)
{
var underlyingFutureContract = kvp.Key.Underlying;
var chain = kvp.Value;
if (chain.Count() == 0) continue;
foreach(var contract in chain)
{
Log($@"Canonical Symbol: {kvp.Key};
Contract: {contract};
Right: {contract.Right};
Expiry: {contract.Expiry};
Bid price: {contract.BidPrice};
Ask price: {contract.AskPrice};
Implied Volatility: {contract.ImpliedVolatility}");
}
if (!Portfolio.Invested)
{
var atmStrike = chain.OrderBy(x => Math.Abs(chain.Underlying.Price - x.Strike)).First().Strike;
var selectedContract = chain.Where(x => x.Strike == atmStrike).OrderByDescending(x => x.Expiry).First();
MarketOrder(selectedContract.Symbol, 1);
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
Debug($"{Time} {orderEvent.ToString()}");
}
}
}

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", "8220"},
{"Total Trades", "2700"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "13.500%"},
{"Expectancy", "-0.818"},
{"Net Profit", "-13.517%"},
{"Sharpe Ratio", "-98.781"},
{"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.676"},
{"Beta", "0.042"},
{"Annual Standard Deviation", "0.01"},
{"Annual Variance", "0"},
{"Information Ratio", "-73.981"},
{"Tracking Error", "0.233"},
{"Treynor Ratio", "-23.975"},
{"Total Fees", "$15207.00"},
{"Estimated Strategy Capacity", "$8000.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.033"},
{"Fitness Score", "0.001"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-8.62"},
{"Return Over Maximum Drawdown", "-7.81"},
{"Portfolio Turnover", "302.321"},
{"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", "35b3f4b7a225468d42ca085386a2383e"}
{"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);
// The following statements yield the same filtering criteria
_futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
_futureGold.SetFilter(0, 182);
}
/// <summary>
@@ -76,15 +80,17 @@ namespace QuantConnect.Algorithm.CSharp
select futuresContract
).FirstOrDefault();
// if found, trade it
if (contract != null && IsMarketOpen(contract.Symbol))
// 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();
}
@@ -111,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
@@ -123,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"},
@@ -164,7 +170,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "909088689d7030fa33c5da3c15fba98e"}
{"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", "1988"},
{"Average Win", "0.01%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-4.120%"},
{"Drawdown", "4.200%"},
{"Expectancy", "-0.870"},
{"Net Profit", "-4.150%"},
{"Sharpe Ratio", "-6.061"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "97%"},
{"Win Rate", "3%"},
{"Profit-Loss Ratio", "2.92"},
{"Alpha", "-0.027"},
{"Beta", "-0.006"},
{"Annual Standard Deviation", "0.005"},
{"Total Trades", "638"},
{"Average Win", "0.02%"},
{"Average Loss", "-0.01%"},
{"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.66"},
{"Information Ratio", "-1.473"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "4.919"},
{"Total Fees", "$3677.80"},
{"Estimated Strategy Capacity", "$2000.00"},
{"Treynor Ratio", "3.179"},
{"Total Fees", "$1456.18"},
{"Estimated Strategy Capacity", "$6000.00"},
{"Lowest Capacity Asset", "ES VP274HSU1AF5"},
{"Fitness Score", "0.128"},
{"Fitness Score", "0.045"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-6.856"},
{"Return Over Maximum Drawdown", "-0.995"},
{"Portfolio Turnover", "0.648"},
{"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", "87d2b127c9859cad9d2c65ac9d76deb5"}
{"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)
{

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

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -28,7 +28,7 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
public override void Initialize()
{
SetStartDate(2000, 01, 01);
SetEndDate(2017, 01, 01);
SetEndDate(2022, 01, 01);
SetBenchmark(dt => 1m);
AddEquity("SPY");
}
@@ -42,4 +42,4 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
}
}
}
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -34,7 +34,7 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
UniverseSettings.Resolution = Resolution.Minute;
SetStartDate(2017, 11, 01);
SetEndDate(2018, 01, 01);
SetEndDate(2018, 3, 01);
SetCash(50000);
AddUniverse(CoarseSelectionFunction, FineSelectionFunction);
@@ -98,4 +98,4 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
_changes = changes;
}
}
}
}

View File

@@ -0,0 +1,87 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Data;
namespace QuantConnect.Algorithm.CSharp.Benchmarks
{
/// <summary>
/// Benchmark Algorithm: Loading and synchronization of 500 equity minute symbols and their options.
/// </summary>
public class EmptyEquityAndOptions400Benchmark : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2022, 5, 11);
SetEndDate(2022, 5, 12);
var equity_symbols = new[] {
"MARK", "TSN", "DT", "RDW", "CVE", "NXPI", "FIVN", "CLX", "SPXL", "BKSY", "NUGT", "CF", "NEGG",
"RH", "SIRI", "ITUB", "CSX", "AUR", "LIDR", "CMPS", "DHI", "GLW", "NTES", "CIFR", "S", "HSBC",
"HIPO", "WTRH", "AMRN", "BIIB", "RIO", "EDIT", "TEAM", "CNK", "BUD", "MILE", "AEHR", "DOCN",
"CLSK", "BROS", "MLCO", "SBLK", "ICLN", "OPK", "CNC", "SKX", "SESN", "VRM", "ASML", "BBAI",
"HON", "MRIN", "BLMN", "NTNX", "POWW", "FOUR", "HOG", "GOGO", "MGNI", "GENI", "XPDI",
"DG", "PSX", "RRC", "CORT", "MET", "UMC", "INMD", "RBAC", "ISRG", "BOX", "DVAX", "CRVS", "HLT",
"BKNG", "BENE", "CLVS", "ESSC", "PTRA", "BE", "FPAC", "YETI", "DOCS", "DB", "EBON", "RDS.B",
"ERIC", "BSIG", "INTU", "MNTS", "BCTX", "BLU", "FIS", "MAC", "WMB", "TTWO", "ARDX", "SWBI",
"ELY", "INDA", "REAL", "ACI", "APRN", "BHP", "CPB", "SLQT", "ARKF", "TSP", "OKE", "NVTA", "META",
"CSTM", "KMX", "IBB", "AGEN", "WOOF", "MJ", "HYZN", "RSI", "JCI", "EXC", "HPE", "SI", "WPM",
"PRTY", "BBD", "FVRR", "CANO", "INDI", "MDLZ", "KOLD", "AMBA", "SOXS", "RSX", "ZEN", "PUBM",
"VLDR", "CI", "ISEE", "GEO", "BKR", "DHR", "GRPN", "NRXP", "ACN", "MAT", "BODY", "ENDP",
"SHPW", "AVIR", "GPN", "BILL", "BZ", "CERN", "ARVL", "DNMR", "NTR", "FSM", "BMBL", "PAAS",
"INVZ", "ANF", "CL", "XP", "CS", "KD", "WW", "AHT", "GRTX", "XLC", "BLDP", "HTA", "APT", "BYSI",
"ENB", "TRIT", "VTNR", "AVCT", "SLI", "CP", "CAH", "ALLY", "FIGS", "PXD", "TPX", "ZI", "BKLN", "SKIN",
"LNG", "NU", "CX", "GSM", "NXE", "REI", "MNDT", "IP", "BLOK", "IAA", "TIP", "MCHP", "EVTL", "BIGC",
"IGV", "LOTZ", "EWC", "DRI", "PSTG", "APLS", "KIND", "BBIO", "APPH", "FIVE", "LSPD", "SHAK",
"COMM", "NAT", "VFC", "AMT", "VRTX", "RGS", "DD", "GBIL", "LICY", "ACHR", "FLR", "HGEN", "TECL",
"SEAC", "NVS", "NTAP", "ML", "SBSW", "XRX", "UA", "NNOX", "SFT", "FE", "APP", "KEY", "CDEV",
"DPZ", "BARK", "SPR", "CNQ", "XL", "AXSM", "ECH", "RNG", "AMLP", "ENG", "BTI", "REKR",
"STZ", "BK", "HEAR", "LEV", "SKT", "HBI", "ALB", "CAG", "MNKD", "NMM", "BIRD", "CIEN", "SILJ",
"STNG", "GUSH", "GIS", "PRPL", "SDOW", "GNRC", "ERX", "GES", "CPE", "FBRX", "WM", "ESTC",
"GOED", "STLD", "LILM", "JNK", "BOIL", "ALZN", "IRBT", "KOPN", "AU", "TPR", "RWLK", "TROX",
"TMO", "AVDL", "XSPA", "JKS", "PACB", "LOGI", "BLK", "REGN", "CFVI", "EGHT", "ATNF", "PRU",
"URBN", "KMB", "SIX", "CME", "ENVX", "NVTS", "CELH", "CSIQ", "GSL", "PAA", "WU", "MOMO",
"TOL", "WEN", "GTE", "EXAS", "GDRX", "PVH", "BFLY", "SRTY", "UDOW", "NCR", "ALTO", "CRTD",
"GOCO", "ALK", "TTM", "DFS", "VFF", "ANTM", "FREY", "WY", "ACWI", "PNC", "SYY", "SNY", "CRK",
"SO", "XXII", "PBF", "AER", "RKLY", "SOL", "CND", "MPLX", "JNPR", "FTCV", "CLR", "XHB", "YY",
"POSH", "HIMS", "LIFE", "XENE", "ADM", "ROST", "MIR", "NRG", "AAP", "SSYS", "KBH", "KKR", "PLAN",
"DUK", "WIMI", "DBRG", "WSM", "LTHM", "OVV", "CFLT", "EWT", "UNFI", "TX", "EMR", "IMGN", "K",
"ONON", "UNIT", "LEVI", "ADTX", "UPWK", "DBA", "VOO", "FATH", "URI", "MPW", "JNUG", "RDFN",
"OSCR", "WOLF", "SYF", "GOGL", "HES", "PHM", "CWEB", "ALDX", "BTWN", "AFL", "PPL", "CIM"
};
Settings.DataSubscriptionLimit = 1000000;
SetWarmUp(TimeSpan.FromDays(1));
foreach(var ticker in equity_symbols)
{
var option = AddOption(ticker);
option.SetFilter(1, 7, 0, 90);
}
AddEquity("SPY");
}
public override void OnData(Slice slice)
{
if (IsWarmingUp)
{
return;
}
Quit("The end!");
}
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -30,8 +30,8 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
{
public override void Initialize()
{
SetStartDate(2015, 10, 1);
SetEndDate(2015, 11, 15);
SetStartDate(2015, 9, 1);
SetEndDate(2015, 12, 1);
foreach (var symbol in Symbols.Equity.All.Take(400))
{
AddSecurity(SecurityType.Equity, symbol);
@@ -402,4 +402,4 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
#endregion
}
}
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -27,7 +27,7 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
public override void Initialize()
{
SetStartDate(2008, 01, 01);
SetEndDate(2009, 01, 01);
SetEndDate(2008, 06, 01);
SetBenchmark(dt => 1m);
AddEquity("SPY", Resolution.Second);
}
@@ -36,4 +36,4 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
{
}
}
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -23,7 +23,7 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
public override void Initialize()
{
SetStartDate(2010, 01, 01);
SetEndDate(2018, 01, 01);
SetEndDate(2022, 01, 01);
SetCash(10000);
_symbol = AddEquity("SPY").Symbol;
}
@@ -38,4 +38,4 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
var dailyOpen = dailyHistory.Open;
}
}
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -32,7 +32,7 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
public override void Initialize()
{
SetStartDate(2010, 01, 01);
SetEndDate(2018, 01, 01);
SetEndDate(2022, 01, 01);
AddSecurity(SecurityType.Equity, "SPY", Resolution.Minute);
@@ -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;
@@ -68,4 +68,4 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
}
}
}
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
@@ -24,7 +24,7 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
public override void Initialize()
{
SetStartDate(2011, 1, 1);
SetEndDate(2018, 1, 1);
SetEndDate(2022, 1, 1);
SetCash(100000);
AddEquity("SPY");
foreach (int period in Enumerable.Range(0, 300))
@@ -37,4 +37,4 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
public override void OnData(Slice data) { }
private void Rebalance() { }
}
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -29,8 +29,8 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
{
UniverseSettings.Resolution = Resolution.Daily;
SetStartDate(2017, 11, 01);
SetEndDate(2018, 01, 01);
SetStartDate(2017, 1, 01);
SetEndDate(2019, 1, 01);
SetCash(50000);
AddUniverse(CoarseSelectionFunction);

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -27,8 +27,8 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
{
UniverseSettings.Resolution = Resolution.Daily;
SetStartDate(2017, 11, 01);
SetEndDate(2018, 01, 01);
SetStartDate(2017, 1, 01);
SetEndDate(2019, 1, 01);
SetCash(50000);
AddUniverse(CoarseSelectionFunction);

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.21%"},
{"Average Win", "1.50%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "2.412%"},
{"Compounding Annual Return", "2.993%"},
{"Drawdown", "1.600%"},
{"Expectancy", "0"},
{"Net Profit", "1.209%"},
{"Sharpe Ratio", "0.782"},
{"Probabilistic Sharpe Ratio", "40.528%"},
{"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.005"},
{"Beta", "0.099"},
{"Annual Standard Deviation", "0.022"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.724"},
{"Beta", "0.114"},
{"Annual Standard Deviation", "0.026"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-2.672"},
{"Tracking Error", "0.076"},
{"Treynor Ratio", "0.171"},
{"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.587"},
{"Return Over Maximum Drawdown", "1.952"},
{"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", "95c62255290b4ad375579b398290230c"}
{"OrderListHash", "ebeeac4c57ccacef7b458b6160190f5b"}
};
}
}

View File

@@ -97,13 +97,16 @@ namespace QuantConnect.Algorithm.CSharp
_lastDateLog = Time;
Log($"{Time}- {Securities[_continuousContract.Symbol].GetLastData()}");
if (Portfolio.Invested)
if (_continuousContract.Exchange.ExchangeOpen)
{
Liquidate();
if (Portfolio.Invested)
{
Liquidate();
}
else
{
Buy(_continuousContract.Mapped, 1);
}
else
{
Buy(_continuousContract.Mapped, 1);
}
if(Time.Month == 1 && Time.Year == 2013)
@@ -147,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
@@ -160,32 +163,32 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "1.21%"},
{"Average Win", "1.50%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "2.392%"},
{"Compounding Annual Return", "2.959%"},
{"Drawdown", "1.600%"},
{"Expectancy", "0"},
{"Net Profit", "1.199%"},
{"Sharpe Ratio", "0.775"},
{"Probabilistic Sharpe Ratio", "40.287%"},
{"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.726"},
{"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.169"},
{"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.516"},
{"Return Over Maximum Drawdown", "1.935"},
{"Sortino Ratio", "0.32"},
{"Return Over Maximum Drawdown", "2.573"},
{"Portfolio Turnover", "0.016"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -200,7 +203,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "5fc26c7f1f2d9fff97d36a5b58853840"}
{"OrderListHash", "88e74055be58b3759f493b2c47e4c097"}
};
}
}

View File

@@ -114,7 +114,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 40881;
public virtual long DataPoints => 9949;
/// <summary>
/// Data Points count of the algorithm history
@@ -124,7 +124,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", "1"},
{"Average Win", "0%"},
@@ -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", "9408389924d9b7333a9f0a4f64b08d27"}
{"OrderListHash", "1fcd459f69177160b35f7daf96b01a0d"}
};
}
}

View File

@@ -0,0 +1,39 @@
/*
* 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;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Continuous Futures History Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
/// </summary>
public class ContinuousFutureHistoryTimeSpanWarmupRegressionAlgorithm : ContinuousFutureHistoryRegressionAlgorithm
{
public override void Initialize()
{
base.Initialize();
// We want to match the start time of the base algorithm. ES futures data time zone is UTC, algorithm time zone is new york (default).
// Base algorithm warmup is 1 bar of daily resolution starts at 8 PM new york time of T-1. So to match the same start time
// we go back a 1 day + 4 hours. This is calculated by 'Time.GetStartTimeForTradeBars'
SetWarmup(TimeSpan.FromHours(24 + 4));
}
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 14915;
}
}

View File

@@ -0,0 +1,137 @@
/*
* 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 QuantConnect.Securities;
using System.Collections.Generic;
using QuantConnect.Securities.Future;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Continuous Futures Regression algorithm reproducing GH issue #6490 asserting limit if touched order works as expected
/// </summary>
public class ContinuousFutureLimitIfTouchedOrderRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private OrderTicket _ticket;
private Future _continuousContract;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 6);
SetEndDate(2013, 10, 10);
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
dataMappingMode: DataMappingMode.LastTradingDay
);
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (_ticket == null)
{
_ticket = LimitIfTouchedOrder(_continuousContract.Mapped, -1, _continuousContract.Price, _continuousContract.Price);
}
}
public override void OnEndOfAlgorithm()
{
if (_ticket == null || _ticket.Status != OrderStatus.Filled)
{
throw new Exception("Order ticket was not placed or filled!");
}
}
/// <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 => 19876;
/// <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", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-99.258%"},
{"Drawdown", "6.300%"},
{"Expectancy", "0"},
{"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.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.028"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"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"},
{"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", "f0e1235ff2d29030e374d966b3e225fa"}
};
}
}

View File

@@ -148,6 +148,12 @@ namespace QuantConnect.Algorithm.CSharp
{
throw new Exception($"Unexpected symbol changed events: {_mappings.Count}, was expecting {expectedMappingCounts}");
}
var securities = Securities.Values.Where(sec => !sec.IsTradable && !sec.Symbol.IsCanonical() && sec.Symbol.SecurityType == SecurityType.Future).ToList();
if (securities.Count != 1)
{
throw new Exception("We should have a non tradable future contract security!");
}
}
/// <summary>
@@ -163,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
@@ -176,32 +182,32 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "1.21%"},
{"Average Win", "1.50%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "2.392%"},
{"Compounding Annual Return", "2.959%"},
{"Drawdown", "1.600%"},
{"Expectancy", "0"},
{"Net Profit", "1.199%"},
{"Sharpe Ratio", "0.775"},
{"Probabilistic Sharpe Ratio", "40.287%"},
{"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.726"},
{"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.169"},
{"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.516"},
{"Return Over Maximum Drawdown", "1.935"},
{"Sortino Ratio", "0.32"},
{"Return Over Maximum Drawdown", "2.573"},
{"Portfolio Turnover", "0.016"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -216,7 +222,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "8ad040c62ad255e4f9cd423364147e85"}
{"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,144 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Data;
using QuantConnect.Data.Fundamental;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm showing how to implement a custom universe selection model and asserting it's behavior
/// </summary>
public class CustomUniverseSelectionModelRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2014, 3, 24);
SetEndDate(2014, 4, 7);
UniverseSettings.Resolution = Resolution.Daily;
SetUniverseSelection(new CustomUniverseSelectionModel());
}
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
foreach (var kvp in ActiveSecurities)
{
SetHoldings(kvp.Key, 0.1);
}
}
}
private class CustomUniverseSelectionModel : FundamentalUniverseSelectionModel
{
private bool _selected;
public CustomUniverseSelectionModel(): base(true, null)
{
}
public override IEnumerable<Symbol> SelectCoarse(QCAlgorithm algorithm, IEnumerable<CoarseFundamental> coarse)
{
return new[] { QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA) };
}
public override IEnumerable<Symbol> SelectFine(QCAlgorithm algorithm, IEnumerable<FineFundamental> fine)
{
if (!_selected)
{
_selected = true;
return fine.Select(x => x.Symbol);
}
return Data.UniverseSelection.Universe.Unchanged;
}
}
/// <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 => 7208;
/// <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", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-7.765%"},
{"Drawdown", "0.400%"},
{"Expectancy", "0"},
{"Net Profit", "-0.332%"},
{"Sharpe Ratio", "-5.288"},
{"Probabilistic Sharpe Ratio", "5.408%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.049"},
{"Beta", "0.1"},
{"Annual Standard Deviation", "0.011"},
{"Annual Variance", "0"},
{"Information Ratio", "0.413"},
{"Tracking Error", "0.087"},
{"Treynor Ratio", "-0.578"},
{"Total Fees", "$2.89"},
{"Estimated Strategy Capacity", "$1600000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-8.448"},
{"Return Over Maximum Drawdown", "-19.517"},
{"Portfolio Turnover", "0.007"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "9b40745cd4c47eb3f442071c2a841821"}
};
}
}

View File

@@ -0,0 +1,82 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm which reproduces GH issue 4446, in the case of daily resolution.
/// </summary>
public class DelistedFutureLiquidateDailyRegressionAlgorithm : DelistedFutureLiquidateRegressionAlgorithm
{
protected override Resolution Resolution => Resolution.Daily;
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
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
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "7.78%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "38.033%"},
{"Drawdown", "0.200%"},
{"Expectancy", "0"},
{"Net Profit", "7.779%"},
{"Sharpe Ratio", "3.2"},
{"Probabilistic Sharpe Ratio", "99.459%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"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.019"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "28.065"},
{"Return Over Maximum Drawdown", "246.484"},
{"Portfolio Turnover", "0.019"},
{"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", "bbd8ee011b21ef33f4b15b0509c96bbb"}
};
}
}

View File

@@ -30,6 +30,7 @@ namespace QuantConnect.Algorithm.CSharp
public class DelistedFutureLiquidateRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _contractSymbol;
protected virtual Resolution Resolution => Resolution.Minute;
/// <summary>
/// Initialize your algorithm and add desired assets.
@@ -39,7 +40,7 @@ namespace QuantConnect.Algorithm.CSharp
SetStartDate(2013, 10, 08);
SetEndDate(2013, 12, 30);
var futureSP500 = AddFuture(Futures.Indices.SP500EMini);
var futureSP500 = AddFuture(Futures.Indices.SP500EMini, Resolution);
futureSP500.SetFilter(0, 182);
}
@@ -91,7 +92,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1224778;
public virtual long DataPoints => 398985;
/// <summary>
/// Data Points count of the algorithm history
@@ -101,35 +102,35 @@ 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", "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"},
@@ -144,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

@@ -0,0 +1,83 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Orders;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm reproducing issue #5160 where delisting order would be cancelled because it was placed at the market close on the delisting day,
/// in the case of daily resolution.
/// </summary>
public class DelistingFutureOptionDailyRegressionAlgorithm : DelistingFutureOptionRegressionAlgorithm
{
protected override Resolution Resolution => Resolution.Daily;
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
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
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "16"},
{"Average Win", "0.01%"},
{"Average Loss", "-0.02%"},
{"Compounding Annual Return", "-0.111%"},
{"Drawdown", "0.100%"},
{"Expectancy", "-0.678"},
{"Net Profit", "-0.111%"},
{"Sharpe Ratio", "-0.951"},
{"Probabilistic Sharpe Ratio", "0.000%"},
{"Loss Rate", "80%"},
{"Win Rate", "20%"},
{"Profit-Loss Ratio", "0.61"},
{"Alpha", "-0.001"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.075"},
{"Tracking Error", "0.107"},
{"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.126"},
{"Return Over Maximum Drawdown", "-0.995"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "2152bd1d4f1770068595a4c3bc8585ee"}
};
}
}

View File

@@ -19,6 +19,7 @@ using QuantConnect.Interfaces;
using QuantConnect.Securities;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Orders;
namespace QuantConnect.Algorithm.CSharp
{
@@ -27,6 +28,7 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public class DelistingFutureOptionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected virtual Resolution Resolution => Resolution.Minute;
private bool _traded;
private int _lastMonth;
@@ -36,11 +38,15 @@ namespace QuantConnect.Algorithm.CSharp
SetEndDate(2013, 1, 1);
SetCash(10000000);
var dc = AddFuture(Futures.Dairy.ClassIIIMilk, Resolution.Minute, Market.CME);
var dc = AddFuture(Futures.Dairy.ClassIIIMilk, Resolution, Market.CME);
dc.SetFilter(1, 120);
AddFutureOption(dc.Symbol, universe => universe.Strikes(-2, 2));
_lastMonth = -1;
// This is required to prevent the algorithm from automatically delisting the underlying. Without this, future options will be subscribed
// with resolution default to Minute insted of this.Resolution. This could be replaced after GH issue #6491 is implemented.
UniverseSettings.Resolution = Resolution;
}
public override void OnData(Slice data)
@@ -100,8 +106,8 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 15228955;
/// </summary>0
public virtual long DataPoints => 5117455;
/// <summary>
/// Data Points count of the algorithm history
@@ -111,7 +117,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", "16"},
{"Average Win", "0.01%"},
@@ -132,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,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.
*
@@ -46,6 +46,14 @@ namespace QuantConnect.Algorithm.CSharp
public override void OnData(Slice data)
{
foreach (var point in data)
{
if (point.Value.IsFillForward)
{
throw new Exception("We requested no fill forwarding!");
}
}
foreach (var chain in data.FutureChains)
{
_receivedData = true;
@@ -81,7 +89,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 972466;
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"}
};
}
}

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