Compare commits

...

192 Commits

Author SHA1 Message Date
hsm207
e869765759 Fix typo (#5361) 2021-03-04 15:28:21 -03:00
Martin-Molinero
c7fb6165e2 Revert "Upgrade IBAutomater to v1.0.51 (#5359)" (#5362)
This reverts commit caedddddf0.
2021-03-04 15:20:15 -03:00
IlshatGaripov
d9d02bc2d0 Applies a fix (#5358) 2021-03-04 13:13:41 -03:00
Stefano Raggi
caedddddf0 Upgrade IBAutomater to v1.0.51 (#5359) 2021-03-04 13:03:31 -03:00
Martin-Molinero
4e00324b57 Bug insight internal to procted internal (#5357)
* Update Insight.cs

* Insight protected to protected internal

Co-authored-by: Jared <jaredbroad@gmail.com>
2021-03-03 16:14:36 -08:00
Martin-Molinero
1b6301d813 Update Insight.cs (#5356) 2021-03-03 16:02:57 -08:00
Jared
d24695856d Update Insight.cs (#5355) 2021-03-03 15:17:25 -08:00
hsm207
17e13665eb Fix typo (#5353) 2021-03-03 10:23:05 -03:00
Gerardo Salazar
8c6aa6a3b3 Refactors Capacity Estimation and moves estimation to main event loop (#5351)
* Adds CapacityEstimate and SymbolCapacity

  The capacity estimation has been moved from
  the report generator and wired directly into
  Lean via the ResultHandler. In addition,
  the capacity estimation strategy has changed
  to account for errors in the previous iteration
  of the capacity estimation.

  Many many thanks to Jared for being much of the
  mastermind behind this project. It would have
  been harder to complete without him to bounce ideas
  off of.

  * Moves old tests to regression algorithms
  * Adds Estimated Capacity statistic
  * Removes old capacity estimation tests

Final report capacity estimation. Pushing to save state

* Fixes bugs, cleans up code and adds comments

  * Adds forced sampling to Capacity Estimation
  * Misc. bug fixes for daily data

* Updates capacity test cases' Estimated Strategy Capacity statistic

* Adds Capacity Estimate to all regression algorithms

* Removes Report's StrategyCapacity class and fixes bug in tests

  * Adds null check in BacktestingResultHandler to fix
    BacktestingTransactionHandler failing tests

  * Deletes old capacity estimation classes

  * Retrieve capacity estimates from backtest statistics results
    instead of calculating at runtime

* Make $0.00 capacity return as "-" and Result = 0 in report

* Adds capacity to runtime statistics

* Converts capacity to number denoted by financial figures in RuntimeStats

* Addresses review: code cleanup for Capacity and adds comments to regression tests
2021-03-02 18:46:31 -03:00
IlshatGaripov
83da0affc5 Implements Coin API HistoryProvider (#5298)
* CoinApi HistoryProvider impl.

* Small fix of ToTradeBar()

* Revert the change : CreateSliceEnumerableFromSubscriptions

* More tests and fixes.

* Removes redundant ToList()

* too much spacing

* Fixes to get data for an unlimited period of time, by means of pagination
2021-03-02 11:08:14 -03:00
Jasper van Merle
60798df64c Make optimizer usable in Docker and improve its logging (#5344)
* Make optimizer usable in Docker and improve its logging

* Wait for reset event instead of polling state
2021-02-26 15:50:16 -03:00
Martin-Molinero
bb20f9d9df IB will not load holdings internally if requested (#5342) 2021-02-25 11:43:38 -08:00
Martin-Molinero
32686db739 NotificationJsonConverter is case insensitive (#5341)
- NotificationJsonConverter will be case insensitive. Adding unit test
2021-02-25 11:42:42 -08:00
Stefano Raggi
7d97f05133 Tradier Brokerage updates (#5326)
* Add options support

- Added IDataQueueUniverseProvider implementation
- Fix subscribe ticker for options

* Tradier DataQueueHandler web sockets implementation

- Equities and Options (trades and quotes)

* Add error handling

* Add support for options

* Fix log messages

* Address review

- Updated Tick constructor usage
- Use $empty$ symbol for last unsubscribe message
- Added symbol mapper unit tests
2021-02-25 10:41:47 -03:00
Colton Sellers
8b173f2306 Add dotnet 5 to Lean Foundation Image (#5307)
* Add dotnet 5 to foundation image

* Address review. Remove net5 package after install

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-02-24 21:09:59 -03:00
Jasper van Merle
9cde4344fc Re-apply changes from #4870 to fix ThreadAbortException in ToolBox (#5339) 2021-02-24 20:50:56 -03:00
Martin-Molinero
785c706d4c Live delisting will only ask mapfile for equities (#5336)
* Live delisting will only ask mapfile for equities

* Remove unrequired log error
2021-02-24 14:14:50 -03:00
Gerardo Salazar
0dc521f787 Reduces log spam on long backtests when generating capacity (#5334) 2021-02-23 16:22:49 -08:00
Martin-Molinero
94d9996b21 Enforce USD account currency if allocation is limited (#5333)
* Enforce USD account currency if allocation is limited

- Enforce USD account currency if allocation is limited. Adding unit
  test

* Adjust currency log message
2021-02-23 11:57:48 -08:00
Martin-Molinero
67b3873205 Reduce live coarse selection interval check to 10 min (#5332)
* Reduce live coarse selection interval check to 10 min

- Reduce live coarse selection interval check to 10 min. Adding unit
  tests, reducing code duplication in tests.

* Adjust unit test after self review
2021-02-23 16:37:08 -03:00
Gerardo Salazar
acd9ef4cfd Removes SevenZipSharp library from ToolBox (#5329)
* Removes SevenZipSharp library from ToolBox

  - Library removal required for update to .NET 5.0 since it's not
    compatible with it and Linux is unsupported.

  * Adds new extract 7z functionality to Compression project
  * Refactors AlgoSeekFuturesConverter 7z extract
  * Refactors DukascopyDataDownloader 7z extract

* Addresses review: code cleanup + exception type change on timeout

  * Removes not needed stream of data in Dukascopy downloader
  * Makes output directory non-optional
2021-02-23 11:38:07 -03:00
Gerardo Salazar
7f934b2adf Remove unused dependency WebSocketSharpFork (#5331) 2021-02-23 11:33:17 -03:00
Martin-Molinero
596e940ccd Update R library (#5328)
* Update R.Net libraries

* Update R installation version
2021-02-22 19:24:05 -03:00
Gerardo Salazar
f38ff0d1f2 Reduces StrategyCapacity memory load and boosts performance (#5327)
* Adds logging for progress tracking
  * Reads data one day at a time rather than loading all data at once
2021-02-22 11:53:12 -08:00
Gerardo Salazar
37d26a35ce Fixes various bugs in estimated capacity class (#5324)
* Fixes potential mapping issue, caused by not mapping Symbols before
    reading data off disk

  * Fixes issue where some results would evaluate to zero capacity

  * Loads of refactoring, mostly resulting in cleaner code
2021-02-19 18:00:08 -08:00
Martin-Molinero
834326760d Fix regression test History Request (#5321)
- After https://github.com/QuantConnect/Lean/pull/5207 history requests
  are selecting the correct data type and cause the regression test to
  fail because there is no QuoteBars for daily equity. Updating and
  fixing this.
- Centralizing the logic around getting the SubscriptionDataConfig to
  use
2021-02-19 20:39:50 -03:00
Martin-Molinero
d4ebd93586 Limit live cash allocation (#5320)
* Add brokerage data cash limit feature

* Expand unit test to asser orders are skipped

* Add algorithm debug messages

* Ignore account changed event
2021-02-19 20:08:32 -03:00
Gerardo Salazar
0645513f5e Capacity estimation in report generator (#5318)
* Adds strategy capacity estimation in report generator

* Style and license fixes

* Adds comments, constants, and new method accessibility

* Removes unneeded imports
2021-02-18 17:51:40 -08:00
Martin-Molinero
ecf91546e6 Update Nlog Math and fasterflect (#5310)
* Update Nlog Math and fasterflect

* Remove NLog
2021-02-18 20:18:07 -03:00
Martin-Molinero
c834a1c902 Revert Lean.Launcher nuget package rename (#5317) 2021-02-18 19:39:05 -03:00
Colton Sellers
43a540cbb1 OpenInterest Bug Fixes (#5207)
* Filter values that are before subscription start time; also adjust starttime for OpenInterest

* Use data EndTime for comparison

* Allow Auxiliary data through

* Fix OpenInterest DataReader Logic

* Add regression

* Address review

* Ignore open interest for time slice

- TimeSliceFactory will directly ignore open interest for determining if
  the slice has data or not. Open interest will still be available
  through the Tick collection. Reverting some of the previous commits
  changes since they are no longer required.
- HistoryRequests and SubscriptionRequest will use AlwaysOpen exchange
  for open interest requests. Adding unit test reproducing issue
- Adding `BaseDataRequest` to avoid duplication logic.

* Make OpenInterest an internal feed and ignored by default in history

- Adding unit tests

* Revert SubscriptionFilterEnumerator Start time addition

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-02-18 19:04:29 -03:00
Alexandre Catarino
c5bb840bde Adds Static AlgorithmCreationTimeout Property to BaseSetupHandler (#5316)
* Adds Static AlgorithmCreationTimeout Property to BaseSetupHandler

This value will be used to set maximum time that the creation of an algorithm can take.

* Adds Additional Logging to AlgorithmPythonWrapper

It will informing the user how long it takes to import the module.

* Changes How AlgorithmCreationTimeout is Initialized

It will prevent callling Config.GetDouble on every call.
2021-02-18 19:00:33 -03:00
Martin-Molinero
4632840da9 Add license file for project packages (#5314) 2021-02-18 18:57:36 -03:00
Martin-Molinero
ba4c45d729 Remove version checking (#5315) 2021-02-18 18:32:07 -03:00
Martin-Molinero
9232427663 Remove all nuspec files (#5311) 2021-02-18 17:13:11 -03:00
Martin-Molinero
c30929f612 Add support for live trading delisting events (#5195)
* Add support for live trading delisting events

- Adding `LiveDelistingEventProviderEnumerator` that will emit delisting
  events. Adding unit tests
- Remove unused `LiveAuxiliaryDataEnumerator`.
- Refactor the corporate event providers being used per security type

* Self review: compare date component

* Add new LiveDataBaseDelistingEventProvider for equities

- Add support for delisting events for equities. Adding unit tests

* Fix cleanup of delisting equity subscription
2021-02-17 19:53:53 -03:00
Martin-Molinero
df6e133833 Fixes for assembly information (#5306)
- Update version to 2.5
- Normalize version and assembly information
- Remove commented and unrequired code
2021-02-17 16:42:23 -03:00
Juan José D'Ambrosio
2d99afc8c3 Refactor IPrimaryExchangeProvider.GetPrimaryExchange (#5302)
* Refactor IPrimaryExchangeProvider.GetPrimaryExchange 

now it returns a PrimaryExchange instead of a string

* Update MapFilePrimaryExchangeProvider.cs

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-02-17 12:43:41 -03:00
Gerardo Salazar
b3835510d0 Changes calculation of rolling/series graphs to use EOD equity (#5303)
* To maintain consistency between calculations, we will use
    the end of day equity value to calculate the returns per day.
    This fixes a bug where daily equity series would zero out and result
    in an exception being thrown since no elements were being passed to
    the Sharpe calculation.
2021-02-16 13:43:27 -08:00
Stefano Raggi
239fa29bf3 Tradier Brokerage updates (#5265)
* Tradier brokerage updates

- Removed old authentication code (refresh tokens) and settings
- Added "tradier-use-sandbox" config setting

* Fix brokerage unit tests

* Update Tradier config.json settings

* Add sandbox check in Subscribe

* Bug fixes + unit test updates

* Trigger build

* Fix Tradier fee model

* Address review
2021-02-16 13:37:46 -03:00
Juan José D'Ambrosio
df4abd3c3a Bug algoseek taq writes tick exchanges correctly (#5301)
* Implements wrapper to get the exchange as a single letter representation

Also replace lower 'l' with capital 'L' in condition flags enums. it is a new warning on the compiler and it looks cool :)

* There are cases where the exchange is null or empty, in those cases return null

* Add tests for single character exchange representation

* Update GlobalTest.cs

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-02-16 12:51:08 -03:00
Gerardo Salazar
7d93f43d38 Calculate more report elements using LiveResult data in report generator (#5300)
* Calculate PSR for live algorithms in report generator

* Use live series for calculating of CAGR, Max DD, and PSR

  * Removes Kelly Estimate from report and template.html

* Update template.html

* Rolling Beta bug fix when using daily data

  * Max drawdown output as percent

* Make days live report element use equity curve last day instead of today

Co-authored-by: Jared <jaredbroad@gmail.com>
2021-02-15 19:56:52 -08:00
Gerardo Salazar
c435caa7d1 Add check for new deployments to DaysLiveReportElement (#5299)
* This fixes a potential exception thrown when trying to access the
    first element of the Live equity series, when no equity series
    exists.
2021-02-15 21:30:12 -03:00
Aaron Janeiro Stone
643e8754ed Feature 5162 - LimitIfTouched Orders (#5164)
* Adds LimitIfTouched order.

TODO:
-- Add tests.
-- Add into existing regression algorithms.
-- Refactors (?)

* Fixes

- Remove unrequired space changes
- Fix EquityFillModel min/max limit price fill
- Add TriggerPrice for UpdateOrderRequest.

Quote info used w.r.t. comparing against Limit prices for LIT

FillModel.cs implementation is fixed to use quotes when comparing against set limit prices.
Also changes test implementations to assert which of quotes/trade-bars are being used

Reviewer-suggested fixes
------------
Merge remote-tracking branch 'origin/limiftouched' into limiftouched
Styling
Adds missing null check for quotebar
Styling
Adds missing null check for quotebar
Merge remote-tracking branch 'origin/limiftouched' into limiftouched
High/Low w.r.t. trigger price for determining if TriggerTouched changed to Current price
0462ad668a (r569832380)
fill fixes:
FillModel.cs: Fills exactly at the limit
EquityFillModel.cs: https://www1.interactivebrokers.com/en/index.php?f=608
Equity fill now uses quotebars
Revert - use new constructor which emulates former SubmitOrderRequest
Style changes
Reverts order model to original by means if new constructor
High/Low w.r.t. trigger price for determining if TriggerTouched changed to Current price
0462ad668a (r569832380)
fill fixes:
FillModel.cs: Fills exactly at the limit
EquityFillModel.cs: https://www1.interactivebrokers.com/en/index.php?f=608
Equity fill now uses quotebars
Revert - use new constructor which emulates former SubmitOrderRequest
Style changes
Reverts order model to original by means if new constructor
Merge commit 'bf4c96d2a055ea808fa4293662528c11a89b72c7'

* Suggested style fixes

* Review fixes
-------------------
- Suggested style fixes
- Changes LIT regression to better incorporate order modifications
- TODO: orderlisthash must be fixed
Fixed LIT regression algo
-----------------------
- Includes asserts in OnOrderEvent

* Fix OrderListHash

OrderListHash -> -292689487

* Re-adds quote nullchecks

* EquityFillModelTests fixes asserts

* Reordering FillModel.cs

* Fixes quote logic, adds methods in FillModel.cs

* Refactoring + LIT regression fixes
-- revert unneeded changes

* Fixes list hash

* Rebase -- catch up upstream

* OrderListHash fix

* Various fixes by reviewer

* Final requested changes

* tagged time -> utcinvariant

* Fixes listorderhash

* Time changed to UtcTime.ToString(DateFormat.US, CultureInfo.InvariantCulture)

* Adds Python LimitIfTouchedRegressionAlgorithm

* adds LimitIfTouchedRegressionAlgorithm.py

* adds LimitIfTouchedRegressionAlgorithm.py

* Minor changes to LIT regression algorithms

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-02-15 10:29:51 -03:00
IlshatGaripov
d17fe34c74 Fixing up Coin API streaming (#5295)
* fixing up Coin API streaming

* Fixing file name

* Adding log showing CoinApi product plan

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-02-15 09:55:00 -03:00
Stefano Raggi
512000d500 Update IBAutomater to v1.0.44 (#5290) 2021-02-12 12:10:02 -03:00
Gerardo Salazar
f5e730d776 Re-enable second page of reports generation (#5294) 2021-02-11 17:12:30 -08:00
Martin-Molinero
a0f39ec6a4 Remove Microsoft.Net.Compilers (#5282)
* Remove Microsoft.Net.Compilers

* Remove deprecated analyzer packages

- Replace deprecated analyzer packages

* Travis will use dotnet for building
2021-02-11 09:31:37 -03:00
IlshatGaripov
54bbdacd76 Just a small fix (#5287) 2021-02-10 12:17:43 -03:00
Gerardo Salazar
096e34212c Replace AppDomain.CurrentDomain with AssemblyBuilder (#5284)
* .NET Core/5.0 will not compile when calling
    AppDomain.CurrentDomain.DefineDynamicAssembly() since it was removed
    in .NET Core.

    AssemblyBuilder replaces this specific functionality since
    AppDomains were deprecated in .NET Core
2021-02-09 18:37:39 -03:00
Martin-Molinero
6d8e38a692 Update IB Api dll (#5278) 2021-02-09 17:35:55 -03:00
Gerardo Salazar
fefac8ab34 Move report statistics JSON output to in-memory string as out param (#5283) 2021-02-09 12:27:10 -08:00
Gerardo Salazar
3f53ba9b2f Report Generator Portfolio Result Statistics Output + TradesPerDayReportElement Bug Fix (#5281)
* Report generator statistics output

* Fixes issue where unsorted list could cause a negative trades/day kpi
2021-02-09 11:51:00 -08:00
Gerardo Salazar
e2964dd4b1 Make OrderListHash deterministic by using MD5 as its underlying hash function (#5276)
* Update OrderListHash to use MD5 as hash instead of hash code

* Update regression algorithm OrderListHash statistic

* Use full MD5 hash as OrderListHash, update regression statistic

* Fixes failing regression tests
2021-02-09 12:19:25 -03:00
Martin-Molinero
a1cbe13bb0 Minor logging improvements (#5277)
* Minor logging improvements

- Remove Thread.Sleep() call when logging debug
- FileLogHandler will capture lock after generating message to log
- ConsoleLogHandler will log time as UTC, cheaper than converting time
  zones

* Fix typo

Fix typo
2021-02-09 11:17:01 -03:00
Gerardo Salazar
17dbadea5b Remove cross-platform incompatible Thread.Abort() + ThreadAbortException (#5274)
* Remove cross-platform incompatible Thread.Abort() + ThreadAbortException

* Retrigger build

* Refactor thread abort logic into call to StopSafely()
2021-02-08 20:41:05 -03:00
Martin-Molinero
d077651f32 Package updates (#5273)
- Update `System.Collections.Immutable`
2021-02-08 15:49:15 -03:00
Adalyat Nazirov
c02ad0a89f Brokerage models improvements (#5267)
* fix Atreyu brokerage type full name

* improve brokerage models

-AtreyuBrokerageModel
-TradingTechnologiesBrokerageModel

* remove Limit price checks
2021-02-05 20:23:54 -03:00
Gerardo Salazar
aef2a47892 Updates CPU performance metrics gathering approach (#5261)
* Updates CPU performance metrics gathering for project modernization

  * PerformanceCounters are not supported cross-platform in
    .NET Core/5.0, which requires the use of an alternative method
    in the gathering of performance metrics. Since no exposed .NET API
    exists to gather these metrics without blocking, a new thread is
    created to block the time necessary for the CPU performance to be
    calculated.

* Address review: remove ResetEvent and make CpuPercent atomic

* Dispose of CpuPerformance instance before exiting Lean

* Minor tweak for Task and comment

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-02-05 20:23:30 -03:00
Gerardo Salazar
bc4dbf5707 Removes extra day added to CBOE Time causing data to shift one day forward (#5266)
* Added test
2021-02-05 19:42:01 -03:00
Gerardo Salazar
fe1948d0ae Removes/updates System.ComponentModel.Composition package (#5257) 2021-02-05 12:03:49 -03:00
Gerardo Salazar
254d0896f1 Replaces Microsoft.Extensions.CommandLineUtils with McMaster CLI utils (#5255)
* Replaces Microsoft.Extensions.CommandLineUtils with McMaster CLI utils

  * Updates ValueTuple to 5.0.0 for compatibility with package.

* Retrigger build

* Retrigger build
2021-02-03 19:56:14 -03:00
Gerardo Salazar
115dcab789 Removes app.config and sets automatic binding redirects (#5248)
* Some app.config files were kept to either enable features
    that are only enable-able via the config files, or binding redirects
    for DLLs that are not packaged with NuGet (i.e. VisualStudio
    package, required to run tests successfully @ 15.0.0.0)
2021-02-03 11:45:29 -03:00
Gerardo Salazar
5117609ea5 Fixes CBOE custom data consolidation (#5252)
* Adds regression algorithm testing consolidation of data.
2021-02-03 10:56:58 -03:00
Stefano Raggi
6040cc8e90 Add TradingTechnologies brokerage model + configuration (#5250)
* Add TradingTechnologies brokerage model + config

* Address review
2021-02-03 10:45:16 -03:00
Martin-Molinero
eb25dce462 Remove Alpaca brokerage implementation (#5249)
- Removing Alpaca brokerage implementation. See https://www.quantconnect.com/forum/discussion/10079/alpaca-paper-disabled
2021-02-02 20:16:34 -03:00
IlshatGaripov
0d0389ef6a BrokerageSetupHandler min resolution variable default value bug fix (#5243)
* fix

* Minor tweaks adding unit tests

* Address reviews

- BrokerageSetupHandler will use UniverseSettings.Resolution as default
  resolution

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-02-02 12:10:18 -03:00
IlshatGaripov
3e962b2e76 Fixes Bitfinex Brokerage history call bug (#5242)
* Fixes a bug #5173

* This is not timestamp but total ms.

* BitfinexBrokerageHistoryProviderTests fix
2021-02-01 21:58:57 -03:00
Adalyat Nazirov
f263fd49a7 Atreyu Brokerage initial setup (#5247)
* Atreyu Brokerage initial setup, and changes required for integration with main Atreyu project

* Address reviews

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-02-01 21:57:25 -03:00
IlshatGaripov
9b38bf3d91 More details: (#5244)
Bitfinex exchange may return us an empty result - if we request data for a small time interval during which no trades occurred - for example 1 minute interval - can happen even with most liquid pairs, like "ETHUSD" - would be good to have some time margin  for such scenario. and pump more data to warm up conversion rates
2021-02-01 21:57:10 -03:00
Aaron Janeiro Stone
7d70698c9a Feature #5098 - Time Series Indicators (#5099)
* Cleans history for ArimaIndicator/TimeSeriesIndicator.

-- removes commits from a tracked, already merged branch
-- removes artifacts from debugging sessions

* Removes AR/MA method as a user-specifiable method.
-- Prevents need to reference dll for MathNet in Tests (and potentially elsewhere).
-- Wrapper can be implemented around this functionality.

* Removes AR/MA method as a user-specifiable method.
-- Prevents need to reference dll for MathNet in Tests (and potentially elsewhere).
-- Wrapper can be implemented around this functionality.

* Better adherence to established code style

* Makes _intercept = true by default in constructor where it is not parameter

* WIP -- addressing reviews

* Passing tests following prior refactor

* Rearranged code, access modifiers adjusted

* Fixed indexing of _mafits, adds example algorithm

* Adds regression algo in python + addresses some refactors

* Addresses review

* Adds regression stats

* Fixes missing value signs

* Removes redundant code

* style changes

* style changes

* style: "err" -> "error"

* Minor tweaks

* Fixes python arima regression test

* Refactors AutoregressiveIntegratedMovingAverageTests.cs

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-02-01 20:17:49 -03:00
Martin-Molinero
1606b12475 Fix IB future chain being started at reset hours (#5246)
* Fix IB future chain being started at reset hours

- Fix IB future chain being started at reset hours. Adding unit test

* Refactor CanAdvanceTime into CanPerformSelection
2021-02-01 18:53:33 -03:00
Juan José D'Ambrosio
3a483fc4ec Migrate TradeConditionFlags and QuoteConditionFlags to Lean (#5227)
* Migrate TradeConditionFlags and QuoteConditionFlags to Lean

* Address revirew

Implement flag systems using long, this allows us to declare up to 64 flags
2021-02-01 13:11:30 -03:00
Gerardo Salazar
fe74d037c6 Updates NodaTime to latest version (3.0.5) (#5237)
* Updates NodaTime to version 3.0.5

  * Updates code to ensure compatibility with new NodaTime version
  * Updates System.Runtime.CompilerServices.Unsafe to 5.0.0
    - Required by NodaTime

* Adds comments explaining changes in NodaTime
2021-02-01 13:06:56 -03:00
Martin-Molinero
43e9cad2d6 Remove deprecated Http package (#5235) 2021-01-29 18:26:38 -03:00
Balamurali Pandranki
403ea22606 Setup GitHub Actions CI (#5192)
* Create gh-actions.yml

* Run github actions on all branches

* Setup Python and Deps

* Escape brackets

* Move to mono runtime instead of dotnet core

* lock mono version

* pin mono dep version

* Update gh-actions.yml

* Update gh-actions.yml

* Use Ubuntu 16.04

Use Ubuntu 16.04

* Update gh-actions.yml

* Try on container

* Fix indentation

* Try Self Hosted runner

* switch back to ubuntu runner

* Update gh-actions.yml
2021-01-29 12:38:05 -03:00
Gerardo Salazar
6cb103b17a DockerfileLeanFoundation package updates and new additions (#5072)
* Updates and adds new Python packages to DockerfileLeanFoundation

* Remove torch-geometric packages due to import issues

Torch geometric packages installed from pip as they are here result in an error saying to install the CUDA version of the packages. When the CUDA version is installed, we get a symbol error when attempting to link the `_version.so` shared object.
2021-01-29 10:25:14 -03:00
Martin-Molinero
8cbdfcaf28 Fix hour resolution mapping data handling (#5233)
- In some cases hour resolution data subscription would end early
  because of remapping not being correctly handled. Adding regression
  test
2021-01-28 20:41:04 -03:00
Juan José D'Ambrosio
1778462505 Fix broken regression tests (#5234) 2021-01-28 20:14:03 -03:00
Colton Sellers
472896c2d0 Update JSON Library (#5218)
* Update NewtonSoft.Json from 10.0.3 to 12.0.3

* Remove JsonSerializer.Populate(), values are already populated
2021-01-28 19:24:49 -03:00
Stefano Raggi
15cb846570 Add missing connection check in IB brokerage GetHistory (#5230) 2021-01-28 15:43:04 -03:00
Stefano Raggi
553b50a92e Ignore IB error 506 when disconnected (#5229) 2021-01-28 15:42:53 -03:00
Gerardo Salazar
5f73a05e04 Set default market hours for futures exchanges to 16:00 Central Time (#5226) 2021-01-27 20:00:19 -03:00
Colton Sellers
a5eaa43e35 Remove F# and VB Projects (#5223)
* Remove F# and VB projects

* Remove FSharp.Core package

* Readd FSharp to engine

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-01-27 11:31:49 -03:00
Martin-Molinero
e91af0814f Add notification targets and events to live packet (#5210)
* Add notification targets and events to live packet

- Add notification targets and events to live packet. Adding unit tests

* Add project name to job packet

* Add ShortToString and WebNotification Header

- Adding ShortToString implemnetation of OrderEvent and Insight
- Add Web notification headers

* Add more unit tests

* Revert json lower case fields
2021-01-27 10:26:35 -03:00
Colton Sellers
a2850fb20c Address Non-Compiled Files (#5225)
* Include MortgageRateVolatilityAlpha and fixes

* Include PlaceHolder PythonAlgorithm.cs

* Delete BinanceUtil

* Remove unused Regression Algorithms

* Minor tweaks

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-01-27 09:56:03 -03:00
Colton Sellers
c86fceac97 Fix regression typo (#5224) 2021-01-26 15:31:57 -03:00
Stefano Raggi
9997df45af IB Brokerage updates (#5222)
* Upgrade IBAutomater to v1.0.40

* Fix FinancialAdvisor account id check

- The Ixxxxxx account code is the Master Account for Fully Disclosed Brokers and this account is not tradable. Proprietary accounts for Brokers/Dealers used for proprietary trading have the Uxxxxxx account code.

* Update IBAutomater to v1.0.42

* Update IBAutomater to v1.0.43

* Log server version in ConnectAck handler
2021-01-26 09:52:05 -08:00
Jared
1ef92b3eca Update Crisis.cs 2021-01-25 10:47:15 -08:00
Adalyat Nazirov
c6d29c8be5 add FIX Protocol UTC timestamp format (#5212) 2021-01-25 11:24:54 -03:00
Derek Melchin
97deb4bbc6 Fix typo (#5216) 2021-01-25 10:24:15 -03:00
Gerardo Salazar
6ab40c102b Only report daily point-in-time portfolios instead of every trade (#5214)
* Only report daily point-in-time portfolios instead of every trade

* Allow for cash holdings to be visible in point-in-time portfolio output
2021-01-22 17:00:09 -08:00
Gerardo Salazar
41417593aa Writes point-in-time portfolios to disk (#5213)
* Writes point-in-time portfolios to disk

* Adds optional argument to Report constructor in ReportGenerator
2021-01-22 15:17:19 -08:00
Martin-Molinero
3ccf428498 Adjust delisting liquidation time (#5203)
* Adjust delisting liquidation time

- Adjust delisting liquidation time to 15 min before market closes.
  Adding unit tests. Updating existing.
- Handle `Statistics.CompoundingAnnualPerformance` invalid calculation
  to avoid exception.
- AlgorithmManager will not handle delisting events in live trading
- Fix bug where due to a split driven liquidation matching delisting
  date a position in the option would remain open. Reproduced by
  `BasicTemplateOptionsFrameworkAlgorithm`

* Address review

- Address review add documentation on delisting offset span
2021-01-22 14:41:29 -03:00
Colton Sellers
5d8a62c2e1 Symbol Alias Fix (#5205)
* Fix Symbol Alias

- Fix Symbol Alias being wrong in some cases for futures and options

* Add test cases

* Address review

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-01-22 13:00:14 -03:00
Martin-Molinero
5df29f16dd Fix thread safety of Mapfile exchange provider (#5208) 2021-01-21 19:02:50 -08:00
Martin-Molinero
56a0d52212 Allow limiting streaming security Types per job packet (#5206) 2021-01-21 21:23:32 -03:00
Juan José D'Ambrosio
765f2cab3b Add primary exchage to map files (#5194)
* Add main exchange to map file

minimum minimorum test

* Add MainExchange to MapFilRow IEquatable implementation
Also write CSV line correctly

* Normalize exchanges

Also add small test form MapFileRow

* Exchange name normalization

- Exchange name normalization.
- Tick will protobuf `ExchangeCode` which will set existing `Exchange`

* Include single character exchange code

* Encode exchange as byte, Include exchange name as Enum

* Update MapFileRow.cs to accept a byte instead a string for primary exchange

* Fix issues in encoding exchanges map

* Fix broken MapFile tests

* Rename Main Exchange property in MapFileRow

* Use BATS instead of BATSZ

* Add primary exchange from map file

* Move MapFilePrimaryExchangeProvider to its own file

* Implement Char for primary exchange in map files

* Fix broken tests after implementing char exchange into map file

* Add a new constructor for MapFileRow

it  accepts a PrimaryExxchange object as parameter

* Fix broken test 

WIP

* Address review 

WIP

* Handles unexpected encoded exchanges

* Keep addressing review

* Address review

* Fix broken tests

Make PrimaryExchange as default even if the IPrimaryExchangeProvider is not instantiated

* Revert breaking change.

* Add a check that resolved map file actually have content

The issue that leads to this change was caused by a map file resolved to APC in the CoarseFundamentalTop3Algorithm. 
The resolver returns a not-null MapFile, but it is empty.
To my best understand, the MapFile Resolver should return only existing map files in the map_files folder. But the LocalMapFileProvider returned a map file with a permtick that doesn't exist in the file system as CSV.

* Set PrimaryExchange.UNKNOWN as default

* Address review couple minor bugs

- Use SID market instead of USA
- Default ticke exchange is UNKNOWN

* Update map files with latest format and latest info

This include:
 - VXX, it was delisted, then VXXB appears and later it chnages from VXXB -> VXX
 - AAA delisting and a new listing with ticker AAA
 - FOXA ticker changue to TFCFA and later it was delisted

* Update test after updating latest map files

* Fix bug with factor files after updating map files

* Fix bug with factor files after updating map files

and revert statistics in regression tests

* Update OrderHash in regression test

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-01-21 18:46:12 -03:00
Martin-Molinero
f175ac6c6b Fix universe selection symbol cache removal (#5193)
- Only remove symbol from cache during universe selection if there is no
  other universe using it. Adding regression test reproducing issue
2021-01-21 15:48:33 -03:00
Gerardo Salazar
79c544d3a2 Reduces output log size and warnings emitted when building with mono's msbuild (#5200) 2021-01-21 11:09:16 -03:00
Aaron Janeiro Stone
5dcbed535d 5052 - Adds missing constructor routing (#5201)
* Adds missing constructor routing

* Minor tweak remove unrequired lines and format

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-01-21 10:49:27 -03:00
Gerardo Salazar
35393b66a3 Updates report generator template.crisis.html (#5202) 2021-01-20 18:01:44 -08:00
Karthik Kailash
ce42c888ce Add 2001-12-24 to US equities early closes in market-hours-database.json (#5184) 2021-01-19 13:21:00 -08:00
Colton Sellers
f2fd10d9d2 Build Configuration Hotfix (#5186)
* Reflect properties prior to migration onto projects

* Do not prefer 32bit

* Reinstate SelectedOptimization var
2021-01-19 09:38:16 -03:00
Colton Sellers
94d766ff89 Refactor Default Benchmark (#5158)
* Have BrokerageModel determine default benchmark

* Add DefaultBenchmark to Python wrapper

* Handle Null benchmark case

* Add NullBenchmarkRegressionAlgorithm

* Refactor solution to have BrokerageModel return IBenchmark; also refactor QCAlgorithm benchmark handling

* Always create a new security for benchmark

* Drop security overload, Always create a new security for benchmark

* Check our securities for a symbol matching the ticker before creating a new one

* No Python version of this regression

* Address review

* Create shared SecurityBenchmark creator function

* Add Python regression and needed FuncBenchmark constructor
2021-01-19 08:40:41 -03:00
Martin-Molinero
592d037085 Fix delisted liquidation orders being cancelled (#5169)
* Fix delisted liquidation orders being cancelled

- Place delisted liquidation orders 10 min before market closes of 10
  min before the end of the delisting warning date. Adding regression
  test and unit tests. Updating existing tests.

* Fix failing python option unit tests

* Fix bug where positions would be open delisting liquidation

* Fix universe selection and delisting

- Delisting will happen ASAP for all types. Giving priority to close
  positions on derivates first
- Fix bug in universe selection where OptionChain would remove
  underlying even if holding a position in derivate.
- Updating regression tests statistics

* Add unit test, fix unit test expected stats
2021-01-18 22:02:40 -03:00
Gerardo Salazar
17ab10531a Fixes ETB/shortable regression algorithms that were previously failing (#5174)
* Fixes ETB/shortable regression algorithms that were previously failing

* Addresses review and fixes bug

  * Fixes bug where orders would be denied regardless of direction
    whenever they exceeded the absolute value of the shortable quantity

  * Updates regression algorithm + statistics + simplifies test

  * Fixes python regression algorithm

* Addresses review: removes comments and unneeded imports
2021-01-18 21:19:42 -03:00
Juan José D'Ambrosio
9d576a4121 Update regression tests statistics (#5187)
Those statistic were affected for the new early market close entries in MHBD.
2021-01-18 21:06:26 -03:00
Aaron Janeiro Stone
7aefe07274 4553 - Refactor RenkoConsolidator (#5052)
* Separated Update calls and other non-common RenkoConsolidator.cs artifacts.

* Added type safe init for wicked

* Refactor; moved wicked-specific fields to WickedRenkoConsolidator.cs

* Addresses requested changes (and compacts constructors)

* Separated Update calls and other non-common RenkoConsolidator.cs artifacts.

* Added type safe init for wicked

* Refactor; moved wicked-specific fields to WickedRenkoConsolidator.cs

* Addresses requested changes (and compacts constructors)

* Removes base class for brevity

* Delete BaseRenkoConsolidator.cs

* Fixes naming for classic Renko consolidator

* Addresses review concerns

* Fixes missing null checks and missing typesafe constructor

* Adds warning

* WickedRenkoConsolidator -> RenkoConsolidator calls

* Separated Update calls and other non-common RenkoConsolidator.cs artifacts.

* Added type safe init for wicked

* Refactor; moved wicked-specific fields to WickedRenkoConsolidator.cs

* Addresses requested changes (and compacts constructors)

* Removes base class for brevity

* Fixes naming for classic Renko consolidator

* Separated Update calls and other non-common RenkoConsolidator.cs artifacts.

* Added type safe init for wicked

* Refactor; moved wicked-specific fields to WickedRenkoConsolidator.cs

* Addresses requested changes (and compacts constructors)

* Delete BaseRenkoConsolidator.cs

* Addresses review concerns

* Fixes missing null checks and missing typesafe constructor

* Adds warning

* WickedRenkoConsolidator -> RenkoConsolidator calls

* Addresses review

* unneeded tag removed

* Minor tweaks address reviews

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-01-18 15:54:15 -03:00
Karthik Kailash
6de9a146a9 Issue 5149: Added missing early closes for 1999-2008 (#5163)
* Added missing early closes for 1999-2008

See GitHub issue for details

* Fix expected Treynor ratio for backtest in test suite

This backtest runs from 2008-10-10 to 2010-10-10 so it is affected by the early close date now recorded on 2008-12-24.
2021-01-15 11:22:44 -03:00
Gerardo Salazar
4d4ad92fa7 Easy To Borrow Hotfix (#5167) 2021-01-14 15:07:54 -08:00
Jared
345fe7357e Update readme.md 2021-01-14 13:58:26 -08:00
Gerardo Salazar
3e7af17e02 Implements Easy To Borrow Reality Modeling (WIP) (#5159)
* Creates IShortableProvider interface + interface impls

  * This is the foundational work for the addition of the shortable stocks
    feature for backtesting and live trading. Note that the QCAlgorithm
    API and the backend transaction handling will be implemented
    separately.

* temp; work on preorder checks

* improve checks

* tmep

* Enforces ETB checks at BrokerageTransactionHandler

  * Adds ETB Shortable Provider to QCAlgorithm and IAlgorithm
  * Removes ETB check from PreOrderChecksImpl
  * Removes outdated test, new test to come soon for relevant class

* Work in progress commit, pushing for review.

  * Adds new regression algorithm (WIP)
  * Enhances ShortableProviderOrdersRejectedRegressionAlgorithm
  * Adds new methods to QCAlgorithm
  * Move IShortableProvider to have BrokerageModel own it
  * Comments updates
  * Adds new properties to Equity Security for shortable

  * Fixes bug where retrieving open order quantities would aggregate the
    submitted order quantity rather than the remaining order quantity for
    open orders.

  * Fixes bug where quantity of zero would result in a
    false positive in QCAlgorithm.Shortable(...)

  * Code refactoring and comments updates

Co-authored-by: Jared <jaredbroad@gmail.com>
2021-01-14 13:33:44 -08:00
Colton Sellers
a2a874e333 CSProj Update (#5145)
* Migrate to newer CSProj format; build succesful

Rebase onto master

* Maintain binaries directory

* Reinstate FSharp default condition

* Remove reference to packages.config

* Test project fixes

* Remove nuget.config and "Solution Items"

* Remove repetitive assembly info

* Reinstate default compiles and cleanup redundant settings

* Reinstate any specific settings that defaults are unclear for

* Reinstate Framework.nuspec

* Make test internal classes public for composer use; undo assembly change

Rebase onto master part 2

* Address review; restore some settings

* Restore RootNamespace and AssemblyName attributes

* Use NugetPackageRoot instead of NugetPackageFolders

* Reinstate "RestorePackages" setting

* Transfer compilied Python files to launcher and tests bin

* Remove conflicting settings

* Fix WebSocketSharpFork references

* Fix FSharp Core reference

* Upgrade TestPlatform.ObjectModel to 16.8.3, and redirect V11 binding

* Add Mono.Cecil package

* Address review
2021-01-14 12:55:09 -08:00
Juan José D'Ambrosio
96592b3387 Update RTY price multiplier (#5166) 2021-01-14 16:45:24 -03:00
Colton Sellers
7e3741d983 Allow Custom Security Properties and MarketHours (#5100)
* Add interface to allow custom security entries for MHDB and SPD

* Simplify adding custom Properties and MarketHours via AddData overload

* Refactor

* Remove AddData and GetDatabaseSymbolKey overloads

* Add unit tests

* Remove AddData overload, for real.

* Nit changes

* Set CustomDataBitcoinAlgorithm back to original

* Add Python and C# Regression

* nit typo

* nit typo actual

* Reset symbol property to default

* Reflect last change to py regression

* Revert "Remove AddData overload, for real."

This reverts commit dc877495c0.

* Implement AddData solution fully

* Function nit fix

* Address review

* nit - remove param comment

* Address review
2021-01-14 11:34:02 -03:00
Martin-Molinero
e6d16882f7 Remove raw Sleeps for Sleeps+Event (#5153)
- Remove raw Thread.Sleep for Event driven wait/sleeps. Improves startup
  performance significantly
2021-01-12 19:12:07 -03:00
Gerardo Salazar
d5aa9e65f3 Adds FuturesOptionsUnderlyingMapper and FuturesListing (#5142)
* Adds FuturesOptionsUnderlyingMapper

  This adds a mapper for Futures options that have a different
  contract month between the FOP and the underlying future, as is
  observed in the contracts ZB, ZC, ZS, ZT, ZW, HG, SI, GC.
  An example of this is GC (e.g. OGH21 -> GCJ21). Other contracts follow
  different rules, which have been included as part of this commit.

  * Adds unit tests for FuturesOptionsUnderlyingMapper

  * Adds unit and regresssion tests for underlying Futures mapping for FOPs

* Addresses review and adds FuturesListings

  * Removes dependency on IFuturesChainProvider in
    FuturesOptionsUnderlyingMapper

  * Fixes bugs related to FuturesOptionsUnderlyingMapper and incorrect
    results

  * Modifies misc. code to handle new results correctly from FOPs
    underlying mapper

  * Makes FOPs underlying mapper static, and makes other methods private

  * Adds new tests for FuturesListings

* Addresses review: code cleanup

* Address review: Makes arrays to List in FuturesListing private methods
2021-01-12 06:12:00 -08:00
Mathieu Paquette
ec1c4b7142 update IQFeed.CSharpApiClient (#5148)
* update IQFeed.CSharpApiClient

fixes #5147

* Update IQFeed client csproj referece

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-01-11 18:11:16 -03:00
Adalyat Nazirov
9a0d943f1d Fill forward data points until delisted date (#4973)
* fill forward data points until expiry date

* wip: test non Delisting

* handle Aux not-Delisting dp; keep order while ff'ing

* simplify test checks

* wip

* fix liquidation expected date

* change statistics

* check EndTime, because it's used for time synchronization

* clean up code; remove duplicated test
2021-01-11 16:45:09 -03:00
Ari Cooperman
771244aaa0 Add order related mappings to resolve type & status IDs in pure python (#5075)
* Add order related mappings to resolve tye & status IDs in pure python

* Update order.py

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-01-11 15:45:51 -03:00
Alexandre Catarino
659a57884c Improves Error Message for Api.Download (#5038)
* Improves Error Message for Api.Download

Catches the exceptios, logs it and returns null.

* Replace Logging for Re-Throwing the Exception
2021-01-11 15:40:46 -03:00
Martin-Molinero
3f2a558f91 Remove pythonNet from stacktrace (#5146)
* Avoid pythonNet  stackTrace in algorithm status

* Handle algorithm initialization exception
2021-01-11 10:28:32 -03:00
Martin-Molinero
9bb7c77fb7 Fix UniverseSelectionAddAndRemove race condition (#5144)
* Fix UniverseSelectionAddAndRemove race condition

- Fix unit test UniverseSelectionAddAndRemove thread race condition

* Avoid boolean flag thread race condition

* Exclude test from travis build
2021-01-08 19:18:58 -03:00
Derek Melchin
c8eb9e0099 Fix MACD WarmUpPeriod and Updating (#5110)
* Fix MACD WarmUpPeriod and Updating

* Add System to use Math library

* Fix WarmUpPeriod math and add tests

* Fix SchaffTrendCycle Indicator WarmUpPeriod

* Ensure fastPeriod < slowPeriod

* Minor tweaks

- Remove unrequired Math.Max operation
- Remove unrequired changes in solution file

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-01-08 16:58:53 -03:00
Jovad Uribe
b85a32a391 Bug #5030 Generation of CFD data not working (#5112)
* Update RandomDataGeneratorProgram.cs

Replaced AddMonths(6) with a Datetime value half way between settings.Start and settings.End.

* Update RandomDataGeneratorProgram.cs

* Update to bug-5030-CFDdatanotoworking

* Added midpoint unit test

* Minor test assert improvement

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-01-08 11:38:36 -03:00
Martin-Molinero
31d101253c LeanDataReader future/option data (#5117)
* LeanDataReader future option data

- The LeanDataReader will be able to read an entire zip of future and
  option data, currently it's just returning the first entry in the zip
  file. Adding unit tests

* Fix added unit test data path
2021-01-08 11:13:05 -03:00
Aaron Janeiro Stone
7531046f14 Feature 4999 -- Adds RVI (#5041)
* adds RVI

* RVI refactor and tests
TODO: fix ComparesWithExternalDataRviSignal

* Fixed to allow all tests to pass.

* Addresses requested changes

* Addresses requested changes

* Addresses reviewer recommendations
2021-01-08 11:11:00 -03:00
Martin-Molinero
6b99266669 Update IBAutomator increased init timeout (#5139)
- Updating IBAutomator to 1.0.40 which has an increased initialization
  timeout
2021-01-07 19:13:07 -03:00
Adalyat Nazirov
8d48996948 fix covesion to string: decimal are represented using comma decimal separator for non-US English cultures, but expected dot (#5138) 2021-01-07 17:35:51 -03:00
Martin-Molinero
7f381cb135 Universe dispose and removal (#5134)
* Universe dispose and removal

- Fix bug where in some cases the disposed universe would not get removed
from UniverseManager not allowing new universes to get added correctly,
using the same symbol. Adding regression test
- Fix bug where in some cases selected symbols would not get removed
  when the parent universe would get disposed of.
- Minor normalization on UniverseSelection call

* Address review

- Add status plots for the added regression test

* Adding regression algorithm reproducing issue 3914
2021-01-07 12:03:17 -03:00
Riley Shea
2b7372783a Fix column headings in Data/equity/readme.md (#5125)
* Swapped incorrect column heading postions
2021-01-07 11:01:51 -03:00
Adalyat Nazirov
54fce3f666 FillForward enumerator does not loop infinitely if fillforward resolution is different from data resolution (#5118)
* change filename template. add fillforward resolution suffix

* replicate GH issue 5116 on master

it's easy to reproduce on FXCM market by using data resolution different from fillforward resolution.
in this cases daily vs hour/minute were added

* change priorities of Time & EndTime values.

it's necessary to calculate EndTime  properly, and then we can align Time to it.
potential end time should be also calculated using ptoper TZ. Because of we store open hours without TZ movement TZ in market-hours it's necessary to reapply TZ

fix tests

* Miss 2AM bar on Sunday of DST; FF 2AM bar on Sunday ST

* use UTC TimeZone as baseline during comparison
2021-01-06 20:18:08 -03:00
Colton Sellers
12db2261dc Allow Saving of Octet Stream in API (#5130)
* Allow downloading of octet stream

* Refactor solution

* Match lowercase ContentType
2021-01-06 19:46:09 -03:00
Alexandre Catarino
c6d4888e70 Refactors Market Fill of Equity Fill Model (#5114)
* Refactors Market Fill Model

Create `GetBidPrice` and `GetAskPrice` methods to request the most suitable price to fill market orders.

Fix unit tests to show that new implementation prevents using non-market data to fill the order.

* Addresses Peer Review …

Modifies EquityTickQuoteAdjustedModeRegressionAlgorithm to reflect changes in the market fill method. The previous implementation only looks for the last tick when it should look for the last tick of quote type, so current implementation is an improvement.
2021-01-06 12:35:33 -03:00
Martin-Molinero
33b58b0dbc Fixes for IB malformed symbols (#5127)
* Fixes for IB malformed symbols

- Add handling for IB future malformed symbols. Adding unit test
- Fix IB option malformed symbols which had more whitespaces than
  expected. Adding unit test

* Address review
2021-01-06 11:59:22 -03:00
Martin-Molinero
56cb9fbec5 IB will wait for connection response (#5124)
- IB.Connect() will wait for connection response before starting reader
2021-01-05 19:44:04 -03:00
Jared
194e6f6b58 Update benchmark algorithm to include disabling (#5115)
* Update benchmark algorithm to include disabling

* Update C# benchmark example algo

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2021-01-04 18:11:18 -03:00
Martin-Molinero
612c4f8b66 Fix BTC future price multiplier (#5113) 2021-01-04 15:44:38 -03:00
Martin-Molinero
d3b9f8bc7a Protobuf OpenInterest (#5107)
- Add OpenInterest protobuf support. Adding unit test
- Use composer for future and option chain provider
2021-01-04 10:40:35 -03:00
Gerardo Salazar
c4a1c245a7 Adds data parsing for malformed option contracts for InteractiveBrokers (#5101)
* Adds data parsing for malformed option contracts in IBBrokerage

  * Some contracts come in malformed from IB when downloading our
    account holdings. We attempt to detect whenever this happens with
    our options Symbols and try to recover the contract.

* Addresses review and fixes bug

  * Uses contract currency for the new contract created from the
    malformed contract.

  * Bug fix: Sets ibSymbol to new Symbol of the contract once the
    malformed contract has been parsed.

  * Adds support for Futures and FOPs

  * Refactoring code and cleanup

* Addresses review: code cleanup and refactoring

* Addresses review: remove redundant logging of contract in log statement
2020-12-30 16:28:33 -08:00
Martin-Molinero
050dadc21f Increase low resolution cache size (#5105)
- Increasing low resolution cache size so it can hold QC500
2020-12-30 20:59:36 -03:00
Colton Sellers
7b0ea0982e Update ExpectedStatistics (#5094) 2020-12-29 12:04:36 -03:00
Adalyat Nazirov
f8cf923d7b upload SHY quote bars (#5097) 2020-12-29 11:58:13 -03:00
Colton Sellers
14b44bbe17 Reduce Travis Logs v2 (#5049)
* Silence DotNet in building stubs

* Reapply silence to stub publishing

* Have QuantBook store and restore initial LogHandler

* Add assembly action to maintain LogHandler

* Allow AlgorithmRunner to use ConsoleLogHandler

* Use MaintainLogHandlerAttribute to provide current test logger

* Refactor LogHandler creation
2020-12-28 21:10:21 -03:00
Colton Sellers
2ed221b623 Linux PyCharm Docker Debugger Fix (#5092)
* Map host.docker.internal to host ip

* Typo fix

* Only add host in Linux environment
2020-12-28 21:08:34 -03:00
Gerardo Salazar
3f1c33e1c5 Fixes DockerfileLeanFoundation build and adds/updates new packages (#5036)
* Fixes DockerfileLeanFoundation build

  * Updates DockerfileLeanFoundation packages and adds new packages
  * apt-get performance improvements

* Moves packages to CDN and install packages from CDN

  * Updates all CDN downloads to HTTPS

* Removes interactive `rm` command arg in DockerfileLeanFoundation cleanup
2020-12-28 18:22:15 -03:00
Adalyat Nazirov
017b464e21 Map legacy symbols using map file (#5017)
* map IB brokerage symbol

* map Alpaca symbols

* improve empty symbol checking
2020-12-28 17:54:00 -03:00
Gerardo Salazar
4dec21ccc0 Fixes failing option chain provider test for futures options (#5088)
* The test didn't take into account that the contract expiring on
    December would mean that there would temporarily be no Dec. FOP
    contract. We fix this by looking for the Mar. contract instead
    if the december contract has expired.
2020-12-28 16:28:41 -03:00
Martin-Molinero
529d0a3634 Fix low resolution cache (#5080)
* Replace cache size for MB

* Remove setting capacity

* Custom cache implementation

* Reduce locks in custom cache

* Add cache performance unit test
2020-12-28 16:27:11 -03:00
Martin-Molinero
9c89e8d403 Fix backtest result packet deserializing (#5084)
* added test covering minValue / maxValue issue with JsonRoundingConverter

* change namespaces

* JsonRoundingConverter fix decimal.Min and MaxValues (cannot deserialize)

* remove dependency on 3rd party library

* c# 6 compatible code (remove pattern matching)

* Fixes BacktestResultPacket deserializing

- Serializing decimals as strings to avoid precision loss, since json
  convert will use floating point precision. Updating unit tests.
- Fix logging unit test failing to delete file being used.

Co-authored-by: Mark Virchenko <mark.virchenko@calienteam.com>
2020-12-28 16:26:40 -03:00
Adalyat Nazirov
1988ad1ae5 Bug 4925 daylight out of order bar (#4941)
* test

* wip

* Revert "Fix duplicated history entries when contains daylight saving time change (#4700)"

Use proper rounding down

* regression test

* remove unused parameters

* more tests

* fix name and comment

* improve regression test

* more tests: oanda market hours

* re-apply Exchange TZ to bar EndTime

* fix expected results

* we can't substract minute because it can harm algorithm on minute resolution; so we could use tick?

* rename prop: conflict with QCAlgorithm.StartDate

* do not log messages to pass travis ci log limit

* assign loghandler in AlgorithmSetupHandler

* reference to PR for more description

* due to https://github.com/QuantConnect/Lean/pull/5039 we don't need to override it manually
2020-12-28 16:24:33 -03:00
Martin-Molinero
3658fb1405 Update config.json (#5086) 2020-12-28 13:06:07 -03:00
Colton Sellers
0ac79487d7 IB Brokerage Restore Subscriptions Fix (#5078)
* Return true after all symbols have been processed

* Continue on Canonical Future Symbols
2020-12-23 20:56:07 -03:00
Gerardo Salazar
38120a3217 Converts QuantConnect.Common.csproj file to .NET Sdk format (#5071) 2020-12-23 13:15:29 -03:00
Martin-Molinero
01a13a095a Remove cloud-api-url config setting (#5073) 2020-12-22 22:51:00 -03:00
Colton Sellers
704a5cb00e Pycharm Docker Debugging Fix (#5069)
* Move PyCharm Debugger to port 6000 and expose it

* Change PyCharm default configurations to port 6000
2020-12-22 15:22:46 -03:00
Martin-Molinero
490ad08c89 Optimization handling of failed backtest init (#5068)
- Optimizer will increment failed count and notify the strategy of
  failed backtest initialization
2020-12-21 19:27:27 -03:00
Martin-Molinero
a60cd95611 Optimizer will clean lean before last update (#5063)
- LeanOptimizer will clean up any lean instance before calling the last
  udpate, so that runtime stats are correct.
2020-12-21 15:17:44 -03:00
Colton Sellers
eed8e9c763 Improve IBBrokerage Symbol Mapping Error Message (#5051)
* Improve IBBrokerage Error Message

* Add exception message to catch statement

* Address review

* Address review edits
2020-12-21 13:04:05 -03:00
Marco Grassi
365f53dfc7 Fix the missed rename of OptimizationStatus.Ended to Completed (#5060) 2020-12-19 19:06:09 -03:00
Martin-Molinero
48a86c2626 Rename OptimizationStatus from Ended to Completed (#5059) 2020-12-18 16:53:29 -08:00
Martin-Molinero
2de9c21b6d Optimization tweaks (#5056)
* Add progress for runtimeStats

- Add optimization progress runtimestats
- Add ServerStatistics for the last backtesting package

* Add StaticOptimizationParameter

- Add StaticOptimizationParameter. Updating unit tests
2020-12-18 16:01:44 -08:00
Martin-Molinero
649aafc952 Adding Api.ReadBacktest optional getCharts (#5054)
* Adding Api.ReadBacktest optional getCharts

- Optionally allow users not to fetch backtest charts when reading a
  backtest, it can be slow

* Fix null reference for deleted/cancelled backtests

* Get Leaky bucket config settings once
2020-12-18 14:17:40 -03:00
Gerardo Salazar
25fa4c6fb6 Adds holidays to ES futures (#5045)
* Adds holidays to ES futures

* Adds CME equity product market hours and holidays (ES, NQ, YM)
2020-12-17 21:12:20 -03:00
Martin-Molinero
d1b35f7974 Optimization status update (#5050) 2020-12-17 17:09:01 -03:00
Colton Sellers
4006ba01e4 Reduce Travis Log (#5039)
* Reduce Travis setup verbosity

* Introduce ConsoleErrorLogHandler

* Change Console.WriteLine to Log statements

* Quiet wget

* Route build stubs stdout to null

* Fix Quantbook history test

* Silence stub packages directly

* Use parameterized log-handler for testing

* Rename AssemblyInitialize Setup

* Fix AlgorithmRunner file logging

* Drop all overriden LogHandlers in tests

* Change to OneTimeSetup to maintain LogHandlers

* Permit any ILogHandler to be defined in params

* Fix for AlgorithmRunner Handlers V2
2020-12-17 12:59:13 -03:00
Martin-Molinero
6d824b40a6 Add handling for custom host name (#5043)
* Add handling for custom host name

* Credit cost as decimal
2020-12-16 21:54:00 -03:00
Colton Sellers
8e410fcaf1 Update old Hourly/Daily data for ApiDataProvider (#5034)
* Update old Hourly/Daily data for ApiDataProvider

* Add unit test for IsOutOfDate

* Address review

* Fix reference to static function in test
2020-12-16 19:04:06 -03:00
Adalyat Nazirov
d136428556 ignore *.DotSettings files (#5035)
This layer is designated for common settings that enforce your team preferences for the current solution.
Since we don't have specific resharper settings we want to share within the team we ignore this file
2020-12-16 12:38:01 -03:00
Gerardo Salazar
40d81965be Adds debug logging for MapSymbol(...) method in IB Brokerage (#5040) 2020-12-15 17:44:00 -08:00
Aaron Janeiro Stone
c650eb6c1c Adds DeM indicator (#5002)
* Adds DeM indicator

* Added reference to param movingaverage type

* Fixed variable declarations

* Added nameless initialize

* Missing DeM "type" args added

* Missing DeM "type" args added

* refactor

* Undid _previousInput → protected

* Demarker symbol: DeM →DEM

* Symbol change: DeM → DEM

* Updated symbols

TestDivByZero originally had dem as cmf.

* Symbol: DeM →DEM

Co-authored-by: Alexandre Catarino <AlexCatarino@users.noreply.github.com>
2020-12-15 08:29:55 -03:00
Charles Naccio
aa2f9f927a Fixed QuantBook import path for CSharp example (#5028)
Now requires a relative path for loading QuantBook.csx
2020-12-14 21:22:22 -03:00
Charles Naccio
c698a65a84 Replaced obsolete Gitter badge with Slack (#5031) 2020-12-14 12:55:35 -03:00
Charles Naccio
181283a4cd Noted Polygon downloaded in Readme (#5025) 2020-12-11 16:55:58 -08:00
Martin-Molinero
b247724a34 Improve Optimizer runtime statistics (#5024)
- Adding optimization Id to backtests packets
- SeriesSampler will allow truncating the samples
- Removing OptimizationEstimate, simplifying getting estimate and
  runtime stats separatly
2020-12-11 16:39:13 -08:00
Gerardo Salazar
dde3576161 Fixes intraday delistings not occurring before contract expiry for Futures and FOPs (#5007)
* Fixes intraday delistings not occurring for Futures and FOPs

  * Previously, we would wait until the next market open to
    liquidate futures and futures options contracts. Since these
    contracts can not be traded at the next market open and require
    intraday delisting, changes were made to liquidate at the first
    available place where we know the market is open. This means
    we now liquidate futures and FOPs intraday as a market order.

  * Maintains backwards compatability with equities and equity options
    delisting behavior

* Addresses review: adds additional protections for ProcessDelistedSymbols

  * We choose to adjust the delisting date to the next market open only
    if the market is not open at the current time, otherwise the time
    would have been adjusted to the market open of the next trading day

* Addresses review: reverts changes and fixes error message in regression algo
2020-12-11 20:46:56 -03:00
Gerardo Salazar
e8734a0797 Adds/Fixes Futures Options History Research Support (#5013)
* Adds Futures Options History Research Support

* Address review: make canonical future throw when calling GetOptionHistory

* Improve error message, recommending users to user FutureChainProvider
2020-12-11 20:46:41 -03:00
Aaron Janeiro Stone
7f5d69bbec Adds the Awesome Oscillator (#5005)
* Adds the awesome oscillator.

* added missing type hint for AO

* cleaned initializations

* refactor in call for AO(fast,slow,type)

* added missing type parameter for AO

* Changes AO sub-indicators to public.

Co-authored-by: Alexandre Catarino <AlexCatarino@users.noreply.github.com>
2020-12-11 20:46:07 -03:00
Colton Sellers
f6be7a41a5 Bug python runtime issue with local report generation (#5014)
* Fixed Python runtime issue that was occurring when trying to generate reports locally on OSX/mono, but assume the issue impacts all configurations.

* Move Python.Runtime config to common

* Remove duplicate files

* Update readme

* Typo

* Change destination in build directory

Co-authored-by: Charles Naccio <cnaccio@gmail.com>
2020-12-11 20:45:26 -03:00
Stefano Raggi
7f30c0cd00 Downgrade IB error codes from Warning to Information (#5015) 2020-12-11 18:53:25 -03:00
Colton Sellers
6694fe01f8 Api Chart Hotfix (#5023)
* Api Chart Hotfix

* Use IsNullOrEmpty
2020-12-11 18:43:18 -03:00
Aaron Janeiro Stone
32ab4fdea1 Adds ChaikinMoneyFlow indicator (#4986)
* Added CMF indicator

CMF is a volume-weighted average of accumulation and distribution over a period.

* Added initializer for CMF

Registration for ChaikinMoneyFlow implemented.

* Added CMF tests.

* Added CMF tests.

* spy_cmf.txt changed to external indicator data.

* Implement suggestions of @AlexCatarino

* added sum terms as subindicators.

* added sum terms as subindicators.

* Removal of vestigial rolling window

* Minor nit changes

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2020-12-11 18:04:17 -03:00
Colton Sellers
fc81f606e4 Reserve Names for Pandas Mapper (#4978)
* Fix for #4886 and unit test

* Fix test function

* Address review

* Clarify comments
2020-12-11 16:39:13 -03:00
Stefano Raggi
ec74abd4d0 Fix Bitfinex brokerage currency mapping (#5011) 2020-12-11 16:12:57 -03:00
Colton Sellers
bd3ead3480 ApiDataProvider Zip Download Fixes (#5020)
* Stop non zip responses from being saved as a zip

* Capture and log message

* Log as Error
2020-12-11 16:01:57 -03:00
Colton Sellers
45849962a3 Readme expansion and additional VS build tasks (#5018) 2020-12-11 14:49:29 -03:00
Gerardo Salazar
8279cf7eac Improve exception message for indicators using Update(DateTime, decimal) (#5019) 2020-12-11 14:36:42 -03:00
Colton Sellers
4c4a699cb0 Stop Emitting Insights on Delisted Securities (#4997)
* Verify insights are valid before emitting

* nit

* Address review

* Address review and unit tests

* nit - remove extra lines

* Address review

* Initialize insight fields
2020-12-10 11:44:37 -03:00
Colton Sellers
31a2c31c0a Api Update November 2020 (#4981)
* WIP Backtest adjustments

* Workaround awaiting changes

* Adjustments to API Changes

* Nit fix

* Custom Newtonsoft Deserializer for AlphaRuntimeStatistics

* Workaround Travis build error

* Drop AlphaRuntimeStatistics converter; use Decimal converter

* Use StringDecimalJsonConverter

* Undo set properties

* Add more members to de-serializer class
2020-12-09 16:51:58 -03:00
Jared
877a123276 Update readme.md 2020-12-08 12:26:21 -08:00
Gerardo Salazar
4134b05bfd Fixes options order crash in ReportGenerator/PortfolioLooper (#4992) 2020-12-07 12:39:53 -03:00
916 changed files with 28144 additions and 26292 deletions

31
.github/workflows/gh-actions.yml vendored Normal file
View File

@@ -0,0 +1,31 @@
name: Build & Test Lean
on:
push:
branches: ['*']
pull_request:
branches: [master]
jobs:
build:
runs-on: ubuntu-16.04
container:
image: quantconnect/lean:foundation
steps:
- uses: actions/checkout@v2
- name: Restore nuget dependencies
run: |
nuget restore QuantConnect.Lean.sln -v quiet
nuget install NUnit.Runners -Version 3.11.1 -OutputDirectory testrunner
- name: Build
run: msbuild /p:Configuration=Release /p:VbcToolExe=vbnc.exe /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
- name: Run Tests
run: mono ./testrunner/NUnit.ConsoleRunner.3.11.1/tools/nunit3-console.exe ./Tests/bin/Release/QuantConnect.Tests.dll --where "cat != TravisExclude" --labels=Off --params:log-handler=ConsoleErrorLogHandler
- name: Generate & Publish python stubs
run: |
chmod +x ci_build_stubs.sh
./ci_build_stubs.sh -d -t -g #Ignore Publish as of since credentials are missing on CI

1
.gitignore vendored
View File

@@ -144,6 +144,7 @@ $tf/
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings
*.DotSettings.user
# JustCode is a .NET coding addin-in

4
.idea/workspace.xml generated
View File

@@ -3,7 +3,7 @@
<component name="RunManager" selected="Python Debug Server.Debug in Container">
<configuration name="Debug Local" type="PyRemoteDebugConfigurationType" factoryName="Python Remote Debug">
<module name="LEAN" />
<option name="PORT" value="5678" />
<option name="PORT" value="6000" />
<option name="HOST" value="localhost" />
<PathMappingSettings>
<option name="pathMappings">
@@ -16,7 +16,7 @@
</configuration>
<configuration name="Debug in Container" type="PyRemoteDebugConfigurationType" factoryName="Python Remote Debug">
<module name="LEAN" />
<option name="PORT" value="5678" />
<option name="PORT" value="6000" />
<option name="HOST" value="localhost" />
<PathMappingSettings>
<option name="pathMappings">

View File

@@ -1,11 +1,12 @@
sudo: required
language: csharp
dotnet: 5.0
mono:
- 5.12.0
solution: QuantConnect.Lean.sln
before_install:
- export PATH="$HOME/miniconda3/bin:$PATH"
- wget https://cdn.quantconnect.com/miniconda/Miniconda3-4.5.12-Linux-x86_64.sh
- wget -q https://cdn.quantconnect.com/miniconda/Miniconda3-4.5.12-Linux-x86_64.sh
- bash Miniconda3-4.5.12-Linux-x86_64.sh -b
- rm -rf Miniconda3-4.5.12-Linux-x86_64.sh
- sudo ln -s $HOME/miniconda3/lib/libpython3.6m.so /usr/lib/libpython3.6m.so
@@ -17,10 +18,9 @@ before_install:
- conda install -y scipy=1.4.1
- conda install -y wrapt=1.12.1
install:
- nuget restore QuantConnect.Lean.sln
- nuget install NUnit.Runners -Version 3.11.1 -OutputDirectory testrunner
script:
- msbuild /p:Configuration=Release /p:VbcToolExe=vbnc.exe QuantConnect.Lean.sln
- mono ./testrunner/NUnit.ConsoleRunner.3.11.1/tools/nunit3-console.exe ./Tests/bin/Release/QuantConnect.Tests.dll --where "cat != TravisExclude" --labels=Off
- dotnet build /p:Configuration=Release /p:VbcToolExe=vbnc.exe /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
- mono ./testrunner/NUnit.ConsoleRunner.3.11.1/tools/nunit3-console.exe ./Tests/bin/Release/QuantConnect.Tests.dll --where "cat != TravisExclude" --labels=Off --params:log-handler=ConsoleErrorLogHandler
- chmod +x ci_build_stubs.sh
- sudo -E ./ci_build_stubs.sh -d -t -g -p

17
.vscode/readme.md vendored
View File

@@ -13,7 +13,7 @@ Before anything we need to ensure a few things have been done:
1. Get [Visual Studio Code](https://code.visualstudio.com/download)
* Get the Extension [Mono Debug](https://marketplace.visualstudio.com/items?itemName=ms-vscode.mono-debug) for C# Debugging
* Get the Extension [Mono Debug **15.8**](https://marketplace.visualstudio.com/items?itemName=ms-vscode.mono-debug) for C# Debugging
* Get the Extension [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) for Python Debugging
2. Get [Docker](https://docs.docker.com/get-docker/):
@@ -35,7 +35,8 @@ Before anything we need to ensure a few things have been done:
* Download the repo or clone it using: _git clone[ https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)_
* Open the folder using VS Code
**NOTES**:
- Mono Extension Version 16 and greater fails to debug the docker container remotely, please install **Version 15.8**. To install an older version from within VS Code go to the extensions tab, search "Mono Debug", and select "Install Another Version...".
<br />
<h1>Develop Algorithms Locally, Run in Container</h1>
@@ -66,7 +67,7 @@ Before we can use this method with Windows or Mac OS we need to share the Lean d
Next we need to be sure that our Lean configuration at **.\Launcher\config.json** is properly set. Just like running lean locally the config must reflect what we want Lean to run.
You configuration file should look something like this for the following languages:
Your configuration file should look something like this for the following languages:
<h3>Python:</h3>
@@ -112,6 +113,12 @@ In VS Code click on the debug/run icon on the left toolbar, at the top you shoul
As defaults these are all great! Feel free to change them as needed for your setup.
**NOTE:** VSCode may try and throw errors when launching this way regarding build on `QuantConnect.csx` and `Config.json` these errors can be ignored by selecting "*Debug Anyway*". To stop this error message in the future select "*Remember my choice in user settings*".
If using C# algorithms ensure that msbuild can build them successfully.
<br />
<h3>Option 2</h3>
@@ -194,4 +201,6 @@ _Figure 2: Python Debugger Messages_
<h1>Common Issues</h1>
Here we will cover some common issues with setting this up. This section will expand as we get user feedback!
* Error messages about build in VSCode points to comments in JSON. Either select **ignore** or follow steps described [here](https://stackoverflow.com/questions/47834825/in-vs-code-disable-error-comments-are-not-permitted-in-json) to remove the errors entirely.
* Any error messages about building in VSCode that point to comments in JSON. Either select **ignore** or follow steps described [here](https://stackoverflow.com/questions/47834825/in-vs-code-disable-error-comments-are-not-permitted-in-json) to remove the errors entirely.
* `Errors exist after running preLaunchTask 'run-docker'`This VSCode error appears to warn you of CSharp errors when trying to use `Debug in Container` select "Debug Anyway" as the errors are false flags for JSON comments as well as `QuantConnect.csx` not finding references. Neither of these will impact your debugging.
* `The container name "/LeanEngine" is already in use by container "****"` This Docker error implies that another instance of lean is already running under the container name /LeanEngine. If this error appears either use Docker Desktop to delete the container or use `docker kill LeanEngine` from the command line.

28
.vscode/tasks.json vendored
View File

@@ -20,6 +20,34 @@
},
"problemMatcher": "$msCompile"
},
{
"label": "rebuild",
"type": "shell",
"command": "msbuild",
"args": [
"/p:Configuration=Debug",
"/p:DebugType=portable",
"/t:rebuild",
],
"group": "build",
"presentation": {
"reveal": "silent"
},
"problemMatcher": "$msCompile"
},
{
"label": "clean",
"type": "shell",
"command": "msbuild",
"args": [
"/t:clean",
],
"group": "build",
"presentation": {
"reveal": "silent"
},
"problemMatcher": "$msCompile"
},
{
"label": "force build linux",
"type": "shell",

View File

@@ -94,6 +94,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.212"},
{"Treynor Ratio", "-2.13"},
{"Total Fees", "$199.00"},
{"Estimated Strategy Capacity", "$280000000.00"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "38.64"},
{"Kelly Criterion Probability Value", "0.229"},
@@ -113,7 +114,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"},
{"OrderListHash", "1256341962"}
{"OrderListHash", "0a28eedf6304023f5002ef672b489b88"}
};
}
}

View File

@@ -130,6 +130,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.367"},
{"Treynor Ratio", "-4.079"},
{"Total Fees", "$14.33"},
{"Estimated Strategy Capacity", "$29000000.00"},
{"Fitness Score", "0.408"},
{"Kelly Criterion Estimate", "16.447"},
{"Kelly Criterion Probability Value", "0.315"},
@@ -149,7 +150,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "100%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-887015098"}
{"OrderListHash", "506e9fe18984ba6e569b2e327030de3a"}
};
}
}

View File

@@ -185,6 +185,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.043"},
{"Treynor Ratio", "0"},
{"Total Fees", "$7.40"},
{"Estimated Strategy Capacity", "$28000000.00"},
{"Fitness Score", "1"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -204,7 +205,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1074366800"}
{"OrderListHash", "35738733ff791eeeaf508faec804cab0"}
};
}
}

View File

@@ -219,6 +219,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.044"},
{"Treynor Ratio", "0.479"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$12000.00"},
{"Fitness Score", "0.41"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -238,7 +239,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1532330301"}
{"OrderListHash", "9347e3b610cfa21f7cbd968a0135c8af"}
};
}
}

View File

@@ -131,14 +131,15 @@ namespace QuantConnect.Algorithm.CSharp
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.92"},
{"Alpha", "-0.023"},
{"Beta", "0.005"},
{"Alpha", "-0.021"},
{"Beta", "-0.01"},
{"Annual Standard Deviation", "0.006"},
{"Annual Variance", "0"},
{"Information Ratio", "-3.424"},
{"Tracking Error", "0.057"},
{"Treynor Ratio", "-4.775"},
{"Information Ratio", "-3.374"},
{"Tracking Error", "0.058"},
{"Treynor Ratio", "2.133"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$6400000.00"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -158,7 +159,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1185639451"}
{"OrderListHash", "486118a60d78f74811fe8d927c2c6b43"}
};
}
}

View File

@@ -191,6 +191,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.042"},
{"Treynor Ratio", "0.286"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$1400000.00"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -210,7 +211,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "721476625"}
{"OrderListHash", "ae0b430e9c728966e3736fb352a689c6"}
};
}
}

View File

@@ -230,6 +230,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$6.00"},
{"Estimated Strategy Capacity", "$3000.00"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -249,7 +250,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "731140098"}
{"OrderListHash", "cf8f76fa441c2a5e3b2dbbabcab32cd2"}
};
}
}

View File

@@ -131,6 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.072"},
{"Treynor Ratio", "2.933"},
{"Total Fees", "$26.39"},
{"Estimated Strategy Capacity", "$2200000.00"},
{"Fitness Score", "0.374"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -150,7 +151,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1779055144"}
{"OrderListHash", "5f7ba8b5defb310a2eaf98b11abd3b74"}
};
}
}

View File

@@ -84,6 +84,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.006"},
{"Treynor Ratio", "2.029"},
{"Total Fees", "$9.77"},
{"Estimated Strategy Capacity", "$28000000.00"},
{"Fitness Score", "0.747"},
{"Kelly Criterion Estimate", "38.64"},
{"Kelly Criterion Probability Value", "0.229"},
@@ -103,7 +104,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"},
{"OrderListHash", "-887190565"}
{"OrderListHash", "0b8cbbafdb77bae2f7abe3cf5e05ac5c"}
};
}
}

View File

@@ -103,6 +103,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.376"},
{"Treynor Ratio", "-0.084"},
{"Total Fees", "$13.98"},
{"Estimated Strategy Capacity", "$31000000.00"},
{"Fitness Score", "0.146"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "1"},
@@ -122,7 +123,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1917702312"}
{"OrderListHash", "8971c92ba163cec8526379865d9b9ee4"}
};
}
}

View File

@@ -110,6 +110,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.194"},
{"Treynor Ratio", "-0.962"},
{"Total Fees", "$25.92"},
{"Estimated Strategy Capacity", "$16000000.00"},
{"Fitness Score", "0.004"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "1"},
@@ -129,7 +130,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1674230481"}
{"OrderListHash", "ce59e51c8e404b5dbbc02911473aed1c"}
};
}
}

View File

@@ -0,0 +1,237 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Brokerages;
using QuantConnect.Data;
using QuantConnect.Data.Shortable;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Tests filtering in coarse selection by shortable quantity
/// </summary>
public class AllShortableSymbolsCoarseSelectionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private static readonly DateTime _20140325 = new DateTime(2014, 3, 25);
private static readonly DateTime _20140326 = new DateTime(2014, 3, 26);
private static readonly DateTime _20140327 = new DateTime(2014, 3, 27);
private static readonly DateTime _20140328 = new DateTime(2014, 3, 28);
private static readonly DateTime _20140329 = new DateTime(2014, 3, 29);
private static readonly Symbol _aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
private static readonly Symbol _bac = QuantConnect.Symbol.Create("BAC", SecurityType.Equity, Market.USA);
private static readonly Symbol _gme = QuantConnect.Symbol.Create("GME", SecurityType.Equity, Market.USA);
private static readonly Symbol _goog = QuantConnect.Symbol.Create("GOOG", SecurityType.Equity, Market.USA);
private static readonly Symbol _qqq = QuantConnect.Symbol.Create("QQQ", SecurityType.Equity, Market.USA);
private static readonly Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
private DateTime _lastTradeDate;
private static readonly Dictionary<DateTime, bool> _coarseSelected = new Dictionary<DateTime, bool>
{
{ _20140325, false },
{ _20140326, false },
{ _20140327, false },
{ _20140328, false },
};
private static readonly Dictionary<DateTime, Symbol[]> _expectedSymbols = new Dictionary<DateTime, Symbol[]>
{
{ _20140325, new[]
{
_bac,
_qqq,
_spy
}
},
{ _20140326, new[]
{
_spy
}
},
{ _20140327, new[]
{
_aapl,
_bac,
_gme,
_qqq,
_spy,
}
},
{ _20140328, new[]
{
_goog
}
},
{ _20140329, new Symbol[0] }
};
public override void Initialize()
{
SetStartDate(2014, 3, 25);
SetEndDate(2014, 3, 29);
SetCash(10000000);
AddUniverse(CoarseSelection);
UniverseSettings.Resolution = Resolution.Daily;
SetBrokerageModel(new AllShortableSymbolsRegressionAlgorithmBrokerageModel());
}
public override void OnData(Slice data)
{
if (Time.Date == _lastTradeDate)
{
return;
}
foreach (var symbol in ActiveSecurities.Keys)
{
if (!Portfolio.ContainsKey(symbol) || !Portfolio[symbol].Invested)
{
if (!Shortable(symbol))
{
throw new Exception($"Expected {symbol} to be shortable on {Time:yyyy-MM-dd}");
}
// Buy at least once into all Symbols. Since daily data will always use
// MOO orders, it makes the testing of liquidating buying into Symbols difficult.
MarketOrder(symbol, -(decimal)ShortableQuantity(symbol));
_lastTradeDate = Time.Date;
}
}
}
private IEnumerable<Symbol> CoarseSelection(IEnumerable<CoarseFundamental> coarse)
{
var shortableSymbols = AllShortableSymbols();
var selectedSymbols = coarse
.Select(x => x.Symbol)
.Where(s => shortableSymbols.ContainsKey(s) && shortableSymbols[s] >= 500)
.OrderBy(s => s)
.ToList();
var expectedMissing = 0;
if (Time.Date == _20140327)
{
var gme = QuantConnect.Symbol.Create("GME", SecurityType.Equity, Market.USA);
if (!shortableSymbols.ContainsKey(gme))
{
throw new Exception("Expected unmapped GME in shortable symbols list on 2014-03-27");
}
if (!coarse.Select(x => x.Symbol.Value).Contains("GME"))
{
throw new Exception("Expected mapped GME in coarse symbols on 2014-03-27");
}
expectedMissing = 1;
}
var missing = _expectedSymbols[Time.Date].Except(selectedSymbols).ToList();
if (missing.Count != expectedMissing)
{
throw new Exception($"Expected Symbols selected on {Time.Date:yyyy-MM-dd} to match expected Symbols, but the following Symbols were missing: {string.Join(", ", missing.Select(s => s.ToString()))}");
}
_coarseSelected[Time.Date] = true;
return selectedSymbols;
}
public override void OnEndOfAlgorithm()
{
if (!_coarseSelected.Values.All(x => x))
{
throw new AggregateException($"Expected coarse selection on all dates, but didn't run on: {string.Join(", ", _coarseSelected.Where(kvp => !kvp.Value).Select(kvp => kvp.Key.ToStringInvariant("yyyy-MM-dd")))}");
}
}
private class AllShortableSymbolsRegressionAlgorithmBrokerageModel : DefaultBrokerageModel
{
public AllShortableSymbolsRegressionAlgorithmBrokerageModel() : base()
{
ShortableProvider = new RegressionTestShortableProvider();
}
}
private class RegressionTestShortableProvider : LocalDiskShortableProvider
{
public RegressionTestShortableProvider() : base(SecurityType.Equity, "testbrokerage", Market.USA)
{
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "5"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "36.294%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0.340%"},
{"Sharpe Ratio", "21.2"},
{"Probabilistic Sharpe Ratio", "99.990%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.274"},
{"Beta", "0.138"},
{"Annual Standard Deviation", "0.011"},
{"Annual Variance", "0"},
{"Information Ratio", "7.202"},
{"Tracking Error", "0.068"},
{"Treynor Ratio", "1.722"},
{"Total Fees", "$307.50"},
{"Estimated Strategy Capacity", "$710000.00"},
{"Fitness Score", "0.173"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0.173"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "6b1b205e5a6461ffd5bed645099714cd"}
};
}
}

View File

@@ -19,28 +19,27 @@ using QuantConnect.Indicators;
using QuantConnect.Orders.Fees;
using QuantConnect.Data.Custom;
using System.Collections.Generic;
using QuantConnect.Algorithm.Framework;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Algorithm.Framework.Selection;
namespace QuantConnect.Algorithm.CSharp
namespace QuantConnect.Algorithm.CSharp.Alphas
{
/// <summary>
/// This Alpha Model uses Wells Fargo 30-year Fixed Rate Mortgage data from Quandl to
/// generate Insights about the movement of Real Estate ETFs. Mortgage rates can provide information
/// regarding the general price trend of real estate, and ETFs provide good continuous-time instruments
/// to measure the impact against. Volatility in mortgage rates tends to put downward pressure on real
/// estate prices, whereas stable mortgage rates, regardless of true rate, lead to stable or higher real
/// estate prices. This Alpha model seeks to take advantage of this correlation by emitting insights
/// based on volatility and rate deviation from its historic mean.
/// This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
///<summary>
/// This Alpha Model uses Wells Fargo 30-year Fixed Rate Mortgage data from Quandl to
/// generate Insights about the movement of Real Estate ETFs. Mortgage rates can provide information
/// regarding the general price trend of real estate, and ETFs provide good continuous-time instruments
/// to measure the impact against. Volatility in mortgage rates tends to put downward pressure on real
/// estate prices, whereas stable mortgage rates, regardless of true rate, lead to stable or higher real
/// estate prices. This Alpha model seeks to take advantage of this correlation by emitting insights
/// based on volatility and rate deviation from its historic mean.
///
/// This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
/// sourced so the community and client funds can see an example of an alpha.
/// <summary>
public class MortgageRateVolatilityAlgorithm : QCAlgorithmFramework
///</summary>
public class MortgageRateVolatilityAlgorithm : QCAlgorithm
{
public override void Initialize()
{
@@ -51,8 +50,8 @@ namespace QuantConnect.Algorithm.CSharp
SetSecurityInitializer(security => security.FeeModel = new ConstantFeeModel(0));
// Basket of 6 liquid real estate ETFs
Func<string, Symbol> ToSymbol = x => QuantConnect.Symbol.Create(x, SecurityType.Equity, Market.USA);
var realEstateETFs = new[] { "VNQ", "REET", "TAO", "FREL", "SRET", "HIPS" }.Select(ToSymbol).ToArray();
Func<string, Symbol> toSymbol = x => QuantConnect.Symbol.Create(x, SecurityType.Equity, Market.USA);
var realEstateETFs = new[] { "VNQ", "REET", "TAO", "FREL", "SRET", "HIPS" }.Select(toSymbol).ToArray();
SetUniverseSelection(new ManualUniverseSelectionModel(realEstateETFs));
SetAlpha(new MortgageRateVolatilityAlphaModel(this));
@@ -64,8 +63,6 @@ namespace QuantConnect.Algorithm.CSharp
SetRiskManagement(new NullRiskManagementModel());
}
public void OnData(QuandlMortgagePriceColumns data) { }
private class MortgageRateVolatilityAlphaModel : AlphaModel
{
@@ -79,7 +76,7 @@ namespace QuantConnect.Algorithm.CSharp
private readonly StandardDeviation _mortgageRateStd;
public MortgageRateVolatilityAlphaModel(
QCAlgorithmFramework algorithm,
QCAlgorithm algorithm,
int indicatorPeriod = 15,
double insightMagnitude = 0.0005,
int deviations = 2,
@@ -102,7 +99,7 @@ namespace QuantConnect.Algorithm.CSharp
WarmUpIndicators(algorithm);
}
public override IEnumerable<Insight> Update(QCAlgorithmFramework algorithm, Slice data)
public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
{
var insights = new List<Insight>();
@@ -141,7 +138,7 @@ namespace QuantConnect.Algorithm.CSharp
return insights;
}
private void WarmUpIndicators(QCAlgorithmFramework algorithm)
private void WarmUpIndicators(QCAlgorithm algorithm)
{
// Make a history call and update the indicators
algorithm.History(new[] { _mortgageRate }, _indicatorPeriod, _resolution).PushThrough(bar =>

View File

@@ -0,0 +1,124 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm to test the behaviour of ARMA versus AR models at the same order of differencing.
/// In particular, an ARIMA(1,1,1) and ARIMA(1,1,0) are instantiated while orders are placed if their difference
/// is sufficiently large (which would be due to the inclusion of the MA(1) term).
/// </summary>
public class AutoRegressiveIntegratedMovingAverageRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private AutoRegressiveIntegratedMovingAverage _arima;
private AutoRegressiveIntegratedMovingAverage _ar;
private decimal _last;
public override void Initialize()
{
SetStartDate(2013, 1, 07);
SetEndDate(2013, 12, 11);
EnableAutomaticIndicatorWarmUp = true;
AddEquity("SPY", Resolution.Daily);
_arima = ARIMA("SPY", 1, 1, 1, 50);
_ar = ARIMA("SPY", 1, 1, 0, 50);
}
public override void OnData(Slice slice)
{
if (_arima.IsReady)
{
if (Math.Abs(_ar.Current.Value - _arima.Current.Value) > 1) // Difference due to MA(1) being included.
{
if (_arima.Current.Value > _last)
{
MarketOrder("SPY", 1);
}
else
{
MarketOrder("SPY", -1);
}
}
_last = _arima.Current.Value;
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "65"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "0.145%"},
{"Drawdown", "0.100%"},
{"Expectancy", "2.190"},
{"Net Profit", "0.134%"},
{"Sharpe Ratio", "0.993"},
{"Probabilistic Sharpe Ratio", "49.669%"},
{"Loss Rate", "29%"},
{"Win Rate", "71%"},
{"Profit-Loss Ratio", "3.50"},
{"Alpha", "0.001"},
{"Beta", "0"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.168"},
{"Tracking Error", "0.099"},
{"Treynor Ratio", "-5.187"},
{"Total Fees", "$65.00"},
{"Estimated Strategy Capacity", "$2300000000.00"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "1.51"},
{"Return Over Maximum Drawdown", "1.819"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "c4c9c272037cfd8f6887052b8d739466"}
};
}
}

View File

@@ -168,6 +168,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.441"},
{"Treynor Ratio", "-0.008"},
{"Total Fees", "$20.35"},
{"Estimated Strategy Capacity", "$19000000.00"},
{"Fitness Score", "0.138"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -187,7 +188,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1453269600"}
{"OrderListHash", "7c841ca58a4385f42236838e5bf0c382"}
};
}
}

View File

@@ -130,6 +130,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.001"},
{"Treynor Ratio", "1.922"},
{"Total Fees", "$3.26"},
{"Estimated Strategy Capacity", "$15000000.00"},
{"Fitness Score", "0.248"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -149,7 +150,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "491919591"}
{"OrderListHash", "25885f979ca8c7b44f5d0f7daf00b241"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -303,21 +303,40 @@ namespace QuantConnect.Algorithm.CSharp
{"Drawdown", "0.400%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.323%"},
{"Sharpe Ratio", "-0.888"},
{"Sharpe Ratio", "-11.098"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.035"},
{"Beta", "0.183"},
{"Annual Standard Deviation", "0.004"},
{"Alpha", "-0.002"},
{"Beta", "0.099"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "12.058"},
{"Tracking Error", "0.017"},
{"Treynor Ratio", "-0.018"},
{"Information Ratio", "9.899"},
{"Tracking Error", "0.019"},
{"Treynor Ratio", "-0.23"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0.213"},
{"OrderListHash", "904167951"}
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-73.456"},
{"Portfolio Turnover", "0.426"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "72a6ced0ed0c2da7136f3be652eb4744"}
};
}
}

View File

@@ -88,6 +88,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$85000.00"},
{"Fitness Score", "0.506"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -107,7 +108,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1575550889"}
{"OrderListHash", "18dc611407abec4ea47092e71f33f983"}
};
}
}

View File

@@ -97,6 +97,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.001"},
{"Treynor Ratio", "1.922"},
{"Total Fees", "$3.26"},
{"Estimated Strategy Capacity", "$15000000.00"},
{"Fitness Score", "0.248"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -116,7 +117,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "491919591"}
{"OrderListHash", "25885f979ca8c7b44f5d0f7daf00b241"}
};
}
}
}

View File

@@ -223,6 +223,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$85.34"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0.5"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -242,7 +243,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "956597072"}
{"OrderListHash", "1bf1a6d9dd921982b72a6178f9e50e68"}
};
}
}

View File

@@ -88,6 +88,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.221"},
{"Treynor Ratio", "-13.568"},
{"Total Fees", "$3.26"},
{"Estimated Strategy Capacity", "$130000000.00"},
{"Fitness Score", "0.111"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -107,7 +108,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1268340653"}
{"OrderListHash", "82fee25cd17100c53bb173834ab5f0b2"}
};
}
}

View File

@@ -109,6 +109,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.002"},
{"Treynor Ratio", "1.839"},
{"Total Fees", "$9.77"},
{"Estimated Strategy Capacity", "$20000000.00"},
{"Fitness Score", "0.747"},
{"Kelly Criterion Estimate", "38.64"},
{"Kelly Criterion Probability Value", "0.229"},
@@ -128,7 +129,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"},
{"OrderListHash", "951346025"}
{"OrderListHash", "17e29d58e5dabd93569da752c4552c70"}
};
}
}

View File

@@ -147,6 +147,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.504"},
{"Treynor Ratio", "1.011"},
{"Total Fees", "$15207.00"},
{"Estimated Strategy Capacity", "$8800000.00"},
{"Fitness Score", "0.033"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -166,7 +167,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1197265007"}
{"OrderListHash", "35b3f4b7a225468d42ca085386a2383e"}
};
}
}

View File

@@ -155,6 +155,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.188"},
{"Treynor Ratio", "-3.318"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$13000000.00"},
{"Fitness Score", "0.009"},
{"Kelly Criterion Estimate", "-112.972"},
{"Kelly Criterion Probability Value", "0.671"},
@@ -174,7 +175,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1624258832"}
{"OrderListHash", "18ffd3a774c68da83d867e3b09e3e05d"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -160,6 +160,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -179,7 +180,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "371857150"}
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}
}

View File

@@ -134,6 +134,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$778.00"},
{"Estimated Strategy Capacity", "$180000.00"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -153,7 +154,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-702975961"}
{"OrderListHash", "5484aef1443064c826e0071f757cb0f7"}
};
}
}

View File

@@ -131,6 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$2600000.00"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -150,7 +151,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1130102123"}
{"OrderListHash", "9d9f9248ee8fe30d87ff0a6f6fea5112"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -102,7 +102,7 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
@@ -122,6 +122,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -141,7 +142,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "687310345"}
{"OrderListHash", "92d8a50efe230524512404dab66b19dd"}
};
}
}

View File

@@ -160,7 +160,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$4.00"},
{"Total Fees", "$3.00"},
{"Estimated Strategy Capacity", "$74000.00"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0.327"},
{"Kelly Criterion Probability Value", "1"},
@@ -180,7 +181,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "50.0482%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "352959406"}
{"OrderListHash", "ce06ddfa4b2ffeb666a8910ac8836992"}
};
}
}

View File

@@ -94,6 +94,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.09"},
{"Treynor Ratio", "0.82"},
{"Total Fees", "$41.70"},
{"Estimated Strategy Capacity", "$2000000.00"},
{"Fitness Score", "0.634"},
{"Kelly Criterion Estimate", "13.656"},
{"Kelly Criterion Probability Value", "0.228"},
@@ -113,7 +114,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "50%"},
{"Rolling Averaged Population Direction", "12.6429%"},
{"Rolling Averaged Population Magnitude", "12.6429%"},
{"OrderListHash", "-2004493274"}
{"OrderListHash", "3edd51956c7c97af4863aa6059c11f1a"}
};
}
}

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.IO;
using QuantConnect.Data;
using QuantConnect.Data.Custom.CBOE;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Tests the consolidation of custom data with random data
/// </summary>
public class CBOECustomDataConsolidationRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _vix;
private BollingerBands _bb;
private bool _invested;
/// <summary>
/// Initializes the algorithm with fake VIX data
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 7);
SetEndDate(2013, 10, 11);
SetCash(100000);
_vix = AddData<IncrementallyGeneratedCustomData>("VIX", Resolution.Daily).Symbol;
_bb = BB(_vix, 30, 2, MovingAverageType.Simple, Resolution.Daily);
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (_bb.Current.Value == 0)
{
throw new Exception("Bollinger Band value is zero when we expect non-zero value.");
}
if (!_invested && _bb.Current.Value > 0.05m)
{
MarketOrder(_vix, 1);
_invested = true;
}
}
/// <summary>
/// Incrementally updating data
/// </summary>
private class IncrementallyGeneratedCustomData : CBOE
{
private const decimal _start = 10.01m;
private static decimal _step;
/// <summary>
/// Gets the source of the subscription. In this case, we set it to existing
/// equity data so that we can pass fake data from Reader
/// </summary>
/// <param name="config">Subscription configuration</param>
/// <param name="date">Date we're making this request</param>
/// <param name="isLiveMode">Is live mode</param>
/// <returns>Source of subscription</returns>
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
return new SubscriptionDataSource(Path.Combine(Globals.DataFolder, "equity", "usa", "minute", "spy", $"{date:yyyyMMdd}_trade.zip#{date:yyyyMMdd}_spy_minute_trade.csv"), SubscriptionTransportMedium.LocalFile, FileFormat.Csv);
}
/// <summary>
/// Reads the data, which in this case is fake incremental data
/// </summary>
/// <param name="config">Subscription configuration</param>
/// <param name="line">Line of data</param>
/// <param name="date">Date of the request</param>
/// <param name="isLiveMode">Is live mode</param>
/// <returns>Incremental BaseData instance</returns>
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
var vix = new CBOE();
_step += 0.10m;
var open = _start + _step;
var close = _start + _step + 0.02m;
var high = close;
var low = open;
return new IncrementallyGeneratedCustomData
{
Open = open,
High = high,
Low = low,
Close = close,
Time = date,
Symbol = new Symbol(
SecurityIdentifier.GenerateBase(typeof(IncrementallyGeneratedCustomData), "VIX", Market.USA, false),
"VIX"),
Period = vix.Period,
DataType = vix.DataType
};
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
/// <remarks>
/// Unable to be tested in Python, due to pythonnet not supporting overriding of methods from Python
/// </remarks>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0.029%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0.000%"},
{"Sharpe Ratio", "28.4"},
{"Probabilistic Sharpe Ratio", "88.597%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-7.067"},
{"Tracking Error", "0.193"},
{"Treynor Ratio", "7.887"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "918912ee4f64cd0290f3d58deca02713"}
};
}
}

View File

@@ -147,6 +147,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$370000.00"},
{"Fitness Score", "0.501"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -166,7 +167,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1349023435"}
{"OrderListHash", "aea2e321d17414c1f3c6fa2491f10c88"}
};
}
}

View File

@@ -0,0 +1,102 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Tests capacity by trading SPY (beast) alongside a small cap stock ABUS (penny)
/// </summary>
public class BeastVsPenny : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spy;
public override void Initialize()
{
SetStartDate(2020, 1, 1);
SetEndDate(2020, 3, 31);
SetCash(10000);
_spy = AddEquity("SPY", Resolution.Hour).Symbol;
var penny = AddEquity("ABUS", Resolution.Hour).Symbol;
Schedule.On(DateRules.EveryDay(_spy), TimeRules.AfterMarketOpen(_spy, 1, false), () =>
{
SetHoldings(_spy, 0.5m);
SetHoldings(penny, 0.5m);
});
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "70"},
{"Average Win", "0.07%"},
{"Average Loss", "-0.51%"},
{"Compounding Annual Return", "-89.548%"},
{"Drawdown", "49.900%"},
{"Expectancy", "-0.514"},
{"Net Profit", "-42.920%"},
{"Sharpe Ratio", "-0.797"},
{"Probabilistic Sharpe Ratio", "9.019%"},
{"Loss Rate", "57%"},
{"Win Rate", "43%"},
{"Profit-Loss Ratio", "0.13"},
{"Alpha", "-0.24"},
{"Beta", "1.101"},
{"Annual Standard Deviation", "1.031"},
{"Annual Variance", "1.063"},
{"Information Ratio", "-0.351"},
{"Tracking Error", "0.836"},
{"Treynor Ratio", "-0.747"},
{"Total Fees", "$81.45"},
{"Estimated Strategy Capacity", "$21000.00"},
{"Fitness Score", "0.01"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-1.284"},
{"Return Over Maximum Drawdown", "-1.789"},
{"Portfolio Turnover", "0.038"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "67c9083f604ed16fb68481e7c26878dc"}
};
}
}

View File

@@ -0,0 +1,147 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Tests an illiquid asset that has bursts of liquidity around 11:00 A.M. Central Time
/// with an hourly in and out strategy.
/// </summary>
public class CheeseMilkHourlyRebalance : QCAlgorithm, IRegressionAlgorithmDefinition
{
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
private Symbol _contract;
private DateTime _lastTrade;
public override void Initialize()
{
SetStartDate(2021, 1, 1);
SetEndDate(2021, 2, 17);
SetTimeZone(TimeZones.Chicago);
SetCash(100000);
SetWarmup(1000);
var dc = AddFuture("DC", Resolution.Minute, Market.CME);
dc.SetFilter(0, 10000);
}
public override void OnData(Slice data)
{
var contract = data.FutureChains.Values.SelectMany(c => c.Contracts.Values)
.OrderBy(c => c.Symbol.ID.Date)
.FirstOrDefault()?
.Symbol;
if (contract == null)
{
return;
}
if (_contract != contract || (_fast == null && _slow == null))
{
_fast = EMA(contract, 600);
_slow = EMA(contract, 1200);
_contract = contract;
}
if (!_fast.IsReady || !_slow.IsReady)
{
return;
}
if (Time - _lastTrade <= TimeSpan.FromHours(1) || Time.TimeOfDay <= new TimeSpan(10, 50, 0) || Time.TimeOfDay >= new TimeSpan(12, 30, 0))
{
return;
}
if (!Portfolio.ContainsKey(contract) || (Portfolio[contract].Quantity <= 0 && _fast > _slow))
{
SetHoldings(contract, 0.5);
_lastTrade = Time;
}
else if (Portfolio.ContainsKey(contract) && Portfolio[contract].Quantity >= 0 && _fast < _slow)
{
SetHoldings(contract, -0.5);
_lastTrade = Time;
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "19"},
{"Average Win", "39.16%"},
{"Average Loss", "-8.81%"},
{"Compounding Annual Return", "-99.857%"},
{"Drawdown", "82.900%"},
{"Expectancy", "-0.359"},
{"Net Profit", "-57.725%"},
{"Sharpe Ratio", "-0.555"},
{"Probabilistic Sharpe Ratio", "10.606%"},
{"Loss Rate", "88%"},
{"Win Rate", "12%"},
{"Profit-Loss Ratio", "4.45"},
{"Alpha", "-1.188"},
{"Beta", "0.603"},
{"Annual Standard Deviation", "1.754"},
{"Annual Variance", "3.075"},
{"Information Ratio", "-0.759"},
{"Tracking Error", "1.753"},
{"Treynor Ratio", "-1.612"},
{"Total Fees", "$2558.55"},
{"Estimated Strategy Capacity", "$20000.00"},
{"Fitness Score", "0.351"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.602"},
{"Return Over Maximum Drawdown", "-1.415"},
{"Portfolio Turnover", "14.226"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "4f5fd2fb25e957bd0cb7cb6d275ddb97"}
};
}
}

View File

@@ -0,0 +1,231 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Tests a wide variety of liquid and illiquid stocks together, with bins
/// of 20 ranging from micro-cap to mega-cap stocks.
/// </summary>
public class EmaPortfolioRebalance100 : QCAlgorithm, IRegressionAlgorithmDefinition
{
public List<SymbolData> Data;
public override void Initialize()
{
SetStartDate(2020, 1, 1);
SetEndDate(2020, 2, 5);
SetWarmup(1000);
SetCash(100000);
Data = new List<SymbolData> {
new SymbolData(this, AddEquity("AADR", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AAMC", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AAU", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ABDC", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ABIO", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ABUS", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AC", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACER", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACES", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACGLO", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACH", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACHV", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACIO", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACIU", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACNB", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACRS", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACSI", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACT", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACT", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACTG", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZYNE", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZYME", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZUO", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZUMZ", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZTR", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZSL", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZSAN", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZROZ", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZLAB", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZIXI", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZIV", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZIOP", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZGNX", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZG", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZEUS", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZAGG", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("YYY", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("YRD", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("YRCW", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("YPF", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AA", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AAN", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AAP", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AAXN", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ABB", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ABC", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACAD", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACC", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACGL", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACIW", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACM", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACWV", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ACWX", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ADM", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ADPT", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ADS", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ADUS", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AEM", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AEO", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AEP", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ZTS", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("YUM", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("XLY", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("XLV", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("XLRE", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("XLP", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("XLNX", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("XLF", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("XLC", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("XLB", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("XEL", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("XBI", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("X", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("WYNN", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("WW", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("WORK", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("WMB", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("WM", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("WELL", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("WEC", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AAPL", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("ADBE", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AGG", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AMD", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("AMZN", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("BA", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("BABA", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("BAC", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("BMY", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("C", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("CMCSA", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("CRM", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("CSCO", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("DIS", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("EEM", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("EFA", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("FB", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("GDX", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("GE", Resolution.Minute).Symbol),
new SymbolData(this, AddEquity("SPY", Resolution.Minute).Symbol)
};
}
public override void OnData(Slice data)
{
var fastFactor = 0.005m;
foreach (var sd in Data)
{
if (!Portfolio.Invested && sd.Fast * (1 + fastFactor) > sd.Slow)
{
SetHoldings(sd.Symbol, 0.01);
}
else if (Portfolio.Invested && sd.Fast * (1 - fastFactor) < sd.Slow)
{
Liquidate(sd.Symbol);
}
}
}
public class SymbolData
{
public Symbol Symbol;
public ExponentialMovingAverage Fast;
public ExponentialMovingAverage Slow;
public bool IsCrossed => Fast > Slow;
public SymbolData(QCAlgorithm algorithm, Symbol symbol) {
Symbol = symbol;
Fast = algorithm.EMA(symbol, 20);
Slow = algorithm.EMA(symbol, 300);
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1015"},
{"Average Win", "0.01%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-12.674%"},
{"Drawdown", "1.400%"},
{"Expectancy", "-0.761"},
{"Net Profit", "-1.328%"},
{"Sharpe Ratio", "-12.258"},
{"Probabilistic Sharpe Ratio", "0.000%"},
{"Loss Rate", "95%"},
{"Win Rate", "5%"},
{"Profit-Loss Ratio", "3.67"},
{"Alpha", "-0.142"},
{"Beta", "0.038"},
{"Annual Standard Deviation", "0.01"},
{"Annual Variance", "0"},
{"Information Ratio", "-4.389"},
{"Tracking Error", "0.123"},
{"Treynor Ratio", "-3.359"},
{"Total Fees", "$1125.52"},
{"Estimated Strategy Capacity", "$300.00"},
{"Fitness Score", "0.007"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-14.315"},
{"Return Over Maximum Drawdown", "-9.589"},
{"Portfolio Turnover", "0.406"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "4c165e8d648d54a85bb7b564050a6f85"}
};
}
}

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.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Scalps SPY using an EMA cross strategy at minute resolution.
/// This tests equity strategies that trade at a higher frequency, which
/// should have a reduced capacity estimate as a result.
/// </summary>
public class IntradayMinuteScalping : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spy;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
public override void Initialize()
{
SetStartDate(2020, 1, 1);
SetEndDate(2020, 1, 30);
SetCash(100000);
SetWarmup(100);
_spy = AddEquity("SPY", Resolution.Minute).Symbol;
_fast = EMA(_spy, 20);
_slow = EMA(_spy, 40);
}
public override void OnData(Slice data)
{
if (Portfolio[_spy].Quantity <= 0 && _fast > _slow)
{
SetHoldings(_spy, 1);
}
else if (Portfolio[_spy].Quantity >= 0 && _fast < _slow)
{
SetHoldings(_spy, -1);
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "150"},
{"Average Win", "0.16%"},
{"Average Loss", "-0.11%"},
{"Compounding Annual Return", "-19.320%"},
{"Drawdown", "3.900%"},
{"Expectancy", "-0.193"},
{"Net Profit", "-1.730%"},
{"Sharpe Ratio", "-1.606"},
{"Probabilistic Sharpe Ratio", "21.397%"},
{"Loss Rate", "67%"},
{"Win Rate", "33%"},
{"Profit-Loss Ratio", "1.45"},
{"Alpha", "-0.357"},
{"Beta", "0.635"},
{"Annual Standard Deviation", "0.119"},
{"Annual Variance", "0.014"},
{"Information Ratio", "-4.249"},
{"Tracking Error", "0.106"},
{"Treynor Ratio", "-0.302"},
{"Total Fees", "$449.14"},
{"Estimated Strategy Capacity", "$27000000.00"},
{"Fitness Score", "0.088"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-3.259"},
{"Return Over Maximum Drawdown", "-7.992"},
{"Portfolio Turnover", "14.605"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "f5a0e9547f7455004fa6c3eb136534e9"}
};
}
}

View File

@@ -0,0 +1,123 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Scalps BTCETH using an EMA cross strategy at minute resolution.
/// This tests crypto strategies that trade at a higher frequency, which
/// should have a reduced capacity estimate as a result. This also tests
/// that currency conversions are handled properly in the strategy capacity
/// calculation class.
/// </summary>
public class IntradayMinuteScalpingBTCETH : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _ethbtc;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
public override void Initialize()
{
SetStartDate(2021, 1, 1);
SetEndDate(2021, 1, 30);
SetCash(100000);
SetWarmup(100);
var ethbtc = AddCrypto("ETHBTC", Resolution.Minute, Market.GDAX);
ethbtc.BuyingPowerModel = new BuyingPowerModel();
_ethbtc = ethbtc.Symbol;
_fast = EMA(_ethbtc, 20);
_slow = EMA(_ethbtc, 40);
}
public override void OnData(Slice data)
{
if (Portfolio[_ethbtc].Quantity <= 0 && _fast > _slow)
{
SetHoldings(_ethbtc, 1);
}
else if (Portfolio[_ethbtc].Quantity >= 0 && _fast < _slow)
{
SetHoldings(_ethbtc, -1);
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1005"},
{"Average Win", "0.96%"},
{"Average Loss", "-0.33%"},
{"Compounding Annual Return", "76.267%"},
{"Drawdown", "77.100%"},
{"Expectancy", "-0.012"},
{"Net Profit", "4.768%"},
{"Sharpe Ratio", "1.01909630017278E+24"},
{"Probabilistic Sharpe Ratio", "93.814%"},
{"Loss Rate", "75%"},
{"Win Rate", "25%"},
{"Profit-Loss Ratio", "2.95"},
{"Alpha", "1.3466330963256E+25"},
{"Beta", "25.59"},
{"Annual Standard Deviation", "13.214"},
{"Annual Variance", "174.61"},
{"Information Ratio", "1.02164274756513E+24"},
{"Tracking Error", "13.181"},
{"Treynor Ratio", "5.2622435344112E+23"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$1300000.00"},
{"Fitness Score", "0.38"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.239"},
{"Return Over Maximum Drawdown", "-1.385"},
{"Portfolio Turnover", "81.433"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "6a779e7a8d12b4808845c75b88d43b3a"}
};
}
}

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.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Scalps EURUSD using an EMA cross strategy at minute resolution.
/// This tests FOREX strategies that trade at a higher frequency, which
/// should have a reduced capacity estimate as a result.
/// </summary>
public class IntradayMinuteScalpingEURUSD : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _eurusd;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
public override void Initialize()
{
SetStartDate(2021, 1, 1);
SetEndDate(2021, 1, 30);
SetCash(100000);
SetWarmup(100);
_eurusd = AddForex("EURUSD", Resolution.Minute, Market.Oanda).Symbol;
_fast = EMA(_eurusd, 20);
_slow = EMA(_eurusd, 40);
}
public override void OnData(Slice data)
{
if (Portfolio[_eurusd].Quantity <= 0 && _fast > _slow)
{
SetHoldings(_eurusd, 1);
}
else if (Portfolio[_eurusd].Quantity >= 0 && _fast < _slow)
{
SetHoldings(_eurusd, -1);
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "671"},
{"Average Win", "0.07%"},
{"Average Loss", "-0.04%"},
{"Compounding Annual Return", "-80.820%"},
{"Drawdown", "12.200%"},
{"Expectancy", "-0.447"},
{"Net Profit", "-12.180%"},
{"Sharpe Ratio", "-13.121"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "79%"},
{"Win Rate", "21%"},
{"Profit-Loss Ratio", "1.61"},
{"Alpha", "-0.746"},
{"Beta", "-0.02"},
{"Annual Standard Deviation", "0.057"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-4.046"},
{"Tracking Error", "0.161"},
{"Treynor Ratio", "37.346"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$44000000.00"},
{"Fitness Score", "0.025"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-16.609"},
{"Return Over Maximum Drawdown", "-7.115"},
{"Portfolio Turnover", "52.476"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "74ee44736b9300c0262dc75c0cd140e1"}
};
}
}

View File

@@ -0,0 +1,143 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Scalps ES futures contracts (E-mini SP500) using an EMA cross strategy at minute resolution.
/// This tests futures strategies that trade at a higher frequency, which
/// should have a reduced capacity estimate as a result.
/// </summary>
/// <remarks>
/// The insanely high capacity estimate of this strategy is realistic.
/// ES notional contract value traded is around $600 Billion USD per day (!!!), which
/// is what the capacity is set to.
/// </remarks>
public class IntradayMinuteScalpingFuturesES : QCAlgorithm, IRegressionAlgorithmDefinition
{
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
private Symbol _contract;
public override void Initialize()
{
SetStartDate(2021, 1, 1);
SetEndDate(2021, 1, 31);
SetCash(100000);
SetWarmup(1000);
var a = AddFuture("ES", Resolution.Minute, Market.CME);
a.SetFilter(0, 10000);
}
public override void OnData(Slice data)
{
var contract = data.FutureChains.Values.SelectMany(c => c.Contracts.Values)
.OrderBy(c => c.Symbol.ID.Date)
.FirstOrDefault()?
.Symbol;
if (contract == null)
{
return;
}
if (_contract != contract || (_fast == null && _slow == null))
{
_fast = EMA(contract, 10);
_slow = EMA(contract, 20);
_contract = contract;
}
if (!_fast.IsReady || !_slow.IsReady)
{
return;
}
if (!Portfolio.ContainsKey(contract) || (Portfolio[contract].Quantity <= 0 && _fast > _slow))
{
SetHoldings(contract, 1);
}
else if (Portfolio.ContainsKey(contract) && Portfolio[contract].Quantity >= 0 && _fast < _slow)
{
SetHoldings(contract, -1);
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1217"},
{"Average Win", "2.69%"},
{"Average Loss", "-0.93%"},
{"Compounding Annual Return", "-99.756%"},
{"Drawdown", "77.200%"},
{"Expectancy", "-0.047"},
{"Net Profit", "-40.013%"},
{"Sharpe Ratio", "-0.52"},
{"Probabilistic Sharpe Ratio", "19.865%"},
{"Loss Rate", "75%"},
{"Win Rate", "25%"},
{"Profit-Loss Ratio", "2.88"},
{"Alpha", "-1.279"},
{"Beta", "-3.686"},
{"Annual Standard Deviation", "1.85"},
{"Annual Variance", "3.422"},
{"Information Ratio", "-0.463"},
{"Tracking Error", "1.895"},
{"Treynor Ratio", "0.261"},
{"Total Fees", "$19843.10"},
{"Estimated Strategy Capacity", "$560000000.00"},
{"Fitness Score", "0.334"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.837"},
{"Return Over Maximum Drawdown", "-1.402"},
{"Portfolio Turnover", "1174.125"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "f353843132df7b0604eff3a37b134ca2"}
};
}
}

View File

@@ -0,0 +1,118 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Scalps GBPJPY using an EMA cross strategy at minute resolution.
/// This tests FOREX strategies that trade at a higher frequency, which
/// should have a reduced capacity estimate as a result. This test also
/// tests that currency conversion rates are applied and calculated correctly.
/// </summary>
public class IntradayMinuteScalpingGBPJPY : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _gbpjpy;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
public override void Initialize()
{
SetStartDate(2021, 1, 1);
SetEndDate(2021, 1, 30);
SetCash(100000);
SetWarmup(100);
_gbpjpy = AddForex("GBPJPY", Resolution.Minute, Market.Oanda).Symbol;
_fast = EMA(_gbpjpy, 20);
_slow = EMA(_gbpjpy, 40);
}
public override void OnData(Slice data)
{
if (Portfolio[_gbpjpy].Quantity <= 0 && _fast > _slow)
{
SetHoldings(_gbpjpy, 1);
}
else if (Portfolio[_gbpjpy].Quantity >= 0 && _fast < _slow)
{
SetHoldings(_gbpjpy, -1);
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "735"},
{"Average Win", "0.08%"},
{"Average Loss", "-0.05%"},
{"Compounding Annual Return", "-93.946%"},
{"Drawdown", "19.900%"},
{"Expectancy", "-0.592"},
{"Net Profit", "-19.794%"},
{"Sharpe Ratio", "-10.054"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "84%"},
{"Win Rate", "16%"},
{"Profit-Loss Ratio", "1.56"},
{"Alpha", "-0.895"},
{"Beta", "0.068"},
{"Annual Standard Deviation", "0.09"},
{"Annual Variance", "0.008"},
{"Information Ratio", "-4.929"},
{"Tracking Error", "0.164"},
{"Treynor Ratio", "-13.276"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$49000000.00"},
{"Fitness Score", "0.049"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-10.846"},
{"Return Over Maximum Drawdown", "-4.904"},
{"Portfolio Turnover", "58.921"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "66f04c9622ab242993c8ce951418e6d9"}
};
}
}

View File

@@ -0,0 +1,118 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Scalps TRYJPY using an EMA cross strategy at minute resolution.
/// This tests FOREX strategies that trade at a higher frequency, which
/// should have a reduced capacity estimate as a result. This tests that
/// currency conversions are applied properly to the capacity estimate calculation.
/// </summary>
public class IntradayMinuteScalpingTRYJPY : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _tryjpy;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
public override void Initialize()
{
SetStartDate(2021, 1, 1);
SetEndDate(2021, 1, 30);
SetCash(100000);
SetWarmup(100);
_tryjpy = AddForex("TRYJPY", Resolution.Minute, Market.Oanda).Symbol;
_fast = EMA(_tryjpy, 20);
_slow = EMA(_tryjpy, 40);
}
public override void OnData(Slice data)
{
if (Portfolio[_tryjpy].Quantity <= 0 && _fast > _slow)
{
SetHoldings(_tryjpy, 1);
}
else if (Portfolio[_tryjpy].Quantity >= 0 && _fast < _slow)
{
SetHoldings(_tryjpy, -1);
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "603"},
{"Average Win", "0.20%"},
{"Average Loss", "-0.26%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "73.200%"},
{"Expectancy", "-0.849"},
{"Net Profit", "-73.118%"},
{"Sharpe Ratio", "-2.046"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "91%"},
{"Win Rate", "9%"},
{"Profit-Loss Ratio", "0.75"},
{"Alpha", "-0.95"},
{"Beta", "0.541"},
{"Annual Standard Deviation", "0.489"},
{"Annual Variance", "0.239"},
{"Information Ratio", "-1.863"},
{"Tracking Error", "0.487"},
{"Treynor Ratio", "-1.849"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$4400000.00"},
{"Fitness Score", "0.259"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-2.135"},
{"Return Over Maximum Drawdown", "-1.389"},
{"Portfolio Turnover", "49.501"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "4eb4d703a9f200b6bb3d8b0ebbc9db7f"}
};
}
}

View File

@@ -0,0 +1,111 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Rebalances ultra-liquid stocks monthly, testing
/// bursts of orders centered around the start of the month at Daily resolution
/// </summary>
public class MonthlyRebalanceDaily : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2019, 12, 31);
SetEndDate(2020, 4, 5);
SetCash(100000);
var spy = AddEquity("SPY", Resolution.Daily).Symbol;
AddEquity("GE", Resolution.Daily);
AddEquity("FB", Resolution.Daily);
AddEquity("DIS", Resolution.Daily);
AddEquity("CSCO", Resolution.Daily);
AddEquity("CRM", Resolution.Daily);
AddEquity("C", Resolution.Daily);
AddEquity("BAC", Resolution.Daily);
AddEquity("BABA", Resolution.Daily);
AddEquity("AAPL", Resolution.Daily);
Schedule.On(DateRules.MonthStart(spy), TimeRules.Noon, () =>
{
foreach (var symbol in Securities.Keys)
{
SetHoldings(symbol, 0.10);
}
});
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "35"},
{"Average Win", "0.07%"},
{"Average Loss", "-0.07%"},
{"Compounding Annual Return", "-68.407%"},
{"Drawdown", "32.400%"},
{"Expectancy", "-0.309"},
{"Net Profit", "-25.901%"},
{"Sharpe Ratio", "-1.503"},
{"Probabilistic Sharpe Ratio", "2.878%"},
{"Loss Rate", "64%"},
{"Win Rate", "36%"},
{"Profit-Loss Ratio", "0.90"},
{"Alpha", "-0.7"},
{"Beta", "-0.238"},
{"Annual Standard Deviation", "0.386"},
{"Annual Variance", "0.149"},
{"Information Ratio", "-0.11"},
{"Tracking Error", "0.712"},
{"Treynor Ratio", "2.442"},
{"Total Fees", "$38.99"},
{"Estimated Strategy Capacity", "$19000000.00"},
{"Fitness Score", "0.003"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-2.021"},
{"Return Over Maximum Drawdown", "-2.113"},
{"Portfolio Turnover", "0.014"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "76d8164a3c0d4a7d45e94367c4ba5be1"}
};
}
}

View File

@@ -0,0 +1,111 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Rebalances ultra-liquid stocks monthly, testing
/// bursts of orders centered around the start of the month at Hourly resolution
/// </summary>
public class MonthlyRebalanceHourly : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2019, 12, 31);
SetEndDate(2020, 4, 5);
SetCash(100000);
var spy = AddEquity("SPY", Resolution.Hour).Symbol;
AddEquity("GE", Resolution.Hour);
AddEquity("FB", Resolution.Hour);
AddEquity("DIS", Resolution.Hour);
AddEquity("CSCO", Resolution.Hour);
AddEquity("CRM", Resolution.Hour);
AddEquity("C", Resolution.Hour);
AddEquity("BAC", Resolution.Hour);
AddEquity("BABA", Resolution.Hour);
AddEquity("AAPL", Resolution.Hour);
Schedule.On(DateRules.MonthStart(spy), TimeRules.Noon, () =>
{
foreach (var symbol in Securities.Keys)
{
SetHoldings(symbol, 0.10);
}
});
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "35"},
{"Average Win", "0.05%"},
{"Average Loss", "-0.10%"},
{"Compounding Annual Return", "-72.444%"},
{"Drawdown", "36.500%"},
{"Expectancy", "-0.449"},
{"Net Profit", "-28.406%"},
{"Sharpe Ratio", "-1.369"},
{"Probabilistic Sharpe Ratio", "4.398%"},
{"Loss Rate", "64%"},
{"Win Rate", "36%"},
{"Profit-Loss Ratio", "0.51"},
{"Alpha", "-0.175"},
{"Beta", "0.892"},
{"Annual Standard Deviation", "0.503"},
{"Annual Variance", "0.253"},
{"Information Ratio", "-0.822"},
{"Tracking Error", "0.138"},
{"Treynor Ratio", "-0.772"},
{"Total Fees", "$38.83"},
{"Estimated Strategy Capacity", "$6000000.00"},
{"Fitness Score", "0.004"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-2.033"},
{"Return Over Maximum Drawdown", "-2.079"},
{"Portfolio Turnover", "0.018"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1de9bcf6cda0945af6ba1f74c4dcb22c"}
};
}
}

View File

@@ -0,0 +1,112 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Tests that splits do not cause the algorithm to report capacity estimates
/// above or below the actual capacity due to splits. The stock HTGM is illiquid,
/// trading only $1.2 Million per day on average with sparse trade frequencies.
/// </summary>
public class SplitTestingStrategy : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _htgm;
public override void Initialize()
{
SetStartDate(2020, 11, 1);
SetEndDate(2020, 12, 5);
SetCash(100000);
var htgm = AddEquity("HTGM", Resolution.Hour);
htgm.SetDataNormalizationMode(DataNormalizationMode.Raw);
_htgm = htgm.Symbol;
}
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
SetHoldings(_htgm, 1);
}
else
{
SetHoldings(_htgm, -1);
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "162"},
{"Average Win", "0.10%"},
{"Average Loss", "-0.35%"},
{"Compounding Annual Return", "-94.432%"},
{"Drawdown", "30.400%"},
{"Expectancy", "-0.564"},
{"Net Profit", "-23.412%"},
{"Sharpe Ratio", "-1.041"},
{"Probabilistic Sharpe Ratio", "12.971%"},
{"Loss Rate", "66%"},
{"Win Rate", "34%"},
{"Profit-Loss Ratio", "0.29"},
{"Alpha", "-4.827"},
{"Beta", "1.43"},
{"Annual Standard Deviation", "0.876"},
{"Annual Variance", "0.767"},
{"Information Ratio", "-4.288"},
{"Tracking Error", "0.851"},
{"Treynor Ratio", "-0.637"},
{"Total Fees", "$2655.91"},
{"Estimated Strategy Capacity", "$11000.00"},
{"Fitness Score", "0.052"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-2.2"},
{"Return Over Maximum Drawdown", "-3.481"},
{"Portfolio Turnover", "0.307"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "54f571c11525656e9b383e235e77002e"}
};
}
}

View File

@@ -0,0 +1,103 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Rebalances between SPY and BND. Tests capacity of the weakest link, which in this
/// case is BND, dragging down the capacity estimate.
/// </summary>
public class SpyBondPortfolioRebalance : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spy;
public override void Initialize()
{
SetStartDate(2020, 1, 1);
SetEndDate(2020, 3, 31);
SetCash(10000);
_spy = AddEquity("SPY", Resolution.Hour).Symbol;
var bnd = AddEquity("BND", Resolution.Hour).Symbol;
Schedule.On(DateRules.EveryDay(_spy), TimeRules.AfterMarketOpen(_spy, 1, false), () =>
{
SetHoldings(_spy, 0.5m);
SetHoldings(bnd, 0.5m);
});
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "21"},
{"Average Win", "0.02%"},
{"Average Loss", "-0.03%"},
{"Compounding Annual Return", "-33.564%"},
{"Drawdown", "19.700%"},
{"Expectancy", "-0.140"},
{"Net Profit", "-9.655%"},
{"Sharpe Ratio", "-0.99"},
{"Probabilistic Sharpe Ratio", "13.754%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.72"},
{"Alpha", "-0.022"},
{"Beta", "0.538"},
{"Annual Standard Deviation", "0.309"},
{"Annual Variance", "0.096"},
{"Information Ratio", "0.826"},
{"Tracking Error", "0.269"},
{"Treynor Ratio", "-0.569"},
{"Total Fees", "$21.00"},
{"Estimated Strategy Capacity", "$1100000.00"},
{"Fitness Score", "0.005"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-1.524"},
{"Return Over Maximum Drawdown", "-1.688"},
{"Portfolio Turnover", "0.02"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "95a130426900aaf227a08a5d1c617b2b"}
};
}
}

View File

@@ -95,6 +95,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0.5"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -114,7 +115,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1456907343"}
{"OrderListHash", "6ea6184a2a8d0d69e552ad866933bfb6"}
};
}
}

View File

@@ -181,6 +181,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.149"},
{"Treynor Ratio", "-1.405"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$6000000.00"},
{"Fitness Score", "0.076"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -200,7 +201,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1465929889"}
{"OrderListHash", "edd9e9ffc8a1cdfb7a1e6ae601e61b12"}
};
}
}

View File

@@ -164,6 +164,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "3.579"},
{"Treynor Ratio", "383485597312030"},
{"Total Fees", "$13.00"},
{"Estimated Strategy Capacity", "$3000000.00"},
{"Fitness Score", "0.232"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -183,7 +184,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1630141557"}
{"OrderListHash", "12470afd9a74ad9c9802361f6f092777"}
};
}
}

View File

@@ -136,6 +136,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.126"},
{"Treynor Ratio", "-0.607"},
{"Total Fees", "$11.63"},
{"Estimated Strategy Capacity", "$13000000.00"},
{"Fitness Score", "0.013"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -155,7 +156,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1623759093"}
{"OrderListHash", "3d1ae61492b34c39115b76757510c058"}
};
}
}

View File

@@ -114,6 +114,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.096"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -133,7 +134,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "371857150"}
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -120,6 +120,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.105"},
{"Treynor Ratio", "1.667"},
{"Total Fees", "$2.91"},
{"Estimated Strategy Capacity", "$96000000.00"},
{"Fitness Score", "0.141"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -139,7 +140,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1959413055"}
{"OrderListHash", "718d73fbddccb63aeacbf4659938b4b8"}
};
}
}

View File

@@ -91,6 +91,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.101"},
{"Treynor Ratio", "5.409"},
{"Total Fees", "$67.00"},
{"Estimated Strategy Capacity", "$2400000.00"},
{"Fitness Score", "0.501"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -110,7 +111,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-28636839"}
{"OrderListHash", "ba44309886ea8ff515ef593a24456c47"}
};
}
}

View File

@@ -85,6 +85,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.009"},
{"Treynor Ratio", "1.575"},
{"Total Fees", "$22.77"},
{"Estimated Strategy Capacity", "$19000000.00"},
{"Fitness Score", "0.999"},
{"Kelly Criterion Estimate", "38.64"},
{"Kelly Criterion Probability Value", "0.229"},
@@ -104,7 +105,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"},
{"OrderListHash", "-1225025518"}
{"OrderListHash", "e0f388bf9e88b34388c866150b292573"}
};
}
}

View File

@@ -94,6 +94,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.165"},
{"Treynor Ratio", "1.212"},
{"Total Fees", "$6.00"},
{"Estimated Strategy Capacity", "$32000000.00"},
{"Fitness Score", "0.063"},
{"Kelly Criterion Estimate", "38.64"},
{"Kelly Criterion Probability Value", "0.229"},
@@ -113,7 +114,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"},
{"OrderListHash", "501060991"}
{"OrderListHash", "07eb3e2c199575b547459a534057eb5e"}
};
}
}

View File

@@ -164,6 +164,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.441"},
{"Treynor Ratio", "-0.008"},
{"Total Fees", "$20.35"},
{"Estimated Strategy Capacity", "$19000000.00"},
{"Fitness Score", "0.138"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -183,7 +184,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1453269600"}
{"OrderListHash", "7c841ca58a4385f42236838e5bf0c382"}
};
}
}

View File

@@ -190,6 +190,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.176"},
{"Treynor Ratio", "-1.46"},
{"Total Fees", "$7.82"},
{"Estimated Strategy Capacity", "$6000000.00"},
{"Fitness Score", "0.1"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -209,7 +210,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-611289773"}
{"OrderListHash", "71984e154883ece4aef1d71bafbfccaf"}
};
}
}

View File

@@ -144,8 +144,9 @@ namespace QuantConnect.Algorithm.CSharp
{"Annual Variance", "0.027"},
{"Information Ratio", "-0.391"},
{"Tracking Error", "0.239"},
{"Treynor Ratio", "-1.416"},
{"Treynor Ratio", "-1.435"},
{"Total Fees", "$755.29"},
{"Estimated Strategy Capacity", "$150000000.00"},
{"Fitness Score", "0.024"},
{"Kelly Criterion Estimate", "-0.84"},
{"Kelly Criterion Probability Value", "0.53"},
@@ -165,7 +166,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "48.2217%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1370210213"}
{"OrderListHash", "95f34359f25a7a7a2725f0343a75a105"}
};
}
}

View File

@@ -38,6 +38,10 @@ namespace QuantConnect.Algorithm.CSharp
// Find more symbols here: http://quantconnect.com/data
AddSecurity(SecurityType.Equity, "SPY", Resolution.Second);
// Disabling the benchmark / setting to a fixed value
// SetBenchmark(time => 0);
// Set the benchmark to AAPL US Equity
SetBenchmark("AAPL");
}
@@ -95,6 +99,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.168"},
{"Treynor Ratio", "2.38"},
{"Total Fees", "$3.26"},
{"Estimated Strategy Capacity", "$75000000.00"},
{"Fitness Score", "0.245"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -114,7 +119,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "2069976135"}
{"OrderListHash", "9cd604d2c1e3c273697e2ff2cc7faef1"}
};
}
}

View File

@@ -96,6 +96,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0.988"},
{"Total Fees", "$7.78"},
{"Estimated Strategy Capacity", "$2200000.00"},
{"Fitness Score", "0.031"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -115,7 +116,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "519536519"}
{"OrderListHash", "be3334e4aeb9dd7cca4ecc07419d0f95"}
};
}
}

View File

@@ -113,6 +113,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "1.04"},
{"Treynor Ratio", "5.073"},
{"Total Fees", "$30.00"},
{"Estimated Strategy Capacity", "$2800000.00"},
{"Fitness Score", "0.418"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -132,7 +133,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "639761089"}
{"OrderListHash", "b88362c462e9ab2942cbcb8dfddc6ce0"}
};
}
}

View File

@@ -119,6 +119,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.112"},
{"Treynor Ratio", "-6.121"},
{"Total Fees", "$3.50"},
{"Estimated Strategy Capacity", "$6900000.00"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -138,7 +139,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "559673838"}
{"OrderListHash", "6b05339bfcb5bd93bfd66e32a1d2181a"}
};
}
}

View File

@@ -124,6 +124,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.112"},
{"Treynor Ratio", "-6.121"},
{"Total Fees", "$3.50"},
{"Estimated Strategy Capacity", "$6900000.00"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -143,7 +144,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "559673838"}
{"OrderListHash", "6b05339bfcb5bd93bfd66e32a1d2181a"}
};
}
}

View File

@@ -131,6 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.19"},
{"Treynor Ratio", "2.159"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$14000000.00"},
{"Fitness Score", "0.1"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -150,7 +151,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1531253381"}
{"OrderListHash", "214f38f9084bc350c93010aa2fb69822"}
};
}
}

View File

@@ -0,0 +1,261 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression test to demonstrate setting custom Symbol Properties and Market Hours for a custom data import
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="custom data" />
/// <meta name="tag" content="crypto" />
/// <meta name="tag" content="regression test" />
public class CustomDataPropertiesRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private string _ticker = "BTC";
private Security _bitcoin;
/// <summary>
/// Initialize the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2011, 9, 13);
SetEndDate(2015, 12, 01);
//Set the cash for the strategy:
SetCash(100000);
// Define our custom data properties and exchange hours
var properties = new SymbolProperties("Bitcoin", "USD", 1, 0.01m, 0.01m, _ticker);
var exchangeHours = SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork);
// Add the custom data to our algorithm with our custom properties and exchange hours
_bitcoin = AddData<Bitcoin>(_ticker, properties, exchangeHours);
//Verify our symbol properties were changed and loaded into this security
if (_bitcoin.SymbolProperties != properties)
{
throw new Exception("Failed to set and retrieve custom SymbolProperties for BTC");
}
//Verify our exchange hours were changed and loaded into this security
if (_bitcoin.Exchange.Hours != exchangeHours)
{
throw new Exception("Failed to set and retrieve custom ExchangeHours for BTC");
}
// For regression purposes on AddData overloads, this call is simply to ensure Lean can accept this
// with default params and is not routed to a breaking function.
AddData<Bitcoin>("BTCUSD");
}
/// <summary>
/// Event Handler for Bitcoin Data Events: These Bitcoin objects are created from our
/// "Bitcoin" type below and fired into this event handler.
/// </summary>
/// <param name="data">One(1) Bitcoin Object, streamed into our algorithm synchronized in time with our other data streams</param>
public void OnData(Bitcoin data)
{
//If we don't have any bitcoin "SHARES" -- invest"
if (!Portfolio.Invested)
{
//Bitcoin used as a tradable asset, like stocks, futures etc.
if (data.Close != 0)
{
//Access custom data symbols using <ticker>.<custom-type>
Order("BTC.Bitcoin", Portfolio.MarginRemaining / Math.Abs(data.Close + 1));
}
}
}
public override void OnEndOfAlgorithm()
{
// Reset our Symbol property value, for testing purposes.
SymbolPropertiesDatabase.SetEntry(Market.USA, MarketHoursDatabase.GetDatabaseSymbolKey(_bitcoin.Symbol), SecurityType.Base,
SymbolProperties.GetDefault("USD"));
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "155.262%"},
{"Drawdown", "84.800%"},
{"Expectancy", "0"},
{"Net Profit", "5123.242%"},
{"Sharpe Ratio", "2.067"},
{"Probabilistic Sharpe Ratio", "68.833%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.732"},
{"Beta", "0.037"},
{"Annual Standard Deviation", "0.841"},
{"Annual Variance", "0.707"},
{"Information Ratio", "1.902"},
{"Tracking Error", "0.848"},
{"Treynor Ratio", "46.992"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "2.238"},
{"Return Over Maximum Drawdown", "1.832"},
{"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", "1f54fb75ebcc0daafa5d45bfbaa4fbcb"}
};
/// <summary>
/// Custom Data Type: Bitcoin data from Quandl - http://www.quandl.com/help/api-for-bitcoin-data
/// </summary>
public class Bitcoin : BaseData
{
[JsonProperty("timestamp")]
public int Timestamp = 0;
[JsonProperty("open")]
public decimal Open = 0;
[JsonProperty("high")]
public decimal High = 0;
[JsonProperty("low")]
public decimal Low = 0;
[JsonProperty("last")]
public decimal Close = 0;
[JsonProperty("bid")]
public decimal Bid = 0;
[JsonProperty("ask")]
public decimal Ask = 0;
[JsonProperty("vwap")]
public decimal WeightedPrice = 0;
[JsonProperty("volume")]
public decimal VolumeBTC = 0;
public decimal VolumeUSD = 0;
/// <summary>
/// 1. DEFAULT CONSTRUCTOR: Custom data types need a default constructor.
/// We search for a default constructor so please provide one here. It won't be used for data, just to generate the "Factory".
/// </summary>
public Bitcoin()
{
Symbol = "BTC";
}
/// <summary>
/// 2. RETURN THE STRING URL SOURCE LOCATION FOR YOUR DATA:
/// This is a powerful and dynamic select source file method. If you have a large dataset, 10+mb we recommend you break it into smaller files. E.g. One zip per year.
/// We can accept raw text or ZIP files. We read the file extension to determine if it is a zip file.
/// </summary>
/// <param name="config">Configuration object</param>
/// <param name="date">Date of this source file</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>String URL of source file.</returns>
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
if (isLiveMode)
{
return new SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.Rest);
}
//return "http://my-ftp-server.com/futures-data-" + date.ToString("Ymd") + ".zip";
// OR simply return a fixed small data file. Large files will slow down your backtest
return new SubscriptionDataSource("https://www.quantconnect.com/api/v2/proxy/quandl/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc&api_key=WyAazVXnq7ATy_fefTqm", SubscriptionTransportMedium.RemoteFile);
}
/// <summary>
/// 3. READER METHOD: Read 1 line from data source and convert it into Object.
/// Each line of the CSV File is presented in here. The backend downloads your file, loads it into memory and then line by line
/// feeds it into your algorithm
/// </summary>
/// <param name="line">string line from the data source file submitted above</param>
/// <param name="config">Subscription data, symbol name, data type</param>
/// <param name="date">Current date we're requesting. This allows you to break up the data source into daily files.</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>New Bitcoin Object which extends BaseData.</returns>
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
var coin = new Bitcoin();
if (isLiveMode)
{
//Example Line Format:
//{"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"}
try
{
coin = JsonConvert.DeserializeObject<Bitcoin>(line);
coin.EndTime = DateTime.UtcNow.ConvertFromUtc(config.ExchangeTimeZone);
coin.Value = coin.Close;
}
catch { /* Do nothing, possible error in json decoding */ }
return coin;
}
//Example Line Format:
//Date Open High Low Close Volume (BTC) Volume (Currency) Weighted Price
//2011-09-13 5.8 6.0 5.65 5.97 58.37138238, 346.0973893944 5.929230648356
try
{
string[] data = line.Split(',');
coin.Time = DateTime.Parse(data[0], CultureInfo.InvariantCulture);
coin.Open = Convert.ToDecimal(data[1], CultureInfo.InvariantCulture);
coin.High = Convert.ToDecimal(data[2], CultureInfo.InvariantCulture);
coin.Low = Convert.ToDecimal(data[3], CultureInfo.InvariantCulture);
coin.Close = Convert.ToDecimal(data[4], CultureInfo.InvariantCulture);
coin.VolumeBTC = Convert.ToDecimal(data[5], CultureInfo.InvariantCulture);
coin.VolumeUSD = Convert.ToDecimal(data[6], CultureInfo.InvariantCulture);
coin.WeightedPrice = Convert.ToDecimal(data[7], CultureInfo.InvariantCulture);
coin.Value = coin.Close;
}
catch { /* Do nothing, skip first title row */ }
return coin;
}
}
}
}

View File

@@ -101,6 +101,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.848"},
{"Treynor Ratio", "46.996"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -120,7 +121,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-541549381"}
{"OrderListHash", "0e7d560d0db2829adb19d3e403c30d97"}
};
/// <summary>

View File

@@ -141,6 +141,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.726"},
{"Treynor Ratio", "0.142"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0.127"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -160,7 +161,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1014157203"}
{"OrderListHash", "1c319ae4b15416184a247bb47b31aabc"}
};
/// <summary>

View File

@@ -212,6 +212,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.118"},
{"Treynor Ratio", "-0.591"},
{"Total Fees", "$62.24"},
{"Estimated Strategy Capacity", "$100000000.00"},
{"Fitness Score", "0.147"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -231,7 +232,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "852026186"}
{"OrderListHash", "71c17655bd0731eb25433727526e95ba"}
};
}
}

View File

@@ -103,6 +103,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.251"},
{"Treynor Ratio", "9.323"},
{"Total Fees", "$3.26"},
{"Estimated Strategy Capacity", "$220000000.00"},
{"Fitness Score", "0.201"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -122,7 +123,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1268340653"}
{"OrderListHash", "82fee25cd17100c53bb173834ab5f0b2"}
};
}
}

View File

@@ -193,6 +193,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.211"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -212,7 +213,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "371857150"}
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -118,6 +118,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.183"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -137,7 +138,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "371857150"}
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -118,6 +118,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.212"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -137,7 +138,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "371857150"}
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -16,7 +16,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NodaTime;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
@@ -45,7 +44,26 @@ namespace QuantConnect.Algorithm.CSharp
for (int i = 0; i < _symbols.Length; i++)
{
var symbol = _symbols[i];
var history = History<QuoteBar>(symbol, 10, Resolution.Daily);
IEnumerable<BaseData> history;
if (symbol.SecurityType == SecurityType.Equity)
{
try
{
history = History<QuoteBar>(symbol, 10, Resolution.Daily).Select(bar => bar as BaseData);
throw new Exception("We were expecting an argument exception to be thrown. Equity does not have daily QuoteBars!");
}
catch (ArgumentException)
{
// expected
}
history = History<TradeBar>(symbol, 10, Resolution.Daily).Select(bar => bar as BaseData);
}
else
{
history = History<QuoteBar>(symbol, 10, Resolution.Daily)
.Select(bar => bar as BaseData);
}
var duplications = history
.GroupBy(k => k.Time)
@@ -93,6 +111,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -112,7 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "371857150"}
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -136,6 +136,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -155,7 +156,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "371857150"}
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -100,25 +100,26 @@ namespace QuantConnect.Algorithm.CSharp
{"Drawdown", "1.300%"},
{"Expectancy", "0"},
{"Net Profit", "1.634%"},
{"Sharpe Ratio", "2.476"},
{"Probabilistic Sharpe Ratio", "92.194%"},
{"Sharpe Ratio", "2.495"},
{"Probabilistic Sharpe Ratio", "92.298%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.006"},
{"Beta", "0.158"},
{"Annual Standard Deviation", "0.032"},
{"Annual Standard Deviation", "0.033"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-4.89"},
{"Information Ratio", "-4.942"},
{"Tracking Error", "0.08"},
{"Treynor Ratio", "0.509"},
{"Treynor Ratio", "0.517"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$38000000.00"},
{"Fitness Score", "0.019"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "1.362"},
{"Return Over Maximum Drawdown", "9.699"},
{"Portfolio Turnover", "0.022"},
{"Portfolio Turnover", "0.023"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -132,7 +133,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1252326142"}
{"OrderListHash", "00d6dc8775da38f7f79defad06de240a"}
};
}
}

View File

@@ -45,7 +45,7 @@ namespace QuantConnect.Algorithm.CSharp
SetEndDate(2007, 05, 25); //Set End Date
SetCash(100000); //Set Strategy Cash
// Find more symbols here: http://quantconnect.com/data
AddSecurity(SecurityType.Equity, "AAA", Resolution.Daily);
AddSecurity(SecurityType.Equity, "AAA.1", Resolution.Daily);
AddSecurity(SecurityType.Equity, "SPY", Resolution.Daily);
}
@@ -58,7 +58,7 @@ namespace QuantConnect.Algorithm.CSharp
_dataCount += data.Bars.Count;
if (Transactions.OrdersCount == 0)
{
SetHoldings("AAA", 1);
SetHoldings("AAA.1", 1);
Debug("Purchased Stock");
}
@@ -71,7 +71,7 @@ namespace QuantConnect.Algorithm.CSharp
// the slice can also contain delisting data: data.Delistings in a dictionary string->Delisting
var aaa = Securities["AAA"];
var aaa = Securities["AAA.1"];
if (aaa.IsDelisted && aaa.IsTradable)
{
throw new Exception("Delisted security must NOT be tradable");
@@ -160,6 +160,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.155"},
{"Treynor Ratio", "1.589"},
{"Total Fees", "$55.05"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -179,7 +180,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-2022527947"}
{"OrderListHash", "61f4d3c109fc4b6b9eb14d2e4eec4843"}
};
}
}

View File

@@ -0,0 +1,149 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using System.Collections.Generic;
using System.Linq;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm reproducing issue #5160 where delisting order would be cancelled because it was placed at the market close on the delisting day
/// </summary>
public class DelistingFutureOptionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private bool _traded;
private int _lastMonth;
public override void Initialize()
{
SetStartDate(2012, 1, 1);
SetEndDate(2013, 1, 1);
SetCash(10000000);
var dc = AddFuture(Futures.Dairy.ClassIIIMilk, Resolution.Minute, Market.CME);
dc.SetFilter(1, 120);
AddFutureOption(dc.Symbol, universe => universe.Strikes(-2, 2));
_lastMonth = -1;
}
public override void OnData(Slice data)
{
if (Time.Month != _lastMonth)
{
_lastMonth = Time.Month;
var investedSymbols = Securities.Values
.Where(security => security.Invested)
.Select(security => security.Symbol)
.ToList();
var delistedSecurity = investedSymbols.Where(symbol => symbol.ID.Date.AddDays(1) < Time).ToList();
if (delistedSecurity.Count > 0)
{
throw new Exception($"[{UtcTime}] We hold a delisted securities: {string.Join(",", delistedSecurity)}");
}
Log($"Holdings({Time}): {string.Join(",", investedSymbols)}");
}
if (Portfolio.Invested)
{
return;
}
foreach (var chain in data.OptionChains.Values)
{
foreach (var contractsValue in chain.Contracts.Values)
{
MarketOrder(contractsValue.Symbol, 1);
_traded = true;
}
}
}
public override void OnEndOfAlgorithm()
{
if (!_traded)
{
throw new Exception("We expected some FOP trading to happen");
}
if (Portfolio.Invested)
{
throw new Exception("We shouldn't be invested anymore");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "16"},
{"Average Win", "0.01%"},
{"Average Loss", "-0.02%"},
{"Compounding Annual Return", "-0.111%"},
{"Drawdown", "0.100%"},
{"Expectancy", "-0.679"},
{"Net Profit", "-0.112%"},
{"Sharpe Ratio", "-1.052"},
{"Probabilistic Sharpe Ratio", "0.000%"},
{"Loss Rate", "80%"},
{"Win Rate", "20%"},
{"Profit-Loss Ratio", "0.61"},
{"Alpha", "-0.001"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.187"},
{"Tracking Error", "0.115"},
{"Treynor Ratio", "1.545"},
{"Total Fees", "$37.00"},
{"Estimated Strategy Capacity", "$58000.00"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.128"},
{"Return Over Maximum Drawdown", "-0.995"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "de309ab56d2fcd80ff03df2802d9feda"}
};
}
}

View File

@@ -186,6 +186,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.204"},
{"Treynor Ratio", "-8.165"},
{"Total Fees", "$46.75"},
{"Estimated Strategy Capacity", "$96000000.00"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -205,7 +206,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-807056289"}
{"OrderListHash", "7c4fcd79dd817a9cd3bf44525eaed96c"}
};
}
}

View File

@@ -204,6 +204,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.171"},
{"Treynor Ratio", "-1.761"},
{"Total Fees", "$8669.41"},
{"Estimated Strategy Capacity", "$170000.00"},
{"Fitness Score", "0.675"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -223,7 +224,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-75671425"}
{"OrderListHash", "0b6746b5759ecd45ab21360fd40858bb"}
};
}
}

View File

@@ -177,6 +177,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.171"},
{"Treynor Ratio", "-1.971"},
{"Total Fees", "$6806.67"},
{"Estimated Strategy Capacity", "$150000.00"},
{"Fitness Score", "0.694"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -196,7 +197,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1142077166"}
{"OrderListHash", "a7a893a17a5afa7c2f73a444a7aea507"}
};
}
}

View File

@@ -110,6 +110,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.193"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -129,7 +130,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "371857150"}
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -91,6 +91,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$14.92"},
{"Estimated Strategy Capacity", "$85000.00"},
{"Fitness Score", "0.258"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -110,7 +111,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1296183675"}
{"OrderListHash", "21ac8e4179b36d9658f0080868c0e552"}
};
}
}

View File

@@ -131,6 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.29"},
{"Treynor Ratio", "4.005"},
{"Total Fees", "$18.28"},
{"Estimated Strategy Capacity", "$200000000.00"},
{"Fitness Score", "0.052"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -150,7 +151,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1300818910"}
{"OrderListHash", "17245c38f1b192d2041ca1f3e88250be"}
};
}
}

View File

@@ -127,6 +127,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.204"},
{"Treynor Ratio", "-1.424"},
{"Total Fees", "$16.26"},
{"Estimated Strategy Capacity", "$250000000.00"},
{"Fitness Score", "0.003"},
{"Kelly Criterion Estimate", "12.539"},
{"Kelly Criterion Probability Value", "0.367"},
@@ -146,7 +147,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "50%"},
{"Rolling Averaged Population Direction", "50%"},
{"Rolling Averaged Population Magnitude", "50%"},
{"OrderListHash", "-218498072"}
{"OrderListHash", "4178a84209934b1eb6d03c2267654f32"}
};
}
}

View File

@@ -148,6 +148,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "1.441"},
{"Treynor Ratio", "-0.15"},
{"Total Fees", "$33.30"},
{"Estimated Strategy Capacity", "$4200000.00"},
{"Fitness Score", "0.079"},
{"Kelly Criterion Estimate", "-9.366"},
{"Kelly Criterion Probability Value", "0.607"},
@@ -167,7 +168,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "25.058%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1105779454"}
{"OrderListHash", "f4c4b763b5ade918cfb7932e276d069f"}
};
}
}

View File

@@ -85,11 +85,11 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-0.500%"},
{"Drawdown", "0.000%"},
{"Average Loss", "-0.12%"},
{"Compounding Annual Return", "-9.062%"},
{"Drawdown", "0.100%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.006%"},
{"Net Profit", "-0.121%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
@@ -103,12 +103,13 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.22"},
{"Treynor Ratio", "0"},
{"Total Fees", "$6.41"},
{"Fitness Score", "0.248"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0.249"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-82.815"},
{"Portfolio Turnover", "0.497"},
{"Return Over Maximum Drawdown", "-79.031"},
{"Portfolio Turnover", "0.498"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -122,7 +123,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1213851303"}
{"OrderListHash", "af92d7f4e0810bc4a95d5ccb5542b438"}
};
}
}

View File

@@ -184,6 +184,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.123"},
{"Treynor Ratio", "-1.288"},
{"Total Fees", "$669.76"},
{"Estimated Strategy Capacity", "$8100000.00"},
{"Fitness Score", "0.021"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -203,7 +204,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1040964928"}
{"OrderListHash", "2cd87d138f8f9f5fcab28b6f983f68b1"}
};
}
}

View File

@@ -147,6 +147,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.049"},
{"Treynor Ratio", "-0.934"},
{"Total Fees", "$22.26"},
{"Estimated Strategy Capacity", "$3600000.00"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -166,7 +167,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1961710414"}
{"OrderListHash", "9f381f81ea9939f285b432207fa0d024"}
};
}
}

View File

@@ -122,6 +122,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.186"},
{"Treynor Ratio", "1.557"},
{"Total Fees", "$4.00"},
{"Estimated Strategy Capacity", "$1400000.00"},
{"Fitness Score", "0.012"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -141,7 +142,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1717552327"}
{"OrderListHash", "ee79a87e6a386f5ee620d77b7bfbd964"}
};
}
}

View File

@@ -174,6 +174,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$804.33"},
{"Estimated Strategy Capacity", "$21000.00"},
{"Fitness Score", "0.504"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -193,7 +194,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1116140375"}
{"OrderListHash", "c84d1ceacb0da30c1c1c0314f9fc850c"}
};
}
}

View File

@@ -0,0 +1,124 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression test algorithm simply fetch and compare data of minute resolution around daylight saving period
/// reproduces issue reported in GB issue GH issue https://github.com/QuantConnect/Lean/issues/4925
/// related issues https://github.com/QuantConnect/Lean/issues/3707; https://github.com/QuantConnect/Lean/issues/4630
/// </summary>
public class FillForwardEnumeratorOutOfOrderBarRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private decimal _exptectedClose = 84.09m;
private DateTime _exptectedTime = new DateTime(2008, 3, 10, 9, 30, 0);
private Symbol _shy;
/// <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(2008, 3, 7);
SetEndDate(2008, 3, 10);
_shy = AddEquity("SHY", Resolution.Minute).Symbol;
// just to make debugging easier, less subscriptions
SetBenchmark(time => 1);
}
public override void OnData(Slice slice)
{
var trackingBar = slice.Bars.Values.FirstOrDefault(s => s.Time.Equals(_exptectedTime));
if (trackingBar != null)
{
if (!Portfolio.Invested)
{
SetHoldings(_shy, 1);
}
if (trackingBar.Close != _exptectedClose)
{
throw new Exception(
$"Bar at {_exptectedTime.ToStringInvariant()} closed at price {trackingBar.Close.ToStringInvariant()}; expected {_exptectedClose.ToStringInvariant()}");
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$5.93"},
{"Estimated Strategy Capacity", "$200000.00"},
{"Fitness Score", "0.499"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-105.726"},
{"Portfolio Turnover", "0.998"},
{"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", "5315f54b62b2eaf9d587602137d641a5"}
};
}
}

View File

@@ -0,0 +1,170 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Securities.Option;
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data.Market;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm checks FillForwardEnumerator should FF the data until it reaches the delisting date
/// replicates GH issue https://github.com/QuantConnect/Lean/issues/4872
/// </summary>
public class FillForwardUntilExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private DateTime _realEndDate = new DateTime(2014, 06, 07);
private SecurityExchange _exchange;
private Dictionary<Symbol, HashSet<DateTime>> _options;
private string[] _contracts =
{
"TWX 140621P00067500",
"TWX 140621C00067500",
"TWX 140621C00070000",
"TWX 140621P00070000"
};
public override void Initialize()
{
SetStartDate(2014, 06, 05);
SetEndDate(2014, 06, 30);
_options = new Dictionary<Symbol, HashSet<DateTime>>();
var _twxOption = AddOption("TWX", Resolution.Minute);
_exchange = _twxOption.Exchange;
_twxOption.SetFilter((x) => x
.Contracts(c => c.Where(s => _contracts.Contains(s.Value))));
SetBenchmark(t => 1);
}
public override void OnData(Slice data)
{
foreach (var value in data.OptionChains.Values)
{
foreach (var contact in value.Contracts)
{
BaseData bar = null;
QuoteBar quoteBar;
if (bar == null && value.QuoteBars.TryGetValue(contact.Key, out quoteBar))
{
bar = quoteBar;
}
TradeBar tradeBar;
if (bar == null && value.TradeBars.TryGetValue(contact.Key, out tradeBar))
{
bar = tradeBar;
}
if (bar.IsFillForward)
{
_options[contact.Key].Add(value.Time.Date);
}
}
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var security in changes.AddedSecurities.OfType<Option>())
{
_options.Add(security.Symbol, new HashSet<DateTime>());
}
}
public override void OnEndOfAlgorithm()
{
if (_options.Count != _contracts.Length)
{
throw new Exception($"Options weren't setup properly. Expected: {_contracts.Length}");
}
foreach (var option in _options)
{
for (DateTime date = _realEndDate; date < option.Key.ID.Date; date = date.AddDays(1))
{
if (_exchange.Hours.IsDateOpen(date) &&
!option.Value.Contains(date))
{
throw new Exception("Delisted security should be FF until expiry date");
}
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"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

@@ -105,6 +105,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.394"},
{"Treynor Ratio", "-5.313"},
{"Total Fees", "$5.40"},
{"Estimated Strategy Capacity", "$59000000.00"},
{"Fitness Score", "0.244"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -124,7 +125,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-423205673"}
{"OrderListHash", "189eee984d524162b9676b83dab4d73c"}
};
}
}

View File

@@ -153,6 +153,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.107"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -172,7 +173,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "371857150"}
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -157,6 +157,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.107"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -176,7 +177,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "371857150"}
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

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