Compare commits

...

388 Commits

Author SHA1 Message Date
Stefano Raggi
148b9c8d45 IB Brokerage updates (#5695)
* Update IBAutomater to v2.0.39

* Downgrade IB logging level from Detail (5) to Information (4)

- The online documentation warns of performance overhead when setting logLevel=5
2021-06-23 11:34:33 -03:00
Jared
65cecef030 Update readme.md 2021-06-22 18:15:35 -07:00
Stefano Raggi
4fed304eb7 Update Lean Foundation docker files to IBGateway v984 (#5686) 2021-06-22 17:20:47 -03:00
Colton Sellers
a987e0231f Scheduled Events for Start/End Week/Month Fix (#5690)
* Apply fix for both start and end month cases

* Add unit tests for both cases

* Fix weekstart/weekend for same issue; add unit tests

* nit - rename tests

* Adjust logic
2021-06-22 14:20:00 -03:00
Colton Sellers
f47775338c Expand Lean Default Charts and Reduce Clutter (#5680)
* Update charts that are not empty and not default values

* Testing

* Filter final results

* Explicitly filter alpha charts if not needed

* Use filtered charts for Live results handler

* Refactor solution to manage alpha charts internally by creator

* nit comment fixes

* Implement drawdown as default chart

* Implement Capacity Estimate for backtest default chart

* Add default values to QC.Plotting

* Adjust drawdown calculation

* Only sample "Capacity" once a day

* Implement Volume chart

* Nit fixes

* Volume Chart adjustments and fixes

* Rename to "Assets Sales Volume"

* Implement Exposure Sampling

* Store algorithm currency symbol, round capacity to nearest 1k

* Add new plots to default charts

* nit change name

* Address reviews

* Reduce duplication and clean up exposure sampling

* Address reviews

* Improve sample exposure

* Address review

* Only enumerate holdings once

* nit - comments

* Post rebase fix

* Don't need to round anymore
2021-06-22 11:19:48 -03:00
Colton Sellers
fa1e97bc60 Round Capacity Estimate for Runtime Statistics (#5688)
* Refactor solution to deal with rounding in CapacityEstimate

* Use DiscretelyRoundBy + adjust regressions
2021-06-21 21:06:09 -03:00
Martin-Molinero
8fb649ceb4 SymbolJsonConverter improvements (#5683)
* SymbolJsonConverter improvements

- SymbolJsonConverter will be able to deserialize symbols expressed in
  user friendly format. Adding unit test
- Adding a couple of helper methods, removing duplicated code

* Fix FOPs expiration year parsing
2021-06-21 21:02:46 -03:00
Stefano Raggi
7d8754f33c Update IBAutomater to v2.0.38 (#5682)
* Update IBAutomater to v2.0.38

* Trigger build
2021-06-21 12:23:55 -03:00
Stefano Raggi
080511fa5a Add IResultHandler.BrokerageMessage (#5681)
* Add IResultHandler.BrokerageMessage

- Result handlers can receive notifications for brokerage message events

* Make LiveTradingResultHandler.RuntimeError virtual
2021-06-21 12:23:46 -03:00
Martin-Molinero
5146329c0f CoinApi: reduce thread contention by lock per symbol (#5677)
- Reduce thread contention in coinApi DQH by taking a lock per symbol
  versus a global lock.
- Improve tick creating by reducing object being wasted on empty
  constructor
2021-06-17 20:47:57 -03:00
Stefano Raggi
47fb4e64f2 Update IBAutomater to v2.0.37 (#5676) 2021-06-17 16:14:38 -03:00
Alexandre Catarino
5361f87dd1 Updates Equity Market Data (#5576)
* Updates Equity Market Data

* Updates Unit Tests

* Updates Regression Tests

In this commit we include regression tests with small changes (slightly different CAGR, Alpha, etc, but same number of trades) due to the data update.

* Updates Regression Tests 2

The following regression tests were adapt because of verification of hard-coded market data values:
- `AdjustedVolumeRegressionAlgorithm`
- `HistoryWithSymbolChangesRegressionAlgorithm`
- `OptionRenameRegressionAlgorithm`
- `RawDataRegressionAlgorithm`
- `SwitchDataModeRegressionAlgorithm`

The following regression tests have more trades since adjusted prices allowed more 1-2 shares trades that were rounded down to zero before:
- `AddUniverseSelectionModelCoarseAlgorithm` 23 -> 35
- `MeanVarianceOptimizationFrameworkAlgorithm` 12 -> 14
- `PortfolioRebalanceOnDateRulesRegressionAlgorithm` 298 -> 324
- `PortfolioRebalanceOnInsightChangesRegressionAlgorithm` 83 -> 86
- `ScheduledUniverseSelectionModelRegressionAlgorithm` 86 -> 90
- `SectorExposureRiskFrameworkAlgorithm` 17 -> 22
- `SetHoldingsMultipleTargetsRegressionAlgorithm` 8 -> 9
- `StandardDeviationExecutionModelRegressionAlgorithm` 196 -> 199
- `UniverseUnchangedRegressionAlgorithm` 11 -> 17
- `VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm` 237 -> 238

Especial cases:
- `BlackLittermanPortfolioOptimizationFrameworkAlgorithm` 18 -> 17
 - BLM model sensibility
- `OptionChainedAndUniverseSelectionRegressionAlgorithm`

The following regression tests have different Capacity because of different volume from lowest capacity asset, except:
- `OptionEquityCoveredCallRegressionAlgorithm` New lowest capacity asset is underlying
- `OptionEquityCoveredPutRegressionAlgorithm` New lowest capacity asset is underlying

* Revert File Update for SPWR and SPWRA

* Fix Regression Tests

Temporarily removes python regression test for `MeanVarianceOptimizationFrameworkAlgorithm` as the `MeanVarianceOptimizationPortfolioConstructionModel` for each version are yeilding different results. If we use C# version in `MeanVarianceOptimizationPortfolioConstructionModel.py`, the results match.

* Changes Optimization Method in MinimumVariancePortfolioOptimizer [Py]

Uses `trust-constr`  method.
See https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html
2021-06-17 14:04:51 -03:00
Jasper van Merle
72fb362f96 Fix futures not working with IQFeed (#5675)
* Fix futures not working with IQFeed

* Trim slash from value instead of using ID.Symbol
2021-06-17 08:46:03 -07:00
Martin-Molinero
24e3a71581 Coinapi improvements (#5672)
- Add centralized download extension helper method
- Update coinApi client
2021-06-16 20:30:51 -03:00
Colton Sellers
15555f710d Python Loading and Debugging Refactor (#5670)
* Use Python algorithms directly in their location; also refactor pythonpath additions to one method

* Update VSCode Launch options

* Drop issue these changes fixes

* Use AddRange
2021-06-16 20:30:33 -03:00
Martin-Molinero
3d13fb6935 Implement Atreyu fees (#5674)
* Empty

* Implement Atreyu fees
2021-06-16 19:43:27 -03:00
Colton Sellers
74f0c89499 Option Chain Provider Symbol Map Resolve (#5664)
* Use mapFileProvider to resolve symbol mapping

* Add reproducing unit test

* Only resolve mapping for types that require it

* address review
2021-06-16 19:42:38 -03:00
Martin-Molinero
0991f089d0 Reduce disk usage in the cloud (#5673) 2021-06-16 18:43:55 -03:00
Colton Sellers
424fa36703 Organization Product ID and ApiDataProvider Fix (#5671)
* Add ID to Organization Products

* Use Product ID to verify subscription
2021-06-16 15:01:53 -03:00
Colton Sellers
afbd058dad Add Site-Package Issue to Readme (#5668)
* Add information to Python and Research readme

* Adjust doc
2021-06-16 13:57:13 -03:00
Stefano Raggi
66d2f42d01 IBAutomater updates (#5669)
* Update IBAutomater to v2.0.36

* Trigger build
2021-06-16 12:52:43 -03:00
Martin-Molinero
11f8dc2958 Improvements for CoinApi subscription (#5666) 2021-06-15 19:49:14 -03:00
Martin-Molinero
03f56481d4 Refactor python algorithm import (#5657)
* Python research import improvements

- Improve start.py for research env
- Remove unrequired imports

* Centralize algorithm imports

* Add regression test GH action

* Unit test python import clean up

* Join research and main imports

* More python import clean up

* Fix failing skipped regression algorithm
2021-06-15 19:06:06 -03:00
Stefano Raggi
c367451c6d Update IBAutomater to v2.0.35 (#5663) 2021-06-15 16:58:31 -03:00
Alexandre Catarino
c4e6e7f8dc Changes VIXCentralContango.F9 to Nullable (#5662)
According to the data, the contract 8 months away from the front-month contract, `F9`, can be null.
2021-06-14 16:23:28 -07:00
Colton Sellers
ef5f7fbc50 QuantBook Provider and Composer Fix (#5660)
* Use Composer instance for QB so providers are the same across Lean; also initialize map and factorfiles

* Don't need map and file initialize
2021-06-14 19:17:53 -03:00
Colton Sellers
7f9d35f666 Research BollingerBands Value Error (#5656)
* Stop update when properties will fail to update

* Only enforce our case after the BB is ready

* Nit comment fixes

* Add unit test

* Use faster DateTime.UtcNow
2021-06-14 14:23:05 -03:00
Gerardo Salazar
be0fc9a879 Fixes case where crypto has short exposure in ReportGenerator in long-only strategies (#5655) 2021-06-11 21:40:49 -03:00
Colton Sellers
a882aadeef Research Fixes and Doc Updates (#5649)
* Updates to default notebooks

* Update readme

* Notebook adjustments

* Drop launch script support

* Use our cwd if no QC dlls are in AppDomain directory

* Modify Intialize.csx to use parent directory only if QC files are detected there

* Clean up some details after testing

* Adjustments

* nit, NullOrWhiteSpace
2021-06-11 16:06:47 -03:00
Stefano Raggi
02f7742878 Update IBAutomater to v2.0.34 (#5652) 2021-06-11 14:38:45 -03:00
Martin-Molinero
b7c18cbfe7 Update pythonNet to net5 (#5653)
- Csproj clean up legacy build print logs
- Update pythonNet to net5
2021-06-11 13:51:09 -03:00
Martin-Molinero
6e6a1631dc Enable loading crypto live virtual position tracking (#5651)
* Enable loading live virtual position tracking

- Enable GDAX paper trading configurations
- GDAX will optionally load existing holdings from live job package
- Bitfinex will try loading existing holdings from live job package for
  cash account type

* Binance live holdings loading
2021-06-10 20:05:23 -03:00
Gerardo Salazar
250ffa1fec Adds VIXCentralContango data, modifies cached alternative data sourcing in live mode (#5648)
* Adds VIXCentral Contango data

  * Refactor cached alternative data in live mode to
    use web endpoint if the data is not available locally

* Remove fallback to cache bucket for CBOE/FRED/EIA/VIXCentralContango

* Address review: force VIX as ticker for all VIXCentralContango data
2021-06-09 20:44:53 -03:00
Martin-Molinero
7e2678d0f6 Normalize live holdings initialization (#5647)
* Normalize live holdings initialization

* PaperBrokerage config based live state recovery

- Increase algorithm status storing sampling period
- Fix bug where duplicate cash entries could happen
2021-06-09 20:11:38 -03:00
Louis Szeto
9f15ca4c9c feature-<#5631>-<Create SpreadExecutionModel> (#5633)
* Create SpreadExecutionModel.py

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.py

* Create SpreadExecutionModel.cs

* Create SpreadExecutionModelTests.cs

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModel.cs

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModel.cs

* Update SpreadExecutionModel.cs

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModel.cs

* Update QuantConnect.Algorithm.Framework.csproj

* Create SpreadExecutionModelRegressionAlgorithm.py

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.cs

* Address review

- Adding CSharp regression algorithm implementation
- Updating unit tests, minor format changes

* Address review. Add comment and Abs spread percent

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-06-09 14:55:00 -03:00
IlshatGaripov
d23ac25b67 Polygon IO limited aggregate bars per request. Fix. (#5363)
* Applies a fix

* Fixing the tests to cover downloader func. Fixing the queue handler

* this has to be removed

* -- Fixes -- [WIP]

* Implements the way to upload historical bars in async fashion. [ WIP ]

* Finishes GetEquityTradeTicks() impl.

* Do not break iteration if result is null

* Uses DisposeSafely and fixes a typo

* To use IEnumerable for return type in GetHistoryAsync

* Fixes GetEquityQuoteTicks()

* Removes GetHistoryAsync() and reverts the associated with it changes

* SubscriptionManager -> revert the changes

* PolygonDataQueueHandler -> use SIP timestamp as it keeps the order

* PolygonDataQueueHandler -> use Log.Trace for the no data {date} message

* Fixes GetForexQuoteTicks()

* Introduce ResponseSizeLimitAggregateData

* Fixes up GetCryptoTradeTicks()

* Small fixes for tick processing methods

* Removes launchSettings.json

* Refactor download data logic

- Replace WebClient for HttpClient
- Remove duplicated download logic and parsing for a single static
  method

* Update PolygonDataQueueHandler.cs

Remove commented code

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-06-09 10:43:34 -03:00
Colton Sellers
8f7f862563 Ignore Tests (#5646) 2021-06-09 10:25:07 -03:00
Colton Sellers
0f0eeaff82 DataProvider Updates & Refactoring (#5641)
* Use DataProvider for fetching Shortable and FutureMargins files

* Use data provider for AllShortableSymbols

* Refactor of NeedToDownload logic

* Adjustments

* nit - cleanup

* Expand test cases

* Create the directory if it doesn't exist
2021-06-08 22:11:21 -03:00
Martin-Molinero
e8cf002238 Live trading holding improvements (#5644)
- Store holdings at end of algorithm
- Warmup holding market price if 0
2021-06-08 21:55:17 -03:00
Stefano Raggi
e875b111d7 IB Brokerage updates (#5642)
* Add immediate logging for IB brokerage unit tests

* Filter brokerage message event for IB warning

- 10197 - No market data during competing live session.

* Update IBAutomater to v2.0.32

* Update IBAutomater to v2.0.33
2021-06-08 11:29:29 -03:00
Martin-Molinero
a231a7d47a Update python net to 2.0.3 (#5640)
* Update pythonNet version to 2.0.3

* Fix outputPath causing issues with nuget
2021-06-07 21:37:26 -03:00
Colton Sellers
37cce922d3 Api Data Request Path Format Issue (#5639)
* Address some format issues for data request paths

* Add reproducing test

* Drop logging for failure, let Api take care of it
2021-06-07 20:59:39 -03:00
Colton Sellers
5f9e4a6bca Option Exercise Quantity Fix (#5638)
* Use determined quantity for exercise order

* Add regression algorithm for issue

* Minor tweaks

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-06-07 18:51:52 -03:00
Martin-Molinero
42c58d6e53 Ensure data is downloaded only once (#5635)
- Ensure data is downloaded only once with the ApiDataProvider. Adding
  unit test
- Log invalid securityType ApiDataProvider requests once
- Assert Factor file and map file providers are compatible with the
  ApiDataProvider
2021-06-07 14:26:24 -03:00
Colton Sellers
ab6027723f Refactor Api (#5251)
* Use lean data key as param for request

* key -> filePath rename and some cleanup

* Refactor

* Add Organizations Endpoints

* Add some organization api wrapper objects

* Address namespace issue

* Reorganize Api Test into seperate files using one ApiTestBase

* Add Organization tests

* Use capitalized "API" test namespace to reduce amount of file changes

* Add License to test base

* Update /data endpoint functions and response objects

* Update ApiDataProvider Logic

* Handle deserialization of organization products

* Simplify converter

* Only throw for equity requests when not subscribed to map/factor files

* Add missing header

* Make arguement exception

* Api adjustments

* Add Zip factor and map file providers

- Common project will now reference Compression project and not the other way
  round.
- Adding Zip FactorFile and MapFile providers

* Refactor FactorFileProvider to use DataProvider to fetch files

* Use resulting MinimumDate in construction of FactorFile

* Nit FactorFile comments and arrangement

* Refactor MapFileProviders to use DataProvider for fetching files

* Refactor ZipFileProvider

* Clean up

* Refactor Backtesting Future/Option chain providers to use dataprovider

* Fixes for data/ endpoints and test adjustments

* Response objects adjustments/cleanups

* ApiDateProvider fixes and testing

* Add LocalZipFactorFileTests

* Update ApiDataProvider download test to verify stream is not null

* Implement posting of agreement summary and signed time

* Mark all Api related tests as explicit and document details on running

* Clarify default token on ApiTestBase

* Adjust summary

* Update Api responses for QCC, except org products which are sold in USD

* Implement cache expiration for zip MapFile and FactorFiles. Adding unit tests

* Fix multiple markets for ZipFactorFile provider

* Use Symbol as cache key

* Api.cs review

* Dispose of factorFileStream after reading

* Use zip.EntryFileNames

* Address a few reviews

* Few more fixes

* Address Api Review

* Add Job Org id to config

* Minor tweaks

* Compare with invariant culture

* Fixes Option Universe selection

* ZipEntryNameSubscriptionDataSourceReader will use IDataProvider

* Fix research

* Fix null reference exception

* Make duplicate log debug

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-06-07 11:37:44 -03:00
Alexandre Catarino
37473c4580 Fixes OverflowException in FuturesOptionsMarginModel (#5629) 2021-06-04 21:24:19 -03:00
Gerardo Salazar
677661766b Fixes filtering of CoinAPI raw data in CoinApiDataConverter (#5625)
* Fixes bug where raw data was incorrectly be filtered when ID was duped

* Filter CoinAPI raw data by distinct Symbol created from the SymbolMapper

* Fixes bug where only quotes or trades would be processed, not both

* Trigger rebuild
2021-06-04 13:53:47 -03:00
Martin-Molinero
c66a26e01d Fix build: Holding.Type is not setable (#5628) 2021-06-03 21:03:18 -03:00
Martin-Molinero
effa2da594 Avoid need for Holding Type update build status (#5623) 2021-06-03 20:21:18 -03:00
Stefano Raggi
572aa99743 IBAutomater updates (#5626)
* Update IBAutomater to v2.0.27

* Update IBAutomater to v2.0.28

* Update IBAutomater to v2.0.29

* Update IBAutomater to v2.0.30

* Trigger build
2021-06-03 19:04:54 -03:00
Gerardo Salazar
e77e202373 Adds support for LeanDataWriter minute/second/tick writing for files w/ more than 2GB uncompressed (#5620) 2021-06-02 18:29:50 -03:00
Martin-Molinero
f9c50e28ef Add data libraries into image (#5619) 2021-06-02 12:45:28 -03:00
Martin-Molinero
4c773c348c Update readme.md 2021-05-31 11:13:13 -03:00
Colton Sellers
41f9d9da94 Remove SecurityInitializer from Universe Selection (#5418)
* Attempt to remove SecurityInitializer from UniverseSelection stack entirely

* Fix broken Python Universe Selection model

* Remove mistake change (meant for another branch)
2021-05-28 14:53:13 -03:00
Martin-Molinero
5f6a40fd9c Update readme.md 2021-05-28 12:18:52 -03:00
Martin-Molinero
0335b49edf Update pythonNet to 2.0.2 (#5611) 2021-05-28 12:10:55 -03:00
Derek Melchin
1175c304e1 Fix live timestamp alignment in CustomDataBitcoinAlgorithm (#5603)
* Fix python version

* Make C# version match

* Revert c# changes, make python version use exchange timezone
2021-05-27 20:09:48 -03:00
Colton Sellers
6c42f58b68 VS Code Tasks and Python Debugging Fixes (#5601)
* ~Fix Python debugging and update docs

* Cleanup tasks
2021-05-27 16:34:04 -03:00
Alexandre Catarino
22a5378604 Reduce Leverage for Equity to 1 in Alpha Stream Brokerage Model (#5598)
All security type use 1 as leverage but Forex and CFD that are allow to use 10.
2021-05-27 15:31:34 -03:00
Martin-Molinero
2df6715301 Add hostname to initial log message (#5608) 2021-05-26 19:27:05 -03:00
Colton Sellers
459f812223 Duplicated Points in Custom DataFrame Fix (#5606)
* Don't add "value" to series twice

* Reproducing unit test
2021-05-26 18:44:13 -03:00
Martin-Molinero
22caf9ef2a FOPs margin as a curve (#5607)
* FOPs margin as a curve

- Adjust FOPs margin requirement so that it behaves like an 'S' curve
  for the contract strike, around the underlying price and it's margin requirement.
  Based on IB behavior. Adding unit tests for different future contracts
- Improve a couple of unit test cleanup

* Add ES Short Call unit test
2021-05-26 18:09:05 -03:00
Gerardo Salazar
94fb9293dc Adds filtering of negative ticks in CoinAPI converter consolidation (#5597)
* Adds filtering of negative ticks in CoinAPI converter

  * Tick data will remain the same, only aggregated data
    will have changes reflected in its output as a result

* Adds suspicious tick filtering to ticks

* Address review: Add Crypto Trade Tick suspicious test case
2021-05-25 19:38:53 -03:00
Stefano Raggi
59266d84bf IB Automater update (#5599)
* Update IBAutomater to v2.0.23

* Update IBAutomater to v2.0.24
2021-05-25 16:50:17 -03:00
Colton Sellers
8ee9432bda Wicked Renko Consolidator Fix (#5589)
* Round first value to Renko BarSize

* Add unit tests
2021-05-24 21:39:21 -03:00
Adalyat Nazirov
99088d6dd8 Atreyu Brokerage model (#5593)
* move AtreyuOrderProperties

* config

* make method public

* allow override base GetCashBalance test method
2021-05-24 21:09:39 -03:00
Stefano Raggi
15183cefe8 Update IBAutomater to v2.0.22 (#5592)
* Update IBAutomater to v2.0.22

* Add Sleep before restarting IBAutomater

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-05-24 20:09:50 -03:00
Martin-Molinero
9e96aeb440 Language update. Csproj clean up (#5590)
- Update CSharp language version to latest 9
- Remove old csproj build configurations
2021-05-24 11:10:03 -03:00
Colton Sellers
a2beeffcde Add Useful Error Message on TradingCalendar (#5588)
* Add warning when start and end are reversed

* Throw arguement exception; add unit test
2021-05-24 11:09:29 -03:00
IlshatGaripov
c384fe0e2a Implements PivotPointsHighLow indicator + tests (#5352)
* Implements PivotPointsHighLow indicator + tests

# Conflicts:
#	Tests/QuantConnect.Tests.csproj

* Some fixes

* Refactoring + Adds NewPivotPointFormed event

* Fixing tests

* Some fixes for the Get methods to not throw when points array is empty

* To address review + more fixes

* Fixing xml comments typos

* Implements separate rolling windows to calculate highs and low

* Makes the number of last stored indicator values as an input parameter

* Overrides Reset()

* Adds a helper method

* Change numerical return to Enum types

* Changes IsReady condition :

the indicator is ready and starts calculating the pivot point when any of the rollings is ready

* Address reviews

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-05-24 11:09:07 -03:00
Martin-Molinero
ee6631dd8a Update readme.md 2021-05-21 18:50:04 -03:00
Martin-Molinero
4fdb748b42 Add Alphas Streams SDK to Lean image (#5587) 2021-05-21 18:31:51 -03:00
Colton Sellers
ff0ecc7ed2 CFD Capacity Estimate (#5582)
* Use forex method of estimation for CFDs by hard setting volume

* Update regression

* Use a unique volume estimation factor for CFDs
2021-05-21 16:24:29 -03:00
Colton Sellers
dcdfc7fdb3 Update Oanda CFDs Lot Sizes and Market Hours (#5581)
* Update lot sizes on symbols

* Update some incorrect marketHours

* Update all Oanda CFD market hours

* unify rollover to next day endtime
2021-05-21 16:16:26 -03:00
Colton Sellers
a83eb7bf88 Update GDAX Brokerage MinimumOrderSizes (#5586)
* Update GDAX Brokerage MinimumOrderSizes

* Re-add XRP for historical purposes
2021-05-21 15:44:16 -03:00
Stefano Raggi
4e0ef94c97 Fix IBAutomater timeout error (part 2) (#5585)
* Update IBAutomater to v2.0.20

* Update IBAutomater to v2.0.21
2021-05-21 13:54:37 -03:00
Jasper van Merle
c4db451416 Increase Binance rate limit to 1 message per 250ms (#5584) 2021-05-20 17:47:07 -03:00
Colton Sellers
112c14e0e8 IDE Integration Updates & Doc Updates (#5550)
* Update launch options and tasks

* Update readme

* Mention building manually is optional

* Add portable pdbs to use C# coreclr debugging

* Update VS and VSCode docs

* Add reference to Lean CLI in main readme

* remove run_docker scripts

* Remove PyCharm files

* Cleanup

* Remove run_docker tasks from VS Code

* Address typos
2021-05-20 13:47:33 -03:00
Jason Harmon
87b16bc20c Implemented AlphaVantageDataDownloader (#5475)
* Implemented AlphaVantageDataDownloader

* Style and documentation changes requested

* Throw exception for unexpected response content

* Added rate limiting to AlphaVantageDataDownloader

* Minor tweaks and rebase

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-05-20 13:36:25 -03:00
Jasper van Merle
bb8bd27fe5 Support 2-leg currency conversions (#5552)
* Apply changes from #2146 on current master

Credit for most of these changes goes to https://github.com/viliwonka.
Rebasing three years of changes didn't go so well, so I manually
applied the changes in #2146 on the current master branch.

This commit attempts to represent the changes in #2146 as closely as
possible, no cleanup has been performed yet. Despite this, some changes
were inevitable because part of #2146 has been implemented another way
in the past three years.

* Clean up

* Process review comments

* Add tests

* symbol -> potentialConversionRateSymbol

* Ensure regression tests run/get data

* Fix broken test

* Process review comments

* Process review comments

* Simplify currency conversion logic

* Performance improvement, doc updates and test rename

* Rebase fixes

* Remove obsolete properties

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-05-20 13:19:39 -03:00
Martin-Molinero
978da37cda Minor tweaks (#5580)
* Minor tweaks

- Add AccountCurrency and symbol for live result packet
- Improve performance of Tick clone and reading

* Reduce unit test from 9s to 500ms
2021-05-20 12:00:42 -03:00
Colton Sellers
4bb7fc17a2 Resolve Currency ConversionRate Backup (#5575)
* Attempt to use daily resolution request to resolve currency conversion

* Add BaseSetupHandlerTests

* Minor tweaks. Adding missing dispose call.

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-05-19 19:54:02 -03:00
Jasper van Merle
d903ca60ef Fix AdjustedVolumeRegressionAlgorithm on Linux (#5579) 2021-05-19 19:09:08 -03:00
Colton Sellers
ec77cf3ca5 Delisted Warning Time Correction (#5568)
* Use DelistingDate for Warning event

* Update test

* Add regression

* Cleanup regression

* Add issue reproducing unit test
2021-05-19 15:19:38 -03:00
Stefano Raggi
76600a3a0e Fix IBAutomater timeout error (#5578)
* Update IBAutomater to v2.0.18

* Update IBAutomater to v2.0.19
2021-05-19 14:59:28 -03:00
IlshatGaripov
dcb578cdfb Do not restrict unrequested securities by 1.0m leverage (#5375)
* Do not restrict unrequested securities by 1.0m leverage, let security initializer do its job

* Use UniverseSettings for leverage, fillforward, and extendedmarkethours

* Update unrequested security message

* Use UniverseSettings ExtendedMarketHours for underlying on OptionContracts

* Add unit test to prove setting persistence

* Cleanup unit test

* Adjust crypto unit test assert

Co-authored-by: Colton Sellers <Colton.R.Sellers@gmail.com>
Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-05-19 12:59:42 -03:00
Gerardo Salazar
838e94ec18 Fix large file downloads for SEC causing integer overflow in HttpClient (#5577) 2021-05-19 12:05:10 -03:00
Martin-Molinero
9887a05d77 Fix FutureOptionMarginModel Margin Requirements (#5570)
* Fix FutureOptionMarginModel Margin Requirements

- Fixes FuturesOptionsMarginModel margin requirements being zero due to
  underlying being null on model creation. Adding unit test

* Address reviews

- SecurityService will set underlying when creating a new security when
  provided
2021-05-18 14:04:30 -03:00
Gerardo Salazar
cd0c447bcc Fixes SEC rate limiting issue by adding user-agent and reducing clustering of requests (#5567)
* Fixes SEC rate limiting issue by reducing clustering of requests

  * We add a user-agent header to all outgoing requests for SEC
    as they require it to identify the client, otherwise we're rate
    limited.

  * Some adjustments to how we wait for work to be done, and RateGate
    rate of requests. We wait for all requests now/don't use tasks
    anymore

* Address review - remove class HttpClient in favor of local instance
2021-05-18 13:55:15 -03:00
Colton Sellers
d91ccac4aa Use decimal for Oanda OrderFillQuantity conversion (#5571)
* Use decimal for Oanda OrderFillQuantity conversion

* Use decimals for all order values
2021-05-18 12:46:49 -03:00
Łukasz Szymański
9d93dc1570 Fix wrong market hours for Oanda DE30EUR CFD (#5564)
* Fix wrong market hours for Oanda DE30EUR CFD

* Update unit tests expected result

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-05-17 18:32:58 -03:00
Colton Sellers
5bf72d2432 Adjust Volume for Splits (#5525)
* Adjust TradeBar volume for splits

* Refactor solution to centralized function `Scale`

* Expand BaseData scale/adjust/normalize tests to assert volume behavior

* Add regression algorithm

* Update regression statistics

* Address review

* NOP to trigger cloud build

* adjust QuoteBar ask and bid size

* adjust broken regression

* Update tests to include QuoteBar adjustments

* nit cleanup

* Adjust Quote Tick bid and ask sizes

* Round volume and size values to nearest int in scale()

* nit

* Adjust regressions
2021-05-17 16:47:44 -03:00
Stefano Raggi
d24edf5a6c IB Brokerage updates (#5518)
* Upgrade IBAutomater to v2.0.0

* Upgrade IBAutomater to v2.0.1

* Upgrade IBAutomater to v2.0.6

* Upgrade IBAutomater to v2.0.7

* Upgrade IBAutomater to v2.0.9

* Upgrade IBAutomater to v2.0.10

* Upgrade IBAutomater to v2.0.12

* Upgrade IBAutomater to v2.0.13

* Upgrade IBAutomater to v2.0.14

* Upgrade IBAutomater to v2.0.15

* Reset disconnected flag on IBGateway exit/restart

This bug was causing invalid algorithm termination after reconnection

* Fix unhandled exceptions in exit/restart event handlers

* Upgrade IBAutomater to v2.0.16

* Upgrade IBAutomater to v2.0.17
2021-05-17 15:08:24 -03:00
Martin-Molinero
a0c2e38eae Remove exception being thrown because of lotsize (#5566) 2021-05-17 12:06:36 -03:00
Martin-Molinero
fe2ac131af Remove exception being thrown because of lotsize (#5562) 2021-05-14 21:18:09 -03:00
Alexandre Catarino
b8e3294a5f Improves Position Constructor Exception Message (#5560) 2021-05-14 19:36:10 -03:00
Stefano Raggi
25f4cdd92f Tradier brokerage updates (#5546)
* Update testing OrderProvider to clone orders as BrokerageTransactionHandler

* Add immediate logging for brokerage unit tests

* Tradier brokerage updates

- Fixed NullReferenceException with zero-crossing orders
- Added a few missing null checks
- Fixed issues in error handling
- Added new unit tests for some common errors
2021-05-14 17:59:21 -03:00
Gerardo Salazar
82c9b6ccb7 Updates and improvements to ToolBox projects (#5537)
* Adds processed data directory to read price data from

* Make coarse universe generator look at data directory before failing to find daily data

* Set coarse generator output of missing daily file to debug log

* Add CoarseUniverseGenerator logs

* Fixes 100 nanosecond increment lookahead bias when parsing large numbers

  * Whenever we parse a number that is has precision greater than
    DateTime ticks (sub-100 nanoseconds), if we have nanoseconds
    between [0, 1000), excluding numbers divisible by 100,
    we will have leftover nanoseconds between [0, 100) nanoseconds, but
    they won't be factored in to the DateTime calculation, since casting
    to `long` only takes the integer component of the number, so we lose
    the extra nanoseconds that came with the decimal, and time is set to
    the "floored" value without those nanoseconds.

    Since .NET `DateTime` type has a limitation of only being able
    to represent time in increments of 100 nanoseconds, by not
    considering the sub-100 nanoseconds, we introduce a look-ahead
    bias of at most 100 nanoseconds/1 tick

  * Misc adjustment to make method use `decimal` instead of `double`
    for increased precision when parsing large numbers

* Changes CoinAPI data converter to support processing raw files in original directory structure and file name

  * Removes Market requirement from CoinAPI data converter

* Remove timeout on decompression of raw AlgoSeek futures data

* Updates SEC downloader to use HttpClient where requests were failing

  * For some unknown reason, valid requests to a valid URL were
    failing when using WebClient. Changing our requester to
    HttpClient fixes the issue, and enables us to leverage
    async capabilities where applicable.

  * Added fault tolerance to index file downloads, including a
    rate limit in case we've been rate limited

* Further refactoring; catches 429 errors, adds missing rategate calls

* Replace all usage of WebClient, force retry for all failures

* Adds optional config value for Benzinga News API key in downloader

* Modifies Estimize Downloader api config name and fixes directory not found bug

* Refactor Estimize to speed up processing time

  * Adds ticker limits if desired
  * Misc. bug fixes, performance improvements, code cleanup

* Remove debug log statements leftover from previous commit

* Add support for non-tick Index resolutions in LeanDataWriter

* Empty commit

* Empty commit

* Empty commit

* Empty commit

* Empty commit

* Empty commit

* Lower requests/second for SEC downloader, add missing rategate call

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-05-14 17:06:47 -03:00
Martin-Molinero
9c1722d0b9 Update readme.md 2021-05-14 14:34:28 -03:00
Martin-Molinero
a475178dbb Fix FOPs maintenance margin requirements (#5559)
- Fix FOPs maintenance margin requirements since they were relaying on
  the underlyings holdings cost to return 0 in some cases. Updating unit
  tests
- Fix Option exercise order being rejected because of margin not
  available, will now take into account the margin used by the option
  itself. Adding unit test
2021-05-14 14:02:56 -03:00
Martin-Molinero
e6ffb1ac62 Add missing containsKey dictionary check (#5558) 2021-05-14 12:30:28 -03:00
Jasper van Merle
70996b0507 Increase Binance rate limit timespan (#5556) 2021-05-14 12:13:05 -03:00
Alexandre Catarino
58793acae8 Removes Assets that Are Not Invested and Not Tradable From Capacity Calculations (#5515)
* Add property for capacity. Remove unused variable

* Move SymbolCapacity and CapacityEstimate to common, passed through Symbol to runtime statistics

* Add null checks

* Remove uninvested and untradable assets from capacty calculations

* Add SymbolCapacity influential period

* Updates Regression Tests

- DelistingEventsAlgorithm
  - Allows additional contributions from delisted AAA.1

- DelistingFutureOptionRegressionAlgorithm
  - Removes DC01H12 contributions one month later

- FutureOptionBuySellCallIntradayRegressionAlgorithm
  - Allows additional contributions from future after expiry replacing the contribution of the next contract option

- DelistedFutureLiquidateRegressionAlgorithm
- FutureOptionCallITMExpiryRegressionAlgorithm
- FutureOptionCallITMGreeksExpiryRegressionAlgorithm
- FutureOptionPutITMExpiryRegressionAlgorithm
- FutureOptionShortCallITMExpiryRegressionAlgorithm
- FutureOptionShortPutITMExpiryRegressionAlgorithm
- FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm
  - Allows additional contributions from future after expiry

- FutureOptionCallOTMExpiryRegressionAlgorithm
- FutureOptionPutOTMExpiryRegressionAlgorithm
- FutureOptionShortPutOTMExpiryRegressionAlgorithm
- IndexOptionCallITMGreeksExpiryRegressionAlgorithm
- IndexOptionCallOTMExpiryRegressionAlgorithm
- IndexOptionShortCallOTMExpiryRegressionAlgorithm
  - Allows additional contributions from option after expiry

- MACDTrendAlgorithm
  - Removes contribution when SPY is not invested for over one month

- UniverseSelectionRegressionAlgorithm
  - Allows additional contributions from delisted GOOAV replacing GOOG (new symbols)

* Adds Lowest Capacity Asset to Regression Tests

* Normalize expected value -0, because -0 is also written to file if updated

* Write Symbol.Value for lowestCapacitySymbol or  empty string for empty Symbol

* Update Regressions

* Update 'Lowest Capacity Asset' to Symbol.ID

Co-authored-by: Jared Broad <jaredbroad@gmail.com>
Co-authored-by: Martin-Molinero <martin@quantconnect.com>
Co-authored-by: Colton Sellers <Colton.R.Sellers@gmail.com>
2021-05-13 20:25:19 -03:00
Colton Sellers
6af3f70fed Return empty targets list if no insights are given (#5548) 2021-05-13 19:29:00 -03:00
Jasper van Merle
373c41e568 Fix regression tests on case-sensitive filesystems (#5542) 2021-05-11 19:55:13 -03:00
Alexandre Catarino
96f42eb591 Updates Fundamental Data (#5502)
* Updates Fundamental Data

* Updates Regression Algorithms

- `CoarseFundamentalTop3Algorithm`
  - New coarse has higher `DollarVolume` for `FB`
- `CoarseNoLookAheadBiasAlgorithm`
  - Change from `SPY` update not included in #5493
- `SectorExposureRiskFrameworkAlgorithm`
  - `HasFundamentalData` was false for `GOOG` on 20140401 and 20140402.

* Updates Unit Tests

Minor changes in expected values

* Updates Regression Tests

Should have been included in #5493:
- `OptionsExpiredContractRegression`
- `FuturesExpiredContractRegression`

* Adjusted Quantity By Lot Size in OrderTargetsByMarginImpact

`OrderTargetsByMarginImpact` didn't calculate the order value with the quantity adjusted by order size which less to values that did not reflect the actual order value.
It has a particular affect in `SectorExposureRiskFrameworkAlgorithm` where the Python and C# versions have the same orders but placed in a different sequence because of decimal/double precision.

* Reduce dictionary access x3 on OrderTargetsByMarginImpact

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-05-11 17:54:45 -03:00
Jasper van Merle
62c51ab17c Add new C# and Python libraries (#5536)
* Add new C# and Python libraries

* Remove C# changes

* Update System.Reflection.Emit to 4.7.0

* Add scikit-learn-extra
2021-05-11 17:28:24 -03:00
Stefano Raggi
bbcb81804c Remove unused OpenJDK from DockerfileLeanFoundation (#5540)
- Since IBAutomater 1.0.35 (https://github.com/QuantConnect/IBAutomater/pull/28, merged in #4984) we are using the Java Runtime bundled with IBGateway
2021-05-11 17:27:52 -03:00
David Acker
6dfe492212 Fix IsReady and WarmUpPeriod for RateOfChange (#5501)
* Redefine IsReady and WarmUpPeriod

* Update warm up periods of other indicators to account for ROC warmup change

* Update regressions affected by this change (because of HistoricalReturnsAlphaModel using ROC)

* Add simple unit test for issue #5491

* Cleanup warmup period math and add comments

Co-authored-by: Colton Sellers <Colton.R.Sellers@gmail.com>
2021-05-11 17:12:48 -03:00
Colton Sellers
d76bfaade4 Consolidate SetupHandlers (#5529)
* Reconcile and consolidate SetupHandlers

* Centralize GetConfiguredDataFeeds()

* nit - extra space

* Check for null, also allow null to be passed back if no config value

* Fix breaking test

* Cleanup

* fix return var

* remove unneeded if/else

* Minor changes

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-05-10 22:12:16 -03:00
Colton Sellers
ed077da501 DataNormalizationMode Applies to AddSecurity (#5528)
* Use UniverseSettings.DataNormalizationMode for securities added in Algorithm

* Stop SubscriptionUtils from forcing Adjusted mode

* Return behavior to original and add comments

* nit typo

* Add regression

* Add unit test that verifies DataNormalizationMode can be altered manually by security

* Cleanup and add Py version of regression
2021-05-10 20:58:50 -03:00
Martin-Molinero
1958ac2935 Minor adjustments for WorkScheduler (#5533) 2021-05-07 19:28:14 -03:00
Martin-Molinero
2847d9e27d Update readme.md 2021-05-06 21:09:54 -03:00
Martin-Molinero
cf7a26b8b6 Increase pip install timeouts (#5527) 2021-05-06 17:45:49 -03:00
Martin-Molinero
f3c386663b Feature .net 5 (#5505)
* Update projects to use .NET 5.0, the successor to .NET Core

* Fix ambiguous errors. Add IBAutomator net5

* Remove FXCM

* Upgrade IBAutomater to v1.0.51

ignored, and an empty message aborts the commit.

* Fix rebase

- Fix ambiguous Index
- Remove StrategyCapacity.cs
- Update System.Threading.Tasks.Extensionsy

* Remove unrequired references

* Fixes

- Travis will use dotnet, not nunit nor mono
- Remove mono from foundation image
- Fix python setup in research
- Fix unit tests

* Don't call ReadKey when input is redirected

* Fix ConsoleLeanOptimizer

* Research fixes

* Update comment

* Add vsdbg to Dockerfile

* Fixes

- Revert dockerfile FROM custom changes
- Adjust and fix regression algorithms
   - Option assignment will be deterministic in the order
   - 'Rolling Averaged Population' is calculated using doubles, updating
     expected values.
- Update readme, removing references to mono
- Add missing Py.Gil lock

* Replace ICSharp with .NET Interactive

* Fixes after rebase

* CSharp research fixes

- Adding new Initialize.csx that pre loads all assemblies
- Adjusting template research file
- Moving steps in dockerfilejupyter
- Fix unit tests and regression tests after rebase

Co-authored-by: Gerardo Salazar <gsalaz9800@gmail.com>
Co-authored-by: Stefano Raggi <stefano.raggi67@gmail.com>
Co-authored-by: Jasper van Merle <jaspervmerle@gmail.com>
2021-05-06 17:23:51 -03:00
Colton Sellers
865da14540 Scheduled Universe Timed Triggers Bug (#5521)
* Add unit test

* Make test cover issue case

* Filter out times before startTimeUtc

* Refactor solution, fixes missing first date

* Fix case where none is expected

* Cleanup tests, add TriggerTimesNone

* Drop unused imports

* Add missing dipose call

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-05-05 11:23:38 -03:00
Colton Sellers
019ac01a4c Reset SubmissionTimeBuffer to default value for other regressions (#5522) 2021-05-05 11:17:13 -03:00
Martin-Molinero
4a8bcb82db Add reference to quantconnect/research (#5519) 2021-05-03 19:16:51 -03:00
Colton Sellers
7ddee34e86 Configurable MarketOnCloseOrder Buffer (#5516)
* Create a configurable SubmissionTimeBuffer for MarketClose orders.

* Nit error spacing

* Add Py and C# regression
2021-05-03 18:08:27 -03:00
Jasper van Merle
f00d4655cf Add support for ARM64 Docker images (#5497)
* Add support for ARM64 Docker images

* Update DockerfileLeanFoundationARM base image
2021-05-03 12:58:22 -03:00
Jasper van Merle
83431c956c Move Python stubs deployment from Travis to GH Actions (#5512) 2021-04-30 19:10:40 -03:00
Colton Sellers
772eb4650c Stop UniverseSelection from removing the Symbol from the cache (#5513) 2021-04-30 19:01:29 -03:00
Colton Sellers
a7e5acd8d3 Small test adjustment for changes in #5510 (#5514) 2021-04-30 18:47:16 -03:00
Martin-Molinero
83f9499b4a Option Margin Strategies (#5511)
* Refactor HasSufficientBuyingPowerForOrder implementations

Adds Sufficient and Insufficient helper methods to HashSufficientbuyingPowerForOrderParameters
enabling syntax like:

return paraeeters.Sufficient()
returnparameters.Insufficient(reason)

The next change will add the initial margin required which will simply require
updating both of these helper methods to accept the value.

* IBuyingPowerModel: Add margin functions Maintenance/Initial/ForOrder

These were originally hidden in an effort to only expose what's necessary
for the engine to perform its work. Additionally, we encapsulated all of
the method arguments into parameters classes to prevent having to break
anyone in the future. Not including these foundational methods turns out to
be an oversight. These methods are not required by the engine, but rather by
other models. Another possible solution here is to add an additional abstraction
and include these methods on this new abstraction. BuyingPowerModel would then
explicitly implement these methods and models that depend on them would require
two code paths, one for when the buying power model implements this interface
and another for when it doesn't.

Tests were additionally updated to remove test model implementations created for
the sole purpose of exposing these private methods.

* Add ConstantBuyingPowerModel

Provides an implementation of IBuyingPowerModel that returns the same
constant value

* Update BuyingPowerModelPythonWrapper to use reflection for method names

Having a bunch of hard-coded strings is a sure fire way for someone to
overlook when changing methods. This change ensures that noone needs to
remember that this code exists :)

Cleans up the syntax around verifying a python object implements a particular
C# interface via the ValidateImplementationOf<T> method by having it return a
value since the only use cases are in constructors when setting the models.

I was initially going to update ALL python wrappers to validate the passed
in models, but such a change could break many things that are 'working' right
now. Such an effort should be saved for its own dedicated PR.

* Add Parameters/Result types for new buying power model methods

* Support computing maintenance margin for arbitrary quantities

The existing GetMaintenanceMargin function assumes that we're only interested
in the maintenance margin for the entirety of the provided security's holdings.
This makes it impossible to perform what-if analysis or to even ask how much
maintenance margin is devoted to a particular subset of the security's holdings.
This change adds the quantity to the MaintenanceMarginParameters class. Futures
and Options models also depend on holdings cost and holdings value, so they have
also been added to the parameters type. Finally, static factory methods were
added to improve discernment of intent: ForCurrentHoldings provides the existing
behavior and then ForQuantityAtCurrentPrice to support what-if scenarios where
we're looking for the change in maintenance margin if we were to execute an order
for the securiy at the current time step. Obviously a constructor is provided to
set all of the values explicitly, using any price metric the caller desires.

* Address review

- Fix BPM xml documentation
- Fix python unit tests and PythonWrapper validate method

* Add SecurityHolding.QuantityChanged event

Adding event handlers will allow us to orchestrate complex
events from distant parts of the codebase through wiring
them up. If we continue down this path, it will move us away
from the current, very 'mechanical' data flows expressed in
LEAN and towards a more modern, event processing based system.
This is but a baby step in that direction and the initial use
case is using this QuantityChanged event to trigger resolution
of the algoritm's positions groups. This is part of an effort
to improve the fidelity of options margin modeling where we'll
model an OptionStrategy as an IPositionGroup. This will allow
us to compute the margin requirements of an OptionStrategy as
a unit instead of computing margin of each security individually
in isolation.

See #4065

* PortfolioManager: Group fields and remove unused field

This codebase generally places fields as the first members, but
this class had some fields at the top, then some properties, and
then some more fields. This change brings all the fields together
at the top of the file and also removes pointless comments placed
directly above some of the fields. Additionally, an unused field
was removed.

* Remove unused _currencyConverter from Security

Looks like at some point the only code using this member variable was removed
and the necessary clean up was overlooked.

* Add Parse.Enum functions

* Support disabling regression algorithms by language via config.json

Adds 'regression-test-languages' to config.json and filters regerssion algorithms to
run based on this value. When cycling on a particular feature, it's nice to be able
to run the entire regression set while ignoring the python algorithms. Once the C#
algorithms are all passing, one can then go back and run C# and Python in a final run,
since 99% of feature work doesn't impact python specifically.

* Implement IComparable in SecurityIdentitfier

This can be used to deterministically sort securities and symbols

* Add .editorconfig to enforce common formatting for json/sh files

* Fix typo in IBuyingPowerModel.GetBuyingPower xml docs

* Add ListEquals/GetListHashCode and OrderDirection.Closes(PositionSide)

ListEquals and GetListHashCode are designed to be used together as they
complement each other according to C#'s requirements for Equals and
GetHashCode functions.

PositionSide.ToOrderDirection() extension simply converts a PositionSide
to its logical equivalent OrderDirection. Long->Buy, Short->Sell, None->Hold

OrderDirection.Closes(PositionSide) determines if a particular OrderDirection
would have the effect of reducing a position's absolute size. This function
greatly improves the readability of buying power functions that must provide
adjustments when an order/contemplated trade reduces/closes an existing position.
OrderDirection.Buy.Closes(PositionSide.Short)
OrderDirection.Sell.Closes(PositionSide.Long)
All other combinations return false

Adds ToArray/ToImmutableArray convenience functions that combine a call
to Select followed by To(Immutable)Array all in one function call.

* Add decimal.DiscretelyRoundBy extension method

Supports rounding a decimal value by an arbitrarily chosen maximum precision,
or 'quanta'

* Update FutureMarginBuyingPowerModelTests to respect the security's lot size

* Add core position group classes and abstractions

* Add initial/maintenance margin support, buying power model consistency tests

* Add SufficientBuyingPower and GetReservedBuyingPower to position group model

Includes update to BrokerageTransactionHandler to use position group BPM for
sufficient buying power checks.

* Resolve position groups on each fill

We need to update the state of our position groups on each fill so that
we can properly handle multiple orders within the same time step. We
also limit the number of positions sent into the resolver by removing
securities without any holdings.

* fixup! Add SufficientBuyingPower and GetReservedBuyingPower to position group model

* Add GetMaximumLotsFor{Target|Delta}BuyingPower

Instead of computing order quantity, these functions compute the
maximum number of position group lots, which is the position group
quantity, and is guaranteed to be a whole number, for the provided
target/delta buying power parameters.

The SecurityPositionGroupBuyingPowerModel delegates to the security's
IBuyingPowerModel by applying a scaling factor equal to the security's
lot size.

This change also updates references to IBuyingPowerModel.GetMaximum...
to use the new position group model methods.

* Convert remaining IBuyingPowerModel call sites to position groups

* Rename PositionManasger.CreateDefaultGroup -> GetOrCreateDefaultGroup

Better describes its behavior

* Add Position Groups readme.md

* Add Option Strategy BuyingPowerModel

- Adding CompositePrositionGroupResolver and
  OptionStrategyPositionGroupResolver
- Adding OptionStrategyPositionGroupBuyingPowerModel handling option
  strategies based on IBs margin table. Adding regression algorithms
- Few changes so that option strategies executed by multiple orders are
  detected
- Adjust OptionStrategyDefinitionMatch to include equity legs in the
  matching result
- Minor tweaks fixing previous rebase
- Minor fixes for existing option strategies definitions, adding new
  missing strategies.
- Fixing minor bugs in option strategy matcher. Adding more unit tests

* Address self reviews

- Fixing bug in 'PositionGroupCollection'
- Few minor simplificaitons
- Adding BasicTemplateOptionEquityStrategyAlgorithm

* Address reviews

- Improve regression algorithms margin remaining and used assert logic to be exact. Taking into account spread and fees

Co-authored-by: Michael Handschuh <mhandschuh@gmail.com>
2021-04-30 18:45:27 -03:00
Colton Sellers
a3836a64c4 Refactor StartDateLimited Warning Logs (#5510)
* Refactor to queue up start date changes to log on dispose

* Fix typo in warning collection used

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-04-30 10:55:16 -03:00
Colton Sellers
db61cea3db Refactor logging for SubscriptionDataReader FactorFile processing (#5508)
* Collect and log symbols that had start date adjusted because of factor files

* Only post the message if the set has values

* Modify message to be [Symbol, Date] combo for more information on log

* Set a hard limit on the warning set to keep it from growing unnecessarily large

* Enforce a hard limit and improve message if full

* Enforce limit in log message because of possible threading adding past max

* Cleanup
2021-04-29 11:02:04 -03:00
Colton Sellers
fd4e1dc0a0 Address Security Normalization Changed to Raw Logging (#5509)
* Log security mode change once per universe addition process

* Limit max size of the warning queue to 10

* Only allow to emit once per backtest

* Set limit as var, if at limit suggest more

* Always suggest more warnings may exist because we opted to log only once
2021-04-29 10:54:46 -03:00
Gerardo Salazar
bb9cde1cee Adds StandardDeviationOfReturns configurability and improves greeks warmup for Futures/Index Options (#5495)
* Improves greeks configurability and defaults for all option asset types

  * Makes `StandardDeviationOfReturns` configurable by users, so that
    greeks can be loaded according to user expectations and the series
    of returns that they'd like to compute for `n` periods and timespan
    of `T`, as well as resolution of the data in live mode.

  * Changes resolution to max resolution available for the default
    volatility model created for the security. Usually this only applies
    to live mode, but if creating an instance of the
    `StandardDeviationOfReturns` volatility model and no `updateFrequency`
    is provided, the resolution's time span will be used as the default
    value. Backwards compatibility for equities is maintained.

  * Changes defaults for `StandardDeviationOfReturnsVolatilityModel`
    to warmup greeks faster for other derivative asset types

  * Improves comments on `StandardDeviationOfReturns` for clarity on how
    to use the volatility model for end users

* Fixes bug where TradeBar could not have proper Symbol set when getting
max resolution

  * Applies to QCAlgorithm.Universe and StandardDeviationOfReturnsVolatilityModel
  * Adds tests to check volatility model is updated at specified config intervals

* Address review: add shared method for (Relative)StandardDeviation
volatility models

  * Adjusts logic to determine bar type

* Address review: order by TickType when getting configs inside volatility models
2021-04-28 19:05:00 -03:00
Colton Sellers
c082f0dda3 Address Missing StableCoin Pairs in Crypto Exchanges (#5488)
* Allow USDC in cashbook without USDC-USD pair

* Cover more stablecoin cases unique to our crypto brokers

* Add unit test

* Cleanup and expand test cases

* Add USDCEUR and USDCGBP to GDAX Symbols

* Add missing tickers to SPDB

* Cleanup test
2021-04-28 14:20:15 -03:00
Adalyat Nazirov
845e874132 Modify partially filled (#5500)
* allow partially filled orders to be updated
need unit tests

* test is progress

* implement PartialFillModel
2021-04-27 20:36:32 -03:00
Jasper van Merle
706091b25e Update foundation base to latest stable phusion/baseimage (#5506) 2021-04-27 19:20:31 -03:00
Jared
fe040a55e9 Update readme.md 2021-04-23 14:25:14 -07:00
Martin-Molinero
ab82e75885 Fix undeterministic regression algorithms (#5504)
- Testing net5 uncovered these algorithms to be undeterministic
    - Adjusting AllShortableSymbolsCoarseSelectionRegressionAlgorithm
      internal implementation
    - Order removal of universe members will be deterministic, when the
      entire universe is removed.
2021-04-23 11:58:12 -07:00
Derek Melchin
ba4e2b115c Update Summary of DefaultDataProvider (#5503) 2021-04-23 11:19:46 -03:00
Alexandre Catarino
2b0fd2e607 Updates SPY Market Data (#5493)
* Fixes Double to Decimal Cast in GetAnnualPerformance

`GetAnnualPerformance` raises an exception if the `AnnualPerformance` calculation returns a double that cannot be cast to decimal (smaller than `decimal.MinValue` or bigger than `decimal.MaxValue`).
See `ProbabilisticSharpeRatio` where the same solution was applied.

* Updates SPY Market Data

SPY is a key asset since it is the default benchmark, and any change can lead to different `Alpha` and `Beta`

* Updates Unit Tests to Reflect Data Update

* Updates Regression Tests to Reflect Data Update I

Most of the regression tests change because of updated data (market and factors) of SPY (default benchmark) while the total trade remain the same.

* Updates Regression Tests to Reflect Data Update II

The following regression tests were changed to adapt to adjusted prices and keep the total trades:
- `BacktestingBrokerageRegressionAlgorithm`
- `LimitIfTouchedRegressionAlgorithm`
- `PortfolioRebalanceOnCustomFuncRegressionAlgorithm`
- `SetAccountCurrencySecurityMarginModelRegressionAlgorithm`
- `StopLossOnOrderEventRegressionAlgorithm`
- `TimeInForceAlgorithm`

The following regression tests have more trades since adjusted prices allowed more 1-2 shares trades that were rounded down to zero before:
- `FreePortfolioValueRegressionAlgorithm` 2 -> 3
- `PortfolioRebalanceOnDateRulesRegressionAlgorithm` 291 -> 298
- `TrailingStopRiskFrameworkAlgorithm` 5 -> 7

Especial cases:
- `AutoRegressiveIntegratedMovingAverageRegressionAlgorithm` 65 -> 52
 - ARIMA model sensibility
- `BlackLittermanPortfolioOptimizationFrameworkAlgorithm` 18 -> 19
 - BLM model sensibility
- `ExtendedMarketHoursHistoryRegressionAlgorithm` 20 -> 18
 - Less minute bars before market opens

* Addresses Peer-Review

Fix `BacktestingBrokerageRegressionAlgorithm` to use `CalculateOrderQuantity` and round down `quantity` to an even number to pass a value assertion and update the expected value from 50 to 52.
The quantity calculated by `CalculateOrderQuantity` has changed from 50 to 53 because of factor file update.
2021-04-19 13:31:01 -03:00
Colton Sellers
5b10b3b509 Refactor of Auxiliary Data Filtering (#5485)
* Add futures regression reproducing the issue

* Cleanup futures regression

* Add Options regression

* Add IRegressionAlgorithmDefinition

* Add IRegressionAlgorithmDefinition

* Adjust regressions to compare to expiration date; delisting time is not always correct

* Refactor subscription enumerator filtering of AuxData to top of the stack

* Update broken tests to reflect the split/dividends/delisting subscriptions

* Update regression statistics because of Delisting EOD instead of at time

* Let custom data configurations bypass filter

* Adjust expected count, now that we are letting aux data through to history requests

* another small adjustment

* Use ExpectedBarCount in error message

* Add filter test for both cases

* Add some clarifying comments

* Verify we did recieve data in the regressions

* Make _shouldEmitAuxiliaryData private readonly

* Filter out aux data for history requests

* Remove option to not include aux data in subscriptions

* Refactor filtering to be more explicit for each piece of data; fixes universe selection aux data

* Cleanup comments after removed var

* Refactor order of filtering for performance reasons.
2021-04-19 11:10:47 -03:00
Alexandre Catarino
a7b2d9450f Fixes Double to Decimal Cast in GetAnnualPerformance (#5492)
`GetAnnualPerformance` raises an exception if the `AnnualPerformance` calculation returns a double that cannot be cast to decimal (smaller than `decimal.MinValue` or bigger than `decimal.MaxValue`).
See `ProbabilisticSharpeRatio` where the same solution was applied.
2021-04-19 10:43:47 -03:00
Jasper van Merle
6af20c3d8a Fix using Bitfinex data feed in paper trading (#5490)
* Fix using Bitfinex data feed in paper trading

* Add BrokerageFactory to TradierBrokerage
2021-04-16 12:04:14 -03:00
Colton Sellers
cb9bc95c37 Refactor IndicatorExtensions to use SafeAsManagedObject to convert PyObjects (#5489) 2021-04-16 10:59:10 -03:00
David Acker
72b6a22230 Add Wilder Accumulative Swing Index (#5476)
* Add SI

* Add ASI

* Add Swing Index

* Add Accumulative Swing Index

* Fix XML comment

* Add SI and ASI

* Add test data

* Add SI tests

* Add ASI tests

* Convert get only properties to methods

* Fix indicator name

* Replace special characters

* Fix indicator formula

* Replace test data

* Replace test data

* Update QCAlgorithm.Indicators.cs

* Minor format tweaks

Co-authored-by: Jared <jaredbroad@gmail.com>
Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-04-16 10:54:02 -03:00
Stefano Raggi
6fbc3786b0 GDAXBrokerage bug fixes (#5477)
- Fixed GDAXBrokerage missing fills caused by an incorrect assumption of a global counter for order fills (it is actually per-symbol)
- Filtered out rate limit messages in the fill monitor task
2021-04-12 12:56:52 -03:00
Colton Sellers
ea11fb41c9 LiveDataBasedDelistingEventProvider Fix (#5471)
* Fix race condition in DelistingEventProvider

* Remove logging and speed up test time advancement

* Reduce timeout to original
2021-04-09 20:26:09 -03:00
Colton Sellers
f5b729dc0d Accept symbol array or IEnumerable for TRIN (#5473) 2021-04-09 12:43:55 -07:00
Jasper van Merle
9ba15b23e3 Make random data generator generate symbols with entries in SPD (#5470)
* Make random data generator generate symbols with entries in SPD

* Cap symbol count in generator when needed
2021-04-09 10:37:35 -07:00
Martin-Molinero
6ab91a13e1 Add note for TimeZoneOffsetProvider StartTime (#5469) 2021-04-08 18:00:17 -03:00
Colton Sellers
beaa705646 Loader Support Full Algorithm Name (#5467)
* Apply fix

* Address possible mismatching subset of name
2021-04-08 17:59:08 -03:00
Colton Sellers
4c830c8235 Fix Breaking Unit Test (#5466)
* Adjust Timeout; Reduce time advance

* Move logging of EndTime above asserts
2021-04-07 21:09:56 -03:00
Colton Sellers
395c1123da Remove Obsolete QCAlgorithm.OnEndOfDay() (#5441)
* Remove and replace OnEndOfDay() ref

* Restore functionality of obsolete EOD, waiting for deprecation in August 2021

* Cleanup

* Adjustments to only post message when using obsolete EOD

* nit, extra space

* Address review

* Adjust test to reflect new behaviour

* Move GetPythonArgCount to an extension method

* Add unit test

* nit accidental import

* Refactor broken test

* Use Py.GIL() state for extension
2021-04-07 13:39:49 -03:00
Martin-Molinero
8e50645640 Update System.Threading.Tasks.Extensions (#5340) 2021-04-07 12:36:22 -03:00
Colton Sellers
68ca504d3a Apply fixes (#5464) 2021-04-07 11:46:31 -03:00
Jasper van Merle
12df1c9a31 Fix drawdown plotting failing on single equity point (#5461) 2021-04-06 16:30:23 -07:00
Aaron Janeiro Stone
4de25b6cd4 _lastLow and _lastHigh are given resets under DeM's Reset method (#5449) 2021-04-06 10:15:16 -03:00
dependabot[bot]
cdef9e709a Bump System.Net.Security from 4.3.0 to 4.3.1 in /Tests (#5453)
Bumps System.Net.Security from 4.3.0 to 4.3.1.

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-04-06 10:11:43 -03:00
Colton Sellers
3579fecc58 Live Consolidator Bug Fix (#5429)
* Set _lastEmit before emitting, otherwise _workingBar is always null

* Aggregate bars if the data endTime is past lastEmit

* Add unit test

* Address Review

* Clean up unit tests

* Refactor solution to set consistent _lastEmit behaviour

* Add another unit test

* Make fixture non-parallelizable

* Undo last change, and adjust breaking test directly
2021-04-05 17:05:53 -07:00
Stefano Raggi
3a390cfa9f Add IB brokerage message event filtering (#5452) 2021-04-05 17:17:14 -03:00
Stefano Raggi
58dae061e7 Add REST API exception logging in Tradier brokerage (#5454) 2021-04-05 17:14:52 -03:00
Martin-Molinero
3f2479393f Update clr-loader and remove workaround (#5451) 2021-04-05 14:25:19 -03:00
Jasper van Merle
4849588c3b Fix flipped operator in random data generator (#5446) 2021-04-05 11:07:51 -03:00
Martin-Molinero
3d84c76abb Add missing timedelta import in python custom data regression algorithms. Relate to https://github.com/QuantConnect/Lean/pull/5426/files (#5450) 2021-04-05 10:26:51 -03:00
Colton Sellers
1c3d849ad5 Fix Warnings V2 (#5436)
* Reconcile duplicated code

* Add License header

* CS0219 Fixes: Value assigned, but never used

* CA1507: Use nameof in place of string literals

* CS0108 : Hides Inherited Member; Use new keyword to overwrite formally

* CS0114: Hides inherited member; use override keyword

* CS0168: Variable is declared but never used

* Tests CS1062; using obsolete implicit Symbol -> String; fix via .ToString()

* CS0472: Non Nullable Obj getting Null Checked

* CS0067 Member not used; ignore all cases for future use

* CS00162 : Unreachable code; either removed or ignored for debugging and test cases

* CS0169 Remove non-used fields; ignore those that may be used in future

* CS0414; Field is assigned but never used.

* CS0618; Obsolete properties and members; Only fixes simple ones, rest will have to broken up

* CS0649; Field never assigned too

* CS0659 & CS0661 ; Overwrite operators and equals but not hashcode; I don't really override it but just call base

* Small comment fix

* Cleanup pragma statement
2021-04-02 11:20:01 -07:00
Jasper van Merle
271220083b Fix various map file generation issues (#5443) 2021-04-02 11:08:02 -07:00
Stefano Raggi
b29d0cbfaf Tradier Brokerage Updates (#5445)
* Tradier brokerage updates

- Add missing status check after REST API calls
- Initialize DataQueueHandler on-demand (on first subscribe call)

* Trigger build
2021-04-02 10:58:27 -07:00
Tomas Rampas
27a25cd663 The null value parameter removed from call of OandaBrokerage c'tor from OandaDownloader class (#5430)
Co-authored-by: rampasto <tomas.rampas@outlook.com>
2021-03-30 15:25:54 -07:00
Derek Melchin
5ed61db2bb Fix timestamps in custom data algorithms (#5426)
* Correct custom data timestamp and match performance across languages

* Add EndTime property

* Add comment for crypto SetHoldings
2021-03-30 14:48:59 -07:00
Colton Sellers
4a1485a291 QB Fundamental Test Fix (#5437)
* Use only 1 QB instance for fundamental tests, (want to see github workflow result)

* Fix small bug in test
2021-03-30 06:42:39 -07:00
Alexandre Catarino
d6072c88a5 Fixes LiveOptionChainProvider.FindOptionContracts (#5434)
`LiveOptionChainProvider.FindOptionContracts` handles the following data format:
`SPY  2021 03 26 190 000 C P  0 612 360000000`
where both existing `OptionRight.Call` and `OptionRight.Put` are declared in the same line.
2021-03-29 13:39:41 -07:00
Colton Sellers
20910ca2dc Broken Regressions Fixes (#5421)
* Remove regression references to non-existant Python versions

* Adjust regressions estimated capacity not adjusted by #5389

* Adjusts regression algorithms so that they pass (Index/Index Options)

  * Changes start/end date on BasicTemplateIndexAlgorithm
  * Changes option pricing model to BlackScholes in
    IndexOptionCallITMGreeksExpiryRegressionAlgorithm

    - The root cause of why there are no greeks at times for these
      options was identified. It is most likely due to the underlying's
      VolatilityModel not having had enough data to be "warmed up",
      which means it will return a standard deviation of zero to the
      option pricing model, rendering most metrics as NaN.

* Adds missing index/index options regression algorithms

  - Regression algorithms are now 1-1 between C# and Python for
    Indexes/Index options. All regression tests are now passing

* Fixes broken BasicTemplateIndex regression algorithm

  * Previously traded SPY, but because we have no SPY data in Lean
    master, I instead opted for index options, since data for those
    dates is already included

* Deal with weekend for breaking test case

* Adjust DefaultEndDate test to always pass

* Check todays date for open

Co-authored-by: Gerardo Salazar <gsalaz9800@gmail.com>
2021-03-29 13:35:03 -07:00
Jasper van Merle
c333ccdc4a Check whether storage directory exists before enumerating it (#5432) 2021-03-29 13:32:28 -07:00
Christian Korn
88c4a332bc Update PearsonCorrelationPairsTradingAlphaModel.cs (#5428)
Fix index of out bounds (#5427)
2021-03-26 10:55:19 -07:00
Colton Sellers
5d762d16b2 GetFundamental Default End Date (#5401)
* Change default end date for GetFundamental

* Add DefaultEndDate test
2021-03-23 14:18:07 -07:00
Colton Sellers
e2a0873b7c Fix Lean Warnings V1 (#5408)
Cleanup all non-breaking warnings
2021-03-22 11:08:48 -07:00
Gerardo Salazar
31ebaaeaa9 Fixes live BTC futures contract crashing in IB brokerage (#5409) 2021-03-22 08:48:58 -07:00
Jared
7625e232f4 Update readme.md 2021-03-19 14:53:46 -07:00
Alexandre Catarino
63f3af7afe Remove decimal.py (#5406)
* Removes decimal.py

* Removes References to Decimal in Examples
2021-03-19 14:17:05 -07:00
Colton Sellers
87b42f6fb5 Named Args Unit Tests (#5381)
Add regression and unit test
2021-03-16 16:53:02 -07:00
Gerardo Salazar
f9dc38efab Use trades per period instead of days for capacity calculation (#5389)
Use trades per period instead of days for capacity calculation
Updates regression algorithms
2021-03-16 16:30:49 -07:00
Colton Sellers
5587efaadd Update Python Runtime dll location (#5398) 2021-03-16 15:56:56 -07:00
Colton Sellers
a642d53bf9 Specify clr-loader version (#5400) 2021-03-16 14:50:47 -07:00
Colton Sellers
002151eab2 PythonNet 2.0.1 (#5390)
* Trigger rebuild

* Add Package QC PythonNet 2.0.1

* Update project files

* Push latest package

* Remove test package for shipping
2021-03-12 22:26:28 -03:00
Gerardo Salazar
4c085ff853 Adds Indexes and Index Options asset types (Backtesting/Live, IB only) (#5379)
* Add support for Index SecurityType  🚀 (#5364)

* Add Index SecurityType  🚀

* Extend SecurityIdentifier & Lean Data classes with Index support

* Add Index SecurityType  🚀

* Extend SecurityIdentifier & Lean Data classes with Index support

* Fixes

* Added index cross basic template demonstration

* WIP: Prototype index security type for LEAN as non tradable asset

* Re-adds Index entries to MHDB after rebase

* First steps to getting Index Options running

  * Looks at any instance where we pattern match for an option type
    and replaces it with a generic call to `.IsOption()` for easier
    extensibility in the future for additional option security types

  * Adds IndexOption security and misc. classes

  * Misc. changes, mainly related to any sort of special casing of
    equity options and made index options take the same path

* Enables index options data for backtesting

  * Adds new index options market hours to MHDB
  * Misc. bug fixes for index options
  * WIP: add live support for index options and indexes
  * Use OptionMarginModel for Index Options because they both use the
    same calculation for margin requirements

* Fixes contract not found errors on SPX index options and SPX index in IB

  * Turns out index options' last trading day is the day before expiry,
    which IB was expecting the last trading day.

* Add index option test cases (temp)

* LiveOptionChainProvider fix, use Symbol vs. ticker

  * Description updates to regression algorithms

* Fixes bug in live trading for indexes and index options

  * Adds overridable minimum price variation symbol property
  * Adds variable sized minimum price variation for index options
  * Adjusts symbol properties for index options
  * Misc. bug fixes

* Fixes option assignment simulation for European options

  * Updates index options regression algorithms (WIP)

* Fixes bug where index option exercise would trade index underlying

  * Fixes bugs where SecurityType.Index was getting flagged as tradable

* Regression algorithms updates and addresses review

  * Misc. style fixes and refactoring + a few bug fixes
  * Updates regression algorithms to run without runtime errors
  * Adds data for regression algos

* Sets DefaultOptionStyle on Canonical and support index options

* Update regression algos statistics

* Removes bad line in regression algorithm causing build to fail

* Minor tweaks

* Address review add comment about quoteBar parse scale

Co-authored-by: Balamurali Pandranki <balamurali@live.com>
Co-authored-by: Jared Broad <jaredbroad@gmail.com>
Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-03-12 20:46:23 -03:00
Jasper van Merle
3aa76d4289 Add report creator to Docker image (#5386) 2021-03-11 14:42:26 -08:00
Martin-Molinero
5236fc202d Adding Symbol.Canonical (#5383)
- Adding Symbol.Canonical property which will be cached. Adding unit and
  regression tests
2021-03-11 18:38:20 -03:00
quantify-cflynn
1ca4389ed2 Adds SharpeRatio indicator (#5348)
* RollingSharpeRatio Submission

Creation of RollingSharpeRatio indicator, utilizing LEAN engine. Tests were created and successfully passed by the indicator, using spy_rsr.txt as outside data file which was created during a prior running of the program.

* Fixed Test Case Loading and Added Indicator Function

Added the RSR() function to auto load the indicator in Algorithm\QCAlgorithm.Indicators.cs. Also added a reference for the test file ("spy_rsr.txt") in Tests\QuantConnect.Tests.csproj.

* Fixed SharpeRatio Indicator

Updated the base formula, indicator structure/call, and the testing data for the SharpeRatio indicator.

* Minor Fixes

- Removed dividend yield from calculation
- Fixed typos in code/documentation

* Minor Style Fix and Error Confirmation

- Changed style to match style guide better.
- Checking for confirmation that QuantConnect.Tests.Engine.DataFeeds.LinveTradingDataFeedTests.DelistedEventEmmited_Equity() is server side, as it runs locally and should not have been affected by prior changes

* Simplification and fixing of SR calculation

- Updates calculation to proper SR formula
- Utilizes IndicatorExtensions for SR calculation rather than manual calculation
- Defines counter for 1 extra period offset on warmup (otherwise first datapoint is inaccurate if warmup period is SharpePeriod length)

* Minor Fixes

- Removal of SharpePeriod and RiskFreeRate variables
- Substitution of (SharpePeriod + 1) for WarmUpPeriod
- Outdated comment fixes

* Resubmission for Mono Confirmation Error

Error detected on Git for this version of the program. An error should not occur as only comments and minor variables were edited. Resubmitting to see if it is a false positive mono error.

* Notation Fixes

Fixed notation regarding spacing and outdated comments.

* Removal of Counter Logic

- Replaces counter for warmup with improved IsReady logic

* Fixed Syntax

- Removed unused imports
- Fixed variable readability
- Fixed comments
- Replaced Tabs with spacing

Co-authored-by: quantify-cflynn <quantify-cflynn>
2021-03-11 13:35:08 -08:00
Jared
b8397db0b7 Usability buffer on allocation (#5385) 2021-03-11 11:44:54 -08:00
Martin-Molinero
d4ea5f7b04 Simplify cash limit allocation (#5382) 2021-03-10 14:47:39 -08:00
Martin-Molinero
458272b2ea Fix mono running in research (#5380) 2021-03-10 17:34:59 -03:00
Colton Sellers
6c7353d09a Trigger rebuild (#5377) 2021-03-09 18:44:18 -03:00
Colton Sellers
834d4a4d58 QC PythonNet 2.0 (#5376)
* Update to new QC PythonNet

* Update readme

* Remove Python.Runtime config, replaced by env var

* Allow local packages testing in repo

* Address Review

* Add the LocalPackages readme

* Update Jupyter Image

* Update Research ReadMe
2021-03-09 18:25:31 -03:00
Gerardo Salazar
561aa3cf25 Adds backwards compatibility for MHDB and SPDB for new SecurityTypes (#5373)
* Adds backwards compatibility for MHDB and SPDB for new SecurityTypes

* Skip invalid SecurityTypes in MHDB and SPDB

* One time log invalid SecurityTypes in MHDB/SPDB

* Moves logging of SecurityType into new extension method

  * Adds TryParseSecurityType to Extensions
2021-03-09 10:52:14 -03:00
hsm207
e4af2ef856 Fix typo (#5374) 2021-03-09 10:29:21 -03:00
Martin-Molinero
3f8158a5be Add live trading Cash enforcement flag (#5372)
- Add live trading cash enforcement flag usefull for brokerages like IB
  which allow trading with currecies you don't have. Updating unit test
2021-03-08 22:09:44 -03:00
Jared
0c4a641590 Changes Protection Level of Constructor of Serialized Order Classes (#5366)
Makes `SerializedOrderEvent.Id` a virtual member.

Co-authored-by: Alexandre Catarino <AlexCatarino@users.noreply.github.com>
2021-03-08 17:03:09 -08:00
Stefano Raggi
20986059a9 Add OutsideRth property to InteractiveBrokersOrderProperties (#5360)
* Add OutsideRth property to InteractiveBrokersOrderProperties

* Address review
2021-03-08 20:15:25 -03:00
Balamurali Pandranki
c22a538bad Indian stock markets support & Zerodha brokerage implementation (#4873)
* Indian stock markets & Samco and Zerodha brokerage implementations

* Build fixes & Implement multi leg orders (BracketOrder & CoverOrder)

* Build fixes

* Clean & refactor

* Clean up & remove samco brokerage

* Clean up & remove samco brokerage

* Fix Nifty, BankNifty & Sensex Index futures expiry time functions

* Fix Nifty, BankNifty & Sensex Index futures expiry time functions

* Fix Futures Expiry Testcases

* Fix Futures Expiry Testcases

* Refactor Zerodha Symbol Mapper

* Refactor Zerodha Symbol Mapper

* Add Future symbols to symbol prop db csv

* Fix Symbol Mapper context

* Fix Market Hours Database

* Fix OrderJsonConverter

* Add Zerodha AccountBaseCurrency

* Add QuantConnect License headers to new source files

* cleanup config.json formatting & tick aggregator implementation

* cleanup config.json formatting & tick aggregator implementation

* Refactor ZerodhaBrokerageModel

* Fix

* Build Fixes

* Refactor

* Refactor Brokerage class & remove TextFieldParser

* Refactor Brokerage FeeModel

* Add ZerodhaOrderProperties

* Add Refactor HistoryProvider

* Refactor CanExecuteOrder

* Refactor SymbolMapper

* Refactor market names

* Refactor & remove Zerodha subscription manager

* Refactor & remove ZerodhaWebSocketChannels

* Refactor & remove ZerodhaWebSocketChannels

* Refactor ZerodhaBrokerage

* Refactor symbol prop db

* zerodha update downloader ticker data using symbol name

* 1 Zerodha mapper class update to get instruments based on Market. 2 Zerodha Getholdings data fetch fix.

* Update market-hours-database.json

* Implement basic testcases for ZerodhaBrokerage

* Update market-hours-database.json

* Update Market.cs

* 1 Fix for Zerodha subscriber and unsubscribe 2 User of CSVHelper to read instrument list

* Rename Zerodha DataQueueHandler class implementation

* Changes related to TradeBar and emit tick

* Fix DataQueueUniverseProvider & Handle Timezone conversion in WS EmitQuotes

* Emit Order Fixes

* DataQueueHandler refactoring and build fix

* Update config.json

* Removal of IHistoryProvider impplementation

* Reverting timezone logic as already taken care by BrokerImplementation using Unix time

* Place, modify and cancel order implementation

* fix zerodha test cases

* Updating get quotes and restricting getHoldings to MIS

* Testcase Fixes

* Testcase Fixes

* Testcase Fixes

* Updating emitFillOrder

* Add ProductType to ZerodhaOrderProperties

* Addition of ZerodhaProduct Type property and test update

* Fix for unit tests and minor changes for place and update order

* Unit test fix for Zerodha

* Addition of the product type and trading segment configs

* PR review fixes

* Addition of trading segment and product type configs

* Nuget Fixes

* Fix ZerodhaBrokerage DataQueueHandler

* Cleanup OrderTypes & rm global.json

* Update UpdateOrderRequest.cs

* Removal of custom csvreader

* Implementing additional method CanPerformSelection

* Add LiveOptionChainProvider

* Clean up and add QC license headers

* Quick cleanup

* Update ZerodhaBrokerage.cs

* Fix OrderEvent timezone conversions

* use item.Unrealised for Intraday position holdings

* Refactor Option chain get instruments calls

* Refactor Option chain get instruments calls

* Review fixes

* Remove whitespaces

* Updating options strike price

* Undo time stamp change

* Optional gethistory

* Addition of comments and minor changes

* Build Fixes

* Add comments for LogType enums

* Options fix

* Fix json name in CsvInstrument

* Update tick generation in DataQueueHandler

- Use Timestamp field for both trades and quotes
- Fix incorrect bid/ask sizes
- Avoid reading depth on each tick to find top quote
- Use new Tick constructors
- Remove unnecessary locking

* Add missing null check in Utils.StringToDate

* Order fixes

- Include TriggerPending orders in GetOpenOrders
- Remove unnecessary invalid check in PlaceOrder
- Fix GetOrderPrice and GetOrderTriggerPrice

* Zerodha account balance fetch

* Removal of Futures and Options

* Remove Futures & Options Support

* Update ZerodhaBrokerage.cs

* Update ZerodhaBrokerage.cs

* Add License headers

* Add License Headers

* Refactor

* historical TradeBar & security fee calculation fixes

* fix brokerage test case

* Update ZerodhaBrokerage.cs

* Update ZerodhaBrokerageHistoryProviderTests.cs

Co-authored-by: Aman Ray <ray.aman9876@gmail.com>
Co-authored-by: Stefano Raggi <stefano.raggi67@gmail.com>
2021-03-08 18:51:54 -03:00
Martin-Molinero
5dcda56a73 Revert "Revert "Upgrade IBAutomater to v1.0.51 (#5359)" (#5362)" (#5365)
This reverts commit c7fb6165e2.
2021-03-08 09:54:50 -03:00
Jasper van Merle
8076782ea6 Make random data generator save non-equity data (#5371) 2021-03-08 09:49:17 -03:00
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
1976 changed files with 167472 additions and 120507 deletions

13
.editorconfig Normal file
View File

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

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

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

22
.github/workflows/regression-tests.yml vendored Normal file
View File

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

3
.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
@@ -195,6 +196,7 @@ publish/
# NuGet Packages
*.nupkg
!LocalPackages/*
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
@@ -203,6 +205,7 @@ publish/
#!**/packages/repositories.config
# ignore sln level nuget
.nuget/
!.nuget/NuGet.config
# Windows Azure Build Output
csx/

144
.idea/readme.md generated
View File

@@ -1,144 +0,0 @@
<h1>Local Development & Docker Integration with Pycharm</h1>
This document contains information regarding ways to use Leans Docker image in conjunction with local development in Pycharm.
<br />
<h1>Getting Setup</h1>
Before anything we need to ensure a few things have been done:
1. Get [Pycharm Professional](https://www.jetbrains.com/pycharm/)**
2. Get [Docker](https://docs.docker.com/get-docker/):
* Follow the instructions for your Operating System
* New to Docker? Try docker getting-started
3. Pull Leans latest image from a terminal
* _docker pull quantconnect/lean_
4. Get Lean into Pycharm
* Download the repo or clone it using: _git clone[ https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)_
* Open the folder using Pycharm
_**PyCharms remote debugger requires PyCharm Professional._
<br />
<h1>Develop Algorithms Locally, Run in Container</h1>
We have set up a relatively easy way to develop algorithms in your local IDE and push them into the container to be run and debugged.
Before we can use this method with Windows or Mac OS we need to share the Lean directory with Docker.
<br />
<h2>Activate File Sharing for Docker:</h2>
* Windows:
* [Guide to sharing](https://docs.docker.com/docker-for-windows/#file-sharing)
* Share the LEAN root directory with docker
* Mac:
* [Guide to sharing](https://docs.docker.com/docker-for-mac/#file-sharing)
* Share the LEAN root directory with docker
* Linux:
* (No setup required)
<br />
<h2>Lean Configuration</h2>
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:
<h3>Python:</h3>
"algorithm-type-name": "**AlgorithmName**",
"algorithm-language": "Python",
"algorithm-location": "../../../Algorithm.Python/**AlgorithmName**.py",
<h4>Note About Python Algorithm Location</h4>
Our specific configuration binds the Algorithm.Python directory to the container by default so any algorithm you would like to run should be in that directory. Please ensure your algorithm location looks just the same as the example above. If you want to use a different location refer to the section bellow on setting that argument for the container and make sure your config.json also reflects this.
<br />
<h2>Running Lean in the Container</h2>
This section will cover how to actually launch Lean in the container with your desired configuration.
From a terminal; Pycharm has a built in terminal on the bottom taskbar labeled **Terminal**; launch the run_docker.bat/.sh script; there are a few choices on how to launch this:
1. Launch with no parameters and answer the questions regarding configuration (Press enter for defaults)
*   Enter docker image [default: quantconnect/lean:latest]:
*   Enter absolute path to Lean config file [default: _~currentDir_\Launcher\config.json]:
*   Enter absolute path to Data folder [default: ~_currentDir_\Data\]:
*   Enter absolute path to store results [default: ~_currentDir_\]:
* Would you like to debug C#? (Requires mono debugger attachment) [default: N]:
2. Using the **run_docker.cfg** to store args for repeated use; any blank entries will resort to default values! example: **_./run_docker.bat run_docker.cfg_**
IMAGE=quantconnect/lean:latest
CONFIG_FILE=
DATA_DIR=
RESULTS_DIR=
DEBUGGING=
PYTHON_DIR=
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat DEBUGGING=y_**
* Accepted args for inline include all listed in the file in #2; must follow the **key=value** format
<br />
<h1>Debugging Python</h1>
Debugging your Python algorithms requires an extra step within your configuration and inside of PyCharm. Thankfully we were able to configure the PyCharm launch configurations to take care of most of the work for you!
<br />
<h2>Modifying the Configuration</h2>
First in order to debug a Python algorithm in Pycharm we must make the following change to our configuration (Launcher\config.json) under the comment debugging configuration:
"debugging": true,
"debugging-method": "PyCharm",
In setting this we are telling Lean to reach out and create a debugger connection using PyCharms PyDevd debugger server. Once this is set Lean will **always** attempt to connect to a debugger server on launch. **If you are no longer debugging set “debugging” to false.**
<br />
<h2>Using PyCharm Launch Options</h2>
Now that Lean is configured for the debugger we can make use of the programmed launch options to connect.
**<h3>Container (Recommended)</h3>**
To debug inside of the container we must first start the debugger server in Pycharm, to do this use the drop down configuration “Debug in Container” and launch the debugger. Be sure to set some breakpoints in your algorithms!
Then we will need to launch the container, follow the steps described in the section “[Running Lean in the Container](#Running-Lean-in-the-Container)”. After launching the container the debugging configuration will take effect and it will connect to the debug server where you can begin debugging your algorithm.
**<h3>Local</h3>**
To debug locally we must run the program locally. First, just as the container setup, start the PyCharm debugger server by running the “Debug Local” configuration.
Then start the program locally by whatever means you typically use, such as Mono, directly running the program at **QuantConnect.Lean.Launcher.exe**, etc. Once the program is running it will make the connection to your PyCharm debugger server where you can begin debugging your algorithm.

37
.idea/workspace.xml generated
View File

@@ -1,37 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<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="HOST" value="localhost" />
<PathMappingSettings>
<option name="pathMappings">
<list />
</option>
</PathMappingSettings>
<option name="REDIRECT_OUTPUT" value="true" />
<option name="SUSPEND_AFTER_CONNECT" value="true" />
<method v="2" />
</configuration>
<configuration name="Debug in Container" type="PyRemoteDebugConfigurationType" factoryName="Python Remote Debug">
<module name="LEAN" />
<option name="PORT" value="5678" />
<option name="HOST" value="localhost" />
<PathMappingSettings>
<option name="pathMappings">
<list>
<mapping local-root="$PROJECT_DIR$" remote-root="/Lean" />
</list>
</option>
</PathMappingSettings>
<option name="REDIRECT_OUTPUT" value="true" />
<option name="SUSPEND_AFTER_CONNECT" value="true" />
<method v="2" />
</configuration>
<list>
<item itemvalue="Python Debug Server.Debug Local" />
<item itemvalue="Python Debug Server.Debug in Container" />
</list>
</component>
</project>

10
.nuget/NuGet.config Normal file
View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageRestore>
<add key="enabled" value="true" />
<add key="automatic" value="true" />
</packageRestore>
<packageSources>
<add key="LocalPackages" value="../LocalPackages" />
</packageSources>
</configuration>

View File

@@ -1,11 +1,12 @@
sudo: required
language: csharp
mono:
- 5.12.0
solution: QuantConnect.Lean.sln
mono: none
dotnet: 5.0
os: linux
dist: focal
before_install:
- export PATH="$HOME/miniconda3/bin:$PATH"
- wget https://cdn.quantconnect.com/miniconda/Miniconda3-4.5.12-Linux-x86_64.sh
- export PYTHONNET_PYDLL="$HOME/miniconda3/lib/libpython3.6m.so"
- wget -q https://cdn.quantconnect.com/miniconda/Miniconda3-4.5.12-Linux-x86_64.sh
- bash Miniconda3-4.5.12-Linux-x86_64.sh -b
- rm -rf Miniconda3-4.5.12-Linux-x86_64.sh
- sudo ln -s $HOME/miniconda3/lib/libpython3.6m.so /usr/lib/libpython3.6m.so
@@ -16,11 +17,7 @@ before_install:
- conda install -y cython=0.29.15
- 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
- chmod +x ci_build_stubs.sh
- sudo -E ./ci_build_stubs.sh -d -t -g -p
- dotnet nuget add source $TRAVIS_BUILD_DIR/LocalPackages
- dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
- dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter TestCategory!=TravisExclude -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\)

View File

@@ -1,64 +1,49 @@
<h1>Local Development & Docker Integration with Visual Studio</h1>
<h1>Local Development with Visual Studio</h1>
This document contains information regarding ways to use Visual Studio to work with the Lean engine, this includes a couple options that make lean easy to develop on any machine:
This document contains information regarding ways to use Visual Studio to work with the Lean's Docker image.
- Using Lean CLI -> A great tool for working with your algorithms locally, while still being able to deploy to the cloud and have access to Lean data. It is also able to run algorithms locally through our official docker images **Recommended for algorithm development.
- Locally installing all dependencies to run Lean with Visual Studio on your OS.
<br />
<h1>Getting Setup</h1>
<h1>Setup</h1>
<h2>Option 1: Lean CLI</h2>
Before anything we need to ensure a few things have been done:
1. Get [Visual Studio](https://code.visualstudio.com/download)
* Get the Extension [VSMonoDebugger](https://marketplace.visualstudio.com/items?itemName=GordianDotNet.VSMonoDebugger0d62) for C# Debugging
2. Get [Docker](https://docs.docker.com/get-docker/):
* Follow the instructions for your Operating System
* New to Docker? Try docker getting-started
3. Pull Leans latest image from a terminal
* _docker pull quantconnect/lean_
4. Get Lean into Visual Studio
* Download the repo or clone it using: _git clone[ https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)_
* Open the solution **QuantConnect.Lean.sln** using Visual Studio
To use Lean CLI follow the instructions for installation and tutorial for usage in our [documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli).
<br />
<h1>Develop Algorithms Locally, Run in Container</h1>
<h2>Option 2: Install Locally</h2>
1. Install [.Net 5](https://dotnet.microsoft.com/download) for the project
We have set up a relatively easy way to develop algorithms in your local IDE and push them into the container to be run and debugged.
2. (Optional) Get [Python 3.6.8](https://www.python.org/downloads/release/python-368/) for running Python algorithms
- Follow Python instructions [here](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#installing-python-36) for your platform
Before we can use this method with Windows or Mac OS we need to share the Lean directory with Docker.
3. Get [Visual Studio](https://visualstudio.microsoft.com/vs/)
4. Get Lean into VS
- Download the repo or clone it using: _git clone [https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)_
- Open the project file with VS (QuantConnect.Lean.sln)
Your environment is prepared and ready to run lean
<br />
<h2>Activate File Sharing for Docker:</h2>
<h1>How to use Lean</h1>
* Windows:
* [Guide to sharing](https://docs.docker.com/docker-for-windows/#file-sharing)
* Share the LEAN root directory with docker
* Mac:
* [Guide to sharing](https://docs.docker.com/docker-for-mac/#file-sharing)
* Share the LEAN root directory with docker
* Linux:
* (No setup required)
This section will cover configuring, launching and debugging lean. This is only applicable to option 2 from above. This does not apply to Lean CLI, please refer to [CLI documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli)
<br />
<h2>Lean Configuration</h2>
<h2>Configuration</h2>
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.
We need to be sure that our Lean configuration at **.\Launcher\config.json** is properly set.
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>
@@ -78,59 +63,11 @@ You configuration file should look something like this for the following languag
<br />
<h2>Important Note About C#</h2>
<h2>Launching Lean</h2>
In order to use a custom C# algorithm, the C# file must be compiled before running in the docker, as it is compiled into the file **"QuantConnect.Algorithm.CSharp.dll"**. Any new C# files will need to be added to the csproj compile list before it will compile, check **Algorithm.CSharp/QuantConnect.Algorithm.CSharp.csproj** for all algorithms that are compiled. Once there is an entry for your algorithm the project can be compiled by using **Build > Build Solution**.
If you would like to debug this file in the docker container one small change to the solutions target build is required.
1. Right click on the solution **QuantConnect.Lean** in the _Solution Explorer_
2. Select **Properties**
3. For project entry **QuantConnect.Algorithm.CSharp** change the configuration to **DebugDocker**
4. Select **Apply** and close out of the window.
5. Build the project at least once before running the docker.
Now that lean is configured we can launch. Use Visual Studio's run option, Make sure QuantConnect.Lean.Launcher is selected as the launch project. Any breakpoints in Lean C# will be triggered.
<br />
<h2>Running Lean in the Container</h2>
This section will cover how to actually launch Lean in the container with your desired configuration.
From a terminal launch the run_docker.bat/.sh script; there are a few choices on how to launch this:
1. Launch with no parameters and answer the questions regarding configuration (Press enter for defaults)
*   Enter docker image [default: quantconnect/lean:latest]:
*   Enter absolute path to Lean config file [default: _~currentDir_\Launcher\config.json]:
*   Enter absolute path to Data folder [default: ~_currentDir_\Data\]:
*   Enter absolute path to store results [default: ~_currentDir_\]:
* Would you like to debug C#? (Requires mono debugger attachment) [default: N]:
2. Using the **run_docker.cfg** to store args for repeated use; any blank entries will resort to default values! example: **_./run_docker.bat run_docker.cfg_**
IMAGE=quantconnect/lean:latest
CONFIG_FILE=
DATA_DIR=
RESULTS_DIR=
DEBUGGING=
PYTHON_DIR=
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat DEBUGGING=y_**
* Accepted args for inline include all listed in the file in #2
<br />
<h1>Connecting to Mono Debugger</h1>
If you launch the script with debugging set to **yes** (y), then you will need to connect to the debugging server with the mono extension that you installed in the setup stage.
To setup the extension do the following:
* Go to **Extensions > Mono > Settings...**
* Enter the following for the settings:
* Remote Host IP: 127.0.0.1
* Remote Host Port: 55555
* Mono Debug Port: 55555
* Click **Save** and then close the extension settings
Now that the extension is setup use it to connect to the Docker container by using:
* **Extensions > Mono > Attach to mono debugger**
The program should then launch and trigger any breakpoints you have set in your C# Algorithm.
<h1>Common Issues</h1>
Here we will cover some common issues with setting this up. Feel free to contribute to this section!

73
.vscode/launch.json vendored
View File

@@ -2,74 +2,39 @@
/*
VS Code Launch configurations for the LEAN engine
Launch w/ Mono (Local):
Builds the project with MSBuild and then launches the program using mono locally;
supports debugging. In order to use this you need msbuild and mono on your system path.
As well as the Mono Debug extension from the marketplace.
Debug in Container:
Launches our run_docker script to start the container and attaches to the debugger.
Requires that you have built the project at least once as it will transfer the compiled
csharp files.
Requires Mono Debug extension from the marketplace.
Launch:
Builds the project with dotnet 5 and then launches the program using coreclr; supports debugging.
In order to use this you need dotnet 5 on your system path, As well as the C# extension from the
marketplace.
Attach to Python (Container):
Will attempt to attach to LEAN in the container using PTVSD. Requires that the container is
actively running and config is set: "debugging": true, "debugging-method": "PTVSD",
Requires Python extension from the marketplace.
Attach to Python (Local):
Attach to Python:
Will attempt to attach to LEAN running locally using PTVSD. Requires that the process is
actively running and config is set: "debugging": true, "debugging-method": "PTVSD",
Requires Python extension from the marketplace.
Requires Python extension from the marketplace. Currently only works with algorithms in
Algorithm.Python directory. This is because we map that directory to our build directory
that contains the py file at runtime. If using another location change "localRoot" value
to the directory in use.
*/
"version": "0.2.0",
"configurations": [
{
"name": "Launch w/ Mono (Local)",
"type": "mono",
"name": "Launch",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"cwd": "${workspaceFolder}/Launcher/bin/Debug/",
"program": "${workspaceFolder}/Launcher/bin/Debug/QuantConnect.Lean.Launcher.exe",
"program": "${workspaceFolder}/Launcher/bin/Debug/QuantConnect.Lean.Launcher.dll",
"args": [
"--data-folder",
"${workspaceFolder}/Data",
"--config",
"${workspaceFolder}/Launcher/config.json"],
"console": "externalTerminal"
"${workspaceFolder}/Launcher/config.json"
],
"cwd": "${workspaceFolder}/Launcher/bin/Debug/",
"stopAtEntry": false,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
{
"name": "Debug in Container",
"type": "mono",
"preLaunchTask": "run-docker",
"postDebugTask": "close-docker",
"request": "attach",
"address": "localhost",
"port": 55555
},
{
"name": "Attach to Mono",
"type": "mono",
"request": "attach",
"address": "localhost",
"postDebugTask": "close-docker",
"port": 55555
},
{
"name": "Attach to Python (Container)",
"type": "python",
"request": "attach",
"port": 5678,
"pathMappings":[{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/Lean/"
}]
},
{
"name": "Attach to Python (Local)",
"name": "Attach to Python",
"type": "python",
"request": "attach",
"port": 5678,

156
.vscode/readme.md vendored
View File

@@ -1,72 +1,51 @@
<h1>Local Development & Docker Integration with Visual Studio Code</h1>
This document contains information regarding ways to use Visual Studio Code to work with the Lean engine, this includes a couple options that make lean easy to develop on any machine:
This document contains information regarding ways to use Visual Studio Code to work with the Lean engine, this includes using Leans Docker image in conjunction with local development as well as running Lean locally.
- Using Lean CLI -> A great tool for working with your algorithms locally, while still being able to deploy to the cloud and have access to Lean data. It is also able to run algorithms locally through our official docker images **Recommended for algorithm development.
- Locally installing all dependencies to run Lean with Visual Studio Code on your OS.
<br />
<h1>Getting Setup</h1>
<h1>Setup</h1>
<h2>Option 1: Lean CLI</h2>
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 [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) for Python Debugging
2. Get [Docker](https://docs.docker.com/get-docker/):
* Follow the instructions for your Operating System
* New to Docker? Try docker getting-started
3. Install a compiler for the project **(Only needed for C# Debugging or Running Locally)**
* On Linux or Mac:
* Install [mono-complete](https://www.mono-project.com/docs/getting-started/install/linux/)
* Test msbuild with command: _msbuild -version_
* On Windows:
* Visual Studio comes packed with msbuild or download without VS [here](https://visualstudio.microsoft.com/downloads/?q=build+tools)
* Put msbuild on your system path and test with command: _msbuild -version_
4. Pull Leans latest image from a terminal
* _docker pull quantconnect/lean_
5. Get Lean into VS Code
* Download the repo or clone it using: _git clone[ https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)_
* Open the folder using VS Code
To use Lean CLI follow the instructions for installation and tutorial for usage in our [documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli)
<br />
<h1>Develop Algorithms Locally, Run in Container</h1>
<h2>Option 2: Install Dependencies Locally</h2>
1. Install [.Net 5](https://dotnet.microsoft.com/download) for the project
We have set up a relatively easy way to develop algorithms in your local IDE and push them into the container to be run and debugged.
2. (Optional) Get [Python 3.6.8](https://www.python.org/downloads/release/python-368/) for running Python algorithms
- Follow Python instructions [here](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#installing-python-36) for your platform
Before we can use this method with Windows or Mac OS we need to share the Lean directory with Docker.
3. Get [Visual Studio Code](https://code.visualstudio.com/download)
- Get the Extension [C#](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp) for C# Debugging
- Get the Extension [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) for Python Debugging
4. Get Lean into VS Code
- Download the repo or clone it using: _git clone [https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)_
- Open the folder using VS Code
Your environment is prepared and ready to run lean
<br />
<h2>Activate File Sharing for Docker:</h2>
<h1>How to use Lean</h1>
* Windows:
* [Guide to sharing](https://docs.docker.com/docker-for-windows/#file-sharing)
* Share the LEAN root directory with docker
* Mac:
* [Guide to sharing](https://docs.docker.com/docker-for-mac/#file-sharing)
* Share the LEAN root directory with docker
* Linux:
* (No setup required)
This section will cover configuring, building, launching and debugging lean. This is only applicable to option 2 from above. This does not apply to Lean CLI, please refer to [CLI documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli)
<br />
<h2>Lean Configuration</h2>
<h2>Configuration</h2>
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.
We need to be sure that our Lean configuration at **.\Launcher\config.json** is properly set.
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>
@@ -84,68 +63,34 @@ You configuration file should look something like this for the following languag
"algorithm-location": "QuantConnect.Algorithm.CSharp.dll",
<br />
<h3>Important Note About C#</h3>
<h2>Building</h2>
In order to use a custom C# algorithm, the C# file must be compiled before running in the docker, as it is compiled into the file "QuantConnect.Algorithm.CSharp.dll". Any new C# files will need to be added to the csproj compile list before it will compile, check Algorithm.CSharp/QuantConnect.Algorithm.CSharp.csproj for all algorithms that are compiled. Once there is an entry for your algorithm the project can be compiled by using the “build” task under _“Terminal” > “Run Build Task”._
Before running Lean, we must build the project. Currently the VS Code task will automatically build before launching. But find more information below about how to trigger building manually.
Python **does not** have this requirement as the engine will compile it on the fly.
In VS Code run build task (Ctrl+Shift+B or "Terminal" dropdown); there are a few options:
- __Build__ - basic build task, just builds Lean once
- __Rebuild__ - rebuild task, completely rebuilds the project. Use if having issues with debugging symbols being loaded for your algorithms.
- __Autobuilder__ - Starts a script that builds then waits for files to change and rebuilds appropriately
- __Clean__ - deletes out all project build files
<br />
<h2>Running Lean in the Container</h2>
<h2>Launching Lean</h2>
This section will cover how to actually launch Lean in the container with your desired configuration.
Now that lean is configured and built we can launch Lean. Under "Run & Debug" use the launch option "Launch". This will start Lean with C# debugging. Any breakpoints in Lean C# will be triggered.
<br />
<h3>Option 1 (Recommended)</h3>
<h2>Debugging Python</h2>
In VS Code click on the debug/run icon on the left toolbar, at the top you should see a drop down menu with launch options, be sure to select **Debug in Container**. This option will kick off a launch script that will start the docker. With this specific launch option the parameters are already configured in VS Codes **tasks.json** under the **run-docker** task args. These set arguments are:
"IMAGE=quantconnect/lean:latest",
"CONFIG_FILE=${workspaceFolder}/Launcher/config.json",
"DATA_DIR=${workspaceFolder}/Data",
"RESULTS_DIR=${workspaceFolder}/Results",
"DEBUGGING=Y",
"PYHTON_DIR=${workspaceFolder}/Algorithm.Python"
As defaults these are all great! Feel free to change them as needed for your setup.
Python algorithms require a little extra work in order to be able to debug them. Follow the steps below to get Python debugging working.
<br />
<h3>Option 2</h3>
From a terminal launch the run_docker.bat/.sh script; there are a few choices on how to launch this:
1. Launch with no parameters and answer the questions regarding configuration (Press enter for defaults)
*   Enter docker image [default: quantconnect/lean:latest]:
*   Enter absolute path to Lean config file [default: .\Launcher\config.json]:
*   Enter absolute path to Data folder [default: .\Data\]:
*   Enter absolute path to store results [default: .\Results]:
* Would you like to debug C#? (Requires mono debugger attachment) [default: N]:
2. Using the **run_docker.cfg** to store args for repeated use; any blank entries will resort to default values! example: **_./run_docker.bat run_docker.cfg_**
IMAGE=quantconnect/lean:latest
CONFIG_FILE=
DATA_DIR=
RESULTS_DIR=
DEBUGGING=
PYTHON_DIR=
3. Inline arguments; anything you don't enter will use the default args! example: **_./run_docker.bat DEBUGGING=y_**
* Accepted args for inline include all listed in the file in #2
<br />
<h1>Debugging Python</h1>
Python algorithms require a little extra work in order to be able to debug them locally or in the container. Thankfully we were able to configure VS code tasks to take care of the work for you! Follow the steps below to get Python debugging working.
<br />
<h2>Modifying the Configuration</h2>
<h3>Modifying the Configuration</h3>
First in order to debug a Python algorithm in VS Code we must make the following change to our configuration (Launcher\config.json) under the comment debugging configuration:
@@ -156,27 +101,11 @@ In setting this we are telling Lean to expect a debugger connection using Pyt
<br />
<h2>Using VS Code Launch Options to Connect</h2>
<h3>Using VS Code Launch Options to Connect</h3>
Now that Lean is configured for the python debugger we can make use of the programmed launch options to connect.
Now that Lean is configured for the python debugger we can make use of the programmed launch options to connect to Lean during runtime.
<br />
<h3>Container</h3>
To debug inside of the container we must first start the container, follow the steps described in the section “[Running Lean in the Container](#Running-Lean-in-the-Container)”. Once the container is started you should see the messages in Figure 2.
If the message is displayed, use the same drop down for “Debug in Container” and select “Attach to Python (Container)”. Then press run, VS Code will now enter and debug any breakpoints you have set in your Python algorithm.
<br />
<h3>Local</h3>
To debug locally we must run the program locally using the programmed task found under Terminal > Run Task > “Run Application”. Once Lean is started you should see the messages in Figure 2.
If the message is displayed, use the launch option “Attach to Python (Local)”. Then press run, VS Code will now enter and debug any breakpoints you have set in your python algorithm.
Start Lean using the "Launch" option covered above. Once Lean starts you should see the messages in figure 2 If the message is displayed, use the launch option “Attach to Python”. Then press run, VS Code will now enter and debug any breakpoints you have set in your python algorithm.
<br />
@@ -194,4 +123,5 @@ _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.
- Autocomplete and reference finding with omnisharp can sometimes bug, if this occurs use the command palette to restart omnisharp. (Ctrl+Shift+P "OmniSharp: Restart OmniSharp")
- Any error messages about building in VSCode that point to comments in JSON. Either select **ignore** or follow steps described [here](https://stackoverflow.com/questions/47834825/in-vs-code-disable-error-comments-are-not-permitted-in-json) to remove the errors entirely.

84
.vscode/tasks.json vendored
View File

@@ -8,11 +8,12 @@
{
"label": "build",
"type": "shell",
"command": "msbuild",
"command": "dotnet",
"args": [
"build",
"/p:Configuration=Debug",
"/p:DebugType=portable",
"/t:build",
"/p:WarningLevel=1"
],
"group": "build",
"presentation": {
@@ -21,15 +22,15 @@
"problemMatcher": "$msCompile"
},
{
"label": "force build linux",
"label": "rebuild",
"type": "shell",
"command": "msbuild",
"command": "dotnet",
"args": [
"/property:GenerateFullPaths=true",
"build",
"--no-incremental",
"/p:Configuration=Debug",
"/p:DebugType=portable",
"/t:build",
"/p:ForceLinuxBuild=true"
"/p:WarningLevel=1"
],
"group": "build",
"presentation": {
@@ -38,74 +39,17 @@
"problemMatcher": "$msCompile"
},
{
"label": "run-docker",
"label": "clean",
"type": "shell",
"isBackground": true,
"windows": {
"command": "${workspaceFolder}/run_docker.bat",
},
"linux": {
"command": "${workspaceFolder}/run_docker.sh"
},
"osx": {
"command": "${workspaceFolder}/run_docker.sh"
},
"command": "dotnet",
"args": [
"IMAGE=quantconnect/lean:latest",
"CONFIG_FILE=${workspaceFolder}/Launcher/config.json",
"DATA_DIR=${workspaceFolder}/Data",
"RESULTS_DIR=${workspaceFolder}/Results",
"DEBUGGING=Y",
"PYTHON_DIR=${workspaceFolder}/Algorithm.Python",
"EXIT=Y"
"clean",
],
"problemMatcher": [
{
"pattern": [
{
"regexp": ".",
"file": 1,
"location": 2,
"message": 3
}
],
"background": {
"activeOnStart": true,
"beginsPattern": ".",
"endsPattern": ".",
}
}
]
},
{
"label": "close-docker",
"type": "shell",
"command": "docker stop LeanEngine",
"group": "build",
"presentation": {
"echo": false,
"reveal": "never",
"focus": false,
"panel": "shared",
"showReuseMessage": false,
"clear": true,
"reveal": "silent"
},
"linux":{
"command": "sudo docker stop LeanEngine"
}
},
{
"label": "Run Application",
"type": "process",
"command": "QuantConnect.Lean.Launcher.exe",
"args" : [
"--data-folder",
"${workspaceFolder}/Data",
"--config",
"${workspaceFolder}/Launcher/config.json"
],
"options": {
"cwd": "${workspaceFolder}/Launcher/bin/Debug/"
}
"problemMatcher": "$msCompile"
}
]
}

View File

@@ -77,43 +77,45 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "199"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-12.472%"},
{"Compounding Annual Return", "-12.392%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-0.586"},
{"Net Profit", "-0.170%"},
{"Sharpe Ratio", "-9.693"},
{"Probabilistic Sharpe Ratio", "12.704%"},
{"Net Profit", "-0.169%"},
{"Sharpe Ratio", "-9.597"},
{"Probabilistic Sharpe Ratio", "13.309%"},
{"Loss Rate", "79%"},
{"Win Rate", "21%"},
{"Profit-Loss Ratio", "0.95"},
{"Alpha", "-0.149"},
{"Beta", "0.037"},
{"Beta", "0.036"},
{"Annual Standard Deviation", "0.008"},
{"Annual Variance", "0"},
{"Information Ratio", "-9.471"},
{"Tracking Error", "0.212"},
{"Treynor Ratio", "-2.13"},
{"Information Ratio", "-9.605"},
{"Tracking Error", "0.214"},
{"Treynor Ratio", "-2.136"},
{"Total Fees", "$199.00"},
{"Estimated Strategy Capacity", "$25000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "38.64"},
{"Kelly Criterion Probability Value", "0.229"},
{"Sortino Ratio", "-21.545"},
{"Return Over Maximum Drawdown", "-77.972"},
{"Portfolio Turnover", "1.135"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "-21.623"},
{"Return Over Maximum Drawdown", "-77.986"},
{"Portfolio Turnover", "1.154"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
{"Total Insights Analysis Completed", "99"},
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$126657.6305"},
{"Total Accumulated Estimated Alpha Value", "$20405.9516"},
{"Mean Population Estimated Insight Value", "$206.1207"},
{"Mean Population Direction", "54.5455%"},
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"},
{"OrderListHash", "1256341962"}
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "7baad0d75f652da1b801ec2fc368e710"}
};
}
}

View File

@@ -111,30 +111,32 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "9"},
{"Average Win", "0.89%"},
{"Average Win", "0.86%"},
{"Average Loss", "-0.27%"},
{"Compounding Annual Return", "196.104%"},
{"Compounding Annual Return", "184.364%"},
{"Drawdown", "1.700%"},
{"Expectancy", "1.853"},
{"Net Profit", "1.498%"},
{"Sharpe Ratio", "4.275"},
{"Probabilistic Sharpe Ratio", "60.462%"},
{"Expectancy", "1.781"},
{"Net Profit", "1.442%"},
{"Sharpe Ratio", "4.017"},
{"Probabilistic Sharpe Ratio", "59.636%"},
{"Loss Rate", "33%"},
{"Win Rate", "67%"},
{"Profit-Loss Ratio", "3.28"},
{"Alpha", "1.574"},
{"Beta", "-0.289"},
{"Annual Standard Deviation", "0.276"},
{"Annual Variance", "0.076"},
{"Information Ratio", "-0.495"},
{"Tracking Error", "0.367"},
{"Treynor Ratio", "-4.079"},
{"Total Fees", "$14.33"},
{"Profit-Loss Ratio", "3.17"},
{"Alpha", "1.53"},
{"Beta", "-0.292"},
{"Annual Standard Deviation", "0.279"},
{"Annual Variance", "0.078"},
{"Information Ratio", "-0.743"},
{"Tracking Error", "0.372"},
{"Treynor Ratio", "-3.845"},
{"Total Fees", "$14.78"},
{"Estimated Strategy Capacity", "$47000000.00"},
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
{"Fitness Score", "0.408"},
{"Kelly Criterion Estimate", "16.447"},
{"Kelly Criterion Probability Value", "0.315"},
{"Sortino Ratio", "13.611"},
{"Return Over Maximum Drawdown", "117.635"},
{"Kelly Criterion Estimate", "16.559"},
{"Kelly Criterion Probability Value", "0.316"},
{"Sortino Ratio", "12.447"},
{"Return Over Maximum Drawdown", "106.327"},
{"Portfolio Turnover", "0.411"},
{"Total Insights Generated", "3"},
{"Total Insights Closed", "3"},
@@ -142,14 +144,14 @@ namespace QuantConnect.Algorithm.CSharp
{"Long Insight Count", "0"},
{"Short Insight Count", "3"},
{"Long/Short Ratio", "0%"},
{"Estimated Monthly Alpha Value", "$19868365.6628"},
{"Total Accumulated Estimated Alpha Value", "$3421774.0864"},
{"Mean Population Estimated Insight Value", "$1140591.3621"},
{"Estimated Monthly Alpha Value", "$20784418.6104"},
{"Total Accumulated Estimated Alpha Value", "$3579538.7607"},
{"Mean Population Estimated Insight Value", "$1193179.5869"},
{"Mean Population Direction", "100%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "100%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-887015098"}
{"OrderListHash", "9da9afe1e9137638a55db1676adc2be1"}
};
}
}

View File

@@ -185,6 +185,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.043"},
{"Treynor Ratio", "0"},
{"Total Fees", "$7.40"},
{"Estimated Strategy Capacity", "$28000000.00"},
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
{"Fitness Score", "1"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -204,7 +206,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

@@ -21,6 +21,7 @@ using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
namespace QuantConnect.Algorithm.CSharp
{
@@ -123,9 +124,33 @@ namespace QuantConnect.Algorithm.CSharp
if (!optionInvested && data.ContainsKey(option))
{
var optionContract = Securities[option];
var marginModel = optionContract.BuyingPowerModel as FuturesOptionsMarginModel;
if (marginModel.InitialIntradayMarginRequirement == 0
|| marginModel.InitialOvernightMarginRequirement == 0
|| marginModel.MaintenanceIntradayMarginRequirement == 0
|| marginModel.MaintenanceOvernightMarginRequirement == 0)
{
throw new Exception("Unexpected margin requirements");
}
if (marginModel.GetInitialMarginRequirement(optionContract, 1) == 0)
{
throw new Exception("Unexpected Initial Margin requirement");
}
if (marginModel.GetMaintenanceMargin(optionContract) != 0)
{
throw new Exception("Unexpected Maintenance Margin requirement");
}
MarketOrder(option, 1);
_invested = true;
optionInvested = true;
if (marginModel.GetMaintenanceMargin(optionContract) == 0)
{
throw new Exception("Unexpected Maintenance Margin requirement");
}
}
if (!futureInvested && data.ContainsKey(future))
{
@@ -219,6 +244,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.044"},
{"Treynor Ratio", "0.479"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$41000.00"},
{"Lowest Capacity Asset", "ES 31C3JQTOYO9T0|ES XCZJLC9NOB29"},
{"Fitness Score", "0.41"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -238,7 +265,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,16 @@ 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.011"},
{"Annual Standard Deviation", "0.006"},
{"Annual Variance", "0"},
{"Information Ratio", "-3.424"},
{"Tracking Error", "0.057"},
{"Treynor Ratio", "-4.775"},
{"Information Ratio", "-3.385"},
{"Tracking Error", "0.058"},
{"Treynor Ratio", "2.117"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$45000000.00"},
{"Lowest Capacity Asset", "AOL R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -158,7 +160,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

@@ -183,14 +183,16 @@ namespace QuantConnect.Algorithm.CSharp
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.027"},
{"Beta", "-0.174"},
{"Alpha", "0.024"},
{"Beta", "-0.171"},
{"Annual Standard Deviation", "0.006"},
{"Annual Variance", "0"},
{"Information Ratio", "-11.586"},
{"Tracking Error", "0.042"},
{"Treynor Ratio", "0.286"},
{"Information Ratio", "-11.082"},
{"Tracking Error", "0.043"},
{"Treynor Ratio", "0.291"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$2800000.00"},
{"Lowest Capacity Asset", "AOL VRKS95ENLBYE|AOL R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -210,7 +212,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

@@ -79,19 +79,19 @@ namespace QuantConnect.Algorithm.CSharp
// things like manually added, auto added, internal, and any other boolean state we need to track against a single security)
throw new Exception("The underlying equity data should NEVER be removed in this algorithm because it was manually added");
}
if (_expectedSecurities.AreDifferent(LinqExtensions.ToHashSet(Securities.Keys)))
if (_expectedSecurities.AreDifferent(Securities.Keys.ToHashSet()))
{
var expected = string.Join(Environment.NewLine, _expectedSecurities.OrderBy(s => s.ToString()));
var actual = string.Join(Environment.NewLine, Securities.Keys.OrderBy(s => s.ToString()));
throw new Exception($"{Time}:: Detected differences in expected and actual securities{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
}
if (_expectedUniverses.AreDifferent(LinqExtensions.ToHashSet(UniverseManager.Keys)))
if (_expectedUniverses.AreDifferent(UniverseManager.Keys.ToHashSet()))
{
var expected = string.Join(Environment.NewLine, _expectedUniverses.OrderBy(s => s.ToString()));
var actual = string.Join(Environment.NewLine, UniverseManager.Keys.OrderBy(s => s.ToString()));
throw new Exception($"{Time}:: Detected differences in expected and actual universes{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
}
if (_expectedData.AreDifferent(LinqExtensions.ToHashSet(data.Keys)))
if (_expectedData.AreDifferent(data.Keys.ToHashSet()))
{
var expected = string.Join(Environment.NewLine, _expectedData.OrderBy(s => s.ToString()));
var actual = string.Join(Environment.NewLine, data.Keys.OrderBy(s => s.ToString()));
@@ -183,7 +183,7 @@ namespace QuantConnect.Algorithm.CSharp
if (changes.RemovedSecurities
.Where(x => x.Symbol.SecurityType == SecurityType.Option)
.ToHashSet(s => s.Symbol)
.AreDifferent(LinqExtensions.ToHashSet(_expectedContracts)))
.AreDifferent(_expectedContracts.ToHashSet()))
{
throw new Exception("Expected removed securities to equal expected contracts added");
}
@@ -230,6 +230,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$6.00"},
{"Estimated Strategy Capacity", "$2000.00"},
{"Lowest Capacity Asset", "GOOCV 305RBQ2BZBZT2|GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -249,7 +251,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "731140098"}
{"OrderListHash", "1e7b3e90918777b9dbf46353a96f3329"}
};
}
}

View File

@@ -112,30 +112,32 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "5"},
{"Average Win", "0.47%"},
{"Average Win", "0.46%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "293.067%"},
{"Compounding Annual Return", "296.356%"},
{"Drawdown", "1.400%"},
{"Expectancy", "0"},
{"Net Profit", "1.765%"},
{"Sharpe Ratio", "13.11"},
{"Probabilistic Sharpe Ratio", "80.231%"},
{"Net Profit", "1.776%"},
{"Sharpe Ratio", "13.013"},
{"Probabilistic Sharpe Ratio", "80.409%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.705"},
{"Beta", "0.7"},
{"Annual Standard Deviation", "0.157"},
{"Annual Variance", "0.025"},
{"Information Ratio", "1.76"},
{"Alpha", "0.68"},
{"Beta", "0.707"},
{"Annual Standard Deviation", "0.16"},
{"Annual Variance", "0.026"},
{"Information Ratio", "1.378"},
{"Tracking Error", "0.072"},
{"Treynor Ratio", "2.933"},
{"Total Fees", "$26.39"},
{"Treynor Ratio", "2.946"},
{"Total Fees", "$28.30"},
{"Estimated Strategy Capacity", "$4700000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Fitness Score", "0.374"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "373.973"},
{"Return Over Maximum Drawdown", "372.086"},
{"Portfolio Turnover", "0.374"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -150,7 +152,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1779055144"}
{"OrderListHash", "ac3f4dfcdeb98b488b715412ad2d6c4f"}
};
}
}

View File

@@ -67,28 +67,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "3"},
{"Average Win", "1.02%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "289.119%"},
{"Compounding Annual Return", "296.066%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Net Profit", "1.752%"},
{"Sharpe Ratio", "9.235"},
{"Probabilistic Sharpe Ratio", "68.013%"},
{"Net Profit", "1.775%"},
{"Sharpe Ratio", "9.373"},
{"Probabilistic Sharpe Ratio", "68.302%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.105"},
{"Beta", "1.022"},
{"Annual Standard Deviation", "0.224"},
{"Annual Variance", "0.05"},
{"Information Ratio", "24.59"},
{"Beta", "1.021"},
{"Annual Standard Deviation", "0.227"},
{"Annual Variance", "0.052"},
{"Information Ratio", "25.083"},
{"Tracking Error", "0.006"},
{"Treynor Ratio", "2.029"},
{"Total Fees", "$9.77"},
{"Treynor Ratio", "2.086"},
{"Total Fees", "$10.33"},
{"Estimated Strategy Capacity", "$38000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.747"},
{"Kelly Criterion Estimate", "38.64"},
{"Kelly Criterion Probability Value", "0.229"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "107.109"},
{"Return Over Maximum Drawdown", "107.013"},
{"Portfolio Turnover", "0.747"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
@@ -96,14 +98,14 @@ namespace QuantConnect.Algorithm.CSharp
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$126657.6305"},
{"Total Accumulated Estimated Alpha Value", "$20405.9516"},
{"Mean Population Estimated Insight Value", "$206.1207"},
{"Mean Population Direction", "54.5455%"},
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"},
{"OrderListHash", "-887190565"}
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "af3a9c98c190d1b6b36fad184e796b0b"}
};
}
}

View File

@@ -86,28 +86,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "10"},
{"Average Win", "0%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-14.333%"},
{"Compounding Annual Return", "-13.928%"},
{"Drawdown", "3.300%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.169%"},
{"Sharpe Ratio", "-0.131"},
{"Probabilistic Sharpe Ratio", "45.057%"},
{"Net Profit", "-0.164%"},
{"Sharpe Ratio", "-0.12"},
{"Probabilistic Sharpe Ratio", "45.109%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-3.068"},
{"Beta", "0.595"},
{"Annual Standard Deviation", "0.382"},
{"Annual Variance", "0.146"},
{"Information Ratio", "-13.618"},
{"Tracking Error", "0.376"},
{"Alpha", "-2.892"},
{"Beta", "0.551"},
{"Annual Standard Deviation", "0.385"},
{"Annual Variance", "0.149"},
{"Information Ratio", "-13.646"},
{"Tracking Error", "0.382"},
{"Treynor Ratio", "-0.084"},
{"Total Fees", "$13.98"},
{"Fitness Score", "0.146"},
{"Total Fees", "$22.21"},
{"Estimated Strategy Capacity", "$340000000.00"},
{"Lowest Capacity Asset", "FB V6OIPNZEM8V9"},
{"Fitness Score", "0.147"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "1"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-4.398"},
{"Return Over Maximum Drawdown", "-4.264"},
{"Portfolio Turnover", "0.268"},
{"Total Insights Generated", "15"},
{"Total Insights Closed", "12"},
@@ -122,7 +124,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1917702312"}
{"OrderListHash", "28605a89cd5f0d59ebe14af370764291"}
};
}
}

View File

@@ -90,31 +90,33 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "23"},
{"Total Trades", "25"},
{"Average Win", "0.00%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-75.307%"},
{"Compounding Annual Return", "-75.369%"},
{"Drawdown", "5.800%"},
{"Expectancy", "-0.859"},
{"Net Profit", "-5.586%"},
{"Sharpe Ratio", "-3.257"},
{"Probabilistic Sharpe Ratio", "5.931%"},
{"Loss Rate", "92%"},
{"Win Rate", "8%"},
{"Profit-Loss Ratio", "0.70"},
{"Alpha", "-0.593"},
{"Beta", "0.692"},
{"Expectancy", "-0.748"},
{"Net Profit", "-5.596%"},
{"Sharpe Ratio", "-3.271"},
{"Probabilistic Sharpe Ratio", "5.816%"},
{"Loss Rate", "85%"},
{"Win Rate", "15%"},
{"Profit-Loss Ratio", "0.64"},
{"Alpha", "-0.595"},
{"Beta", "0.707"},
{"Annual Standard Deviation", "0.204"},
{"Annual Variance", "0.042"},
{"Information Ratio", "-2.884"},
{"Tracking Error", "0.194"},
{"Treynor Ratio", "-0.962"},
{"Total Fees", "$25.92"},
{"Annual Variance", "0.041"},
{"Information Ratio", "-2.928"},
{"Tracking Error", "0.193"},
{"Treynor Ratio", "-0.942"},
{"Total Fees", "$35.25"},
{"Estimated Strategy Capacity", "$520000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.004"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "1"},
{"Sortino Ratio", "-4.462"},
{"Return Over Maximum Drawdown", "-13.032"},
{"Sortino Ratio", "-4.466"},
{"Return Over Maximum Drawdown", "-13.048"},
{"Portfolio Turnover", "0.083"},
{"Total Insights Generated", "33"},
{"Total Insights Closed", "30"},
@@ -129,7 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1674230481"}
{"OrderListHash", "93b8c04ef334327062d5a79e6dd73130"}
};
}
}

View File

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

View File

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

View File

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

View File

@@ -160,14 +160,16 @@ namespace QuantConnect.Algorithm.CSharp
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "5.579"},
{"Beta", "-63.972"},
{"Alpha", "5.56"},
{"Beta", "-71.105"},
{"Annual Standard Deviation", "0.434"},
{"Annual Variance", "0.188"},
{"Information Ratio", "0.996"},
{"Tracking Error", "0.441"},
{"Treynor Ratio", "-0.008"},
{"Information Ratio", "1.016"},
{"Tracking Error", "0.44"},
{"Treynor Ratio", "-0.007"},
{"Total Fees", "$20.35"},
{"Estimated Strategy Capacity", "$19000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.138"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -187,7 +189,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

@@ -113,28 +113,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "264.819%"},
{"Compounding Annual Return", "271.453%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Net Profit", "1.668%"},
{"Sharpe Ratio", "8.749"},
{"Probabilistic Sharpe Ratio", "67.311%"},
{"Net Profit", "1.692%"},
{"Sharpe Ratio", "8.888"},
{"Probabilistic Sharpe Ratio", "67.609%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.005"},
{"Beta", "0.996"},
{"Annual Standard Deviation", "0.219"},
{"Annual Variance", "0.048"},
{"Information Ratio", "-14.189"},
{"Annual Standard Deviation", "0.222"},
{"Annual Variance", "0.049"},
{"Information Ratio", "-14.565"},
{"Tracking Error", "0.001"},
{"Treynor Ratio", "1.922"},
{"Total Fees", "$3.26"},
{"Treynor Ratio", "1.978"},
{"Total Fees", "$3.44"},
{"Estimated Strategy Capacity", "$56000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.248"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "93.761"},
{"Return Over Maximum Drawdown", "93.728"},
{"Portfolio Turnover", "0.248"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -149,7 +151,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "491919591"}
{"OrderListHash", "9e4bfd2eb0b81ee5bc1b197a87ccedbe"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -76,9 +76,11 @@ namespace QuantConnect.Algorithm.CSharp
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!_equityBought && data.ContainsKey(_spy)) {
//Buy our Equity
var quantity = CalculateOrderQuantity(_spy, .1m);
if (!_equityBought && data.ContainsKey(_spy))
{
//Buy our Equity.
//Quantity is rounded down to an even number since it will be split in two equal halves
var quantity = Math.Floor(CalculateOrderQuantity(_spy, .1m) / 2) * 2;
_equityBuy = MarketOrder(_spy, quantity, asynchronous: true);
_equityBought = true;
}
@@ -119,7 +121,7 @@ namespace QuantConnect.Algorithm.CSharp
var order = Transactions.GetOrderById(orderEvent.OrderId);
// Based on the type verify the order
switch(order.Type)
switch (order.Type)
{
case OrderType.Market:
VerifyMarketOrder(order, orderEvent);
@@ -140,7 +142,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <param name="order">Order object to analyze</param>
public void VerifyMarketOrder(Order order, OrderEvent orderEvent)
{
switch(order.Status)
switch (order.Status)
{
case OrderStatus.Submitted:
break;
@@ -152,7 +154,7 @@ namespace QuantConnect.Algorithm.CSharp
throw new Exception("LastFillTime should not be null");
}
if (order.Quantity/2 != orderEvent.FillQuantity)
if (order.Quantity / 2 != orderEvent.FillQuantity)
{
throw new Exception("Order size should be half");
}
@@ -215,9 +217,9 @@ namespace QuantConnect.Algorithm.CSharp
}
//Check equity holding, should be invested, profit should be
//Quantity should be 50, AveragePrice should be ticket AverageFillPrice
//Quantity should be 52, AveragePrice should be ticket AverageFillPrice
var equityHolding = Portfolio[_equityBuy.Symbol];
if (!equityHolding.Invested || equityHolding.Quantity != 50 || equityHolding.AveragePrice != _equityBuy.AverageFillPrice)
if (!equityHolding.Invested || equityHolding.Quantity != 52 || equityHolding.AveragePrice != _equityBuy.AverageFillPrice)
{
throw new Exception("Equity holding does not match expected outcome");
}
@@ -299,25 +301,45 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "-0.40%"},
{"Compounding Annual Return", "-22.335%"},
{"Compounding Annual Return", "-22.717%"},
{"Drawdown", "0.400%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.323%"},
{"Sharpe Ratio", "-0.888"},
{"Net Profit", "-0.329%"},
{"Sharpe Ratio", "-11.083"},
{"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.003"},
{"Beta", "0.097"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "12.058"},
{"Tracking Error", "0.017"},
{"Treynor Ratio", "-0.018"},
{"Information Ratio", "9.742"},
{"Tracking Error", "0.021"},
{"Treynor Ratio", "-0.26"},
{"Total Fees", "$2.00"},
{"Fitness Score", "0.213"},
{"OrderListHash", "904167951"}
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0.212"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-73.334"},
{"Portfolio Turnover", "0.425"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "7f99e1a8ce4675a1e8bbe1ba45967ccd"}
};
}
}

View File

@@ -88,6 +88,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$85000.00"},
{"Lowest Capacity Asset", "BTCEUR XJ"},
{"Fitness Score", "0.506"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -107,7 +109,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

@@ -80,28 +80,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "264.819%"},
{"Compounding Annual Return", "271.453%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Net Profit", "1.668%"},
{"Sharpe Ratio", "8.749"},
{"Probabilistic Sharpe Ratio", "67.311%"},
{"Net Profit", "1.692%"},
{"Sharpe Ratio", "8.888"},
{"Probabilistic Sharpe Ratio", "67.609%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.005"},
{"Beta", "0.996"},
{"Annual Standard Deviation", "0.219"},
{"Annual Variance", "0.048"},
{"Information Ratio", "-14.189"},
{"Annual Standard Deviation", "0.222"},
{"Annual Variance", "0.049"},
{"Information Ratio", "-14.565"},
{"Tracking Error", "0.001"},
{"Treynor Ratio", "1.922"},
{"Total Fees", "$3.26"},
{"Treynor Ratio", "1.978"},
{"Total Fees", "$3.44"},
{"Estimated Strategy Capacity", "$56000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.248"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "93.761"},
{"Return Over Maximum Drawdown", "93.728"},
{"Portfolio Turnover", "0.248"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -116,7 +118,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "491919591"}
{"OrderListHash", "9e4bfd2eb0b81ee5bc1b197a87ccedbe"}
};
}
}
}

View File

@@ -223,6 +223,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$85.34"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTCEUR XJ"},
{"Fitness Score", "0.5"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -242,7 +244,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

@@ -71,29 +71,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "246.000%"},
{"Drawdown", "1.100%"},
{"Compounding Annual Return", "246.546%"},
{"Drawdown", "1.200%"},
{"Expectancy", "0"},
{"Net Profit", "3.459%"},
{"Sharpe Ratio", "10.11"},
{"Probabilistic Sharpe Ratio", "83.150%"},
{"Net Profit", "3.464%"},
{"Sharpe Ratio", "9.933"},
{"Probabilistic Sharpe Ratio", "82.470%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.935"},
{"Beta", "-0.119"},
{"Annual Standard Deviation", "0.16"},
{"Annual Variance", "0.026"},
{"Information Ratio", "-4.556"},
{"Tracking Error", "0.221"},
{"Treynor Ratio", "-13.568"},
{"Total Fees", "$3.26"},
{"Fitness Score", "0.111"},
{"Alpha", "1.957"},
{"Beta", "-0.125"},
{"Annual Standard Deviation", "0.164"},
{"Annual Variance", "0.027"},
{"Information Ratio", "-4.577"},
{"Tracking Error", "0.225"},
{"Treynor Ratio", "-13.006"},
{"Total Fees", "$3.45"},
{"Estimated Strategy Capacity", "$970000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.112"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "52.533"},
{"Return Over Maximum Drawdown", "214.75"},
{"Portfolio Turnover", "0.111"},
{"Sortino Ratio", "53.951"},
{"Return Over Maximum Drawdown", "209.464"},
{"Portfolio Turnover", "0.112"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -107,7 +109,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1268340653"}
{"OrderListHash", "33d01821923c397f999cfb2e5b5928ad"}
};
}
}

View File

@@ -92,28 +92,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "-1.01%"},
{"Compounding Annual Return", "254.782%"},
{"Compounding Annual Return", "261.134%"},
{"Drawdown", "2.200%"},
{"Expectancy", "-1"},
{"Net Profit", "1.632%"},
{"Sharpe Ratio", "8.371"},
{"Probabilistic Sharpe Ratio", "66.555%"},
{"Net Profit", "1.655%"},
{"Sharpe Ratio", "8.505"},
{"Probabilistic Sharpe Ratio", "66.840%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.088"},
{"Alpha", "-0.091"},
{"Beta", "1.006"},
{"Annual Standard Deviation", "0.221"},
{"Annual Variance", "0.049"},
{"Information Ratio", "-32.586"},
{"Annual Standard Deviation", "0.224"},
{"Annual Variance", "0.05"},
{"Information Ratio", "-33.445"},
{"Tracking Error", "0.002"},
{"Treynor Ratio", "1.839"},
{"Total Fees", "$9.77"},
{"Treynor Ratio", "1.893"},
{"Total Fees", "$10.32"},
{"Estimated Strategy Capacity", "$27000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.747"},
{"Kelly Criterion Estimate", "38.64"},
{"Kelly Criterion Probability Value", "0.229"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "85.209"},
{"Return Over Maximum Drawdown", "85.095"},
{"Portfolio Turnover", "0.747"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
@@ -121,14 +123,14 @@ namespace QuantConnect.Algorithm.CSharp
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$126657.6305"},
{"Total Accumulated Estimated Alpha Value", "$20405.9516"},
{"Mean Population Estimated Insight Value", "$206.1207"},
{"Mean Population Direction", "54.5455%"},
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"},
{"OrderListHash", "951346025"}
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "ad2216297c759d8e5aef48ff065f8919"}
};
}
}

View File

@@ -139,14 +139,16 @@ namespace QuantConnect.Algorithm.CSharp
{"Loss Rate", "89%"},
{"Win Rate", "11%"},
{"Profit-Loss Ratio", "0.69"},
{"Alpha", "4.398"},
{"Beta", "-0.989"},
{"Alpha", "4.469"},
{"Beta", "-0.961"},
{"Annual Standard Deviation", "0.373"},
{"Annual Variance", "0.139"},
{"Information Ratio", "-12.816"},
{"Tracking Error", "0.504"},
{"Treynor Ratio", "1.011"},
{"Information Ratio", "-13.191"},
{"Tracking Error", "0.507"},
{"Treynor Ratio", "1.04"},
{"Total Fees", "$15207.00"},
{"Estimated Strategy Capacity", "$8000.00"},
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
{"Fitness Score", "0.033"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -166,7 +168,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

@@ -147,14 +147,16 @@ namespace QuantConnect.Algorithm.CSharp
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-1.347"},
{"Alpha", "-1.362"},
{"Beta", "0.257"},
{"Annual Standard Deviation", "0.109"},
{"Annual Variance", "0.012"},
{"Information Ratio", "-14.763"},
{"Tracking Error", "0.188"},
{"Treynor Ratio", "-3.318"},
{"Information Ratio", "-14.947"},
{"Tracking Error", "0.19"},
{"Treynor Ratio", "-3.309"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$52000000.00"},
{"Lowest Capacity Asset", "GC VL5E74HP3EE5"},
{"Fitness Score", "0.009"},
{"Kelly Criterion Estimate", "-112.972"},
{"Kelly Criterion Probability Value", "0.671"},
@@ -174,7 +176,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,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -179,7 +181,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

@@ -0,0 +1,158 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using QuantConnect.Data;
using System.Collections.Generic;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to add index asset types.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="benchmarks" />
/// <meta name="tag" content="indexes" />
public class BasicTemplateIndexAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spx;
private Symbol _spxOption;
private ExponentialMovingAverage _emaSlow;
private ExponentialMovingAverage _emaFast;
/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
public override void Initialize()
{
SetStartDate(2021, 1, 4);
SetEndDate(2021, 1, 15);
SetCash(1000000);
// Use indicator for signal; but it cannot be traded
_spx = AddIndex("SPX", Resolution.Minute).Symbol;
// Trade on SPX ITM calls
_spxOption = QuantConnect.Symbol.CreateOption(
_spx,
Market.USA,
OptionStyle.European,
OptionRight.Call,
3200m,
new DateTime(2021, 1, 15));
AddIndexOptionContract(_spxOption, Resolution.Minute);
_emaSlow = EMA(_spx, 80);
_emaFast = EMA(_spx, 200);
}
/// <summary>
/// Index EMA Cross trading underlying.
/// </summary>
public override void OnData(Slice slice)
{
if (!slice.Bars.ContainsKey(_spx) || !slice.Bars.ContainsKey(_spxOption))
{
return;
}
// Warm up indicators
if (!_emaSlow.IsReady)
{
return;
}
if (_emaFast > _emaSlow)
{
SetHoldings(_spxOption, 1);
}
else
{
Liquidate();
}
}
public override void OnEndOfAlgorithm()
{
if (Portfolio[_spx].TotalSaleVolume > 0)
{
throw new Exception("Index is not tradable.");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "4"},
{"Average Win", "0%"},
{"Average Loss", "-53.10%"},
{"Compounding Annual Return", "-96.172%"},
{"Drawdown", "10.100%"},
{"Expectancy", "-1"},
{"Net Profit", "-9.915%"},
{"Sharpe Ratio", "-4.217"},
{"Probabilistic Sharpe Ratio", "0.052%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.908"},
{"Beta", "0.468"},
{"Annual Standard Deviation", "0.139"},
{"Annual Variance", "0.019"},
{"Information Ratio", "-9.003"},
{"Tracking Error", "0.142"},
{"Treynor Ratio", "-1.251"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$14000000.00"},
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
{"Fitness Score", "0.044"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-1.96"},
{"Return Over Maximum Drawdown", "-10.171"},
{"Portfolio Turnover", "0.34"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "52521ab779446daf4d38a7c9bbbdd893"}
};
}
}

View File

@@ -0,0 +1,180 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using QuantConnect.Data;
using System.Collections.Generic;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to add index asset types and trade index options on SPX.
/// </summary>
public class BasicTemplateIndexOptionsAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spx;
private ExponentialMovingAverage _emaSlow;
private ExponentialMovingAverage _emaFast;
/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
public override void Initialize()
{
SetStartDate(2021, 1, 4);
SetEndDate(2021, 2, 1);
SetCash(1000000);
// Use indicator for signal; but it cannot be traded.
// We will instead trade on SPX options
_spx = AddIndex("SPX", Resolution.Minute).Symbol;
var spxOptions = AddIndexOption(_spx, Resolution.Minute);
spxOptions.SetFilter(filterFunc => filterFunc.CallsOnly());
_emaSlow = EMA(_spx, 80);
_emaFast = EMA(_spx, 200);
}
/// <summary>
/// Index EMA Cross trading index options of the index.
/// </summary>
public override void OnData(Slice slice)
{
if (!slice.Bars.ContainsKey(_spx))
{
Debug($"No SPX on {Time}");
return;
}
// Warm up indicators
if (!_emaSlow.IsReady)
{
Debug($"EMA slow not ready on {Time}");
return;
}
foreach (var chain in slice.OptionChains.Values)
{
foreach (var contract in chain.Contracts.Values)
{
if (contract.Expiry.Month == 3 && contract.Symbol.ID.StrikePrice == 3700m && contract.Right == OptionRight.Call && slice.QuoteBars.ContainsKey(contract.Symbol))
{
Log($"{Time} {contract.Strike}{(contract.Right == OptionRight.Call ? 'C' : 'P')} -- {slice.QuoteBars[contract.Symbol]}");
}
if (Portfolio.Invested)
{
continue;
}
if (_emaFast > _emaSlow && contract.Right == OptionRight.Call)
{
Liquidate(InvertOption(contract.Symbol));
MarketOrder(contract.Symbol, 1);
}
else if (_emaFast < _emaSlow && contract.Right == OptionRight.Put)
{
Liquidate(InvertOption(contract.Symbol));
MarketOrder(contract.Symbol, 1);
}
}
}
}
public override void OnEndOfAlgorithm()
{
if (Portfolio[_spx].TotalSaleVolume > 0)
{
throw new Exception("Index is not tradable.");
}
if (Portfolio.TotalSaleVolume == 0)
{
throw new Exception("Trade volume should be greater than zero by the end of this algorithm");
}
}
public Symbol InvertOption(Symbol symbol)
{
return QuantConnect.Symbol.CreateOption(
symbol.Underlying,
symbol.ID.Market,
symbol.ID.OptionStyle,
symbol.ID.OptionRight == OptionRight.Call ? OptionRight.Put : OptionRight.Call,
symbol.ID.StrikePrice,
symbol.ID.Date);
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "8220"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "13.500%"},
{"Expectancy", "-0.818"},
{"Net Profit", "-13.517%"},
{"Sharpe Ratio", "-2.678"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "89%"},
{"Win Rate", "11%"},
{"Profit-Loss Ratio", "0.69"},
{"Alpha", "4.398"},
{"Beta", "-0.989"},
{"Annual Standard Deviation", "0.373"},
{"Annual Variance", "0.139"},
{"Information Ratio", "-12.816"},
{"Tracking Error", "0.504"},
{"Treynor Ratio", "1.011"},
{"Total Fees", "$15207.00"},
{"Estimated Strategy Capacity", "$8800000.00"},
{"Fitness Score", "0.033"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-8.62"},
{"Return Over Maximum Drawdown", "-7.81"},
{"Portfolio Turnover", "302.321"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "35b3f4b7a225468d42ca085386a2383e"}
};
}
}

View File

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

View File

@@ -134,6 +134,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$778.00"},
{"Estimated Strategy Capacity", "$1000.00"},
{"Lowest Capacity Asset", "GOOCV W78ZFMEBBB2E|GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -153,7 +155,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-702975961"}
{"OrderListHash", "6a88f302b7f29a2c59e4b1e978161da1"}
};
}
}

View File

@@ -131,6 +131,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$1300000.00"},
{"Lowest Capacity Asset", "GOOCV 30AKMEIPOSS1Y|GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -150,7 +152,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,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -141,7 +143,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,9 @@ 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"},
{"Lowest Capacity Asset", "AAPL 2ZQGWTSSZ0WLI|AAPL R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0.327"},
{"Kelly Criterion Probability Value", "1"},
@@ -180,7 +182,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

@@ -28,11 +28,11 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
_symbol = AddEquity("SPY").Symbol;
}
public override void OnEndOfDay()
public override void OnEndOfDay(Symbol symbol)
{
var minuteHistory = History(_symbol, 60, Resolution.Minute);
var minuteHistory = History(symbol, 60, Resolution.Minute);
var lastHourHigh = minuteHistory.Select(minuteBar => minuteBar.High).DefaultIfEmpty(0).Max();
var dailyHistory = History(_symbol, 1, Resolution.Daily).First();
var dailyHistory = History(symbol, 1, Resolution.Daily).First();
var dailyHigh = dailyHistory.High;
var dailyLow = dailyHistory.Low;
var dailyOpen = dailyHistory.Open;

View File

@@ -74,46 +74,48 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "18"},
{"Total Trades", "17"},
{"Average Win", "0%"},
{"Average Loss", "-0.16%"},
{"Compounding Annual Return", "72.164%"},
{"Average Loss", "-0.17%"},
{"Compounding Annual Return", "62.899%"},
{"Drawdown", "1.100%"},
{"Expectancy", "-1"},
{"Net Profit", "0.747%"},
{"Sharpe Ratio", "4.086"},
{"Probabilistic Sharpe Ratio", "61.091%"},
{"Net Profit", "0.671%"},
{"Sharpe Ratio", "3.528"},
{"Probabilistic Sharpe Ratio", "59.247%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.305"},
{"Beta", "0.564"},
{"Annual Standard Deviation", "0.113"},
{"Alpha", "-0.381"},
{"Beta", "0.565"},
{"Annual Standard Deviation", "0.116"},
{"Annual Variance", "0.013"},
{"Information Ratio", "-10.007"},
{"Tracking Error", "0.09"},
{"Treynor Ratio", "0.82"},
{"Total Fees", "$41.70"},
{"Fitness Score", "0.634"},
{"Kelly Criterion Estimate", "13.656"},
{"Kelly Criterion Probability Value", "0.228"},
{"Information Ratio", "-10.77"},
{"Tracking Error", "0.092"},
{"Treynor Ratio", "0.723"},
{"Total Fees", "$43.20"},
{"Estimated Strategy Capacity", "$3200000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Fitness Score", "0.644"},
{"Kelly Criterion Estimate", "13.787"},
{"Kelly Criterion Probability Value", "0.231"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "80.05"},
{"Portfolio Turnover", "0.634"},
{"Total Insights Generated", "17"},
{"Total Insights Closed", "14"},
{"Total Insights Analysis Completed", "14"},
{"Return Over Maximum Drawdown", "66.129"},
{"Portfolio Turnover", "0.644"},
{"Total Insights Generated", "13"},
{"Total Insights Closed", "10"},
{"Total Insights Analysis Completed", "10"},
{"Long Insight Count", "6"},
{"Short Insight Count", "7"},
{"Long/Short Ratio", "85.71%"},
{"Estimated Monthly Alpha Value", "$72447.6813"},
{"Total Accumulated Estimated Alpha Value", "$12477.1007"},
{"Mean Population Estimated Insight Value", "$891.2215"},
{"Mean Population Direction", "50%"},
{"Mean Population Magnitude", "50%"},
{"Rolling Averaged Population Direction", "12.6429%"},
{"Rolling Averaged Population Magnitude", "12.6429%"},
{"OrderListHash", "-2004493274"}
{"Estimated Monthly Alpha Value", "$52003.0716"},
{"Total Accumulated Estimated Alpha Value", "$8956.0846"},
{"Mean Population Estimated Insight Value", "$895.6085"},
{"Mean Population Direction", "70%"},
{"Mean Population Magnitude", "70%"},
{"Rolling Averaged Population Direction", "94.5154%"},
{"Rolling Averaged Population Magnitude", "94.5154%"},
{"OrderListHash", "b6b918fcc982a0126901ccbf14792d54"}
};
}
}

View File

@@ -0,0 +1,182 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using 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.163"},
{"Tracking Error", "0.195"},
{"Treynor Ratio", "8.093"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "VIX.IncrementallyGeneratedCustomData 2S"},
{"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,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$370000.00"},
{"Lowest Capacity Asset", "ETHUSD XJ"},
{"Fitness Score", "0.501"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -166,7 +168,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

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

View File

@@ -75,32 +75,34 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "167"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Total Trades", "251"},
{"Average Win", "0.01%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-37.465%"},
{"Drawdown", "0.300%"},
{"Expectancy", "-0.285"},
{"Net Profit", "-0.257%"},
{"Sharpe Ratio", "-40.568"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Loss Rate", "66%"},
{"Win Rate", "34%"},
{"Profit-Loss Ratio", "1.08"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Standard Deviation", "0.006"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Information Ratio", "-40.568"},
{"Tracking Error", "0.006"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Fitness Score", "0.5"},
{"Estimated Strategy Capacity", "$660000.00"},
{"Lowest Capacity Asset", "DE30EUR 8I"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-325.922"},
{"Portfolio Turnover", "9.561"},
{"Sortino Ratio", "-23.868"},
{"Return Over Maximum Drawdown", "-170.818"},
{"Portfolio Turnover", "12.673"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -114,7 +116,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1456907343"}
{"OrderListHash", "6745cf313aa3ef780d052ca3ba933c6c"}
};
}
}

View File

@@ -164,28 +164,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "2"},
{"Average Win", "1.16%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "32.515%"},
{"Compounding Annual Return", "32.505%"},
{"Drawdown", "1.400%"},
{"Expectancy", "0"},
{"Net Profit", "1.164%"},
{"Sharpe Ratio", "2.857"},
{"Probabilistic Sharpe Ratio", "64.822%"},
{"Net Profit", "1.163%"},
{"Sharpe Ratio", "2.876"},
{"Probabilistic Sharpe Ratio", "64.984%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.237"},
{"Beta", "-0.182"},
{"Annual Standard Deviation", "0.09"},
{"Beta", "-0.188"},
{"Annual Standard Deviation", "0.089"},
{"Annual Variance", "0.008"},
{"Information Ratio", "2.425"},
{"Tracking Error", "0.149"},
{"Treynor Ratio", "-1.405"},
{"Information Ratio", "2.409"},
{"Tracking Error", "0.148"},
{"Treynor Ratio", "-1.358"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$49000000.00"},
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
{"Fitness Score", "0.076"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "27.329"},
{"Return Over Maximum Drawdown", "24.003"},
{"Sortino Ratio", "27.328"},
{"Return Over Maximum Drawdown", "24.002"},
{"Portfolio Turnover", "0.076"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -200,7 +202,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1465929889"}
{"OrderListHash", "159887a90516df8ba8e8d35b9c30b227"}
};
}
}

View File

@@ -147,29 +147,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "13"},
{"Average Win", "0.65%"},
{"Average Loss", "-0.05%"},
{"Compounding Annual Return", "3216040423556140000000000%"},
{"Compounding Annual Return", "79228162514264337593543950335%"},
{"Drawdown", "0.500%"},
{"Expectancy", "1.393"},
{"Net Profit", "32.840%"},
{"Sharpe Ratio", "7.14272222483913E+15"},
{"Net Profit", "149.699%"},
{"Sharpe Ratio", "4.743312616499238E+27"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "83%"},
{"Win Rate", "17%"},
{"Profit-Loss Ratio", "13.36"},
{"Alpha", "2.59468989671647E+16"},
{"Beta", "67.661"},
{"Annual Standard Deviation", "3.633"},
{"Annual Variance", "13.196"},
{"Information Ratio", "7.24987266907741E+15"},
{"Tracking Error", "3.579"},
{"Treynor Ratio", "383485597312030"},
{"Total Fees", "$13.00"},
{"Fitness Score", "0.232"},
{"Alpha", "7.922816251426434E+28"},
{"Beta", "304.581"},
{"Annual Standard Deviation", "16.703"},
{"Annual Variance", "278.995"},
{"Information Ratio", "4.75893717482582E+27"},
{"Tracking Error", "16.648"},
{"Treynor Ratio", "2.6012216611301735E+26"},
{"Total Fees", "$13.20"},
{"Estimated Strategy Capacity", "$3000000.00"},
{"Lowest Capacity Asset", "AOL VRKS95ENLBYE|AOL R735QTJ8XC9X"},
{"Fitness Score", "0.18"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0.232"},
{"Portfolio Turnover", "0.18"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -183,7 +185,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1630141557"}
{"OrderListHash", "2a6319d0d474f976e653dd1ebc42caac"}
};
}
}

View File

@@ -116,32 +116,34 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "11"},
{"Average Win", "0.51%"},
{"Average Loss", "-0.33%"},
{"Compounding Annual Return", "-31.082%"},
{"Drawdown", "2.700%"},
{"Expectancy", "0.263"},
{"Net Profit", "-1.518%"},
{"Sharpe Ratio", "-2.118"},
{"Probabilistic Sharpe Ratio", "23.259%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "1.53"},
{"Alpha", "-0.208"},
{"Beta", "0.415"},
{"Annual Standard Deviation", "0.119"},
{"Annual Variance", "0.014"},
{"Information Ratio", "-1.167"},
{"Total Trades", "12"},
{"Average Win", "0.55%"},
{"Average Loss", "-0.26%"},
{"Compounding Annual Return", "16.717%"},
{"Drawdown", "1.700%"},
{"Expectancy", "0.850"},
{"Net Profit", "0.637%"},
{"Sharpe Ratio", "1.131"},
{"Probabilistic Sharpe Ratio", "50.538%"},
{"Loss Rate", "40%"},
{"Win Rate", "60%"},
{"Profit-Loss Ratio", "2.08"},
{"Alpha", "0.186"},
{"Beta", "0.465"},
{"Annual Standard Deviation", "0.123"},
{"Annual Variance", "0.015"},
{"Information Ratio", "1.908"},
{"Tracking Error", "0.126"},
{"Treynor Ratio", "-0.607"},
{"Total Fees", "$11.63"},
{"Fitness Score", "0.013"},
{"Treynor Ratio", "0.299"},
{"Total Fees", "$27.94"},
{"Estimated Strategy Capacity", "$200000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.28"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-5.1"},
{"Return Over Maximum Drawdown", "-11.717"},
{"Portfolio Turnover", "0.282"},
{"Sortino Ratio", "3"},
{"Return Over Maximum Drawdown", "9.559"},
{"Portfolio Turnover", "0.308"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -155,7 +157,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1623759093"}
{"OrderListHash", "de456413f89396bd6f920686219ed0a5"}
};
}
}

View File

@@ -110,10 +110,12 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.383"},
{"Information Ratio", "-1.388"},
{"Tracking Error", "0.096"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -133,7 +135,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

@@ -103,28 +103,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "58.336%"},
{"Drawdown", "0.900%"},
{"Compounding Annual Return", "57.657%"},
{"Drawdown", "1.000%"},
{"Expectancy", "0"},
{"Net Profit", "1.012%"},
{"Sharpe Ratio", "5.09"},
{"Probabilistic Sharpe Ratio", "68.472%"},
{"Net Profit", "1.003%"},
{"Sharpe Ratio", "5.024"},
{"Probabilistic Sharpe Ratio", "68.421%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.322"},
{"Beta", "0.265"},
{"Alpha", "0.312"},
{"Beta", "0.27"},
{"Annual Standard Deviation", "0.087"},
{"Annual Variance", "0.008"},
{"Information Ratio", "-0.088"},
{"Information Ratio", "-0.242"},
{"Tracking Error", "0.105"},
{"Treynor Ratio", "1.667"},
{"Total Fees", "$2.91"},
{"Treynor Ratio", "1.616"},
{"Total Fees", "$3.08"},
{"Estimated Strategy Capacity", "$720000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.141"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "9.731"},
{"Return Over Maximum Drawdown", "61.515"},
{"Sortino Ratio", "10.385"},
{"Return Over Maximum Drawdown", "58.709"},
{"Portfolio Turnover", "0.143"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -139,7 +141,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1959413055"}
{"OrderListHash", "50145c3c1d58b09f38ec1b77cfe69eae"}
};
}
}

View File

@@ -40,7 +40,7 @@ namespace QuantConnect.Algorithm.CSharp
UniverseSettings.FillForward = false;
AddUniverse(new CustomDataCoarseFundamentalUniverse(UniverseSettings, SecurityInitializer, CoarseSelectionFunction));
AddUniverse(new CustomDataCoarseFundamentalUniverse(UniverseSettings, CoarseSelectionFunction));
_symbols = new List<Symbol>();
}
@@ -93,8 +93,8 @@ namespace QuantConnect.Algorithm.CSharp
private class CustomDataCoarseFundamentalUniverse : CoarseFundamentalUniverse
{
public CustomDataCoarseFundamentalUniverse(UniverseSettings universeSettings, ISecurityInitializer securityInitializer, Func<IEnumerable<CoarseFundamental>, IEnumerable<Symbol>> selector)
: base(universeSettings, securityInitializer, selector)
public CustomDataCoarseFundamentalUniverse(UniverseSettings universeSettings, Func<IEnumerable<CoarseFundamental>, IEnumerable<Symbol>> selector)
: base(universeSettings, selector)
{ }
public override IEnumerable<SubscriptionRequest> GetSubscriptionRequests(Security security, DateTime currentTimeUtc, DateTime maximumEndTimeUtc,

View File

@@ -74,28 +74,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "7"},
{"Average Win", "0.01%"},
{"Average Loss", "-0.40%"},
{"Compounding Annual Return", "1114.772%"},
{"Compounding Annual Return", "1143.721%"},
{"Drawdown", "1.800%"},
{"Expectancy", "-0.319"},
{"Net Profit", "3.244%"},
{"Sharpe Ratio", "23.478"},
{"Probabilistic Sharpe Ratio", "80.383%"},
{"Expectancy", "-0.321"},
{"Net Profit", "3.275%"},
{"Sharpe Ratio", "23.505"},
{"Probabilistic Sharpe Ratio", "80.498%"},
{"Loss Rate", "33%"},
{"Win Rate", "67%"},
{"Profit-Loss Ratio", "0.02"},
{"Alpha", "4.314"},
{"Beta", "1.239"},
{"Annual Standard Deviation", "0.285"},
{"Annual Variance", "0.081"},
{"Information Ratio", "47.452"},
{"Tracking Error", "0.101"},
{"Treynor Ratio", "5.409"},
{"Total Fees", "$67.00"},
{"Alpha", "4.369"},
{"Beta", "1.255"},
{"Annual Standard Deviation", "0.292"},
{"Annual Variance", "0.085"},
{"Information Ratio", "47.982"},
{"Tracking Error", "0.102"},
{"Treynor Ratio", "5.463"},
{"Total Fees", "$71.36"},
{"Estimated Strategy Capacity", "$3500000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Fitness Score", "0.501"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "148.636"},
{"Return Over Maximum Drawdown", "1502.912"},
{"Sortino Ratio", "148.133"},
{"Return Over Maximum Drawdown", "1487.868"},
{"Portfolio Turnover", "0.501"},
{"Total Insights Generated", "2"},
{"Total Insights Closed", "0"},
@@ -110,7 +112,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-28636839"}
{"OrderListHash", "61b6afca11a1f15a63237d0346f383f7"}
};
}
}

View File

@@ -66,30 +66,32 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "7"},
{"Average Win", "1.02%"},
{"Average Win", "1.01%"},
{"Average Loss", "-1.01%"},
{"Compounding Annual Return", "205.606%"},
{"Compounding Annual Return", "210.936%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0.339"},
{"Net Profit", "1.439%"},
{"Sharpe Ratio", "7.166"},
{"Probabilistic Sharpe Ratio", "64.794%"},
{"Net Profit", "1.461%"},
{"Sharpe Ratio", "7.289"},
{"Probabilistic Sharpe Ratio", "65.077%"},
{"Loss Rate", "33%"},
{"Win Rate", "67%"},
{"Profit-Loss Ratio", "1.01"},
{"Alpha", "-0.341"},
{"Alpha", "-0.349"},
{"Beta", "0.968"},
{"Annual Standard Deviation", "0.213"},
{"Annual Variance", "0.045"},
{"Information Ratio", "-46.719"},
{"Annual Standard Deviation", "0.216"},
{"Annual Variance", "0.046"},
{"Information Ratio", "-47.59"},
{"Tracking Error", "0.009"},
{"Treynor Ratio", "1.575"},
{"Total Fees", "$22.77"},
{"Treynor Ratio", "1.623"},
{"Total Fees", "$24.07"},
{"Estimated Strategy Capacity", "$23000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.999"},
{"Kelly Criterion Estimate", "38.64"},
{"Kelly Criterion Probability Value", "0.229"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "69.159"},
{"Return Over Maximum Drawdown", "69.017"},
{"Portfolio Turnover", "1.242"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
@@ -97,14 +99,14 @@ namespace QuantConnect.Algorithm.CSharp
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$126657.6305"},
{"Total Accumulated Estimated Alpha Value", "$20405.9516"},
{"Mean Population Estimated Insight Value", "$206.1207"},
{"Mean Population Direction", "54.5455%"},
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"},
{"OrderListHash", "-1225025518"}
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "d8d556bcf963ba50f85cea387c55922b"}
};
}
}

View File

@@ -75,30 +75,32 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "6"},
{"Average Win", "0.00%"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "38.059%"},
{"Compounding Annual Return", "38.832%"},
{"Drawdown", "0.600%"},
{"Expectancy", "-0.502"},
{"Net Profit", "0.413%"},
{"Sharpe Ratio", "5.518"},
{"Probabilistic Sharpe Ratio", "66.933%"},
{"Loss Rate", "67%"},
{"Win Rate", "33%"},
{"Profit-Loss Ratio", "0.50"},
{"Alpha", "-0.178"},
{"Beta", "0.249"},
{"Expectancy", "-1"},
{"Net Profit", "0.420%"},
{"Sharpe Ratio", "5.579"},
{"Probabilistic Sharpe Ratio", "67.318%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.184"},
{"Beta", "0.248"},
{"Annual Standard Deviation", "0.055"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-9.844"},
{"Tracking Error", "0.165"},
{"Treynor Ratio", "1.212"},
{"Information Ratio", "-10.012"},
{"Tracking Error", "0.167"},
{"Treynor Ratio", "1.241"},
{"Total Fees", "$6.00"},
{"Estimated Strategy Capacity", "$38000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.063"},
{"Kelly Criterion Estimate", "38.64"},
{"Kelly Criterion Probability Value", "0.229"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "70.188"},
{"Return Over Maximum Drawdown", "70.89"},
{"Portfolio Turnover", "0.063"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
@@ -106,14 +108,14 @@ namespace QuantConnect.Algorithm.CSharp
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$126657.6305"},
{"Total Accumulated Estimated Alpha Value", "$20405.9516"},
{"Mean Population Estimated Insight Value", "$206.1207"},
{"Mean Population Direction", "54.5455%"},
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"},
{"OrderListHash", "501060991"}
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "21e4704a124ba562d042e1e9962f4316"}
};
}
}

View File

@@ -156,14 +156,16 @@ namespace QuantConnect.Algorithm.CSharp
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "5.579"},
{"Beta", "-63.972"},
{"Alpha", "5.56"},
{"Beta", "-71.105"},
{"Annual Standard Deviation", "0.434"},
{"Annual Variance", "0.188"},
{"Information Ratio", "0.996"},
{"Tracking Error", "0.441"},
{"Treynor Ratio", "-0.008"},
{"Information Ratio", "1.016"},
{"Tracking Error", "0.44"},
{"Treynor Ratio", "-0.007"},
{"Total Fees", "$20.35"},
{"Estimated Strategy Capacity", "$19000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.138"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -183,7 +185,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

@@ -172,29 +172,31 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.52%"},
{"Compounding Annual Return", "-31.636%"},
{"Average Loss", "-0.54%"},
{"Compounding Annual Return", "-32.671%"},
{"Drawdown", "0.900%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.520%"},
{"Sharpe Ratio", "-3.097"},
{"Probabilistic Sharpe Ratio", "24.675%"},
{"Net Profit", "-0.540%"},
{"Sharpe Ratio", "-3.168"},
{"Probabilistic Sharpe Ratio", "23.963%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.443"},
{"Alpha", "-0.456"},
{"Beta", "0.157"},
{"Annual Standard Deviation", "0.074"},
{"Annual Variance", "0.005"},
{"Information Ratio", "-9.046"},
{"Tracking Error", "0.176"},
{"Treynor Ratio", "-1.46"},
{"Total Fees", "$7.82"},
{"Annual Standard Deviation", "0.075"},
{"Annual Variance", "0.006"},
{"Information Ratio", "-9.176"},
{"Tracking Error", "0.178"},
{"Treynor Ratio", "-1.514"},
{"Total Fees", "$32.32"},
{"Estimated Strategy Capacity", "$95000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.1"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-35.683"},
{"Return Over Maximum Drawdown", "-36.199"},
{"Portfolio Turnover", "0.2"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -209,7 +211,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-611289773"}
{"OrderListHash", "3b9c93151bf191a82529e6e915961356"}
};
}
}

View File

@@ -128,28 +128,30 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "85"},
{"Average Win", "4.85%"},
{"Average Loss", "-4.21%"},
{"Compounding Annual Return", "-3.100%"},
{"Drawdown", "52.900%"},
{"Expectancy", "-0.052"},
{"Net Profit", "-29.298%"},
{"Sharpe Ratio", "-0.076"},
{"Average Loss", "-4.22%"},
{"Compounding Annual Return", "-3.124%"},
{"Drawdown", "53.000%"},
{"Expectancy", "-0.053"},
{"Net Profit", "-29.486%"},
{"Sharpe Ratio", "-0.078"},
{"Probabilistic Sharpe Ratio", "0.004%"},
{"Loss Rate", "56%"},
{"Win Rate", "44%"},
{"Profit-Loss Ratio", "1.15"},
{"Alpha", "-0.013"},
{"Beta", "0.009"},
{"Annual Standard Deviation", "0.164"},
{"Beta", "0.007"},
{"Annual Standard Deviation", "0.163"},
{"Annual Variance", "0.027"},
{"Information Ratio", "-0.391"},
{"Tracking Error", "0.239"},
{"Treynor Ratio", "-1.416"},
{"Total Fees", "$755.29"},
{"Information Ratio", "-0.393"},
{"Tracking Error", "0.238"},
{"Treynor Ratio", "-1.72"},
{"Total Fees", "$796.82"},
{"Estimated Strategy Capacity", "$1200000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.024"},
{"Kelly Criterion Estimate", "-0.84"},
{"Kelly Criterion Probability Value", "0.53"},
{"Sortino Ratio", "-0.224"},
{"Kelly Criterion Estimate", "-0.9"},
{"Kelly Criterion Probability Value", "0.532"},
{"Sortino Ratio", "-0.228"},
{"Return Over Maximum Drawdown", "-0.058"},
{"Portfolio Turnover", "0.05"},
{"Total Insights Generated", "85"},
@@ -158,14 +160,14 @@ namespace QuantConnect.Algorithm.CSharp
{"Long Insight Count", "42"},
{"Short Insight Count", "43"},
{"Long/Short Ratio", "97.67%"},
{"Estimated Monthly Alpha Value", "$-617339.2"},
{"Total Accumulated Estimated Alpha Value", "$-82686580"},
{"Mean Population Estimated Insight Value", "$-972783.3"},
{"Estimated Monthly Alpha Value", "$-719932.6"},
{"Total Accumulated Estimated Alpha Value", "$-96427970"},
{"Mean Population Estimated Insight Value", "$-1134447"},
{"Mean Population Direction", "51.7647%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "48.2217%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1370210213"}
{"OrderListHash", "177fb7f308a252864365442a30dd9eeb"}
};
}
}

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");
}
@@ -78,28 +82,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "264.819%"},
{"Compounding Annual Return", "272.157%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Net Profit", "1.668%"},
{"Sharpe Ratio", "8.749"},
{"Probabilistic Sharpe Ratio", "67.311%"},
{"Net Profit", "1.694%"},
{"Sharpe Ratio", "8.897"},
{"Probabilistic Sharpe Ratio", "67.609%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.119"},
{"Beta", "0.805"},
{"Annual Standard Deviation", "0.219"},
{"Annual Variance", "0.048"},
{"Information Ratio", "5.494"},
{"Tracking Error", "0.168"},
{"Treynor Ratio", "2.38"},
{"Total Fees", "$3.26"},
{"Fitness Score", "0.245"},
{"Alpha", "1.144"},
{"Beta", "0.842"},
{"Annual Standard Deviation", "0.222"},
{"Annual Variance", "0.049"},
{"Information Ratio", "5.987"},
{"Tracking Error", "0.165"},
{"Treynor Ratio", "2.347"},
{"Total Fees", "$3.45"},
{"Estimated Strategy Capacity", "$310000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.246"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "9.606"},
{"Return Over Maximum Drawdown", "105.85"},
{"Sortino Ratio", "9.761"},
{"Return Over Maximum Drawdown", "107.509"},
{"Portfolio Turnover", "0.249"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -114,7 +120,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "2069976135"}
{"OrderListHash", "e10039d74166b161f3ea2851a5e85843"}
};
}
}

View File

@@ -79,12 +79,12 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "37.355%"},
{"Compounding Annual Return", "34.768%"},
{"Drawdown", "2.300%"},
{"Expectancy", "0"},
{"Net Profit", "0.407%"},
{"Sharpe Ratio", "5.521"},
{"Probabilistic Sharpe Ratio", "60.177%"},
{"Net Profit", "0.382%"},
{"Sharpe Ratio", "5.488"},
{"Probabilistic Sharpe Ratio", "60.047%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
@@ -92,16 +92,18 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "0.997"},
{"Annual Standard Deviation", "0.179"},
{"Annual Variance", "0.032"},
{"Information Ratio", "-7.662"},
{"Information Ratio", "-7.724"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0.988"},
{"Total Fees", "$7.78"},
{"Fitness Score", "0.031"},
{"Treynor Ratio", "0.986"},
{"Total Fees", "$32.11"},
{"Estimated Strategy Capacity", "$66000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.029"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-2.145"},
{"Return Over Maximum Drawdown", "-8.479"},
{"Portfolio Turnover", "0.25"},
{"Sortino Ratio", "-2.336"},
{"Return Over Maximum Drawdown", "-8.991"},
{"Portfolio Turnover", "0.251"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -115,7 +117,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "519536519"}
{"OrderListHash", "9ce7252112d0ad7be0704297f7d48a88"}
};
}
}

View File

@@ -43,7 +43,7 @@ namespace QuantConnect.Algorithm.CSharp
security.SetBuyingPowerModel(new CustomBuyingPowerModel());
}
public void OnData(Slice slice)
public override void OnData(Slice slice)
{
if (Portfolio.Invested)
{
@@ -74,7 +74,11 @@ namespace QuantConnect.Algorithm.CSharp
public override HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerForOrder(
HasSufficientBuyingPowerForOrderParameters parameters)
{
return new HasSufficientBuyingPowerForOrderResult(true);
// if portfolio doesn't have enough buying power:
// parameters.Insufficient()
// this model never allows a lack of funds get in the way of buying securities
return parameters.Sufficient();
}
}
@@ -96,29 +100,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "5672.520%"},
{"Drawdown", "22.500%"},
{"Compounding Annual Return", "4775.196%"},
{"Drawdown", "21.600%"},
{"Expectancy", "0"},
{"Net Profit", "40.601%"},
{"Sharpe Ratio", "40.201"},
{"Probabilistic Sharpe Ratio", "77.339%"},
{"Net Profit", "38.619%"},
{"Sharpe Ratio", "33.779"},
{"Probabilistic Sharpe Ratio", "77.029%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "41.848"},
{"Beta", "9.224"},
{"Annual Standard Deviation", "1.164"},
{"Annual Variance", "1.355"},
{"Information Ratio", "44.459"},
{"Tracking Error", "1.04"},
{"Treynor Ratio", "5.073"},
{"Alpha", "32.812"},
{"Beta", "8.756"},
{"Annual Standard Deviation", "1.11"},
{"Annual Variance", "1.231"},
{"Information Ratio", "37.501"},
{"Tracking Error", "0.985"},
{"Treynor Ratio", "4.281"},
{"Total Fees", "$30.00"},
{"Fitness Score", "0.418"},
{"Estimated Strategy Capacity", "$22000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.395"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "113.05"},
{"Return Over Maximum Drawdown", "442.81"},
{"Portfolio Turnover", "0.418"},
{"Sortino Ratio", "98.148"},
{"Return Over Maximum Drawdown", "384.626"},
{"Portfolio Turnover", "0.395"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -132,7 +138,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "639761089"}
{"OrderListHash", "3df007afa8125770e8f1a49263af90a2"}
};
}
}

View File

@@ -80,7 +80,7 @@ namespace QuantConnect.Algorithm.CSharp
/// OnEndOfDay Event Handler - At the end of each trading day we fire this code.
/// To avoid flooding, we recommend running your plotting at the end of each day.
/// </summary>
public override void OnEndOfDay()
public override void OnEndOfDay(Symbol symbol)
{
//Log the end of day prices:
Plot("Trade Plot", "Price", _lastPrice);

View File

@@ -102,28 +102,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-33.612%"},
{"Compounding Annual Return", "-33.427%"},
{"Drawdown", "2.000%"},
{"Expectancy", "0"},
{"Net Profit", "-1.669%"},
{"Sharpe Ratio", "-4.888"},
{"Probabilistic Sharpe Ratio", "5.495%"},
{"Net Profit", "-1.658%"},
{"Sharpe Ratio", "-4.841"},
{"Probabilistic Sharpe Ratio", "5.714%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.273"},
{"Beta", "0.045"},
{"Alpha", "-0.271"},
{"Beta", "0.046"},
{"Annual Standard Deviation", "0.057"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-1.537"},
{"Information Ratio", "-1.563"},
{"Tracking Error", "0.112"},
{"Treynor Ratio", "-6.121"},
{"Total Fees", "$3.50"},
{"Treynor Ratio", "-6.032"},
{"Total Fees", "$14.45"},
{"Estimated Strategy Capacity", "$370000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-7.289"},
{"Return Over Maximum Drawdown", "-16.95"},
{"Sortino Ratio", "-7.238"},
{"Return Over Maximum Drawdown", "-16.848"},
{"Portfolio Turnover", "0.038"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -138,7 +140,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "559673838"}
{"OrderListHash", "0f5b98e8a608408a9d80d8b32ef3f845"}
};
}
}

View File

@@ -107,28 +107,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-33.612%"},
{"Compounding Annual Return", "-33.427%"},
{"Drawdown", "2.000%"},
{"Expectancy", "0"},
{"Net Profit", "-1.669%"},
{"Sharpe Ratio", "-4.888"},
{"Probabilistic Sharpe Ratio", "5.495%"},
{"Net Profit", "-1.658%"},
{"Sharpe Ratio", "-4.841"},
{"Probabilistic Sharpe Ratio", "5.714%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.273"},
{"Beta", "0.045"},
{"Alpha", "-0.271"},
{"Beta", "0.046"},
{"Annual Standard Deviation", "0.057"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-1.537"},
{"Information Ratio", "-1.563"},
{"Tracking Error", "0.112"},
{"Treynor Ratio", "-6.121"},
{"Total Fees", "$3.50"},
{"Treynor Ratio", "-6.032"},
{"Total Fees", "$14.45"},
{"Estimated Strategy Capacity", "$370000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-7.289"},
{"Return Over Maximum Drawdown", "-16.95"},
{"Sortino Ratio", "-7.238"},
{"Return Over Maximum Drawdown", "-16.848"},
{"Portfolio Turnover", "0.038"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -143,7 +145,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "559673838"}
{"OrderListHash", "0f5b98e8a608408a9d80d8b32ef3f845"}
};
}
}

View File

@@ -114,28 +114,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "31.756%"},
{"Compounding Annual Return", "32.142%"},
{"Drawdown", "0.700%"},
{"Expectancy", "0"},
{"Net Profit", "0.378%"},
{"Sharpe Ratio", "2.708"},
{"Probabilistic Sharpe Ratio", "56.960%"},
{"Net Profit", "0.383%"},
{"Sharpe Ratio", "2.719"},
{"Probabilistic Sharpe Ratio", "57.021%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.079"},
{"Beta", "0.099"},
{"Alpha", "0.086"},
{"Beta", "0.092"},
{"Annual Standard Deviation", "0.079"},
{"Annual Variance", "0.006"},
{"Information Ratio", "-6.058"},
{"Tracking Error", "0.19"},
{"Treynor Ratio", "2.159"},
{"Information Ratio", "-6.123"},
{"Tracking Error", "0.193"},
{"Treynor Ratio", "2.331"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$120000000.00"},
{"Lowest Capacity Asset", "GOOG T1AZ164W5VTX"},
{"Fitness Score", "0.1"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "47.335"},
{"Return Over Maximum Drawdown", "47.911"},
{"Portfolio Turnover", "0.1"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -150,7 +152,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1531253381"}
{"OrderListHash", "831c0062f40b638713d534d080a5ffcc"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -58,7 +58,9 @@ namespace QuantConnect.Algorithm.CSharp
//Weather used as a tradable asset, like stocks, futures etc.
if (data.Close != 0)
{
Order("BTC", (Portfolio.MarginRemaining / Math.Abs(data.Close + 1)));
// It's only OK to use SetHoldings with crypto when using custom data. When trading with built-in crypto data,
// use the cashbook. Reference https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/BasicTemplateCryptoAlgorithm.py
SetHoldings("BTC", 1);
}
Console.WriteLine("Buying BTC 'Shares': BTC: " + data.Close);
}
@@ -117,7 +119,7 @@ namespace QuantConnect.Algorithm.CSharp
//return "http://my-ftp-server.com/futures-data-" + date.ToString("Ymd") + ".zip";
// OR simply return a fixed small data file. Large files will slow down your backtest
return new SubscriptionDataSource("https://www.quandl.com/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc", SubscriptionTransportMedium.RemoteFile);
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>
@@ -154,6 +156,7 @@ namespace QuantConnect.Algorithm.CSharp
{
string[] data = line.Split(',');
coin.Time = DateTime.Parse(data[0], CultureInfo.InvariantCulture);
coin.EndTime = coin.Time.AddDays(1);
coin.Open = Convert.ToDecimal(data[1], CultureInfo.InvariantCulture);
coin.High = Convert.ToDecimal(data[2], CultureInfo.InvariantCulture);
coin.Low = Convert.ToDecimal(data[3], CultureInfo.InvariantCulture);
@@ -169,4 +172,4 @@ namespace QuantConnect.Algorithm.CSharp
}
}
}
}
}

View File

@@ -61,7 +61,7 @@ namespace QuantConnect.Algorithm.CSharp
/// "Nifty" type below and fired into this event handler.
/// </summary>
/// <param name="data">One(1) Nifty Object, streamed into our algorithm synchronised in time with our other data streams</param>
public void OnData(Slice data)
public override void OnData(Slice data)
{
if (data.ContainsKey("USDINR"))
{
@@ -77,7 +77,7 @@ namespace QuantConnect.Algorithm.CSharp
{
_today.NiftyPrice = Convert.ToDouble(data["NIFTY"].Close);
if (_today.Date == data["NIFTY"].EndTime)
if (_today.Date == data["NIFTY"].Time)
{
_prices.Add(_today);
@@ -91,7 +91,7 @@ namespace QuantConnect.Algorithm.CSharp
var quantity = (int)(Portfolio.MarginRemaining * 0.9m / data["NIFTY"].Close);
var highestNifty = (from pair in _prices select pair.NiftyPrice).Max();
var lowestNifty = (from pair in _prices select pair.NiftyPrice).Min();
if (Time.DayOfWeek == DayOfWeek.Wednesday) //prices.Count >= minimumCorrelationHistory &&
{
//List<double> niftyPrices = (from pair in prices select pair.NiftyPrice).ToList();
@@ -121,7 +121,7 @@ namespace QuantConnect.Algorithm.CSharp
/// End of a trading day event handler. This method is called at the end of the algorithm day (or multiple times if trading multiple assets).
/// </summary>
/// <remarks>Method is called 10 minutes before closing to allow user to close out position.</remarks>
public override void OnEndOfDay()
public override void OnEndOfDay(Symbol symbol)
{
Plot("Nifty Closing Price", _today.NiftyPrice);
}
@@ -181,6 +181,7 @@ namespace QuantConnect.Algorithm.CSharp
//2011-09-13 7792.9 7799.9 7722.65 7748.7 116534670 6107.78
var data = line.Split(',');
index.Time = DateTime.Parse(data[0], CultureInfo.InvariantCulture);
index.EndTime = index.Time.AddDays(1);
index.Open = Convert.ToDecimal(data[1], CultureInfo.InvariantCulture);
index.High = Convert.ToDecimal(data[2], CultureInfo.InvariantCulture);
index.Low = Convert.ToDecimal(data[3], CultureInfo.InvariantCulture);
@@ -247,6 +248,7 @@ namespace QuantConnect.Algorithm.CSharp
{
var data = line.Split(',');
currency.Time = DateTime.Parse(data[0], CultureInfo.InvariantCulture);
currency.EndTime = currency.Time.AddDays(1);
currency.Close = Convert.ToDecimal(data[1], CultureInfo.InvariantCulture);
currency.Symbol = "USDINR";
currency.Value = currency.Close;

View File

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

View File

@@ -84,28 +84,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "155.262%"},
{"Compounding Annual Return", "157.497%"},
{"Drawdown", "84.800%"},
{"Expectancy", "0"},
{"Net Profit", "5123.170%"},
{"Sharpe Ratio", "2.066"},
{"Probabilistic Sharpe Ratio", "68.832%"},
{"Net Profit", "5319.007%"},
{"Sharpe Ratio", "2.086"},
{"Probabilistic Sharpe Ratio", "69.456%"},
{"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.996"},
{"Alpha", "1.736"},
{"Beta", "0.142"},
{"Annual Standard Deviation", "0.84"},
{"Annual Variance", "0.706"},
{"Information Ratio", "1.925"},
{"Tracking Error", "0.846"},
{"Treynor Ratio", "12.333"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTC.Bitcoin 2S"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "2.238"},
{"Return Over Maximum Drawdown", "1.832"},
{"Sortino Ratio", "2.269"},
{"Return Over Maximum Drawdown", "1.858"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -120,7 +122,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-541549381"}
{"OrderListHash", "50faa37f15732bf5c24ad1eeaa335bc7"}
};
/// <summary>
@@ -212,6 +214,7 @@ namespace QuantConnect.Algorithm.CSharp
{
string[] data = line.Split(',');
coin.Time = DateTime.Parse(data[0], CultureInfo.InvariantCulture);
coin.EndTime = coin.Time.AddDays(1);
coin.Open = Convert.ToDecimal(data[1], CultureInfo.InvariantCulture);
coin.High = Convert.ToDecimal(data[2], CultureInfo.InvariantCulture);
coin.Low = Convert.ToDecimal(data[3], CultureInfo.InvariantCulture);

View File

@@ -124,28 +124,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-99.920%"},
{"Drawdown", "11.100%"},
{"Compounding Annual Return", "-99.907%"},
{"Drawdown", "11.000%"},
{"Expectancy", "0"},
{"Net Profit", "-10.486%"},
{"Sharpe Ratio", "-1.534"},
{"Net Profit", "-10.343%"},
{"Sharpe Ratio", "-1.554"},
{"Probabilistic Sharpe Ratio", "0.001%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.898"},
{"Beta", "-7.027"},
{"Annual Standard Deviation", "0.651"},
{"Annual Variance", "0.424"},
{"Information Ratio", "-1.396"},
{"Tracking Error", "0.726"},
{"Treynor Ratio", "0.142"},
{"Alpha", "-0.91"},
{"Beta", "-5.602"},
{"Annual Standard Deviation", "0.643"},
{"Annual Variance", "0.413"},
{"Information Ratio", "-1.378"},
{"Tracking Error", "0.736"},
{"Treynor Ratio", "0.178"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "NWSA.CustomDataUsingMapping T3MO1488O0H0"},
{"Fitness Score", "0.127"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-9.383"},
{"Return Over Maximum Drawdown", "-9.481"},
{"Portfolio Turnover", "0.249"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -160,7 +162,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-1014157203"}
{"OrderListHash", "d4cf2839e74df7fa436e30f44be4cb57"}
};
/// <summary>

View File

@@ -193,30 +193,32 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "62"},
{"Average Win", "0.10%"},
{"Average Win", "0.11%"},
{"Average Loss", "-0.06%"},
{"Compounding Annual Return", "-7.727%"},
{"Compounding Annual Return", "-7.236%"},
{"Drawdown", "2.400%"},
{"Expectancy", "-0.197"},
{"Net Profit", "-0.673%"},
{"Sharpe Ratio", "-1.565"},
{"Probabilistic Sharpe Ratio", "22.763%"},
{"Expectancy", "-0.187"},
{"Net Profit", "-0.629%"},
{"Sharpe Ratio", "-1.475"},
{"Probabilistic Sharpe Ratio", "23.597%"},
{"Loss Rate", "70%"},
{"Win Rate", "30%"},
{"Profit-Loss Ratio", "1.70"},
{"Alpha", "-0.14"},
{"Beta", "0.124"},
{"Profit-Loss Ratio", "1.73"},
{"Alpha", "-0.136"},
{"Beta", "0.126"},
{"Annual Standard Deviation", "0.047"},
{"Annual Variance", "0.002"},
{"Information Ratio", "-5.163"},
{"Information Ratio", "-5.094"},
{"Tracking Error", "0.118"},
{"Treynor Ratio", "-0.591"},
{"Total Fees", "$62.24"},
{"Fitness Score", "0.147"},
{"Treynor Ratio", "-0.547"},
{"Total Fees", "$62.25"},
{"Estimated Strategy Capacity", "$52000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.16"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-2.792"},
{"Return Over Maximum Drawdown", "-3.569"},
{"Sortino Ratio", "-2.59"},
{"Return Over Maximum Drawdown", "-3.337"},
{"Portfolio Turnover", "2.562"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -231,7 +233,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "852026186"}
{"OrderListHash", "1118fb362bfe261323a6b496d50bddde"}
};
}
}

View File

@@ -86,28 +86,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "241.885%"},
{"Drawdown", "1.100%"},
{"Compounding Annual Return", "240.939%"},
{"Drawdown", "1.200%"},
{"Expectancy", "0"},
{"Net Profit", "1.698%"},
{"Sharpe Ratio", "7.17"},
{"Probabilistic Sharpe Ratio", "68.718%"},
{"Net Profit", "1.694%"},
{"Sharpe Ratio", "6.988"},
{"Probabilistic Sharpe Ratio", "68.188%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.171"},
{"Beta", "0.147"},
{"Annual Standard Deviation", "0.191"},
{"Annual Variance", "0.037"},
{"Information Ratio", "0.035"},
{"Tracking Error", "0.251"},
{"Treynor Ratio", "9.323"},
{"Total Fees", "$3.26"},
{"Alpha", "1.172"},
{"Beta", "0.14"},
{"Annual Standard Deviation", "0.196"},
{"Annual Variance", "0.038"},
{"Information Ratio", "-0.118"},
{"Tracking Error", "0.256"},
{"Treynor Ratio", "9.783"},
{"Total Fees", "$3.45"},
{"Estimated Strategy Capacity", "$970000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.201"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "211.158"},
{"Return Over Maximum Drawdown", "204.701"},
{"Portfolio Turnover", "0.201"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -122,7 +124,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1268340653"}
{"OrderListHash", "33d01821923c397f999cfb2e5b5928ad"}
};
}
}

View File

@@ -189,10 +189,12 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.53"},
{"Tracking Error", "0.211"},
{"Information Ratio", "-2.564"},
{"Tracking Error", "0.214"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -212,7 +214,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

@@ -114,10 +114,12 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.084"},
{"Tracking Error", "0.183"},
{"Information Ratio", "-0.098"},
{"Tracking Error", "0.179"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -137,7 +139,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

@@ -114,10 +114,12 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.096"},
{"Tracking Error", "0.212"},
{"Information Ratio", "-0.111"},
{"Tracking Error", "0.207"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -137,7 +139,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,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -112,7 +132,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,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -155,7 +157,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,27 @@ 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"},
{"Beta", "0.157"},
{"Annual Standard Deviation", "0.033"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-4.89"},
{"Tracking Error", "0.08"},
{"Treynor Ratio", "0.509"},
{"Information Ratio", "-4.901"},
{"Tracking Error", "0.081"},
{"Treynor Ratio", "0.519"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$170000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"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 +134,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

@@ -0,0 +1,172 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
public class DelistedIndexOptionDivestedRegression : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spx;
private Symbol _optionSymbol;
private DateTime _optionExpiry = DateTime.MaxValue;
private string _ticker;
private bool _addOption = true;
private bool _receivedWarning;
public override void Initialize()
{
SetStartDate(2021, 1, 3); //Set Start Date
SetEndDate(2021, 1, 20); //Set End Date
_ticker = "SPX";
var spxSecurity = AddIndex(_ticker, Resolution.Minute);
spxSecurity.SetDataNormalizationMode(DataNormalizationMode.Raw);
_spx = spxSecurity.Symbol;
}
public override void OnData(Slice slice)
{
if (!slice.ContainsKey(_spx))
{
return;
}
if (_addOption)
{
var contracts = OptionChainProvider.GetOptionContractList(_spx, Time);
contracts = contracts.Where(x =>
x.ID.OptionRight == OptionRight.Put &&
x.ID.Date.Date == new DateTime(2021, 1, 15));
var option = AddIndexOptionContract(contracts.First(), Resolution.Minute);
_optionExpiry = option.Expiry;
_optionSymbol = option.Symbol;
_addOption = false;
}
if (slice.ContainsKey(_optionSymbol))
{
if (!Portfolio.Invested)
{
SetHoldings(_optionSymbol, 0.25);
}
// Verify the order of delisting; warning then delisting
Delisting delisting;
if (slice.Delistings.TryGetValue(_optionSymbol, out delisting))
{
switch (delisting.Type)
{
case DelistingType.Warning:
_receivedWarning = true;
break;
case DelistingType.Delisted:
if (!_receivedWarning)
{
throw new Exception("Did not receive warning before delisting");
}
break;
}
}
// Verify we aren't receiving expired option data.
if (_optionExpiry < Time.Date)
{
throw new Exception($"Received expired contract {_optionSymbol} expired: {_optionExpiry} current time: {Time}");
}
}
}
public override void OnEndOfAlgorithm()
{
foreach (var holding in Portfolio.Values)
{
Log($"Holding {holding.Symbol.Value}; Invested: {holding.Invested}; Quantity: {holding.Quantity}");
if (holding.Symbol == _optionSymbol && holding.Invested)
{
throw new Exception($"Index option {_optionSymbol.Value} is still invested after delisting");
}
}
}
/// <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", "2"},
{"Average Win", "0%"},
{"Average Loss", "-26.40%"},
{"Compounding Annual Return", "-99.821%"},
{"Drawdown", "45.600%"},
{"Expectancy", "-1"},
{"Net Profit", "-26.400%"},
{"Sharpe Ratio", "-0.557"},
{"Probabilistic Sharpe Ratio", "20.162%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.564"},
{"Beta", "-0.663"},
{"Annual Standard Deviation", "1.752"},
{"Annual Variance", "3.069"},
{"Information Ratio", "-0.906"},
{"Tracking Error", "1.763"},
{"Treynor Ratio", "1.472"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$1000000.00"},
{"Lowest Capacity Asset", "SPX 31KC0UJFONTBI|SPX 31"},
{"Fitness Score", "0.005"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.249"},
{"Return Over Maximum Drawdown", "-2.699"},
{"Portfolio Turnover", "0.016"},
{"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", "4ae4c1d8e4054c41908fd36e893699a6"}
};
}
}

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,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.155"},
{"Treynor Ratio", "1.589"},
{"Total Fees", "$55.05"},
{"Estimated Strategy Capacity", "$43000.00"},
{"Lowest Capacity Asset", "AAA SEVKGI6HF885"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -179,7 +181,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,150 @@
/*
* 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.182"},
{"Tracking Error", "0.117"},
{"Treynor Ratio", "1.617"},
{"Total Fees", "$37.00"},
{"Estimated Strategy Capacity", "$860000000.00"},
{"Lowest Capacity Asset", "DC V5E8P9SH0U0X"},
{"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

@@ -167,30 +167,32 @@ namespace QuantConnect.Algorithm.CSharp
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "7"},
{"Average Win", "19.16%"},
{"Average Win", "19.18%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "16.727%"},
{"Drawdown", "12.200%"},
{"Compounding Annual Return", "16.740%"},
{"Drawdown", "12.400%"},
{"Expectancy", "0"},
{"Net Profit", "153.058%"},
{"Sharpe Ratio", "1.239"},
{"Probabilistic Sharpe Ratio", "66.414%"},
{"Net Profit", "153.224%"},
{"Sharpe Ratio", "1.233"},
{"Probabilistic Sharpe Ratio", "65.906%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.146"},
{"Beta", "-0.018"},
{"Annual Standard Deviation", "0.116"},
{"Annual Variance", "0.013"},
{"Information Ratio", "-0.053"},
{"Beta", "-0.016"},
{"Annual Standard Deviation", "0.117"},
{"Annual Variance", "0.014"},
{"Information Ratio", "-0.052"},
{"Tracking Error", "0.204"},
{"Treynor Ratio", "-8.165"},
{"Total Fees", "$46.75"},
{"Treynor Ratio", "-8.847"},
{"Total Fees", "$49.43"},
{"Estimated Strategy Capacity", "$740000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "1.607"},
{"Return Over Maximum Drawdown", "1.366"},
{"Sortino Ratio", "1.609"},
{"Return Over Maximum Drawdown", "1.351"},
{"Portfolio Turnover", "0.003"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -205,7 +207,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "-807056289"}
{"OrderListHash", "44481c3d7eeb5acd5e3bccfec501a132"}
};
}
}

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