Compare commits

...

100 Commits
14065 ... 14432

Author SHA1 Message Date
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
Jhonathan Abreu
e9409bf207 Add contractDepthOffset parameter to QCAlgorithm.History() (#6438)
* Add contract depth offset parameter to big History() methods

- Added unit tests
- Added little more ED daily data

* Add C# regression algorithm

* Add Python regression algorithm

* Update regression algorithms stats

* Address changes request
2022-06-27 10:04:33 -03:00
Martin-Molinero
867682c923 Set default object store settings from config (#6437)
- Will set default object store settings from config like research
2022-06-24 18:44:00 -03:00
Martin-Molinero
59ac2f57ed Shutdown python manually (#6439) 2022-06-24 18:43:44 -03:00
Martin-Molinero
4c3afa6ff1 Add OpenInterestAnnual (#6436)
- Adding OpenInterestAnnual where the contract maps when any of the back month
  contracts of the next year have a higher volume that the current front month.
- Add support for backwards compatible data mapping mode additions
- Updating ES map and factor files. Adding a little daily data too
2022-06-23 19:22:24 -03:00
Jhonathan Abreu
9128ce1260 Add data normalization mode parameter to QCAlgorithm.History() (#6435)
* Add data normalization mode parameter to big History() methods

* Add C# regression algorithm

* Add Python regression algorithm
2022-06-23 17:02:50 -03:00
Jhonathan Abreu
505ef17565 Add data mapping mode parameter to QCAlgorithm.History() (#6415)
* Add dataMappingMode parameter to QCAlgorithm.History()

* Add C# regression algorithm

* Add Python regression algorithm

* Cleanup

* Add data mapping mode parameter only to big History() methods

* Fix regression algorithms and add required data

* Fix unit test

* Update regression algorithms stats
2022-06-22 19:25:30 -03:00
Martin-Molinero
a12a43c1ef Update VX futures market hours (#6417) 2022-06-22 17:25:18 -03:00
Alexandre Catarino
e3313c7c45 Fixes Contract Multiplier for Treasury Futures (#6418) 2022-06-22 17:25:00 -03:00
Martin-Molinero
f0b59a72fd Fix Train method during warmup (#6416)
- During warmup period the algorithms initial time might not be a rounded date
  value, so it's important to take into account hours/minutes. Adding
  regression algorithm reproducing and asserting issue
2022-06-21 10:05:27 -03:00
Martin-Molinero
a42a53671f Add missing Py.Gil in base PCM (#6414)
- Add missing python Py.Gill in base PortfolioConstructionModel. Adding
  unit test reproducing issue, seg fault
2022-06-20 19:44:31 -03:00
Martin-Molinero
bb0c27fefd Period timespan consolidation improvements (#6408)
* Period timespan consolidation improvements

- If user is trying to consolidate a period providing data of a bigger
  period we will now throw an exception. Adding tests
- If both consolidated and given data share the same period, gently
  adjust the consolidator into a data count of 1. Adding tests
- Fixing bug in QuoteBarConsolidator period double accounting. Adding unit tests

* Add Period and Count regression algorithm
2022-06-20 15:14:44 -03:00
Martin-Molinero
299cb79832 OnWarmupFinished always called (#6413)
* OnWarmupFinished always called

- Always call OnWarmupFinished. Adding regression tests

* Assert method called with counter
2022-06-20 14:24:12 -03:00
Martin-Molinero
8fb188d567 Add missing Juneteenth holiday (#6412)
- Add missing Juneteenth holida. Reference https://www.timeanddate.com/holidays/us/juneteenth
2022-06-20 10:42:37 -03:00
Martin-Molinero
740b40ff11 Fix QuoteBar Non Time Based Consolidator Period (#6409)
* Fix QuoteBar NonTimeBased Consolidator Period

- Fix QuoteBar non timebased consolidator period, that was accounting
  twice for the initial bar period. Updating unit tests

* Improve QuoteBarConsolidator assertion

- Assert quote bar consolidated time and endtime in unit tests
2022-06-17 19:44:37 -03:00
Jhonathan Abreu
e736b28568 Add data normalization mode parameter to AddEquity method (#6407)
* Add DataNormalizationMode parameter to QCAlgorithm.AddEquity method

* Add regression algorithm

* Add Python regression algorithm

* Style changes

* Fix test error
2022-06-17 18:27:06 -03:00
Martin-Molinero
b007d9f962 Fix intermittent ZipMapFile cache test failure (#6406)
- Fix for intermittent ZipMapFile cache test failure and reducing test length
2022-06-16 15:30:20 -03:00
Martin-Molinero
4d7d7def63 Add Log.Error at OptionSymbol.IsOptionContractExpired (#6405)
- Add error log at OptionSymbol.IsOptionContractExpired in the case we
  detect an unexpected expiration time. That could be related to
  Symbol.ID.Date being incorrect
2022-06-16 15:10:17 -03:00
Jhonathan Abreu
09c4a53f95 Fix greeks all being zero on expiration date (#6401)
* Fix option price and greeks always beign zero on the expiration date

* Fix option price and greeks always beign zero on the expiration date

* Updated documentation

* Style and performace changes

* Address changes request

* Fix QL.Settings.includeReferenceDateEvents not being set on every thread

* Updated code documentation
2022-06-16 12:29:51 -03:00
Derek Melchin
714042bb69 Fix remark typos to match docs (#6404) 2022-06-16 12:00:17 -03:00
Martin-Molinero
a8e7a8b27e Reconcile the Market Opening for Futures and Scheduled Events (#6397)
- Changes taken from https://github.com/QuantConnect/Lean/pull/6227
- Rebased + a few more tweaks and added tests
2022-06-15 13:47:00 -03:00
Ronit Jain
182ee51389 Bug handle order status race condition for brokerage tests (#6400)
* update order status from event handler

* choose easy limits to less liquid markets

* increase waiting time for fill for less liquid markets
2022-06-14 17:32:34 -03:00
Jhonathan Abreu
4a41c2ea90 Detect unsupported option style in option price model (#6388)
* Add indicator for allowed option styles to QL option price models

* Add and update option price model tests

* Update option price models methods sumary to indicate allowed option styles

* Add regression algorithms for option price models for different option styles

* Update OptionPriceModel regression algorithms to use Lean local data

* Add Python regression algorithms for option price models for different option styles

* Update OptionPriceModel regression algorithms to assert that greeks are valid

* Address changes request

* Address changes request

* Update OptionPriceModel regression algorithms to check both call and put contracts

* Update OptionPriceModel regression algorithms to use correct test data

* Update OptionPriceModel regression algorithms to throw in OnData

* Address changes request

* Update OptionPriceModel regression algorithms to assert greeks are not all zero
2022-06-13 16:21:20 -04:00
Ronit Jain
c1dc981403 Feature use minimum price variation for roundoff (#6398)
* make thread safe

* use use minimumPriceVariation for roundoff

* cleanup, remove duplication
2022-06-13 11:42:59 -03:00
Martin-Molinero
15e399c96b Live T-1 selection warmup (#6395)
* Live T-1 selection warmup

- Only use BaseDataCollection class
- Reuse collection enumerator
- Remove FuturesChainUniverseSubscriptionEnumeratorFactory
- Universe selection will use Cache providers
- Add null reference check
- Add more tests
- Fixes for warmup fill forwarding. Add more tests

* Address reviews. Add missing comments
2022-06-10 17:25:20 -03:00
Martin-Molinero
3fb267f4ad Update readme.md 2022-06-10 11:24:54 -03:00
Martin-Molinero
a3f4dff299 Refactor chain providers (#6394)
* Refactor chain providers

- ChainProviders will use quote, open interest and trade information,
  which ever is first. Updating regression algorithm changing contract
  being added.
- Add base BacktestingChainProvider for shared logic, reducing
  duplication.
- ChainProviders will now use the given IDataCacheProvider and
  IMapFileProvider
- If Providers are called for a date the exchange is closed they will
  search for the previous available date where the exchange is open.
  Adding unit tests.

* Address reviews. Logging improvements
2022-06-10 11:24:09 -03:00
Martin-Molinero
cbfdd85cef Live Internal Subscription Start Time (#6392)
- Live Trading internal subscription start time will be after warmup.
  Adding unit tests.
2022-06-09 17:28:32 -03:00
Martin-Molinero
223066d6d9 Disable live trading warmup plotting (#6393)
- Disable live trading warmup plotting during warmup
2022-06-09 17:27:55 -03:00
Martin-Molinero
25871497e9 Update readme.md 2022-06-09 12:49:15 -03:00
Martin-Molinero
3ad4695354 Update readme.md 2022-06-09 12:42:46 -03:00
Ronit Jain
1c644297df Extract Tradier brokerage files and dependencies (#6387)
* use research-object-store-name key from config while creating object store for research notebooks

* remove files
2022-06-09 12:33:34 -03:00
Ronit Jain
60c9162b11 Extract Gdax brokerage files and dependencies (#6391)
* use research-object-store-name key from config while creating object store for research notebooks

* initial removal

* remove reference

* move test to private repo containing downloaders
2022-06-09 12:32:27 -03:00
Alexandre Catarino
6e32f46068 Adds Missing UpdateTriggerPrice Method (#6385)
Since there is `UpdateStopPrice`, `UpdateLimitPrice`, `UpdateQuantity` and `UpdateTag` method to make it easier to update the `OrderTicket`, we include `UpdateTriggerPrice` to cover the `LimitIfTouched` case.
Also, updated the docs or the arguments for these methods.

Updates LimitIfTouchedRegressionAlgorithm:
- Adds `UpdateTriggerPrice` call that rounds down the `TriggerPrice`.
2022-06-08 10:35:47 -03:00
469 changed files with 16947 additions and 12200 deletions

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

@@ -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 => 46583;
/// <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", "-47.647%"},
{"Drawdown", "3.200%"},
{"Expectancy", "0"},
{"Net Profit", "-0.530%"},
{"Sharpe Ratio", "-8.194"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-1.345"},
{"Beta", "1.391"},
{"Annual Standard Deviation", "0.06"},
{"Annual Variance", "0.004"},
{"Information Ratio", "-66.031"},
{"Tracking Error", "0.017"},
{"Treynor Ratio", "-0.351"},
{"Total Fees", "$37.00"},
{"Estimated Strategy Capacity", "$3400000.00"},
{"Lowest Capacity Asset", "ES 31C3JQS9D84PW|ES XCZJLC9NOB29"},
{"Fitness Score", "0.5"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-94.467"},
{"Portfolio Turnover", "5.578"},
{"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", "7fbb8c0a1f5eee780f0b37efafbbdc4b"}
};
}
}

View File

@@ -67,7 +67,7 @@ namespace QuantConnect.Algorithm.CSharp
// Test case: custom IndicatorBase<QuoteBar> indicator using Future subscribed symbol
var indicator = new CustomIndicator();
var consolidator = CreateConsolidator(TimeSpan.FromMinutes(1), typeof(QuoteBar));
var consolidator = CreateConsolidator(TimeSpan.FromMinutes(2), typeof(QuoteBar));
RegisterIndicator(_symbol, indicator, consolidator);
AssertIndicatorState(indicator, isReady: false);

View File

@@ -296,7 +296,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1753491;
public long DataPoints => 1748811;
/// <summary>
/// Data Points count of the algorithm history

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

@@ -131,13 +131,13 @@ 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.032%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.004%"},
{"Sharpe Ratio", "-0.369"},
{"Probabilistic Sharpe Ratio", "10.640%"},
{"Net Profit", "-0.016%"},
{"Sharpe Ratio", "-1.173"},
{"Probabilistic Sharpe Ratio", "0.011%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
@@ -145,17 +145,17 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.751"},
{"Information Ratio", "-2.753"},
{"Tracking Error", "0.082"},
{"Treynor Ratio", "-0.616"},
{"Treynor Ratio", "-8.269"},
{"Total Fees", "$3.70"},
{"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.985"},
{"Portfolio Turnover", "0.01"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -170,7 +170,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "bd7fbe57802dfedb36c85609b7234016"}
{"OrderListHash", "d5bb3821a9a78b9fbef422c0f6bb6b4c"}
};
}
}

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

@@ -163,34 +163,34 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "8220"},
{"Total Trades", "8186"},
{"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"},
{"Drawdown", "13.100%"},
{"Expectancy", "-0.817"},
{"Net Profit", "-13.059%"},
{"Sharpe Ratio", "-22.436"},
{"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"},
{"Alpha", "1.976"},
{"Beta", "-0.184"},
{"Annual Standard Deviation", "0.045"},
{"Annual Variance", "0.002"},
{"Information Ratio", "-59.896"},
{"Tracking Error", "0.287"},
{"Treynor Ratio", "5.445"},
{"Total Fees", "$15144.10"},
{"Estimated Strategy Capacity", "$130000.00"},
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
{"Fitness Score", "0.033"},
{"Fitness Score", "0.028"},
{"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", "-10.138"},
{"Return Over Maximum Drawdown", "-8.192"},
{"Portfolio Turnover", "299.379"},
{"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", "fbf8650f2a4f433563f37f44c59cfa0d"}
};
}
}

View File

@@ -54,7 +54,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);
}
@@ -76,8 +76,9 @@ namespace QuantConnect.Algorithm.CSharp
select futuresContract
).FirstOrDefault();
// if found, trade it
if (contract != null && IsMarketOpen(contract.Symbol))
// if found and exchange is open, trade it. Exchange could be closed, for example for a bar after 6:00pm on a friday, when futures
// markets are closed.
if (contract != null && Securities[contract.Symbol].Exchange.ExchangeOpen)
{
_contractSymbol = contract.Symbol;
MarketOrder(_contractSymbol, 1);
@@ -111,7 +112,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 17041;
public virtual long DataPoints => 13559;
/// <summary>
/// Data Points count of the algorithm history
@@ -123,34 +124,34 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "92"},
{"Average Win", "0.08%"},
{"Total Trades", "152"},
{"Average Win", "0.09%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-0.450%"},
{"Drawdown", "0.500%"},
{"Expectancy", "-0.824"},
{"Net Profit", "-0.453%"},
{"Sharpe Ratio", "-1.803"},
{"Compounding Annual Return", "-0.638%"},
{"Drawdown", "0.600%"},
{"Expectancy", "-0.871"},
{"Net Profit", "-0.643%"},
{"Sharpe Ratio", "-2.323"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "98%"},
{"Win Rate", "2%"},
{"Profit-Loss Ratio", "7.09"},
{"Alpha", "-0.003"},
{"Loss Rate", "99%"},
{"Win Rate", "1%"},
{"Profit-Loss Ratio", "8.83"},
{"Alpha", "-0.004"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.394"},
{"Information Ratio", "-1.408"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "4.298"},
{"Total Fees", "$170.20"},
{"Estimated Strategy Capacity", "$36000.00"},
{"Lowest Capacity Asset", "ES VP274HSU1AF5"},
{"Fitness Score", "0.009"},
{"Treynor Ratio", "3.612"},
{"Total Fees", "$281.20"},
{"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", "-0.8"},
{"Sortino Ratio", "-1.45"},
{"Return Over Maximum Drawdown", "-0.992"},
{"Portfolio Turnover", "0.025"},
{"Portfolio Turnover", "0.04"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -164,7 +165,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "09b2f274fa2385597a803e58b784f675"}
{"OrderListHash", "48bfc4d255420cb589e00cf582554e0a"}
};
}
}

View File

@@ -118,7 +118,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

@@ -47,7 +47,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 249038;
public override long DataPoints => 205645;
/// <summary>
/// Data Points count of the algorithm history
@@ -59,34 +59,34 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1988"},
{"Total Trades", "1982"},
{"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"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-4.581%"},
{"Drawdown", "4.600%"},
{"Expectancy", "-0.910"},
{"Net Profit", "-4.615%"},
{"Sharpe Ratio", "-5.78"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "97%"},
{"Win Rate", "3%"},
{"Profit-Loss Ratio", "2.92"},
{"Alpha", "-0.027"},
{"Beta", "-0.006"},
{"Profit-Loss Ratio", "2.09"},
{"Alpha", "-0.03"},
{"Beta", "-0.008"},
{"Annual Standard Deviation", "0.005"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.66"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "4.919"},
{"Total Fees", "$3677.80"},
{"Information Ratio", "-1.694"},
{"Tracking Error", "0.09"},
{"Treynor Ratio", "4.084"},
{"Total Fees", "$3666.70"},
{"Estimated Strategy Capacity", "$2000.00"},
{"Lowest Capacity Asset", "ES VP274HSU1AF5"},
{"Fitness Score", "0.128"},
{"Fitness Score", "0.131"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-6.856"},
{"Sortino Ratio", "-6.174"},
{"Return Over Maximum Drawdown", "-0.995"},
{"Portfolio Turnover", "0.648"},
{"Portfolio Turnover", "0.649"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -100,7 +100,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "87d2b127c9859cad9d2c65ac9d76deb5"}
{"OrderListHash", "2402a307b20aee195b77b8478d7ca64d"}
};
}
}

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)
{
@@ -122,7 +122,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 41730;
public long DataPoints => 39654;
/// <summary>
/// Data Points count of the algorithm history

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)
{
@@ -109,7 +109,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 64216;
public long DataPoints => 32492;
/// <summary>
/// Data Points count of the algorithm history

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

@@ -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.20%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "2.412%"},
{"Compounding Annual Return", "2.387%"},
{"Drawdown", "1.600%"},
{"Expectancy", "0"},
{"Net Profit", "1.209%"},
{"Sharpe Ratio", "0.782"},
{"Probabilistic Sharpe Ratio", "40.528%"},
{"Net Profit", "1.196%"},
{"Sharpe Ratio", "0.773"},
{"Probabilistic Sharpe Ratio", "40.221%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.005"},
{"Alpha", "-0.006"},
{"Beta", "0.099"},
{"Annual Standard Deviation", "0.022"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.724"},
{"Information Ratio", "-2.726"},
{"Tracking Error", "0.076"},
{"Treynor Ratio", "0.171"},
{"Treynor Ratio", "0.169"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$810000000.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.581"},
{"Return Over Maximum Drawdown", "1.931"},
{"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", "9689ea5896706b2ce7e8aebd201de3f0"}
};
}
}

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();
}
else
{
Buy(_continuousContract.Mapped, 1);
if (Portfolio.Invested)
{
Liquidate();
}
else
{
Buy(_continuousContract.Mapped, 1);
}
}
if(Time.Month == 1 && Time.Year == 2013)
@@ -160,14 +163,14 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "1.21%"},
{"Average Win", "1.20%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "2.392%"},
{"Compounding Annual Return", "2.354%"},
{"Drawdown", "1.600%"},
{"Expectancy", "0"},
{"Net Profit", "1.199%"},
{"Sharpe Ratio", "0.775"},
{"Probabilistic Sharpe Ratio", "40.287%"},
{"Net Profit", "1.180%"},
{"Sharpe Ratio", "0.763"},
{"Probabilistic Sharpe Ratio", "39.832%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
@@ -175,17 +178,17 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "0.099"},
{"Annual Standard Deviation", "0.022"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.726"},
{"Information Ratio", "-2.729"},
{"Tracking Error", "0.076"},
{"Treynor Ratio", "0.169"},
{"Treynor Ratio", "0.167"},
{"Total Fees", "$5.55"},
{"Estimated Strategy Capacity", "$67000000.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.511"},
{"Return Over Maximum Drawdown", "1.905"},
{"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", "468572bbb8256bd47d381757b66da0d0"}
};
}
}

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 => 26112;
/// <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%"},
@@ -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", "10cf3584cd0131898df3f19d26df0649"}
};
}
}

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 => 40881;
}
}

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 => 64065;
/// <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", "-98.962%"},
{"Drawdown", "6.200%"},
{"Expectancy", "0"},
{"Net Profit", "-6.066%"},
{"Sharpe Ratio", "-2.143"},
{"Probabilistic Sharpe Ratio", "32.231%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.237"},
{"Beta", "-0.662"},
{"Annual Standard Deviation", "0.161"},
{"Annual Variance", "0.026"},
{"Information Ratio", "-1.265"},
{"Tracking Error", "0.403"},
{"Treynor Ratio", "0.523"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$710000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.018"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-2.218"},
{"Return Over Maximum Drawdown", "-16.972"},
{"Portfolio Turnover", "0.165"},
{"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", "de931c9003e11617ffc012f9ee41093e"}
};
}
}

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>
@@ -176,14 +182,14 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "1.21%"},
{"Average Win", "1.20%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "2.392%"},
{"Compounding Annual Return", "2.354%"},
{"Drawdown", "1.600%"},
{"Expectancy", "0"},
{"Net Profit", "1.199%"},
{"Sharpe Ratio", "0.775"},
{"Probabilistic Sharpe Ratio", "40.287%"},
{"Net Profit", "1.180%"},
{"Sharpe Ratio", "0.763"},
{"Probabilistic Sharpe Ratio", "39.832%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
@@ -191,17 +197,17 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "0.099"},
{"Annual Standard Deviation", "0.022"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.726"},
{"Information Ratio", "-2.729"},
{"Tracking Error", "0.076"},
{"Treynor Ratio", "0.169"},
{"Treynor Ratio", "0.167"},
{"Total Fees", "$5.55"},
{"Estimated Strategy Capacity", "$67000000.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.511"},
{"Return Over Maximum Drawdown", "1.905"},
{"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", "468572bbb8256bd47d381757b66da0d0"}
};
}
}

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 => 1637;
/// <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.034%"},
{"Drawdown", "1.000%"},
{"Expectancy", "0"},
{"Net Profit", "7.779%"},
{"Sharpe Ratio", "2.639"},
{"Probabilistic Sharpe Ratio", "93.699%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.206"},
{"Beta", "0.13"},
{"Annual Standard Deviation", "0.098"},
{"Annual Variance", "0.01"},
{"Information Ratio", "-1.152"},
{"Tracking Error", "0.121"},
{"Treynor Ratio", "1.981"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$62000000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.018"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "4.641"},
{"Return Over Maximum Drawdown", "39.421"},
{"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 => 1224778;
/// <summary>
/// Data Points count of the algorithm history
@@ -101,7 +102,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", "2"},
{"Average Win", "1.64%"},

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 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 => 15192;
/// <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.965"},
{"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.073"},
{"Tracking Error", "0.107"},
{"Treynor Ratio", "1.349"},
{"Total Fees", "$14.80"},
{"Estimated Strategy Capacity", "$2400000.00"},
{"Lowest Capacity Asset", "DC V5E8PHPRCHJ8|DC V5E8P9SH0U0X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.128"},
{"Return Over Maximum Drawdown", "-0.992"},
{"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 => 15228955;
/// <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%"},

View File

@@ -0,0 +1,155 @@
/*
* 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
/// </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)
};
private static 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)
};
private Queue<DateTime> _afterMarketOpenQueue = new Queue<DateTime>(_afterMarketOpen);
private Queue<DateTime> _beforeMarketCloseQueue = new Queue<DateTime>(_beforeMarketClose);
public override void Initialize()
{
SetStartDate(2022, 02, 01);
SetEndDate(2022, 02, 08);
var esFuture = AddFuture("ES").Symbol;
Schedule.On(DateRules.EveryDay(esFuture),
TimeRules.AfterMarketOpen(esFuture),
EveryDayAfterMarketOpen);
Schedule.On(DateRules.EveryDay(esFuture),
TimeRules.BeforeMarketClose(esFuture),
EveryDayBeforeMarketClose);
}
public void EveryDayBeforeMarketClose()
{
var expectedMarketClose = _beforeMarketCloseQueue.Dequeue();
if (Time != expectedMarketClose)
{
throw new Exception($"Expected market close date was {expectedMarketClose} but received {Time}");
}
}
public void EveryDayAfterMarketOpen()
{
var expectedMarketOpen = _afterMarketOpenQueue.Dequeue();
if (Time != expectedMarketOpen)
{
throw new Exception($"Expected market open date was {expectedMarketOpen} but received {Time}");
}
}
public override void OnEndOfAlgorithm()
{
if (!_afterMarketOpenQueue.Any() || !_beforeMarketCloseQueue.Any())
{
throw new Exception($"_afterMarketOpenQueue and _beforeMarketCloseQueue should be empty");
}
}
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 => 7;
/// </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", "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,156 @@
/*
* 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;
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
/// </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),
};
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),
};
private Queue<DateTime> _expectedOpensQueue = new Queue<DateTime>(_expectedOpens);
private Queue<DateTime> _expectedClosesQueue = new Queue<DateTime>(_expectedCloses);
public override void Initialize()
{
SetStartDate(2013, 10, 06);
SetEndDate(2013, 10, 14);
var es = AddSecurity(SecurityType.Future, "ES");
Consolidate<BaseData>(es.Symbol, dataTime =>
{
var start = es.Exchange.Hours.GetPreviousMarketOpen(dataTime, false);
var end = es.Exchange.Hours.GetNextMarketClose(start, 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, false);
}
var period = end - start;
// based on the given data time we return the start time of it's bar and the expected period size
return new CalendarInfo(start, period);
}, bar => Assert(bar));
}
public void Assert(BaseData bar)
{
var open = _expectedOpensQueue.Dequeue();
var close = _expectedClosesQueue.Dequeue();
if (open != bar.Time || close != bar.EndTime)
{
throw new Exception($"Bar span was expected to be from {open} to {close}. " +
$"\n But was from {bar.Time} to {bar.EndTime}.");
}
Logging.Log.Debug($"Consolidator Event span. Start {bar.Time} End : {bar.EndTime}");
}
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 => 94112;
/// </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", "-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

@@ -141,14 +141,14 @@ namespace QuantConnect.Algorithm.CSharp
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.71"},
{"Alpha", "-0.036"},
{"Beta", "-0.012"},
{"Beta", "-0.013"},
{"Annual Standard Deviation", "0.08"},
{"Annual Variance", "0.006"},
{"Information Ratio", "-0.149"},
{"Tracking Error", "0.387"},
{"Treynor Ratio", "2.943"},
{"Treynor Ratio", "2.865"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$280000000.00"},
{"Estimated Strategy Capacity", "$140000000.00"},
{"Lowest Capacity Asset", "ES XFH59UPBIJ7O|ES XFH59UK0MYO1"},
{"Fitness Score", "0.017"},
{"Kelly Criterion Estimate", "0"},
@@ -169,7 +169,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "18f8a17034aa12be40581baecca96788"}
{"OrderListHash", "1f521247474162d17ff94fbaa654385b"}
};
}
}

View File

@@ -225,14 +225,14 @@ namespace QuantConnect.Algorithm.CSharp
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.17"},
{"Alpha", "-0.086"},
{"Beta", "0.004"},
{"Beta", "0.003"},
{"Annual Standard Deviation", "0.07"},
{"Annual Variance", "0.005"},
{"Information Ratio", "-0.283"},
{"Tracking Error", "0.379"},
{"Treynor Ratio", "-23.811"},
{"Treynor Ratio", "-25.997"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$270000000.00"},
{"Estimated Strategy Capacity", "$140000000.00"},
{"Lowest Capacity Asset", "ES XFH59UPBIJ7O|ES XFH59UK0MYO1"},
{"Fitness Score", "0.008"},
{"Kelly Criterion Estimate", "0"},
@@ -253,7 +253,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "b738fdaf1dae6849884df9e51eb6482b"}
{"OrderListHash", "c61ac689d112eab8fde5f2b1f715b7d3"}
};
}
}

View File

@@ -205,9 +205,9 @@ namespace QuantConnect.Algorithm.CSharp
{"Annual Variance", "0.002"},
{"Information Ratio", "-0.206"},
{"Tracking Error", "0.376"},
{"Treynor Ratio", "-23.481"},
{"Treynor Ratio", "-23.833"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$200000000.00"},
{"Estimated Strategy Capacity", "$99000000.00"},
{"Lowest Capacity Asset", "ES XFH59UPHGV9G|ES XFH59UK0MYO1"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
@@ -228,7 +228,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "cf1c12b839e49456dc2793f0e63c7803"}
{"OrderListHash", "498c9958139b70d42ebecc65c4eceeee"}
};
}
}

View File

@@ -231,9 +231,9 @@ namespace QuantConnect.Algorithm.CSharp
{"Annual Variance", "0.002"},
{"Information Ratio", "-0.221"},
{"Tracking Error", "0.376"},
{"Treynor Ratio", "-24.544"},
{"Treynor Ratio", "-28.081"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$330000000.00"},
{"Estimated Strategy Capacity", "$170000000.00"},
{"Lowest Capacity Asset", "ES 31EL5FAOOQON8|ES XFH59UK0MYO1"},
{"Fitness Score", "0.008"},
{"Kelly Criterion Estimate", "0"},
@@ -254,7 +254,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "99f96f433bc76c31cb25bcd9117a6bf1"}
{"OrderListHash", "1d90a4ed7fc218fe364435359358b2d5"}
};
}
}

View File

@@ -204,9 +204,9 @@ namespace QuantConnect.Algorithm.CSharp
{"Annual Variance", "0.004"},
{"Information Ratio", "-0.243"},
{"Tracking Error", "0.378"},
{"Treynor Ratio", "-23.284"},
{"Treynor Ratio", "-23.592"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$360000000.00"},
{"Estimated Strategy Capacity", "$180000000.00"},
{"Lowest Capacity Asset", "ES 31EL5FBZBMXES|ES XFH59UK0MYO1"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
@@ -227,7 +227,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "ec799886c15ac6c4b8fb3d873d7e6b14"}
{"OrderListHash", "76a3f4adc886f92b2f996d7e45e77dad"}
};
}
}

View File

@@ -210,14 +210,14 @@ namespace QuantConnect.Algorithm.CSharp
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "1.79"},
{"Alpha", "0.057"},
{"Beta", "-0.002"},
{"Beta", "-0.003"},
{"Annual Standard Deviation", "0.053"},
{"Annual Variance", "0.003"},
{"Information Ratio", "0.094"},
{"Tracking Error", "0.379"},
{"Treynor Ratio", "-23.276"},
{"Treynor Ratio", "-20.601"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$300000000.00"},
{"Estimated Strategy Capacity", "$150000000.00"},
{"Lowest Capacity Asset", "ES XFH59UP5K75W|ES XFH59UK0MYO1"},
{"Fitness Score", "0.02"},
{"Kelly Criterion Estimate", "0"},
@@ -238,7 +238,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "8a33f32b29bcc66d4dd779b36df9a010"}
{"OrderListHash", "5358f87044d3f8dc5d67cb7362b12cea"}
};
}
}

View File

@@ -198,9 +198,9 @@ namespace QuantConnect.Algorithm.CSharp
{"Annual Variance", "0"},
{"Information Ratio", "0.012"},
{"Tracking Error", "0.375"},
{"Treynor Ratio", "-24.052"},
{"Treynor Ratio", "-23.475"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$78000000.00"},
{"Estimated Strategy Capacity", "$39000000.00"},
{"Lowest Capacity Asset", "ES XFH59UPNF7B8|ES XFH59UK0MYO1"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
@@ -221,7 +221,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "8cb012d36057103bf26a897fe5fa54d6"}
{"OrderListHash", "3e2637348e4985e9398811e0a9ba62ff"}
};
}
}

View File

@@ -212,9 +212,9 @@ namespace QuantConnect.Algorithm.CSharp
{"Annual Variance", "0.001"},
{"Information Ratio", "-0.006"},
{"Tracking Error", "0.375"},
{"Treynor Ratio", "-20.61"},
{"Treynor Ratio", "-15.363"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$200000000.00"},
{"Estimated Strategy Capacity", "$100000000.00"},
{"Lowest Capacity Asset", "ES 31EL5FAOUP0P0|ES XFH59UK0MYO1"},
{"Fitness Score", "0.021"},
{"Kelly Criterion Estimate", "0"},
@@ -235,7 +235,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "eb37251ad1e32dd348af8a69e1888053"}
{"OrderListHash", "e8b27b23cb2bc65318696257af42b82e"}
};
}
}

View File

@@ -197,9 +197,9 @@ namespace QuantConnect.Algorithm.CSharp
{"Annual Variance", "0.002"},
{"Information Ratio", "0.07"},
{"Tracking Error", "0.377"},
{"Treynor Ratio", "-24.401"},
{"Treynor Ratio", "-24.023"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$80000000.00"},
{"Estimated Strategy Capacity", "$40000000.00"},
{"Lowest Capacity Asset", "ES 31EL5FAJQ6SBO|ES XFH59UK0MYO1"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
@@ -220,7 +220,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "76ed4eaa5f6ed50aa6134aecfbbe9e29"}
{"OrderListHash", "9213af45c30119e0a53c3b57d3c553de"}
};
}
}

View File

@@ -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 => 588056;
public long DataPoints => 420232;
/// <summary>
/// Data Points count of the algorithm history

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,181 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Securities.Equity;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression test illustrating how history from custom data sources can be requested.
/// </summary>
public class HistoryWithCustomDataSourceRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _aapl;
private Symbol _spy;
public override void Initialize()
{
SetStartDate(2014, 6, 5);
SetEndDate(2014, 6, 6);
_aapl = AddData<CustomData>("AAPL", Resolution.Minute).Symbol;
_spy = AddData<CustomData>("SPY", Resolution.Minute).Symbol;
}
public override void OnEndOfAlgorithm()
{
// We remove the symbol from history data in order to compare values only
Func<CustomData, Object> getRawCustomData = data => new {
Time = data.Time,
Value = data.Value,
Close = data.Close,
Open = data.Open,
High = data.High,
Low = data.Low,
Volume = data.Volume,
};
var aaplHistory = History<CustomData>("AAPL", StartDate, EndDate, Resolution.Minute).Select(getRawCustomData).ToList();
var spyHistory = History<CustomData>("SPY", StartDate, EndDate, Resolution.Minute).Select(getRawCustomData).ToList();
if (aaplHistory.Count == 0 || spyHistory.Count == 0)
{
throw new Exception("At least one of the history results is empty");
}
// Check that both results contain the same data, since CustomData fetches APPL data regardless of the symbol
if (!aaplHistory.SequenceEqual(spyHistory))
{
throw new Exception("Histories are not equal");
}
}
/// <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 => 2960;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 2938;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
/// <summary>
/// Custom data source for the regression test algorithm, which returns AAPL equity data regardless of the symbol requested.
/// </summary>
public class CustomData : BaseData
{
public decimal Open;
public decimal High;
public decimal Low;
public decimal Close;
public decimal Volume;
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
return new TradeBar().GetSource(
new SubscriptionDataConfig(
config,
typeof(CustomData),
// Create a new symbol as equity so we find the existing data files
// Symbol.Create(config.MappedSymbol, SecurityType.Equity, config.Market)),
Symbol.Create("AAPL", SecurityType.Equity, config.Market)),
date,
isLiveMode);
}
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
var tradeBar = TradeBar.ParseEquity(config, line, date);
return new CustomData {
Symbol = config.Symbol,
Time = tradeBar.Time,
Value = tradeBar.Value,
Close = tradeBar.Close,
Open = tradeBar.Open,
High = tradeBar.High,
Low = tradeBar.Low,
Volume = tradeBar.Volume,
};
}
}
}
}

View File

@@ -0,0 +1,188 @@
/*
* 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.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
using QuantConnect.Data.Market;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm illustrating how to request history data for continuous contracts with different depth offsets.
/// </summary>
public class HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _continuousContractSymbol;
public override void Initialize()
{
SetStartDate(2013, 10, 6);
SetEndDate(2014, 1, 1);
_continuousContractSymbol = AddFuture(Futures.Indices.SP500EMini, Resolution.Daily).Symbol;
}
public override void OnEndOfAlgorithm()
{
var contractDepthOffsets = Enumerable.Range(0, 3).ToList();
var historyResults = contractDepthOffsets.Select(contractDepthOffset =>
{
return History(new [] { _continuousContractSymbol }, StartDate, EndDate, Resolution.Daily, contractDepthOffset: contractDepthOffset).ToList();
}).ToList();
if (historyResults.Any(x => x.Count == 0 || x.Count != historyResults[0].Count))
{
throw new Exception("History results are empty or bar counts did not match");
}
// Check that all history results at least one mapping and that different contracts are used for each offset (which can be checked by
// comparing the underlying symbols)
List<HashSet<Symbol>> underlyingsPerHistory = new();
for (int i = 0; i < historyResults.Count; i++)
{
HashSet<Symbol> underlyings = new();
foreach (var slice in historyResults[i])
{
var underlying = slice.Keys.Single().Underlying;
if (underlyings.Add(underlying) && underlyings.Count > 1)
{
var currentExpiration = underlying.ID.Date;
var frontMonthExpiration = FuturesExpiryFunctions.FuturesExpiryFunction(_continuousContractSymbol)(slice.Time.AddMonths(1));
if (contractDepthOffsets[i] == 0) // Front month
{
if (currentExpiration != frontMonthExpiration.Date)
{
throw new Exception($"Unexpected current mapped contract expiration {currentExpiration}" +
$" @ {Time} it should be AT front month expiration {frontMonthExpiration}");
}
}
else // Back month
{
if (currentExpiration <= frontMonthExpiration.Date)
{
throw new Exception($"Unexpected current mapped contract expiration {currentExpiration}" +
$" @ {Time} it should be AFTER front month expiration {frontMonthExpiration}");
}
}
}
}
if (underlyings.Count == 0)
{
throw new Exception($"History results for contractDepthOffset={contractDepthOffsets[i]} did not contain any mappings");
}
underlyingsPerHistory.Add(underlyings);
}
// Check that underlyings are different for each history result (because we're using different contract depth offsets)
for (int i = 0; i < underlyingsPerHistory.Count; i++)
{
for (int j = i + 1; j < underlyingsPerHistory.Count; j++)
{
if (underlyingsPerHistory[i].SetEquals(underlyingsPerHistory[j]))
{
throw new Exception($"History results for contractDepthOffset={contractDepthOffsets[i]} and {contractDepthOffsets[j]} contain the same underlying");
}
}
}
// Check that prices at each time are different for different contract depth offsets
for (int j = 0; j < historyResults[0].Count; j++)
{
var closePrices = historyResults.Select(hr => hr[j].Bars.Values.SingleOrDefault(new TradeBar()).Close).ToHashSet();
if (closePrices.Count != contractDepthOffsets.Count)
{
throw new Exception($"History results close prices should have been different for each contract depth offset at each time");
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = 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 => 1337;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 449;
/// <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", "-3.681"},
{"Tracking Error", "0.086"},
{"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,160 @@
/*
* 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.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm illustrating how to request history data for different data mapping modes.
/// </summary>
public class HistoryWithDifferentDataMappingModeRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _continuousContractSymbol;
public override void Initialize()
{
SetStartDate(2013, 10, 6);
SetEndDate(2014, 1, 1);
_continuousContractSymbol = AddFuture(Futures.Indices.SP500EMini, Resolution.Daily).Symbol;
}
public override void OnEndOfAlgorithm()
{
var dataMappingModes = ((DataMappingMode[])Enum.GetValues(typeof(DataMappingMode))).ToList();
var historyResults = dataMappingModes.Select(dataMappingMode =>
{
return History(new [] { _continuousContractSymbol }, StartDate, EndDate, Resolution.Daily, dataMappingMode: dataMappingMode).ToList();
}).ToList();
if (historyResults.Any(x => x.Count != historyResults[0].Count))
{
throw new Exception("History results bar count did not match");
}
// Check that all history results have a mapping date at some point in the history
HashSet<DateTime> mappingDates = new HashSet<DateTime>();
for (int i = 0; i < historyResults.Count; i++)
{
var underlying = historyResults[i].First().Bars.Keys.First().Underlying;
int mappingsCount = 0;
foreach (var slice in historyResults[i])
{
var dataUnderlying = slice.Bars.Keys.First().Underlying;
if (dataUnderlying != underlying)
{
underlying = dataUnderlying;
mappingsCount++;
mappingDates.Add(slice.Time.Date);
}
}
if (mappingsCount == 0)
{
throw new Exception($"History results for {dataMappingModes[i]} data mapping mode did not contain any mappings");
}
}
if (mappingDates.Count < dataMappingModes.Count)
{
throw new Exception($"History results should have had different mapping dates for each data mapping mode");
}
// Check that close prices at each time are different for different data mapping modes
for (int j = 0; j < historyResults[0].Count; j++)
{
var closePrices = historyResults.Select(hr => hr[j].Bars.First().Value.Close).ToHashSet();
if (closePrices.Count != dataMappingModes.Count)
{
throw new Exception($"History results close prices should have been different for each data mapping mode at each time");
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = 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 => 1337;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 600;
/// <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", "-3.681"},
{"Tracking Error", "0.086"},
{"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,152 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm illustrating how to request history data for different data normalization modes.
/// </summary>
public class HistoryWithDifferentDataNormalizationModeRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _aaplEquitySymbol;
private Symbol _esFutureSymbol;
public override void Initialize()
{
SetStartDate(2013, 10, 7);
SetEndDate(2014, 1, 1);
_aaplEquitySymbol = AddEquity("AAPL", Resolution.Daily).Symbol;
_esFutureSymbol = AddFuture(Futures.Indices.SP500EMini, Resolution.Daily).Symbol;
}
public override void OnEndOfAlgorithm()
{
var equityDataNormalizationModes = new DataNormalizationMode[]{
DataNormalizationMode.Raw,
DataNormalizationMode.Adjusted,
DataNormalizationMode.SplitAdjusted
};
CheckHistoryResultsForDataNormalizationModes(_aaplEquitySymbol, StartDate, EndDate, Resolution.Daily, equityDataNormalizationModes);
var futureDataNormalizationModes = new DataNormalizationMode[]{
DataNormalizationMode.Raw,
DataNormalizationMode.BackwardsRatio,
DataNormalizationMode.BackwardsPanamaCanal,
DataNormalizationMode.ForwardPanamaCanal
};
CheckHistoryResultsForDataNormalizationModes(_esFutureSymbol, StartDate, EndDate, Resolution.Daily, futureDataNormalizationModes);
}
private void CheckHistoryResultsForDataNormalizationModes(Symbol symbol, DateTime start, DateTime end, Resolution resolution,
DataNormalizationMode[] dataNormalizationModes)
{
var historyResults = dataNormalizationModes
.Select(x => History(new [] { symbol }, start, end, resolution, dataNormalizationMode: x).ToList())
.ToList();
if (historyResults.Any(x => x.Count == 0 || x.Count != historyResults.First().Count))
{
throw new Exception($"History results for {symbol} have different number of bars");
}
// Check that, for each history result, close prices at each time are different for these securities (AAPL and ES)
for (int j = 0; j < historyResults[0].Count; j++)
{
var closePrices = historyResults.Select(hr => hr[j].Bars.First().Value.Close).ToHashSet();
if (closePrices.Count != dataNormalizationModes.Length)
{
throw new Exception($"History results for {symbol} have different close prices at the same time");
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = 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 => 1387;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 772;
/// <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", "-4.178"},
{"Tracking Error", "0.085"},
{"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

@@ -35,9 +35,9 @@ namespace QuantConnect.Algorithm.CSharp
// We assert the following occur in FIFO order in OnOrderEvent
private readonly Queue<string> _expectedEvents = new Queue<string>(new[]
{
"Time: 10/10/2013 13:31:00 OrderID: 72 EventID: 11 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: 144.6434 USD LimitPrice: 144.3551 TriggerPrice: 143.6051 OrderFee: 1 USD",
"Time: 10/10/2013 15:57:00 OrderID: 73 EventID: 11 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: 145.6636 USD LimitPrice: 145.6434 TriggerPrice: 144.8934 OrderFee: 1 USD",
"Time: 10/11/2013 15:37:00 OrderID: 74 EventID: 11 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: 146.7185 USD LimitPrice: 146.6723 TriggerPrice: 145.9223 OrderFee: 1 USD" });
"Time: 10/10/2013 13:31:00 OrderID: 72 EventID: 399 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: 144.6434 USD LimitPrice: 144.3551 TriggerPrice: 143.61 OrderFee: 1 USD",
"Time: 10/10/2013 15:57:00 OrderID: 73 EventID: 156 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: 145.6636 USD LimitPrice: 145.6434 TriggerPrice: 144.89 OrderFee: 1 USD",
"Time: 10/11/2013 15:37:00 OrderID: 74 EventID: 380 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: 146.7185 USD LimitPrice: 146.6723 TriggerPrice: 145.92 OrderFee: 1 USD" });
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
@@ -89,6 +89,7 @@ namespace QuantConnect.Algorithm.CSharp
var newQuantity = _request.Quantity - _negative;
_request.UpdateQuantity(newQuantity, $"LIT - Quantity: {newQuantity}");
_request.UpdateTriggerPrice(_request.Get(OrderField.TriggerPrice).RoundToSignificantDigits(5));
}
}
@@ -175,7 +176,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "359ac5b8cd73a8e42b7897a883f5f73d"}
{"OrderListHash", "5aebd643ee5365f55f10038150b47203"}
};
}
}

View File

@@ -0,0 +1,178 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using System.Collections.Generic;
using QuantConnect.Securities.Future;
using QuantConnect.Data.UniverseSelection;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm for testing limit orders are filled after hours for futures.
/// It also asserts that market and market-on-open orders are not allowed for futures outside of regular market hours
/// </summary>
public class LimitOrdersAreFilledAfterHoursForFuturesRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Future _continuousContract;
private Future _futureContract;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 6);
SetEndDate(2013, 10, 10);
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
dataMappingMode: DataMappingMode.LastTradingDay,
contractDepthOffset: 0
);
_futureContract = AddFutureContract(FutureChainProvider.GetFutureContractList(_continuousContract.Symbol, Time).First());
}
public override void OnWarmupFinished()
{
// Right after warm up we should be outside regular market hours
if (_futureContract.Exchange.ExchangeOpen)
{
throw new Exception("We should be outside regular market hours");
}
// Market order should not be allowed for futures outside of regular market hours
var futureContractMarketOrder = MarketOrder(_futureContract.Symbol, 1);
if (futureContractMarketOrder.Status != OrderStatus.Invalid)
{
throw new Exception($"Market order should not be allowed for futures outside of regular market hours");
}
// Market on open order should not be allowed for futures outside of regular market hours
var futureContractMarketOnOpenOrder = MarketOnOpenOrder(_futureContract.Symbol, 1);
if (futureContractMarketOnOpenOrder.Status != OrderStatus.Invalid)
{
throw new Exception($"Market on open order should not be allowed for futures outside of regular market hours");
}
}
public override void OnData(Slice slice)
{
if (Time.TimeOfDay.Hours > 17 && !Portfolio.Invested)
{
// Limit order should be allowed for futures outside of regular market hours.
// Use a very high limit price so the limit orders get filled immediately
var futureContractLimitOrder = LimitOrder(_futureContract.Symbol, 1, _futureContract.Price * 2m);
var continuousContractLimitOrder = LimitOrder(_continuousContract.Mapped, 1, _continuousContract.Price * 2m);
if (futureContractLimitOrder.Status == OrderStatus.Invalid || continuousContractLimitOrder.Status == OrderStatus.Invalid)
{
throw new Exception($"Limit order should be allowed for futures outside of regular market hours");
}
}
}
public override void OnEndOfAlgorithm()
{
if (Transactions.GetOrders().Any(order => order.Status != OrderStatus.Filled ))
{
throw new Exception("Not all orders were filled");
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
// 13:30 and 21:00 UTC are 9:30 and 17 New york, which are the regular market hours litimits for this security
if (orderEvent.Status == OrderStatus.Filled && !Securities[orderEvent.Symbol].Exchange.DateTimeIsOpen(orderEvent.UtcTime) &&
(orderEvent.UtcTime.TimeOfDay >= new TimeSpan(13, 30, 0) && orderEvent.UtcTime.TimeOfDay < new TimeSpan(21, 0, 0)))
{
throw new Exception($"Order should have been filled during extended market hours");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 81526;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "121.062%"},
{"Drawdown", "3.700%"},
{"Expectancy", "0"},
{"Net Profit", "1.093%"},
{"Sharpe Ratio", "4.285"},
{"Probabilistic Sharpe Ratio", "58.720%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.132"},
{"Beta", "1.285"},
{"Annual Standard Deviation", "0.314"},
{"Annual Variance", "0.098"},
{"Information Ratio", "15.223"},
{"Tracking Error", "0.077"},
{"Treynor Ratio", "1.046"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$39000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.327"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "7.193"},
{"Return Over Maximum Drawdown", "23.933"},
{"Portfolio Turnover", "0.334"},
{"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", "22ca22bec4626a32dc8db29382acf948"}
};
}
}

View File

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

View File

@@ -27,6 +27,7 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public class MinimumOrderSizeRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private bool _sentOrders;
public override void Initialize()
{
SetStartDate(2013, 10, 1);
@@ -37,17 +38,19 @@ namespace QuantConnect.Algorithm.CSharp
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
if (!_sentOrders)
{
_sentOrders = true;
// Place an order that will fail because of the size
var invalidOrder = MarketOnOpenOrder("BTCUSD", 0.00002);
var invalidOrder = MarketOrder("BTCUSD", 0.00002);
if (invalidOrder.Status != OrderStatus.Invalid)
{
throw new Exception("Invalid order expected, order size is less than allowed");
}
// Update an order that fails because of the size
var validOrderOne = MarketOnOpenOrder("BTCUSD", 0.0002, "NotUpdated");
var validOrderOne = LimitOrder("BTCUSD", 0.0002, Securities["BTCUSD"].Price - 0.1m, "NotUpdated");
validOrderOne.Update(new UpdateOrderFields()
{
Quantity = 0.00002m,
@@ -55,7 +58,7 @@ namespace QuantConnect.Algorithm.CSharp
});
// Place and update an order that will succeed
var validOrderTwo = MarketOnOpenOrder("BTCUSD", 0.0002, "NotUpdated");
var validOrderTwo = LimitOrder("BTCUSD", 0.0002, Securities["BTCUSD"].Price - 0.1m, "NotUpdated");
validOrderTwo.Update(new UpdateOrderFields()
{
Quantity = 0.002m,
@@ -106,7 +109,7 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "40"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
@@ -125,7 +128,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.01"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTCUSD E3"},
{"Fitness Score", "0"},
@@ -147,7 +150,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "dda3d03e8154ae0aad7ee17bdfd306cb"}
{"OrderListHash", "9ada3df9647e0e638d12ba0b14eabe05"}
};
}
}

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 QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting <see cref="OnWarmupFinished"/> is called even if no warmup period is set
/// </summary>
public class OnWarmupFinishedNoWarmup : QCAlgorithm, IRegressionAlgorithmDefinition
{
private int _onWarmupFinished;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);
AddEquity("SPY", Resolution.Minute);
}
public override void OnWarmupFinished()
{
_onWarmupFinished++;
}
public override void OnEndOfAlgorithm()
{
if (_onWarmupFinished != 1)
{
throw new Exception($"Unexpected {nameof(OnWarmupFinished)} call count {_onWarmupFinished}!");
}
}
/// <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 => 3943;
/// <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", "-8.91"},
{"Tracking Error", "0.223"},
{"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

@@ -24,7 +24,7 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public class OnWarmupFinishedRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private bool _onWarmupFinished;
private int _onWarmupFinished;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
@@ -40,14 +40,14 @@ namespace QuantConnect.Algorithm.CSharp
public override void OnWarmupFinished()
{
_onWarmupFinished = true;
_onWarmupFinished++;
}
public override void OnEndOfAlgorithm()
{
if (!_onWarmupFinished)
if (_onWarmupFinished != 1)
{
throw new Exception($"OnWarmupFinished was not called!");
throw new Exception($"Unexpected {nameof(OnWarmupFinished)} call count {_onWarmupFinished}!");
}
}

View File

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

View File

@@ -99,7 +99,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Order fill event handler. On an order fill update the resulting information is passed to this method.
/// </summary>
/// <param name="orderEvent">Order event details containing details of the evemts</param>
/// <param name="orderEvent">Order event details containing details of the events</param>
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
public override void OnOrderEvent(OrderEvent orderEvent)
{

View File

@@ -96,7 +96,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

@@ -95,7 +95,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)
{
@@ -120,7 +120,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1752483;
public long DataPoints => 1747803;
/// <summary>
/// Data Points count of the algorithm history

View File

@@ -0,0 +1,166 @@
/*
* 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.Option;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm excersizing an equity covered option asserting that greeks can be accessed
/// and have are not all zero, the same day as the contract expiration date.
/// </summary>
public class OptionExpiryDateTodayRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _optionSymbol;
private bool _triedGreeksCalculation;
public override void Initialize()
{
SetStartDate(2014, 06, 9);
SetEndDate(2014, 06, 15);
var option = AddOption("AAPL", Resolution.Minute);
option.SetFilter((universeFilter) =>
{
return universeFilter.IncludeWeeklys().Strikes(-1, 1).Expiration(0, 10);
});
option.PriceModel = OptionPriceModels.BaroneAdesiWhaley();
_optionSymbol = option.Symbol;
SetWarmUp(TimeSpan.FromDays(3));
}
public override void OnData(Slice slice)
{
if (IsWarmingUp || Time.Hour > 10)
{
return;
}
foreach (var kvp in slice.OptionChains)
{
if (kvp.Key != _optionSymbol)
{
continue;
}
var chain = kvp.Value;
// Find the call options expiring today
var contracts = chain
.Where(contract => contract.Expiry.Date == Time.Date && contract.Strike < chain.Underlying.Price)
.ToList();
if (contracts.Count == 0)
{
return;
}
_triedGreeksCalculation = true;
foreach (var contract in contracts)
{
var greeks = contract.Greeks;
if (greeks.Delta == 0m && greeks.Gamma == 0m && greeks.Theta == 0m && greeks.Vega == 0m && greeks.Rho == 0m)
{
throw new Exception($"Expected greeks to not be zero simultaneously for {contract.Symbol} at contract expiration date {contract.Expiry}");
}
}
}
}
public override void OnEndOfAlgorithm()
{
if (!_triedGreeksCalculation)
{
throw new Exception("Expected to have tried greeks calculation");
}
}
/// <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 => 5227479;
/// <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", "5.176"},
{"Tracking Error", "0.071"},
{"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

@@ -97,7 +97,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

@@ -0,0 +1,153 @@
/*
* 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.Interfaces;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Securities.Option;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Base regression algorithm excersizing for exercising different style options with option price models that migth
/// or might not support them. Also, if the option style is supported, greeks are asserted to be accesible and have valid values.
/// </summary>
public abstract class OptionPriceModelForOptionStylesBaseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private bool _optionStyleIsSupported;
private Option _option;
private bool _checkGreeks;
private bool _triedGreeksCalculation;
public override void OnData(Slice slice)
{
if (IsWarmingUp)
{
return;
}
foreach (var kvp in slice.OptionChains)
{
if (kvp.Key != _option?.Symbol)
{
continue;
}
CheckGreeks(kvp.Value);
}
}
public override void OnEndOfDay(Symbol symbol)
{
_checkGreeks = true;
}
public override void OnEndOfAlgorithm()
{
if (!_triedGreeksCalculation)
{
throw new Exception("Expected greeks to be accessed");
}
}
protected void Init(Option option, bool optionStyleIsSupported)
{
_option = option;
_optionStyleIsSupported = optionStyleIsSupported;
_checkGreeks = true;
_triedGreeksCalculation = false;
}
public void CheckGreeks(OptionChain contracts)
{
if (!_checkGreeks || !contracts.Any())
{
return;
}
_checkGreeks = false;
_triedGreeksCalculation = true;
foreach (var contract in contracts)
{
Greeks greeks = new Greeks();
try
{
greeks = contract.Greeks;
// Greeks should have not been successfully accessed if the option style is not supported
if (!_optionStyleIsSupported)
{
throw new Exception($"Expected greeks not to be calculated for {contract.Symbol.Value}, an {_option.Style} style option, using {_option?.PriceModel.GetType().Name}, which does not support them, but they were");
}
}
catch (ArgumentException)
{
// ArgumentException is only expected if the option style is not supported
if (_optionStyleIsSupported)
{
throw new Exception($"Expected greeks to be calculated for {contract.Symbol.Value}, an {_option.Style} style option, using {_option?.PriceModel.GetType().Name}, which supports them, but they were not");
}
}
// Greeks shpould be valid if they were successfuly accessed for supported option style
if (_optionStyleIsSupported)
{
if (greeks.Delta == 0m && greeks.Gamma == 0m && greeks.Theta == 0m && greeks.Vega == 0m && greeks.Rho == 0m)
{
throw new Exception($"Expected greeks to not be zero simultaneously for {contract.Symbol.Value}, an {_option.Style} style option, using {_option?.PriceModel.GetType().Name}, but they were");
}
if (((contract.Right == OptionRight.Call && (greeks.Delta < 0m || greeks.Delta > 1m || greeks.Rho < 0m))
|| (contract.Right == OptionRight.Put && (greeks.Delta < -1m || greeks.Delta > 0m || greeks.Rho > 0m))
|| greeks.Vega < 0m || greeks.Gamma < 0m))
{
throw new Exception($"Expected greeks to have valid values. Greeks were: Delta: {greeks.Delta}, Rho: {greeks.Rho}, Theta: {greeks.Theta}, Vega: {greeks.Vega}, Gamma: {greeks.Gamma}");
}
}
}
}
/// <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>
abstract public long DataPoints { get; }
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
abstract public int AlgorithmHistoryDataPoints { get; }
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
abstract public Dictionary<string, string> ExpectedStatistics { get; }
}
}

View File

@@ -0,0 +1,100 @@
/*
* 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.Securities.Option;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm excersizing an equity covered American style option, using an option price model
/// that supports American style options and asserting that the option price model is used.
/// </summary>
public class OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm : OptionPriceModelForOptionStylesBaseRegressionAlgorithm
{
public override void Initialize()
{
SetStartDate(2014, 6, 9);
SetEndDate(2014, 6, 9);
var option = AddOption("AAPL", Resolution.Minute);
// BaroneAdesiWhaley model supports American style options
option.PriceModel = OptionPriceModels.BaroneAdesiWhaley();
SetWarmup(2, Resolution.Daily);
Init(option, optionStyleIsSupported: true);
}
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 861931;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override 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 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

@@ -0,0 +1,40 @@
/*
* 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>
/// Regression algorithm excersizing an equity covered American style option, using an option price model
/// that supports American style options and asserting that the option price model is used.
/// </summary>
public class OptionPriceModelForSupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm : OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm
{
public override void Initialize()
{
base.Initialize();
// We want to match the start time of the base algorithm: Base algorithm warmup is 2 bar of daily resolution.
// So to match the same start time we go back 4 days, we need to account for a single weekend. This is calculated by 'Time.GetStartTimeForTradeBars'
SetWarmup(TimeSpan.FromDays(4));
}
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 1781481;
}
}

View File

@@ -0,0 +1,100 @@
/*
* 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.Securities.Option;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm excersizing an index covered European style option, using an option price model
/// that supports European style options and asserting that the option price model is used.
/// </summary>
public class OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm : OptionPriceModelForOptionStylesBaseRegressionAlgorithm
{
public override void Initialize()
{
SetStartDate(2021, 1, 14);
SetEndDate(2021, 1, 14);
var option = AddIndexOption("SPX", Resolution.Hour);
// BlackScholes model supports European style options
option.PriceModel = OptionPriceModels.BlackScholes();
SetWarmup(7, Resolution.Daily);
Init(option, optionStyleIsSupported: true);
}
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 211;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override 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 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

@@ -0,0 +1,41 @@
/*
* 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>
/// Regression algorithm excersizing an index covered European style option, using an option price model
/// that supports European style options and asserting that the option price model is used.
/// </summary>
public class OptionPriceModelForSupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm : OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm
{
public override void Initialize()
{
base.Initialize();
// We want to match the start time of the base algorithm. SPX index options data time zone is chicago, algorithm time zone is new york (default).
// Base algorithm warmup is 7 bar of daily resolution starts at 23 PM new york time of T-1. So to match the same start time
// we go back a 9 day + 23 hours, we need to account for a single weekend. This is calculated by 'Time.GetStartTimeForTradeBars'
SetWarmup(TimeSpan.FromHours(24 * 9 + 23));
}
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 1404;
}
}

View File

@@ -0,0 +1,99 @@
/*
* 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.Securities.Option;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm excersizing an equity covered American style option, using an option price model that does not support American style options and asserting that the option price model is not used.
/// </summary>
public class OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm : OptionPriceModelForOptionStylesBaseRegressionAlgorithm
{
public override void Initialize()
{
SetStartDate(2014, 6, 9);
SetEndDate(2014, 6, 9);
var option = AddOption("AAPL", Resolution.Minute);
// BlackSholes model does not support American style options
option.PriceModel = OptionPriceModels.BlackScholes();
SetWarmup(2, Resolution.Daily);
Init(option, optionStyleIsSupported: false);
}
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 861931;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override 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 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

@@ -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>
/// Regression algorithm excersizing an equity covered American style option, using an option price model that does not support American style options and asserting that the option price model is not used.
/// </summary>
public class OptionPriceModelForUnsupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm : OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm
{
public override void Initialize()
{
base.Initialize();
// We want to match the start time of the base algorithm: Base algorithm warmup is 2 bar of daily resolution.
// So to match the same start time we go back 4 days, we need to account for a single weekend. This is calculated by 'Time.GetStartTimeForTradeBars'
SetWarmup(TimeSpan.FromDays(4));
}
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 1781481;
}
}

View File

@@ -0,0 +1,101 @@
/*
* 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.Securities.Option;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm excersizing an equity covered European style option, using an option price model
/// that does not support European style options and asserting that the option price model is not used.
/// </summary>
public class OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm : OptionPriceModelForOptionStylesBaseRegressionAlgorithm
{
public override void Initialize()
{
SetStartDate(2021, 1, 14);
SetEndDate(2021, 1, 14);
var option = AddIndexOption("SPX", Resolution.Hour);
// BaroneAdesiWhaley model does not support European style options
option.PriceModel = OptionPriceModels.BaroneAdesiWhaley();
SetWarmup(7, Resolution.Daily);
Init(option, optionStyleIsSupported: false);
}
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 211;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override 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 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

@@ -0,0 +1,41 @@
/*
* 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>
/// Regression algorithm excersizing an equity covered European style option, using an option price model
/// that does not support European style options and asserting that the option price model is not used.
/// </summary>
public class OptionPriceModelForUnsupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm : OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm
{
public override void Initialize()
{
base.Initialize();
// We want to match the start time of the base algorithm. SPX index options data time zone is chicago, algorithm time zone is new york (default).
// Base algorithm warmup is 7 bar of daily resolution starts at 23 PM new york time of T-1. So to match the same start time
// we go back a 9 day + 23 hours, we need to account for a single weekend. This is calculated by 'Time.GetStartTimeForTradeBars'
SetWarmup(TimeSpan.FromHours(24 * 9 + 23));
}
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 1404;
}
}

View File

@@ -133,7 +133,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

@@ -121,7 +121,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

@@ -104,7 +104,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

@@ -86,7 +86,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 6266;
public long DataPoints => 7044;
/// <summary>
/// Data Points count of the algorithm history

View File

@@ -165,7 +165,7 @@ namespace QuantConnect.Algorithm.CSharp
return;
}
// if niether order has filled, bring in the limits by a penny
// if neither order has filled, bring in the limits by a penny
var newLongLimit = longOrder.Get(OrderField.LimitPrice) + 0.01m;
var newShortLimit = shortOrder.Get(OrderField.LimitPrice) - 0.01m;
@@ -234,7 +234,7 @@ namespace QuantConnect.Algorithm.CSharp
return;
}
// if niether order has filled, bring in the stops by a penny
// if neither order has filled, bring in the stops by a penny
var newLongStop = longOrder.Get(OrderField.StopPrice) - 0.01m;
var newShortStop = shortOrder.Get(OrderField.StopPrice) + 0.01m;
@@ -258,7 +258,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// StopLimitOrders work as a combined stop and limit order. First, the
/// price must pass the stop price in the same way a StopMarketOrder works,
/// but then we're also gauranteed a fill price at least as good as the
/// but then we're also guaranteed a fill price at least as good as the
/// limit price. This order type can be beneficial in gap down scenarios
/// where a StopMarketOrder would have triggered and given the not as beneficial
/// gapped down price, whereas the StopLimitOrder could protect you from
@@ -279,7 +279,7 @@ namespace QuantConnect.Algorithm.CSharp
// a long stop is triggered when the price rises above the value
// so we'll set a long stop .25% above the current bar's close
// now we'll also be setting a limit, this means we are gauranteed
// now we'll also be setting a limit, this means we are guaranteed
// to get at least the limit price for our fills, so make the limit
// price a little softer than the stop price
@@ -291,7 +291,7 @@ namespace QuantConnect.Algorithm.CSharp
// a short stop is triggered when the price falls below the value
// so we'll set a short stop .25% below the current bar's close
// now we'll also be setting a limit, this means we are gauranteed
// now we'll also be setting a limit, this means we are guaranteed
// to get at least the limit price for our fills, so make the limit
// price a little softer than the stop price
@@ -314,7 +314,7 @@ namespace QuantConnect.Algorithm.CSharp
return;
}
// if niether order has filled, bring in the stops/limits in by a penny
// if neither order has filled, bring in the stops/limits in by a penny
var newLongStop = longOrder.Get(OrderField.StopPrice) - 0.01m;
var newLongLimit = longOrder.Get(OrderField.LimitPrice) + 0.01m;
@@ -494,7 +494,7 @@ namespace QuantConnect.Algorithm.CSharp
}
if (remainingOpenOrders != 0m)
{
throw new Exception($"No remaining quantiy to be filled from open orders was expected");
throw new Exception($"No remaining quantity to be filled from open orders was expected");
}
var symbolOpenOrders = Transactions.GetOpenOrders(symbol).Count;
@@ -507,7 +507,7 @@ namespace QuantConnect.Algorithm.CSharp
}
if (symbolOpenOrdersRemainingQuantity != 0)
{
throw new Exception($"No remaining quantiy to be filled from open orders was expected");
throw new Exception($"No remaining quantity to be filled from open orders was expected");
}
var defaultOrders = Transactions.GetOrders();
@@ -526,7 +526,7 @@ namespace QuantConnect.Algorithm.CSharp
}
if (defaultOpenOrdersRemaining != 0m)
{
throw new Exception($"No remaining quantiy to be filled from open orders was expected");
throw new Exception($"No remaining quantity to be filled from open orders was expected");
}
}

View File

@@ -0,0 +1,141 @@
/*
* 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;
using QuantConnect.Data.Market;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm for testing that period-based history requests are not allowed with tick resolution
/// </summary>
public class PeriodBasedHistoryRequestNotAllowedWithTickResolutionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 09);
var spy = AddEquity("SPY", Resolution.Tick).Symbol;
// Tick resolution is not allowed for period-based history requests
AssertThatHistoryThrowsForTickResolution(() => History<Tick>(spy, 1),
"Tick history call with implicit tick resolution");
AssertThatHistoryThrowsForTickResolution(() => History<Tick>(spy, 1, Resolution.Tick),
"Tick history call with explicit tick resolution");
AssertThatHistoryThrowsForTickResolution(() => History<Tick>(new [] { spy }, 1),
"Tick history call with symbol array with implicit tick resolution");
AssertThatHistoryThrowsForTickResolution(() => History<Tick>(new [] { spy }, 1, Resolution.Tick),
"Tick history call with symbol array with explicit tick resolution");
var history = History<Tick>(spy, TimeSpan.FromHours(12));
if (history.Count() == 0)
{
throw new Exception("On history call with implicit tick resolution: history returned no results");
}
history = History<Tick>(spy, TimeSpan.FromHours(12), Resolution.Tick);
if (history.Count() == 0)
{
throw new Exception("On history call with explicit tick resolution: history returned no results");
}
}
private void AssertThatHistoryThrowsForTickResolution(Action historyCall, string historyCallDescription)
{
try
{
historyCall();
throw new Exception($"{historyCallDescription}: expected an exception to be thrown");
}
catch (ArgumentException)
{
// expected
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 7682413;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 2489880;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -0,0 +1,146 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Data.Market;
using System.Collections.Generic;
using QuantConnect.Data.Consolidators;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting the behavior of a period consolidator
/// </summary>
public class PeriodConsolidatorRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Queue<string> _periodConsolidation = new();
private Queue<string> _countConsolidation = new();
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 08);
var symbol = AddEquity("SPY").Symbol;
var periodConsolidator = new TradeBarConsolidator(Resolution.Minute.ToTimeSpan());
periodConsolidator.DataConsolidated += PeriodConsolidator_DataConsolidated;
var countConsolidator = new TradeBarConsolidator(1);
countConsolidator.DataConsolidated += CountConsolidator_DataConsolidated;
SubscriptionManager.AddConsolidator(symbol, periodConsolidator);
SubscriptionManager.AddConsolidator(symbol, countConsolidator);
}
private void PeriodConsolidator_DataConsolidated(object sender, TradeBar e)
{
_periodConsolidation.Enqueue($"{Time} - {e.EndTime} {e}");
}
private void CountConsolidator_DataConsolidated(object sender, TradeBar e)
{
_countConsolidation.Enqueue($"{Time} - {e.EndTime} {e}");
}
public override void OnEndOfAlgorithm()
{
if (_countConsolidation.Count == 0 || _countConsolidation.Count != _periodConsolidation.Count)
{
throw new Exception($"Unexpected consolidated data count. Period: {_periodConsolidation.Count} Count: {_countConsolidation.Count}");
}
while (_countConsolidation.TryDequeue(out var countData))
{
var periodData = _periodConsolidation.Dequeue();
if (periodData != countData)
{
throw new Exception($"Unexpected consolidated data. Period: '{periodData}' != Count: '{countData}'");
}
}
_periodConsolidation.Clear();
_countConsolidation.Clear();
}
/// <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 => 1582;
/// <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", "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

@@ -34,7 +34,7 @@
<DebugType>portable</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="QuantConnect.pythonnet" Version="2.0.15" />
<PackageReference Include="QuantConnect.pythonnet" Version="2.0.16" />
<PackageReference Include="Accord" Version="3.6.0" />
<PackageReference Include="Accord.Fuzzy" Version="3.6.0" />
<PackageReference Include="Accord.MachineLearning" Version="3.6.0" />

View File

@@ -88,7 +88,7 @@ namespace QuantConnect.Algorithm.CSharp
/// 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

View File

@@ -0,0 +1,147 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities.Equity;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regression algorithm has examples of how to add an equity indicating the <see cref="DataNormalizationMode"/>
/// directly with the <see cref="QCAlgorithm.AddEquity"/> method instead of using the <see cref="Equity.SetDataNormalizationMode"/> method.
/// </summary>
public class SetEquityDataNormalizationModeOnAddEquity : QCAlgorithm, IRegressionAlgorithmDefinition
{
private readonly DataNormalizationMode _spyNormalizationMode = DataNormalizationMode.Raw;
private readonly DataNormalizationMode _ibmNormalizationMode = DataNormalizationMode.Adjusted;
private readonly DataNormalizationMode _aigNormalizationMode = DataNormalizationMode.TotalReturn;
private Dictionary<Equity, Tuple<decimal, decimal>> _priceRanges = new Dictionary<Equity, Tuple<decimal, decimal>>();
public override void Initialize()
{
SetStartDate(2013, 10, 7);
SetEndDate(2013, 10, 7);
var spyEquity = AddEquity("SPY", Resolution.Minute, dataNormalizationMode: _spyNormalizationMode);
CheckEquityDataNormalizationMode(spyEquity, _spyNormalizationMode);
_priceRanges.Add(spyEquity, new Tuple<decimal, decimal>(167.28m, 168.37m));
var ibmEquity = AddEquity("IBM", Resolution.Minute, dataNormalizationMode: _ibmNormalizationMode);
CheckEquityDataNormalizationMode(ibmEquity, _ibmNormalizationMode);
_priceRanges.Add(ibmEquity, new Tuple<decimal, decimal>(135.864131052m, 136.819606508m));
var aigEquity = AddEquity("AIG", Resolution.Minute, dataNormalizationMode: _aigNormalizationMode);
CheckEquityDataNormalizationMode(aigEquity, _aigNormalizationMode);
_priceRanges.Add(aigEquity, new Tuple<decimal, decimal>(48.73m, 49.10m));
}
public override void OnData(Slice slice)
{
foreach (var kvp in _priceRanges)
{
var equity = kvp.Key;
var minExpectedPrice = kvp.Value.Item1;
var maxExpectedPrice = kvp.Value.Item2;
if (equity.HasData && (equity.Price < minExpectedPrice || equity.Price > maxExpectedPrice))
{
throw new Exception($"{equity.Symbol}: Price {equity.Price} is out of expected range [{minExpectedPrice}, {maxExpectedPrice}]");
}
}
}
private void CheckEquityDataNormalizationMode(Equity equity, DataNormalizationMode expectedNormalizationMode)
{
var subscriptions = SubscriptionManager.Subscriptions.Where(x => x.Symbol == equity.Symbol);
if (subscriptions.Any(x => x.DataNormalizationMode != expectedNormalizationMode))
{
throw new Exception($"Expected {equity.Symbol} to have data normalization mode {expectedNormalizationMode} but was {subscriptions.First().DataNormalizationMode}");
}
}
/// <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 => 2355;
/// <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

@@ -63,7 +63,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

@@ -0,0 +1,131 @@
/*
* 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.Market;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting that historical data can be requested with tick resolution without requiring
/// a tick resolution subscription
/// </summary>
public class TickHistoryRequestWithoutTickSubscriptionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2013, 10, 8);
SetEndDate(2013, 10, 8);
// Subscribing SPY and IBM with daily and hour resolution instead of tick resolution
var spy = AddEquity("SPY", Resolution.Daily).Symbol;
var ibm = AddEquity("IBM", Resolution.Hour).Symbol;
// Requesting history for SPY and IBM (separately) with tick resolution
var spyHistory = History<Tick>(spy, TimeSpan.FromDays(1), Resolution.Tick);
if (spyHistory.Count() == 0)
{
throw new Exception("SPY tick history is empty");
}
var ibmHistory = History<Tick>(ibm, TimeSpan.FromDays(1), Resolution.Tick);
if (ibmHistory.Count() == 0)
{
throw new Exception("IBM tick history is empty");
}
// Requesting history for SPY and IBM (together) with tick resolution
var spyIbmHistory = History<Tick>(new [] { spy, ibm }, TimeSpan.FromDays(1), Resolution.Tick);
if (spyIbmHistory.Count() == 0)
{
throw new Exception("Compound SPY and IBM tick history is empty");
}
Quit();
}
/// <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 => 531220;
/// <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

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -14,6 +14,8 @@
*/
using System;
using QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
@@ -22,8 +24,9 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="using quantconnect" />
/// <meta name="tag" content="training" />
/// </summary>
public class TrainingExampleAlgorithm : QCAlgorithm
public class TrainingExampleAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Queue<DateTime> _trainTimes = new();
public override void Initialize()
{
SetStartDate(2013, 10, 7);
@@ -46,6 +49,94 @@ namespace QuantConnect.Algorithm.CSharp
// ML code:
// let's keep this to assert in the end of the algorithm
_trainTimes.Enqueue(Time);
}
/// <summary>
/// Let's assert the behavior of our traning schedule
/// </summary>
public override void OnEndOfAlgorithm()
{
if (_trainTimes.Count != 2)
{
throw new Exception($"Unexpected train count: {_trainTimes.Count}");
}
if (_trainTimes.Dequeue() != StartDate
|| _trainTimes.Dequeue() != new DateTime(2013, 10, 13, 8, 0, 0))
{
throw new Exception($"Unexpected train times!");
}
}
/// <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 => 56;
/// <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", "-7.357"},
{"Tracking Error", "0.161"},
{"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,193 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Indicators;
using QuantConnect.Data.Market;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting warming up with a lower resolution for speed is respected
/// </summary>
public class WarmupDailyResolutionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private long _previousSampleCount;
private bool _warmedUpTradeBars;
private bool _warmedUpQuoteBars;
protected SimpleMovingAverage Sma { get; set; }
protected TimeSpan ExpectedDataSpan { get; set; }
protected TimeSpan ExpectedWarmupDataSpan { get; set; }
public override void Initialize()
{
SetStartDate(2013, 10, 10);
SetEndDate(2013, 10, 11);
AddEquity("SPY", Resolution.Hour);
ExpectedDataSpan = Resolution.Hour.ToTimeSpan();
SetWarmUp(TimeSpan.FromDays(3), Resolution.Daily);
ExpectedWarmupDataSpan = Resolution.Daily.ToTimeSpan();
Sma = SMA("SPY", 2);
}
public override void OnData(Slice data)
{
if (Sma.Samples <= _previousSampleCount)
{
throw new Exception("Indicator was not updated!");
}
_previousSampleCount = Sma.Samples;
var tradeBars = data.Get<TradeBar>();
tradeBars.TryGetValue("SPY", out var trade);
var quoteBars = data.Get<QuoteBar>();
quoteBars.TryGetValue("SPY", out var quote);
var expectedPeriod = ExpectedDataSpan;
if (Time <= StartDate)
{
expectedPeriod = ExpectedWarmupDataSpan;
if (trade != null && trade.IsFillForward || quote != null && quote.IsFillForward)
{
throw new Exception("Unexpected fill forwarded data!");
}
}
// let's assert the data's time are what we expect
if (trade != null && trade.EndTime.Ticks % expectedPeriod.Ticks != 0)
{
throw new Exception($"Unexpected data end time! {trade.EndTime}");
}
if (quote != null && quote.EndTime.Ticks % expectedPeriod.Ticks != 0)
{
throw new Exception($"Unexpected data end time! {quote.EndTime}");
}
if (trade != null)
{
_warmedUpTradeBars |= IsWarmingUp;
if (trade.Period != expectedPeriod)
{
throw new Exception($"Unexpected period for trade data point {trade.Period} expected {expectedPeriod}. IsWarmingUp: {IsWarmingUp}");
}
}
if (quote != null)
{
_warmedUpQuoteBars |= IsWarmingUp;
if (quote.Period != expectedPeriod)
{
throw new Exception($"Unexpected period for quote data point {quote.Period} expected {expectedPeriod}. IsWarmingUp: {IsWarmingUp}");
}
}
}
public override void OnEndOfAlgorithm()
{
if (!_warmedUpTradeBars)
{
throw new Exception("Did not assert data during warmup!");
}
if (ExpectedWarmupDataSpan == QuantConnect.Time.OneDay)
{
if (_warmedUpQuoteBars)
{
throw new Exception("We should of not gotten any quote bar during warmup for daily resolution!");
}
}
else if (!_warmedUpQuoteBars)
{
throw new Exception("Did not assert data during warmup!");
}
}
/// <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 virtual long DataPoints => 37;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
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 virtual 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

@@ -0,0 +1,38 @@
/*
* 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.
*/
namespace QuantConnect.Algorithm.CSharp
{
public class WarmupDataTypesBarCountWarmupRegressionAlgorithm : WarmupDataTypesRegressionAlgorithm
{
/// <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()
{
base.Initialize();
// We want to match the start time of the base algorithm: Base algorithm warmup is 24 bars of hour resolution.
// So to match the same start time we go back 5 days + a few hours, we need to account for weekends. This is calculated by 'Time.GetStartTimeForTradeBars'
// Each day has 7 hour bars => 3 complete days 21 hours + 2 weekend days + 3 hours of the previous day (24 PM - 11 hours = 13 PM - 13/14/15 hour bars)
SetWarmUp(24 * 5 + 11);
}
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 5298;
}
}

View File

@@ -75,7 +75,8 @@ namespace QuantConnect.Algorithm.CSharp
{
throw new Exception("Did not get any TradeBar during warmup");
}
if (!_equityGotQuoteBars)
// we don't have quote bars for equity in daily/hour resolutions
if (!_equityGotQuoteBars && !Settings.WarmupResolution.HasValue)
{
throw new Exception("Did not get any QuoteBar during warmup");
}
@@ -98,17 +99,17 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 5298;
public virtual long DataPoints => 3763;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 41;
public virtual int AlgorithmHistoryDataPoints => 41;
/// <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%"},

View File

@@ -28,12 +28,13 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public class WarmupFutureRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private List<DateTime> _continuousWarmupTimes = new();
private List<DateTime> _chainWarmupTimes = new();
// S&P 500 EMini futures
private const string RootSP500 = Futures.Indices.SP500EMini;
public Symbol SP500 = QuantConnect.Symbol.Create(RootSP500, SecurityType.Future, Market.CME);
protected List<DateTime> ContinuousWarmupTimes { get; } = new();
protected List<DateTime> ChainWarmupTimes { get; } = new();
/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
@@ -60,7 +61,7 @@ namespace QuantConnect.Algorithm.CSharp
{
throw new Exception("Continuous contract price is not set!");
}
_continuousWarmupTimes.Add(Time);
ContinuousWarmupTimes.Add(Time);
}
foreach (var chain in slice.FutureChains)
@@ -81,7 +82,7 @@ namespace QuantConnect.Algorithm.CSharp
{
throw new Exception("Contract price is not set!");
}
_chainWarmupTimes.Add(Time);
ChainWarmupTimes.Add(Time);
}
else if (!Portfolio.Invested && IsMarketOpen(contract.Symbol))
{
@@ -93,11 +94,11 @@ namespace QuantConnect.Algorithm.CSharp
public override void OnEndOfAlgorithm()
{
AssertDataTime(new DateTime(2013, 10, 07, 0, 0, 0), new DateTime(2013, 10, 08, 0, 0, 0), _chainWarmupTimes);
AssertDataTime(new DateTime(2013, 10, 07, 0, 0, 0), new DateTime(2013, 10, 08, 0, 0, 0), _continuousWarmupTimes);
AssertDataTime(new DateTime(2013, 10, 07, 20, 0, 0), new DateTime(2013, 10, 08, 20, 0, 0), ChainWarmupTimes);
AssertDataTime(new DateTime(2013, 10, 07, 20, 0, 0), new DateTime(2013, 10, 08, 20, 0, 0), ContinuousWarmupTimes);
}
private void AssertDataTime(DateTime start, DateTime end, List<DateTime> times)
protected void AssertDataTime(DateTime start, DateTime end, List<DateTime> times)
{
var count = 0;
do
@@ -111,7 +112,14 @@ namespace QuantConnect.Algorithm.CSharp
// if the market is closed there will be no data, so stop moving the index counter
count++;
}
start = start.AddMinutes(1);
if (Settings.WarmupResolution.HasValue)
{
start = start.Add(Settings.WarmupResolution.Value.ToTimeSpan());
}
else
{
start = start.AddMinutes(1);
}
}
while (start < end);
}
@@ -129,7 +137,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 86905;
public virtual long DataPoints => 65577;
/// <summary>
/// Data Points count of the algorithm history
@@ -139,7 +147,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%"},

View File

@@ -0,0 +1,40 @@
/*
* 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
{
public class WarmupFutureTimeSpanWarmupRegressionAlgorithm : WarmupFutureRegressionAlgorithm
{
public override void Initialize()
{
base.Initialize();
SetWarmUp(TimeSpan.FromHours(24 + 4));
}
public override void OnEndOfAlgorithm()
{
AssertDataTime(new DateTime(2013, 10, 07, 0, 0, 0), new DateTime(2013, 10, 08, 0, 0, 0), ChainWarmupTimes);
AssertDataTime(new DateTime(2013, 10, 07, 0, 0, 0), new DateTime(2013, 10, 08, 0, 0, 0), ContinuousWarmupTimes);
}
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 86905;
}
}

View File

@@ -0,0 +1,32 @@
/*
* 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.
*/
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting warming up with a lower resolution for speed is respected
/// </summary>
public class WarmupLowerResolutionBarCountRegressionAlgorithm : WarmupLowerResolutionTimeSpanRegressionAlgorithm
{
public override void Initialize()
{
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 09);
AddEquity("SPY", Resolution.Second);
SetWarmUp(60 * 6 + 30, Resolution.Minute);
}
}
}

View File

@@ -0,0 +1,33 @@
/*
* 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.
*/
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting warming up with a lower resolution for speed is respected
/// </summary>
public class WarmupLowerResolutionBarCountSettingRegressionAlgorithm : WarmupLowerResolutionTimeSpanRegressionAlgorithm
{
public override void Initialize()
{
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 09);
AddEquity("SPY", Resolution.Second);
SetWarmUp(60 * 6 + 30);
Settings.WarmupResolution = Resolution.Minute;
}
}
}

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