Compare commits

...

735 Commits
12759 ... 15436

Author SHA1 Message Date
Ronit Jain
0d6abf5dde Add optimization-id for optimization backtests (#7202)
* add organizatin-id in backtests

* self review
2023-04-20 10:49:04 -03:00
Ricardo Andrés Marino Rojas
6b7be767f5 Implement SecurityDataFilterPythonWrapper.cs (#7201)
- Create `SecurityDataFilterPythonWrapper.cs`
- Modifiy `Security.cs` to set a data filter, whether is a C#, Python derivative or custom data filter custom
- Add Python and C# regression algorithms to assert the changes
2023-04-20 10:45:59 -03:00
Jhonathan Abreu
3888896ed4 Add extendedMarket parameter to History methods (#7191)
* Add extendedMarket parameter to every history api method overload

* Rename extendedMarketHours parameter

New name is extendedHours as in the History API to standarize parameters naming

* Update generic history overloads to use every matching subscription

* Update regression algorithms stats

* Centralize period-based history error for tick resolution

* Rename extended market hours parameter to extendedMarketHours

* Minor changes

* Minor changes

* Minor unit tests changes

* Minor unit tests changes

* Minor changes

* Minor unit tests changes

* Minor unit tests changes
2023-04-20 10:41:32 -03:00
Martin-Molinero
fb383dc73c Minor foundation update (#7196)
* Added PyStan Library in DockerfileLeanFoundation

* Add new libraries and unit tests

---------

Co-authored-by: Ivan Radigales Creus <ivanrdgc@gmail.com>
2023-04-19 15:19:07 -03:00
Louis Szeto
5891f44312 Implement Hilbert Tranform indicator (#7197)
* Implement Hilbert Transform Indicator

* Assign proper names to variables

fixes
https://github.com/QuantConnect/Lean/pull/7148#discussion_r1152325967
https://github.com/QuantConnect/Lean/pull/7148#discussion_r1152328259

* Add license

fixes https://github.com/QuantConnect/Lean/pull/7148#discussion_r1152336946

* Change `_v1` computation to operation instead of `FunctionalIndicator`

and more related changes
fixes https://github.com/QuantConnect/Lean/pull/7148#discussion_r1152332642

* Replace `updatesCount` with `Samples` field

* Implement `inPhase3` and `_quadrature2` as `Delay` indicators

* Minor fix to `WarmUpPeriod`

* Add descriptive names to indicators

* Reset all indicators

https://github.com/QuantConnect/Lean/pull/7148#discussion_r1152338785

* Minor fix

* Rename rest of parameters

* Implement helper method

* Renaming for LEAN's pattern

* Update 3rd party data source

* Refactor and fix bug on HT calculation

* Fix unit test's logic

---------

Co-authored-by: Alexander Myltsev <alexander.myltsev@gmail.com>
2023-04-19 14:41:05 -03:00
Martin-Molinero
841e6f12c2 Update readme.md 2023-04-18 19:14:27 -03:00
Martin-Molinero
afabedbfda Update readme.md 2023-04-18 18:30:59 -03:00
Ricardo Andrés Marino Rojas
02e54d0242 Implement OptionExerciseModelPythonWrapper.cs (#7193)
* Implement `OptionExerciseModelPythonWrapper.cs`
- Modifiy `Option.cs` to set the automatic exercise model, even if it's a python custom option model exercise model
- Add `QuantConnect.Orders.OptionExercise` in `AlgorithmImports.py`
- Add regression algorithms in C# and Python showing how to specify a custom option exercise model

* Address required changes

- Remove unnecessary constructor in
´CustomOptionExerciseModelRegressionAlgorithm.cs´
- Change `.Dispose()` in `OptionExerciseModelPythonWrapper.OptionExercise(9` to ´using´ keyword
- Change `Option.SetOptionExerciseModel()` XML docs

* Minor tweaks

* Update CustomOptionExerciseModelRegressionAlgorithm.cs

---------

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2023-04-18 16:54:53 -03:00
Martin-Molinero
430b30b2ac Update readme.md 2023-04-18 15:09:23 -03:00
Martin-Molinero
c3cdeea0ee Update readme.md 2023-04-18 14:11:25 -03:00
prasom
a4f2c03015 Python ConstantAlphaModel Constructor is Missing an Argument (#7189)
* Python ConstantAlphaModel Constructor is Missing an Argument #7185

* Minor tweak

---------

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2023-04-17 20:03:49 -03:00
Martin-Molinero
d1a2b95ddc Update reserved chart names (#7190) 2023-04-17 20:02:27 -03:00
Jhonathan Abreu
f1076020af Add fillForward parameter to History methods (#7180)
* Add fillForward parameters to every History method

* Remove conflicting Python history method

* Undo removing conflicting Python history method

* Minor changes

* Minor changes

* Minor changes

* Add fillForward and extendedMarket parameters to history request factory

* Minor changes

* Minor changes

* Minor changes

* Minor changes

* Minor unit tests changes

* Rename fillForward parameter in History API

New name if fillDataForward as in the Add*Security API to standarize
parameters naming

* Rename fillForward parameter

Using the shorter fillForward in every API
2023-04-17 16:42:13 -03:00
prasom
cd88806e93 Start research returns permission denied when run inside a devcontainer in VS Code (#7139) (#7188) 2023-04-17 10:45:55 -03:00
Ricardo Andrés Marino Rojas
b5087bf42a Solve Report Generation Conversion Rate Error bug (#7183)
* Solve bug

Remove if sentence that checked if Portfolio contained securities that
needed a conversion, like Forex, Crypto or Cfd. It didn't take into
account CryptoFutures so when the backtest result used that kind of
security types it never found a conversion for them. Making a git blame
for Report.PortfolioLooper constructor it was found the if sentence was
not needed so it was removed and then different reports were made for
algorithms that used security types different than Forex,Crypto,Cfd and
CryptoFutures to check everything was still working as expected.

* Solve bug

Remove if sentence that checked if Portfolio contained securities that
needed a conversion, like Forex, Crypto or Cfd. It didn't take into
account CryptoFutures so when the backtest result used that kind of
security types it never found a conversion for them. Making a git blame
for Report.PortfolioLooper constructor it was found the if sentence was
not needed so it was removed and then different reports were made for
algorithms that used security types different than Forex,Crypto,Cfd and
CryptoFutures to check everything was still working as expected.
2023-04-13 14:43:56 -03:00
Martin-Molinero
4ad0288110 Add missing optimizer launcher reference (#7181) 2023-04-12 19:35:02 -03:00
Martin-Molinero
35469154c4 Update readme.md 2023-04-12 15:39:32 -03:00
Martin-Molinero
9c893e83a2 Minor optimizer improvement (#7179)
- Handle optimization backtest name
- Allow configurable optimizer for Optimizer.Launcher project
2023-04-12 15:35:54 -03:00
Jhonathan Abreu
8134b099fa Updated EMA indicator description (#7178) 2023-04-11 18:58:35 -03:00
Jhonathan Abreu
8d54438eac Add support for iterating FutureHistory and OptionHistory (#7176)
This adds support for accessing the history slices in research
environment
2023-04-11 18:54:58 -03:00
Martin-Molinero
b23bc870e2 Minor regression test update after EMA merge (#7177)
- Minor regression test update after EMA merge
2023-04-11 18:26:48 -03:00
Ricardo Andrés Marino Rojas
9e51f10b77 Add Feature Signal Exports feature (#7145)
* Add Collective2SignalExportClass
Add SignalExportTarget interface

* Collective2SignalExport test working

Add SignalExportManager
Add draft of CrunchDAOSignalExport

* Modify SignalExportManager

Instantiate SignalExportManager in QCAlgorithm constructor
Draft of CrunchDAOSignalExport

* Improve SignalExportManager

- Add regression tests SignalExportDemonstrationAlgorithm in C# and
  Python

* Improve SignalExportDemonstrationAlgorithm

Address requested changes in Collective2SignalExport, SignalExportManger and SignalExportTargetTests.cs

* Add CrunchDAOSignalExport.cs

Add CrunchDAOSignalExport unit tests in SignalExportTargetTests.cs

* Add NumeraiSignalExport.cs

Modify SignalExportDemonstrationAlgorithm.cs to test NumeraiSignalExport
Add unit test in SignalExportTargetTests to test NumeraiSignalExport

* Address required changes

- Add BaseSignalExport.cs
- Add SignalExportParameters.cs
- Add PortfolioSignalExportDemonstrationAlgorithm.cs/py
- Improve Error handling in SignalExport provider classes
- Collective2SignalExport now gets the correct number of shares for each holding
- SignalExportManager now computes the correct holding percentage of each portfolio target
- SignalExportManager now takes into account if the algorithm is in live mode
- Demonstration algorithms now are more simple

* Address last required changes

- PortfolioSignalExportDemonstrationAlgorithm.cs/py now inherits from SignalExportDemonstrationAlgorithm.cs/py
- Add more unit tests to assert SignalExportManager gets the correct percentage quantity for each holding
- Change Collective2SignalExport, CrunchDAOSignalExport and NumeraiSignalExport Send() method to return true if there was no error while sending the signals and false otherwise
- Nit changes

* Remove exceptions thrown

- Add more unit tests and more test cases
- Enhance BaseSignalExport.Dispose() method

* Add Collective2SignalExportClass
Add SignalExportTarget interface

* Collective2SignalExport test working

Add SignalExportManager
Add draft of CrunchDAOSignalExport

* Modify SignalExportManager

Instantiate SignalExportManager in QCAlgorithm constructor
Draft of CrunchDAOSignalExport

* Improve SignalExportManager

- Add regression tests SignalExportDemonstrationAlgorithm in C# and
  Python

* Improve SignalExportDemonstrationAlgorithm

Address requested changes in Collective2SignalExport, SignalExportManger and SignalExportTargetTests.cs

* Add CrunchDAOSignalExport.cs

Add CrunchDAOSignalExport unit tests in SignalExportTargetTests.cs

* Add NumeraiSignalExport.cs

Modify SignalExportDemonstrationAlgorithm.cs to test NumeraiSignalExport
Add unit test in SignalExportTargetTests to test NumeraiSignalExport

* Address required changes

- Add BaseSignalExport.cs
- Add SignalExportParameters.cs
- Add PortfolioSignalExportDemonstrationAlgorithm.cs/py
- Improve Error handling in SignalExport provider classes
- Collective2SignalExport now gets the correct number of shares for each holding
- SignalExportManager now computes the correct holding percentage of each portfolio target
- SignalExportManager now takes into account if the algorithm is in live mode
- Demonstration algorithms now are more simple

* Address last required changes

- PortfolioSignalExportDemonstrationAlgorithm.cs/py now inherits from SignalExportDemonstrationAlgorithm.cs/py
- Add more unit tests to assert SignalExportManager gets the correct percentage quantity for each holding
- Change Collective2SignalExport, CrunchDAOSignalExport and NumeraiSignalExport Send() method to return true if there was no error while sending the signals and false otherwise
- Nit changes

* Remove exceptions thrown

- Add more unit tests and more test cases
- Enhance BaseSignalExport.Dispose() method

* Fix failing regression tests

* Fix failing unit tests

* Nit changes

* Nit change

* Nit change

* Fix failing unit tests

* Changes required

- Break regression algos `SignalExportDemonstrationAlgorithm.cs/py` nad `PortfolioSignalExportDemonstrationAlgorithm.cs/`y` into three ones, one for each signal export provider
- Change SignalExportManager constructor to receive current algorithm as a parameter
- Fix bug in `SignalExportManager.GetPortfolioTargets()`, now it computes the correct percentage for each holding
- Make `BaseSignalExport.DefaultAllowedSecurityTypes` overrdible
- Handle case were `Collective2SignalExport.ConvertPercentageToQuantity()` returns null
- Clean unnecessary code in `Collective2SignalExport()`, `CrunchDAOSignalExport()` and `NumeraiSignalExport()`

* Nit change

* Nit change

* Minor tweaks after review

* Remove indexes from signal exports

* Required changes
- Change EMA indicators period from 200, 300 to 10,100 in regression algorithms
- Remove Indices from regression algorithms
- Add more XML documentation to regression algorithms
- Change `Log.Error` to `_algorithm.Error` in Signal export providers. Besides, fix error message format
- Change default value for `platformId` parameter in `Collective2SignalExport.cs` constructor
- Solve small bugs in SignalExportProvider when verificating the amount of porfolio targets is greater than zero and each portfolio target is allowed
- Handle case when `PortfolioTarget.Percent()` returns null in `Collective2SignalExport.ConvertPercentageToQuantity()`
- Handle error format message from Collective2 API
- Check every ticker signal is between 0 and 1 (inclusive) in `CrunchDAOSignalExport.cs`
- Modifiy `NumeraiSignalExport.cs` constructor to take into account filename given in the arguments
- Fix small bug with the return value of `ConvertTargetsToNumerai()` method in `NumeraiSignalExport.cs`
- Modify `SignalExportManager.cs` to return true when the algorithm being ran is not in live mode
- Remove indices from CrunchDAO unit tests

* Enhance ´CrunchDAOSignalExport.cs´ implementation

---------

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2023-04-11 17:45:07 -03:00
Jhonathan Abreu
ed92e6653b Fix EMA first value calculation (#7173)
* Fix EMA indicator first value calculation

As done by TALib and TradingView, the first EMA value after warmup is
the SMA of the first period.

* Update TSI indicator test data

Data was exported from TradingView

* Update TRIX indicator test data from TradingView

* Update AccumulationDistributionOscillator indicator test data from TradingView

* Update Double EMA indicator test data from TradingView

* Update McClellanSummationIndex indicator test data

* Update SchaffTrendCycle indicator test data

* Update TripleExponentialMovingAverage indicator test data from TradingView

* Update stats for algorithms using EMA

* Update failing unit tests
2023-04-11 17:43:25 -03:00
Martin-Molinero
08a1f84f91 Fix continuous futures back month contracts (#7175)
- Fix continuous futures back month contracts setting which was ignored.
  Updating regression algorithms
2023-04-11 17:42:46 -03:00
Jhonathan Abreu
8e54918378 Account for time zone on MOC orders time buffer check (#7174)
* Use UTC times when checking if MOC order is not past the allowed buffer

* Add unit test
2023-04-11 17:42:34 -03:00
Martin-Molinero
fcab09effb Update LiveTradingDataFeedTests.cs
See https://github.com/QuantConnect/Lean/pull/7169/files
2023-04-10 17:31:10 -03:00
Jhonathan Abreu
5436c72fad Handle margin call orders for position groups (#7137)
* Handle position group margin calls

* Minor changes

* Update regression algorithms

* Minor changes

* Minor changes

* Added regression algorithm

* Peer review

* Peer review

* Peer review

* Peer review

* Minor changes

* Minor changes

* Add unit test

* Allow sufficient buying power when closing position group

* Add unit test

* Improve regression algorithms
2023-04-10 12:42:08 -03:00
Martin-Molinero
f152652f5b Fix api account deserialization (#7172)
- Fix API account deserialization. Adding unit test
2023-04-10 12:38:38 -03:00
Martin-Molinero
f9bbec1e16 Remove internal subscriptions from future chain (#7169)
- Remove internal subscription from slive future chain collection.
  Adding regression algorithm reproducing the bug
2023-04-05 18:23:04 -03:00
Ricardo Andrés Marino Rojas
20c92b0350 Fix bug: Report Color Map Does Not Include Crypto Futures (#7168)
* Fix ReportCharts color_map bug

- Add ´CryptoFuture´ entry in `color_map` dict using color #E55812
- Make ´ReportCharts.py´ color_map a class attribute
- Change ´ReportChartsTests.cs´ to use color_map dict from ´ReportCharts.py´
- Add unit test that fails every time a new SecurityType is added

* Improve unit test

* Nit change

* Nit change
2023-04-05 17:51:16 -03:00
Jhonathan Abreu
375af2ebd2 Updated MHDB and CME currencies futures expiry functions (#7166)
* Updated MHDB and CME currencies futures expiry functions

Some expiry functions needed to take into consideration the security
holidays

* Add more holidays to CME securities in MHDB
2023-04-05 14:49:42 -03:00
Jhonathan Abreu
daae49cc4f Updat AlphaVantageDataDownloaderTests to make it time independent (#7167) 2023-04-05 13:00:54 -03:00
Martin-Molinero
227ade63ed Refactor automatic option assignment (#7165)
- Refactor automatic option assignment to allow overriding behavior.
  Adding & updating existing tests
2023-04-04 17:40:31 -03:00
Jhonathan Abreu
9524f48a33 Fix maximum lots calculation methods in SecurityPositionGroupBuyingPowerModel (#7163)
One of the methods was multiplying the resulting quantity times the lot
size, which is not accurate.
2023-04-04 17:29:22 -03:00
Louis Szeto
d977eb2181 Refactor MACD Alpha Model (#7140)
* Update regression test to check number of insights

* Update model to have insight manager ref and cancel insight when signal goes flat

* Update unit tests and regression tests

* Address peer review: using Insights.Clear
2023-04-04 17:22:15 -03:00
Martin-Molinero
e15614a18f Add live log limit to controls (#7162) 2023-04-04 13:57:38 -03:00
Jhonathan Abreu
2e20b4803d Accounting for the position quantity in margin requirements (#7161)
* Invalidate option strategies orders when short selling over margin

When shorting an option strategy with margin requirements that cannot be
met, the order should be invalidated. The buying power model is now able
to detect said situation and result in unssuficient buying power.

The OptionsMarginModel now uses the parameters instance values instead
of the security holdings to compute margin requirements. This fixes the
situation when calculation buying power for a first time position with
no holdings.

* Add and fix unit tests

* Update regression algorithms

* Peer review
2023-04-03 18:51:05 -03:00
Martin-Molinero
cb0c7b0814 Update KeyStringSynchronizerTests.cs 2023-04-03 14:24:41 -03:00
Martin-Molinero
645e1ca88c Downloader Data Provider Improvements (#7159)
* Downloader data provider fixes

- Fix stored data time zone, which is expected in data time zone
- Minor logging improvements
- LeanData Parse handles etf universes path. Adding unit test
- LeanDataWrite will only map if there's something to map to

* Fix download data provider synchronization

* Synchronization improvements after more testing

- KeyStringSynchronizer will handle reentrancy. Adding unit tests
- Define a unique Synchronizare for downloading data, since not related
  to disk reading & writting
2023-03-31 18:29:55 -03:00
Martin-Molinero
84bb72fddb Remove unrequired csharp debugger (#7156)
- Remove unused & outdated csharp debugger netcoredbg
2023-03-30 19:05:31 -03:00
Martin-Molinero
4d32119576 Unzip to folder from byte[] (#7152)
- Unzip data to folder from a given byte[]. Adding unit tests
2023-03-29 16:06:42 -03:00
Martin-Molinero
c836c62945 LeanDataWriter can handle mapping (#7150)
* LeanDataWriter can handle mapping

- Adjust LeanDataWrite so that it can handle symbol mapping if required.
  Adding unit tests

* Fix Lean Data path parsing
2023-03-29 16:04:23 -03:00
Alexandre Catarino
2069833361 Updates HistoricalReturnsAlphaModel to Cancel Insights Not Emit Flat (#7151)
* Updates Regression Algorithm to Assert the Number of Insights

* Updates HistoricalReturnsAlphaModel to Cancel Insights Not Emit Flat

We expect fewer insights after this change, but no changes to any regression algorithm.

* Updates Regression Algorithm

Assert the new expected number of generated insights.

* Use InsightCollection Clear Method
2023-03-29 16:03:27 -03:00
Alexandre Catarino
b46b50fa50 Adds HistoricalReturnsAlphaModelFrameworkRegressionAlgorithm (#7149) 2023-03-28 16:08:47 -03:00
Derek Melchin
4d77431ae1 Refactor RsiAlphaModel (#7125)
* Update regression tests to check consolidators are removed

* Update model

* Address review
2023-03-28 16:07:08 -03:00
Alexandre Catarino
1bce9bcb71 Improves Validates_SetEndTime Test (#7147)
Uses the "Now" in algorithm default timezone, since that's how `EndDate` is initialized in QCAlgorithm.
2023-03-28 11:01:04 -03:00
Martin-Molinero
2dc40f0477 Update readme.md 2023-03-27 19:34:09 -03:00
Martin-Molinero
403814d64f Handle error sending notification (#7146) 2023-03-27 15:31:53 -07:00
Martin-Molinero
384ec3dbad Update readme.md 2023-03-27 17:10:30 -03:00
Martin-Molinero
708d38d4e5 Update readme.md 2023-03-27 16:49:52 -03:00
Martin-Molinero
03bc23ed8c Add project id for api notification (#7144) 2023-03-27 15:59:51 -03:00
Shukri
73c26ee7ec Fix some typos (#7138)
* Fix typo

who often -> how often

Signed-off-by: hsm207 <hsm207@users.noreply.github.com>

* Fix typo

sometimes bug -> sometimes be buggy

Signed-off-by: hsm207 <hsm207@users.noreply.github.com>

* Correct number of options to run research nbs

Signed-off-by: hsm207 <hsm207@users.noreply.github.com>

---------

Signed-off-by: hsm207 <hsm207@users.noreply.github.com>
2023-03-27 10:29:52 -03:00
Martin-Molinero
ce33c393e6 Update Extensions.cs 2023-03-24 09:40:50 -03:00
Louis Szeto
279a306758 Update TrailingStopRiskManagementModel model to cancel insights (#7131)
* Update risk model to cancel insight

* Updates Regression Tests

---------

Co-authored-by: Alexandre Catarino <AlexCatarino@users.noreply.github.com>
2023-03-23 15:29:04 -03:00
Alexandre Catarino
0247b95edd Adds TrailingStopRiskFrameworkRegressionAlgorithm (#7132)
Replaces old `TrailingStopRiskFrameworkAlgorithm` for `TrailingStopRiskFrameworkRegressionAlgorithm` that inherits from `BaseFrameworkRegressionAlgorithm` as a member of the framework regression tests.
2023-03-23 13:43:09 -03:00
Jhonathan Abreu
d47e073d90 Use data end time to timestamp fundalmental data dictionaries (#7126)
* Use data end time to timestamp fundalmental data dictionaries

* Peer review
2023-03-23 13:41:03 -03:00
Louis Szeto
6d75aee0ce Add regression test for MaximumSectorExposureRiskManagementModel (#7123) 2023-03-23 12:37:30 -03:00
Martin-Molinero
bbbf6f3a74 Minor downloader data provider improvements (#7130)
- Improve start time request for daily/hour files
- Skip custom data since it's not supported by the LeanDataWriter
2023-03-23 12:27:34 -03:00
Louis Szeto
3362a976fa Avoid Invalid historical data piping in StandardDeviationExecutionModel (#7086)
* Remove invalid historical warm up in STD Execution

* refactor

* peer review

* Use `Consolidator.InputType`

* Update regression test
2023-03-23 12:24:42 -03:00
Louis Szeto
f684940a7c Update MaximumUnrealizedProfitPercentPerSecurity model to cancel insights (#7121)
* Update regression test

* Update model to expire insights

* Avoid remove insights

* Update regression test

* Use InsightManager Cancel to Expire All Insights

* Update CompositeRiskManagementModelFrameworkAlgorithm

This regression also depends on `MaximumUnrealizedProfitPercentPerSecurity` and `MaximumDrawdownPercentPerSecurity` but `MaximumDrawdownPercentPerSecurity` doesn't close positions.

---------

Co-authored-by: Alexandre Catarino <AlexCatarino@users.noreply.github.com>
2023-03-23 12:23:42 -03:00
Derek Melchin
9c92a67510 Update MaximumDrawdownPercentPortfolio model to cancel insights (#7105)
* Remove OnEndOfAlgorithm and update expected trades

* Update models to cancel insights

* Update expected results

There are 3 trades instead of 2 because the PCM does a rebalance

* Remove `Remove` method call

* Update to use the new `Cancel` method
2023-03-23 12:02:04 -03:00
Derek Melchin
b401fde07e Update MaximumDrawdownPercentPerSecurity model to cancel insights (#7103)
* Remove OnEndOfAlgorithm and update expected trade count

* Update models to cancel insights

* Update expected results

* Remove `Remove` method call

* Update to use the new `Cancel` method
2023-03-23 11:11:27 -03:00
Martin-Molinero
7db8df3f8d Add Insight expiration helper methods (#7127)
- Add InsightManager expiration helper methods. Adding unit tests
2023-03-22 19:15:47 -03:00
Alexandre Catarino
7feb46fec5 Fixes time zone (#7128)
If we use `.astimezone(dt.tzinfo)`, the new time was convering the timezone from local (e.g. PST) to GMT (dt.tzinfo). In this case, we only want to remove the timezone to enable the operation.
2023-03-22 19:02:11 -03:00
Martin-Molinero
1c81f5d028 Update readme.md 2023-03-22 17:43:50 -03:00
Alexandre Catarino
3b2e165254 Adds BaseFrameworkRegressionAlgorithm and New Regression Algorithms (#7116)
* Renames and Updates BaseAlphaModelFrameworkRegressionAlgorithm

The `BaseFrameworkRegressionAlgorithm ` will be used for multiple framework regression tests

* Updates and Renames EmaCrossAlphaModelFrameworkAlgorithm

Adds "Regression" to inform that it's a regression algorithm.

* Updates and Renames MaximumPortfolioDrawdownFrameworkAlgorithm

Adds "Regression" to inform that it's a regression algorithm, and use the model name: `MaximumDrawdownPercentPortfolio`

* Adds New Regression Algorithms
2023-03-22 11:21:30 -03:00
Martin-Molinero
44d1454ed7 Handle downloader data provider no MHDB entry (#7115)
* Handle downloader data provider no MHDB entry

* Address review: log once
2023-03-21 17:26:09 -03:00
Martin-Molinero
a58f6b679d Minor fake data queue handler fixes (#7114)
- Minor fake data queue handler fixes. Adding unit tests
2023-03-21 15:10:03 -03:00
Alexandre Catarino
761ea2571a Adds BaseAlphaModelFrameworkRegressionAlgorithm (#7107)
* Adds BaseAlphaModelFrameworkRegressionAlgorithm

`BaseAlphaModelFrameworkRegressionAlgorithm` will be used to validate Alpha Model regression algorithm with the same universe.

- HistoricalReturnsAlphaModelFrameworkAlgorithm
- EmaCrossAlphaModelFrameworkAlgorithm
- MacdAlphaModelFrameworkAlgorithm
- RsiAlphaModelFrameworkAlgorithm
- BasePairsTradingAlphaModelFrameworkAlgorithm

* Addresses Peer-Review
2023-03-21 13:22:34 -03:00
Jhonathan Abreu
0b661e70c1 Fix combo order direction determination (#7066)
* Fix fill quantity using group order quantity for combo orders

* Add Order's ComboQuantity property

* Add Order's ComboDirection property

* Minor changes and regression algorithms update

* Minor changes

* Update algorithms stats

* Minor changes and regression algorithms update

* Store the full quantity for each combo order leg in Quantity property instead of the ratio

* Minor changes and regression algorithms update

* A few fixes after pair programming

* Handle grouping position reduction

---------

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2023-03-21 12:26:50 -03:00
Alexandre Catarino
f1d55c3b0b Improves MinimumVariancePortfolioOptimizer Values Handling (#7106)
* Improves MinimumVariancePortfolioOptimizer Values Handling

The C# version of the `MinimumVariancePortfolioOptimizer` generated NaN resulting in unit tests failing.
If the solver returns NaN for an item, we set it to zero. if all items are NaN or Zero, we return the initial guess, since the sum cannot be zero.

* Fixes `RiskParityPortfolioConstructionModelTests`

We need to add insights to insight manager before we call `CreateTargets`.
2023-03-21 11:24:58 -03:00
Alexandre Catarino
497ac8497a Fixes Consolidator Removal from Subscription Manager in Python Algorithms (#7102)
* Adds Unit Test

Asserts that we can remove a consolidator that was previously added.

* AddConsolidator Method Only Wraps Non-C# Consolidators

This behavior was implemented in `QCAlgorithm.RegisterIndicator` to avoid wrapping an object unnecessarily.
2023-03-21 11:08:49 -03:00
Martin-Molinero
1877d59daa Improve aggregation helper methods (#7100)
- Improve LeanData aggregation helper methods to use shared consolidator based implementation
- Adding Tick to tradeBar aggregation
- Adding more unit tests
2023-03-20 16:08:25 -03:00
Martin-Molinero
56881e64fe Expand result state attributes (#7097)
- Add order, insight & log count into result algorithm state
2023-03-20 15:00:57 -03:00
Martin-Molinero
52de357b27 Terminal Link Minor Fixes (#7093)
- Fix data-queue-handler configuration initialization using paper brokerage
- Fix for downloader data provider request times
- Fix null reference exception in live result handler if algorithm is
  null
2023-03-20 12:24:16 -03:00
Derek Melchin
70acb30546 Test EmaCrossAlphaModel (#7081) 2023-03-17 18:08:43 -03:00
Alexandre Catarino
7c68e3f37a Refactor Portfolio Construction Models to Use Insight Manager (#7077)
* Asserts Number of Insights In One PCM Regression Test

If the `EqualWeightingPortfolioConstructionModel` interacts with the `QCAlgorithm.Insights`, the number of elements in the collection should not the sum of emitted insights.

* Refactor Portfolio Construction Models to Use Insight Manager

`PortfolioConstructionModel` will use `QCAlgorithm.Insights" instead of class property `InsightCollection` to manage the insights. It no longer adds insights to the collection, but it removes them if they expire or the securities are removed from the universe.

Updates PCMs that were affected by the change.

* Updates Unit Tests

We need to add the insights to the insight manager before we call `PortfolioConstruction.CreateTargets`
2023-03-17 18:00:43 -03:00
Louis Szeto
8a087f2166 Change python optimizer to Newton, added unit tests and regression test (#7085) 2023-03-17 15:23:31 -03:00
Martin-Molinero
a9c88ad25c ResultHandler state file improvements (#7078)
- Adjust start/end time string format
- In live trading will store the status file at the start, every 10 min
  and at the end
2023-03-16 18:24:49 -03:00
Martin-Molinero
bc6ac5470b Minor IndexOption underlying TZ fix (#7072)
* Minor IndexOption underlying TZ fix

- Fix for option universe chain underlying TZ which might not match the
  options one, bug affected IndexOption specifically.

* Update affected regression tests
2023-03-15 18:41:52 -03:00
Martin-Molinero
06bec5fb8e Add more logs for regression tests (#7073)
- Add holdings & cashbook logs from regression result handler, useful
  for debugging & developing
2023-03-15 18:25:26 -03:00
Martin-Molinero
d6f894eb3b Fix fill forward unit tests (#7070)
- Fix for some fill forward unit tests that were failing when run
  individually due to cache state in the
  TextSubscriptionDataSourceReader.
2023-03-15 12:45:04 -03:00
Martin-Molinero
8ed5f69ea6 Minor fill forward enumerator fix (#7068)
- Make sure the fill forward enumerator does not fill forward beyond the
  subscription end time. Adding tests
2023-03-15 10:18:43 -03:00
Alexandre Catarino
1c6be6438d Removes Cash Account Restriction for Framework Algorithms (#7067)
The user will be responsible for chosing/using models that fit the brokerage account type.
2023-03-14 19:25:20 -03:00
Martin-Molinero
2f03c92e30 Fill forward runtime adjustment (#7065)
- Fix for fill forward adjustment at runtime since the data stack runs
  async, we will remove and readd afected subscriptions.
2023-03-14 18:00:22 -03:00
Martin-Molinero
069246dda5 Performance Improvements (#7064)
* Performance Improvements

- Remove Immutable collection from position groups to improve
  performance. Adding more tests
- Remove ConcurrentDictionary from PortfolioTargetCollection &
  DataManager. Adding more tests
- Add Securities enumerator keys & values cache

* Add test for PortfolioTargetCollection remove by reference
2023-03-14 12:00:42 -03:00
Jhonathan Abreu
fbf8ffd924 Handle price discontinuity on volatility models (#7058)
* Apply splits and dividends to volatility models

* Apply splits and dividends to volatility models using history requests

* Add new ScaleRaw data normalization mode

Handling the new mode in the price scale enumerator.

* DataNormalizationMode.ScaledRaw history requests

* Minor changes

* Minor changes

* Disable new normalization mode in AddSecurity methods and other minor changes

* Peer review

* Minor changes

* Peer review

* Minor changes

* Peer review

* Peer review

* Peer review

* Add scaled raw history regression algorithm

* Add more regression algorithms

* Add more regression algorithms

* Add Slice.TryGet unit tests

* Peer review

* Peer review

* Peer review

* Peer review

* Peer review

* Update algorithms stats

* Peer review

* Peer review
2023-03-13 13:11:30 -03:00
Martin-Molinero
c6322956d9 Live trading holdings key (#7043)
* Fix live trading holdings uniqueness

- Fix live trading holdings key uniqueness

* Fix existing & add new test
2023-03-13 09:51:00 -03:00
Alexandre Catarino
aab5391d80 Fixes Limit Price Above/Below Open Case (#7060)
* Adds Unit Test For Limit Price Above/Below Open

See `LimitOrderFillsAtOpenWithFavorableGap`

* Fixes Limit Price Above/Below Open

If we place a buy/sell limit order below/above the current market price in TWS it fills immediately, so we model this behavior by filling with the opening price of the first trade bar.

* Updates Regression Tests

The number of trades did not change as expected. The fills are better because orders are filling with the open price when the new condition is met.
2023-03-10 14:23:45 -03:00
Martin-Molinero
bbbab6d9a8 Refactor alpha statistics phase I (#7055)
* Refactor alpha statistics

- Refactor alpha statistics, cleaning up and simplifying no longer required calculations and scoring
- Adding new InsightEvaluator abstraction, adding C# & PY regression
  algorithms

* Optimization backtest result json converter update

* Address reviews

- Remove IAlphaHandler, move insight storage responsability to IResultHandler
  and centralizing insight collection on the QCAlgorithm.Insights to be
  reused by the framework models
- Fix portfolio turnover single day backtests and duplicate time
  sampling handling. Updating regression algorithms

* Add InsightCollection tests and minor fixes

* Adding more & improved tests
2023-03-10 13:12:23 -03:00
Alexandre Catarino
4c909f33b9 Reuse Code To Find Best Effort TradeBar (#7057)
The `LimitFill`, `LimitIfTouchedFill` and `StopMaketFill` methods require `TradeBar` data to test price levels. We create a method to serve these methods as well other methods that will require this information.

Removes `Price > 0` check for `TradeType.Trade` data. Unecessary check, since a tick price cannot be less or equal to zero.
2023-03-09 11:06:26 -03:00
Martin-Molinero
e07c6265df Run TensorflowProbability Test Alone (#7056)
- For stability run TensorflowProbability test by itself
2023-03-08 17:18:58 -03:00
Alexandre Catarino
9069246519 Fixes EquityFillModel.StopMarketFill (#7042)
* Adds Unit Tests for Stop Market Fill

These unit tests covers new scenarios:
- Cannot trigger on quote data (QuoteBar or TickRype.Quote);
- Adds missing test for tick data (TickType.Trade)
- Unfavorable gap (see QuantConnect#4545)

* Fixes EquityFillModel StopMarketFill

Use the entire tick history to find the trigger price
Fill price is the stop price, unless there is an unfavorable gap (see #4545).

* Update Regression Tests

All regression tests keep the total trades. The difference are due to the time that the stop market orders are triggered and the prices that are filled. The `StopLossOnOrderEventRegressionAlgorithm` and the `UpdateOrderRegressionAlgorithm` observe the unfavorable gap case.

* Addresses Peer-Review

* Updates Regression Test

New `OrderListHash` because of the change in the fill on open case message.
2023-03-08 16:49:34 -03:00
Louis Szeto
0ed6d7e8b0 Remove annualization in MeanVarianceOptimizationPCM (#7053)
* remove annualization

* Update python optimizer to best fit in convex problem

* rerun test

* test metric

* Add comment to explain using simple return

* Add unit test on PR
2023-03-08 14:13:38 -03:00
Louis Szeto
11c182ed16 Add McClellanOscillator & McClellanSummationIndex Indicator (#7038)
* Add `McClellanOscillator` Indicator

* Add helper class in QCAlgorithm.Indicator

* Add `McClellanSummationIndex` indicator

* typo

* Fix MSI implementation

* Address peer review

* free `MOSC` in `MSI`

* fix bug

* Minor tweaks. Addressing review

---------

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2023-03-07 16:19:24 -03:00
Martin-Molinero
a5586ba562 Enqueable Enumerator Performance Improvement (#7049)
- Refactor enqueable enumerator not to require read lock most of the
  time
2023-03-06 15:40:55 -03:00
Martin-Molinero
1393ce4c5d Performance Securities & CashBook Collections (#7050)
- Improve performance of Securities & CashBook collections
2023-03-06 15:39:32 -03:00
Alexandre Catarino
694ffbbb80 Removes PythonTools from Solution (#7044)
* Removes PythonTools from Solution

Missing removal from #6967.
It results in a runtime error if we use dotnet to list the packages:
`dotnet list ../Lean/QuantConnect.Lean.sln package`

* Update QuantConnect.Lean.sln

---------

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2023-03-06 12:44:02 -03:00
Martin-Molinero
642fe96fde Update Binance Symbol Properties DB (#7040)
- Update Binance SPDB
- Minot fix for ExchangeInfoUpdater
2023-03-03 19:41:53 -03:00
Martin-Molinero
c4433098c3 Refactor Framework Statistics (#7041)
* Refactor framework statistics

* Further insight chart cleanup
2023-03-03 19:40:29 -03:00
Martin-Molinero
38f5a9c60c Bump to pythonNet 2.0.18 (#7036) 2023-03-03 13:11:03 -03:00
Louis Szeto
f4827f2f22 Modify advance decline indicators (#7032) 2023-03-02 15:48:20 -03:00
Jhonathan Abreu
81d1bb5095 Sample exposure for non invested portfolio (#7030) 2023-03-02 15:23:10 -03:00
Jhonathan Abreu
cdcd8fdacd Apply splits to TradeBuilder (#7020)
* Apply splits to TradeBuilder

* Minor tests changes

* Minor changes

* Add regression algorithm
2023-03-02 15:15:40 -03:00
Martin-Molinero
eebe0425d8 Rollback base image to focal (#7033)
* Rollback base image to focal

* Python env blame hang & crash
2023-03-02 12:43:23 -03:00
Martin-Molinero
caadaf62b2 Update readme.md 2023-03-01 20:12:05 -03:00
Louis Szeto
19df3e1e48 Normalization of Minimum Variance Optimizer's output weight (#6999)
* Update Optimizers to use absolute total weight for budgeting

* Update regression test

* address peer review

* added remarks
2023-03-01 17:20:58 -03:00
Martin-Molinero
66c016b284 Feature foundation update (#7028)
* Foundation Update

* Adding more foundation packages

* Update existing libraries

* Further package updates

* Image cleanup

- Update base image to ubuntu 22.04
- Some clean up on dockerfile
- Remove ARM base image

* Test updates

- Minor docker file tweaks
- Update existing python environment tests

* Add more tests & fix Julia

* Remove jupyter-dash

* Remove R from foundation

* Remove Julia

* Remove Tensorforce
2023-03-01 16:30:46 -03:00
Jhonathan Abreu
0c77be0ba8 Allow closed orders tag update (#7016)
* Allow closed orders tag update

* Minor changes
2023-02-27 18:42:24 -03:00
Wayne Adams
47bfdae372 docs: updates python version in vs instructions (#7014) 2023-02-27 10:19:02 -03:00
Jhonathan Abreu
3a2cae037f Fix UniverseDefinitions.ETF|Index overloads (#7006)
* Fix UniverseDefinitions.ETF|Index methods call ambiguity

* Minor changes
2023-02-24 16:35:35 -03:00
Martin-Molinero
b9e6781c96 Add missing exchanges (#7011)
* Add missing exchanges

- Add missing exchange definitions

* Fix and add more tests
2023-02-24 16:31:51 -03:00
Alexandre Catarino
2a6771c1c0 Fixes Liquidate Existing Holdings Behavior for SetHoldings for Multiple Targets (#7009)
* Adds Regression Test

The new regression test asserts that the total trades is 2.

* Fixes Liquidate Existing Holdings Bug

Liquidate existing holdings before open new postions.

* Addresses Peer-Review
2023-02-24 14:46:12 -03:00
Martin-Molinero
56270464cc IsOption Use Underlying Holidays and Early Closes if Empty (#7007)
* IsOption uses underlyings holidays

- Option assets will use underlyings holidays, early closes and late
  opens if their own are not defined

* Update regression algorithms
2023-02-24 12:49:51 -03:00
Alexandre Catarino
8bcd588602 Fixes EquityFillModel.FillModel (#7005)
* Adds Unit Tests

The `LimitFill` method should not fill using `QuoteBar` or `Tick` with `TickType.Quote` type.
Adds missing test for tick data (`TickType.Trade`).

* Fixes EquityFillModel.FillModel

Use `Tick` with `TickType.Trade` or `TradeBar` information to fill limit orders.

* Update Regression Test Expected Statistics

The regression tests changed because of different fills.
The `ExtendedMarketTradingRegressionAlgorithm` has different number of trades because of an extra fill on the 4th order generated by TradeBar with a Low lower than than the QuoteBar.Ask Low:

> 20230222 13:56:24.251 TRACE:: Log: Time: 10/10/2013 12:01:00 OrderID: 4 EventID: 2 Symbol: SPY Status: Filled Quantity: 10 FillQuantity: 10 FillPrice: 143.8998 USD

> asset.Cache.GetData<QuoteBar>().ToString()
"SPY: Bid: O: 144.2457 Bid: H: 144.2629 Bid: **L: 144.2457** Bid: C: 144.2629 Ask: O: 144.2543 Ask: H: 144.2889 Ask: **L: 144.2543** Ask: C: 144.2889 "

> asset.Cache.GetData<TradeBar>().ToString()
"SPY: O: 144.2543 H: 144.4532 **L: 143.4156** C: 144.2716 V: 75423"

* Improves Tick Resolution Unit Test

* Fixes Tick Resolution Case Handling

`master` only considers the latest trade, missing possible fills in the batch of trades.

* Adds Unit Test for Gap

See https://github.com/QuantConnect/Lean/issues/963

* Addresses Fill Optimistic Assumption

If we have a bar that gaps in our favor, we accept the limit price to avoid optimitic fills.

* Fixes Regression Tests

All regression tests with limit orders have worst performance after we remove the optimitic assumption, and use the limit price instead.
2023-02-24 10:35:34 -03:00
Alexandre Catarino
9cd05e9f1f Fixes BasePairsTradingAlphaModel (#7003)
* Updates the PearsonCorrelationPairsTradingAlphaModelFrameworkAlgorithm

Change the `PearsonCorrelationPairsTradingAlphaModelFrameworkAlgorithm` logic to show that it doesn't remove the consolidators used in the Alpha Model's indicators.

* Fixes `BasePairsTradingAlphaModel`

The `BasePairsTradingAlphaModel` will create indicators with class constructors and register them to consolidators that will be removed when the security is removed from the universe.

* Addresses Peer-Review
2023-02-24 10:20:01 -03:00
Jhonathan Abreu
40bff6efb7 Oanda trading hours update (#6998)
* Update Oanda's Forex and Metals CFDs trading hours in the MHDB

* Fix failing unit tests

* Update regression algorithm statistics

* Fix failing unit tests

* Minor changes
2023-02-24 10:14:55 -03:00
Jhonathan Abreu
f5e8966eea Uset GoodTilDate TIF for MOO and MOC orders (#7001)
* Uset GoodTilDate TIF for MOO orders

* Uset GoodTilDate TIF for MOC orders

* Add one-time warning for TIF validation
2023-02-23 17:38:44 -03:00
Ronit Jain
1596ed9846 remove force breakpoint (#7004) 2023-02-23 12:41:52 -03:00
Martin-Molinero
c1c4114dca Newtonsoft & Protobuf & RecyclableMemoryStream Updates (#7002)
* Dependency updates

- Update Newtonsoft to 13.0.2, protobuf to 3.2.0, RecyclableMemoryStream
  to 2.3.1

* Downgrade protobuf to 3.1.33
2023-02-23 12:11:01 -03:00
abhi-kr-2100
6acbcf0832 Brokerage Models Order Supported Types Check (#6989)
* Fix Issue #6937

Some brokerage models don't check the order type in `CanSubmitOrder`.
As a result, unimplemented order types don't cause `CanSubmitOrder`
to return false as it should.

This commit fixes these issues for:
* `FTXBrokerageModel.cs`
* `InteractiveBrokersBrokerageModel.cs`
* `SamcoBrokerageModel.cs`
* `TradierBrokerageModel.cs`
* `ZerodhaBrokerageModel.cs`

Brokerage implementations can be found at
https://github.com/orgs/QuantConnect/repositories. For example, the
Zerodha Brokerage implementation is available at
https://github.com/QuantConnect/Lean.Brokerages.Zerodha.

Signed-off-by: Abhishek Kumar <abhi.kr.2100@gmail.com>

* Use HashSet instead of an array

Checking if an object is contained within a HashSet is faster than
checking the same in an array.

Signed-off-by: Abhishek Kumar <abhi.kr.2100@gmail.com>

* Minor adjustments and normalization

* Add missing OptionExercise for IB

---------

Signed-off-by: Abhishek Kumar <abhi.kr.2100@gmail.com>
Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2023-02-21 13:11:04 -03:00
Jhonathan Abreu
5675e71a32 Handle prices getting stuck on data generation (#6995)
* Handle prices getting stuck on data generation

* Add more unit tests
2023-02-21 13:09:31 -03:00
Martin-Molinero
48914b08db Chart Series Settings Lost (#6997)
* Fix live trading chart series index

- Fix Series loosing their index when handled by the
  LiveTradingResultHandler
- Some clean up for Series.cs

* Fix SeriesSampler loosing Series settings
2023-02-21 13:07:56 -03:00
Martin-Molinero
852c963bbf Remove unsupported HKFE from MHDB (#6990)
* Remove HKFE from MHDB

- Remove unsupported HKFE from MHDB

* Update tests
2023-02-20 20:19:42 -03:00
Alexandre Catarino
99848a1221 Adds NullBuyingPowerModel (#6977)
* Adds NullBuyingPowerModel

The `NullBuyingPowerModel` considers that we have sufficient buying power for all orders.

Adds example using a bull call spread since a equity buy and hold would not show the impact of this model in the position group buing power model.

* Define NullBuyingPowerModel.GetMaintenanceMargin

The `NullBuyingPowerModel.GetMaintenanceMargin` returns a `MaintenanceMargin` of zero. It means the total margin used is always zero and margin calls will not be triggered.

This feature is inspired on the  `ConstantBuyingPowerModel`. We don't inherit from that class, because `ConstantBuyingPowerModel.GetInitialMarginRequirement` gives us very small initial margin that leads to a very large quantity if we use `SetHoldings` or `CalculateOrderQuantity`
2023-02-20 19:50:24 -03:00
Martin-Molinero
7178be4f55 Remove Yahoo auxiliary data generator (#6993)
- Remove yahoo auxiliary data generator and failing tests
2023-02-20 19:23:31 -03:00
Martin-Molinero
017837c5a5 Remove Oanda cash account support (#6994)
- Oanda only supports margin account types
2023-02-20 19:21:50 -03:00
Martin-Molinero
c7294adfe4 Fix OrderQuantityLessThanLotSize typo (#6991) 2023-02-20 19:21:25 -03:00
Martin-Molinero
61fb997f07 Delete unsupported AlgoSeek Option Converter (#6992)
- Delete unsupported algoseek option converter
2023-02-20 19:21:15 -03:00
Alexandre Catarino
7cc6e31c43 Fixes Insight Period Calculation (#6978)
The calculations of `CloseTimeUtc` are correct and consistent: if the exchange is closed when the insight expires, `CloseTimeUtc` is the next open.

However, the definition of the `Period` was not consistent. Normally, it is defined by the different between `CloseTimeUtc` and `GeneratedTimeUtc`, but when we create an Insight with the Resolution and bar count overload, the period was defined by them:

```csharp
insight.Period = Resolution.ToTimeSpan().Multiply(BarCount);
```

which is incorrect, since it doesn't take the days the exchange is closed into account. The `ComputePeriod` method enforced consistency between the Resolution and bar Count overload and the `DateTime` overload, so the period for this overload was also incorrect.
2023-02-20 16:23:13 -03:00
Alexandre Catarino
b5ca1ac461 Removes UncorrelatedUniverseSelectionModel (#6976)
Framework models must have a C#, and Python implementation and algorithms that use them.
2023-02-20 16:21:53 -03:00
Jhonathan Abreu
2a54da9e2c Custom data type history API usage in Python (#6971)
* Custom data type history request in python

* Potential solutions

* Minor changes

* Use Slice.Get(Type) for getting python custom data history

* Minor changes

* Add unit tests

* Add unit tests

* Udpdate regression algorithms

* Peer review

* Peer review

* Add research regression tests

* Minor changes

* Minor changes

* Minor tweaks

---------

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2023-02-20 16:21:37 -03:00
Martin-Molinero
6fd1a002fe Adjust index option data timezone (#6970)
* Fix index option data timezone

- Fix index option data timezone which was 1 hour late than expected

* Update existing index option tests

- Update existing index option tests.
- Disable index option daily resolution support
2023-02-16 17:35:10 -03:00
Martin-Molinero
ace1a1f20d Define MaximumContractDepthOffset (#6969) 2023-02-16 17:23:56 -03:00
Martin-Molinero
75f86f555e Delete unused PythonToolbox (#6967) 2023-02-16 17:23:38 -03:00
Martin-Molinero
20655b334b Update readme.md 2023-02-15 15:16:55 -03:00
Martin-Molinero
3507c91640 Fix future daily price scale factor update (#6963)
* Fix future daily price scale factor update

- Fix future daily price scale factor update which was happening 1 day
  late due to data and exchange time zone differences.
  Adding regression algorithm reproducing and asserting it.

* Address review
2023-02-14 20:09:59 -03:00
Jhonathan Abreu
ebb31d0fb4 Unsettled cash conversion rate update (#6961)
* Update unsettled cashbook cash conversion rates

Also moved conversion rate holding from Cash to the CurrencyConversion
instance

* Minor fixes

* Peer review

* Minor fixes

* Minor fixes

* Minor fixes
2023-02-14 18:19:25 -03:00
Ronit Jain
dcd60d0551 Add support for HTML reports conversion to PDF (#6960)
* add wkhtmltopdf to lean image

* convert html to pdf

* avoid black stripts at bottom of each page

* address reviews

* address review

* address reviews

* self review

* address review
2023-02-14 15:50:19 -03:00
Martin-Molinero
dc2c68c754 Fix security cache reset (#6959)
* Fix security cache reset

- Fix security cache reset so it only happens when no universe has it as
  a member. Adding regression algorithm reproducing issue

* Avoid non deterministic FillForward behavior
2023-02-14 12:09:27 -03:00
Jhonathan Abreu
2791765c94 Make Consolidate Calendar overload with tick type public (#6957) 2023-02-13 16:01:30 -03:00
Martin-Molinero
f270f25eca Fix default future chain universe selection (#6958)
* Fix default future chain universe selection

- Fix default future chain universe selection that should always return
  empty, no selection. In some cases it would allos some contracts
  though. Adding regression algorithm reproducing issue.

* Address review
2023-02-13 15:56:48 -03:00
Martin-Molinero
8235de42a0 Minor debugging improvements (#6954)
* Minor debugging improvements

- Improve exception message if user provides empty/null ticker
- Log margin information on algorithn initialization
- Add unit test asserting option strategy position groups resolve
  correctly for existing holdings

* Symbol Lazy SecurityDefinitionSymbolResolver

- Symbol will have a lazy SecurityDefinitionSymbolResolver instance
  resolution
2023-02-13 10:49:10 -03:00
Martin-Molinero
c2e21df18b Fix combo order prechecks (#6953)
- Apply combo order prechecks before submitting orders. Adding unit test
2023-02-10 19:11:45 -03:00
Jhonathan Abreu
35dfcd73ab Index options MHDB review (#6890)
* Index options MHDB review

* Update MHDB

* Update regression algorithms stats

* Update regression algorithms stats

* Add index and index options holidays

* Peer review

* Update algorithms stats
2023-02-10 14:37:44 -03:00
Jhonathan Abreu
3783900eef Move Brokerages namespace's messages to Messages folder (#6915) 2023-02-10 13:49:15 -03:00
Jhonathan Abreu
9fea859323 Symbol to industry-standard security identifier conversion (#6893)
* Implement SecurityDefinitionSymbolResolver backwards conversion (symbol -> standard id)

* Peer review

* Peer review

* Peer review
2023-02-10 13:12:13 -03:00
Jhonathan Abreu
6e2744af7c Move Securities namespace's messages to Messages folder (#6922)
* Move Securities namespace's messages to Messages folder

* Rebase related fixes

---------

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2023-02-10 11:31:11 -03:00
Martin-Molinero
962b91fc12 Fix Messages namespace collision 2023-02-10 10:50:03 -03:00
Louis Szeto
cf00d3c9f3 OptionStrategies for put calendar spread index weeklies example (#6951) 2023-02-10 10:44:47 -03:00
Louis Szeto
8af5c8b6f2 OptionStrategies for put butterfly index weeklies example (#6950) 2023-02-10 10:42:40 -03:00
Louis Szeto
1fcef8c024 OptionStrategies for Index Option Call Butterfly (#6949)
* OptionStrategies for call butterfly index weeklies example

* fix typo
2023-02-10 10:42:07 -03:00
Jhonathan Abreu
a912638496 Move QuantConnect namespace's messages to Messages folder (#6924) 2023-02-10 10:41:05 -03:00
Jhonathan Abreu
5611b5508a Binance crypto futures fee models (#6874)
* Add Binance Futures and Binance Coin Futures fee models

* Add unit tests

* Add unit tests

* Minor changes

* Peer review

* Peer review
2023-02-09 19:25:27 -03:00
Jhonathan Abreu
b3bd15d3c2 Move Notifications, Optimizer and Python namespaces' messages to Messages folder (#6931) 2023-02-09 19:23:39 -03:00
Jhonathan Abreu
25ab8bdacc Move small namespaces' messages to 'Messages' folder (#6930)
* Move Benchmarks, Exceptions and Indicators namespaces' messages to Messages folder

* Move Command namespace's messages to Messages folder
2023-02-09 19:17:40 -03:00
Jhonathan Abreu
38c5ef3e2b Add CME Ether futures to symbols database (#6884)
* Add Ether futures to symbols database

* Change ETH futures exchange time zone to US/Central

* Add new contracts FuturesExpiryFuntions

* Remove BTIC Micro BTC and BTIC Micro Ether securities

* Add Ether futures IB fees and price multiplier entry

* Update Ethereum price multiplier
2023-02-09 18:42:19 -03:00
Jhonathan Abreu
194f01e621 Move Algorithm namespace's messages to Messages folder (#6916) 2023-02-09 18:35:29 -03:00
Martin-Molinero
61b5231c50 Research GetOptionHistory Weekly Index Improvement (#6946)
- Improve research GetOptionHistory weekly index option support. Adding
  unit test
2023-02-09 18:35:20 -03:00
Louis Szeto
4a06fcdda0 OptionStrategies for Index Option Bull Put Spread (#6945) 2023-02-09 16:10:14 -03:00
Louis Szeto
8325fd18ca OptionStrategies for Index Option Bull Call Spread (#6944) 2023-02-09 16:07:43 -03:00
Louis Szeto
2bc8783082 OptionStrategies for Index Option Bear Put Spread (#6943) 2023-02-09 16:07:00 -03:00
Louis Szeto
0d9f011758 OptionStrategies for Index Option Bear Call Spread (#6942) 2023-02-09 16:06:12 -03:00
Jhonathan Abreu
6dfc6c710c Add algorithm parameters to result (#6878)
* Add algorithm parameters to result's AlgorithmConfiguration

* Peer review
2023-02-09 12:55:30 -03:00
Jhonathan Abreu
e30232e21b Portfolio.UnsettledCashBook update when quote currency is not the account currency (#6871)
* Tracking unsettled cash for non-USD account currency

* Add unit tests

* Peer review

* Move and rename CashBook.UpdateType to Globals
2023-02-09 12:53:52 -03:00
Louis Szeto
8730eeb8a9 Volume Renko Consolidator & Bar (#6888)
* Volume Renko Consolidator & Bar

* address peer review

* Minor fix on tests

---------

Co-authored-by: LouisSzeto <hke0073@hotmail.com>
2023-02-09 10:46:02 -03:00
Jhonathan Abreu
914485c595 Rename SubscriptionRequest.TradableDates to TradableDatesInDataTimeZone for clarity (#6892)
Usages were reviewed to make sure all of them expect it to be in data
time zone instead of exchange time zone
2023-02-08 20:28:37 -03:00
Jhonathan Abreu
02f085ee9e Validate date on security identifier generation (#6897) 2023-02-08 20:26:37 -03:00
Martin-Molinero
f4cf7b6733 Fix SPXW option strategies (#6939)
- Fix SPXW option strategies. Adding regression algorithm
2023-02-08 20:24:30 -03:00
Jhonathan Abreu
d427970762 Check minimum Forex limits in IB Brokerage Model (#6881)
* Checking both min and max forex order size limits in IB brokerage model

Also updated the limits table

* Address peer review
2023-02-08 16:40:18 -03:00
Jhonathan Abreu
66ff14b3bd Patch for missing tick data in history call (#6932)
* Patch for missing tick data in history call

* Update TODO comment to include info on the proposed solution
2023-02-06 13:50:59 -08:00
Jhonathan Abreu
a7a4af6b70 Add Security.SetMarginInterestRateModel methods and its python wrapper (#6879) 2023-02-06 07:57:55 -08:00
Alexandre Catarino
b1a6aa686c Replace Nodes Endpoint in SDK (#6899)
* Adds `project/nodes` Endpoint to SDK

* Removes `nodes` Endpoint from SDK

* Fixes Documentation for `ProjectNodesResponse`
2023-02-05 09:35:11 -08:00
Louis Szeto
14b10f5e81 Add example of bull/bear call spread using index option (#6889)
* Add example of bear call spread using index option

* consistency

* Add bull call spread

* peer review

* peer review

* address peer review

* bug fix

* fix filter

* Address peer review
2023-02-02 13:01:47 -08:00
Louis Szeto
4d85f27f00 Add bull/bear put spread sample algorithms for index weeklies (#6914)
* bear put spread

* bull put spread
2023-02-02 12:34:26 -08:00
Louis Szeto
c2efa65048 Add Call/Put Butterfly sample algorithms for index weeklies (#6913)
* Add index weeklies' Call/Put Butterfly sample algo

* Address peer review
2023-02-02 12:34:04 -08:00
Louis Szeto
75eaf21e43 Add example algo of call & put calendar spread with SPXW (#6907)
* Add example algo of call calendar spread with SPXW

* Add similar example for put calendar spread

* Refine

* consistency

* address peer review

* fix bug

* bug fix

* update

* Improved efficiency

* Address peer review
2023-02-02 12:33:17 -08:00
Louis Szeto
72a6ea9d31 Add SPXW Iron Condor example algorithm (#6880)
* Add SPXW Iron Condor example algorithm

* review

* peer review

* Address peer review
2023-02-02 12:26:34 -08:00
Jhonathan Abreu
2b9662c12e Fix quote tick python consolidate call (#6876) 2023-01-26 18:22:34 -08:00
Jhonathan Abreu
98314d98ed User-facing messages organization (first phase) (#6912)
* Move user-facing order-related messsages to the Messages class

* Group Messages by class

* Move more orders messages

* Minor changes and docs
2023-01-26 16:14:57 -08:00
Jhonathan Abreu
a860cfc32f Combo orders reduced size validation (#6864)
* Combo order legs ratio validation

* Minor changes and unit tests

* Minor changes

* Minor changes

* Minor changes

* Minor changes
2023-01-16 21:11:08 -03:00
Martin-Molinero
6563d6e394 Use any resolution for chain provider (#6860)
* Use any resolution for chain provider

- Use any data resolution available to source symbols for the file based
  chain provider. Adding unit test

* Fix selection timezone bug

- Fix universe selection timezone bug. Updating regression algorithms
2023-01-16 16:10:07 -03:00
Martin-Molinero
11cc062628 Combo limit orders price calculation (#6858)
* Fix limit price calculation for combo limit orders fills

* Update regression algorithms

* Address reviews

* Fix thread race condition

Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
2023-01-13 18:02:25 -03:00
Alexandre Catarino
e8b95b80e1 Polygon Handles Data Subscriptions with One Security Type (#6855)
* Handles Data Subscriptions with One Security Type

Polygon sells data subscriptions for security types separately, so we should not test whether the users have all three subscriptions, Equity, Forex, and Crypto. Users just need the type they will use.

Adds new crypto markets, and unit tests for them. Adapt unit test.

* Fixes ToolBox Downloader

Adds `--api-key` argument.
Closes #6687

* Address reviews

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2023-01-12 17:37:29 -03:00
Martin-Molinero
a52822853d Expand Index option support (#6849)
* Expand Index option support

- Adjust APIs so that the same underlying can be used
  for different options, adding support for SPX weekly options. Adding
  regression tests

* Fix IndexOption.IsStandard

* Add IndexOption test
2023-01-12 16:39:02 -03:00
ChadBett
73e46cc9ae TensorFlow Placeholder Fix (#6852)
Fixed this error from happening when running this code:

tf.placeholder() is not compatible with eager execution.
  at placeholder
    raise RuntimeError("tf.placeholder() is not compatible with "
 in array_ops.py: line 3341
  at NetTrain
    xs = tf.compat.v1.placeholder(tf.float32 in /QuantConnect/backtesting/./cache/algorithm/project/main.py: line 57
2023-01-11 11:18:47 -03:00
Ronit Jain
a9c4d29776 Feature add algorithm state information in result packets (#6839)
* add state to backtesting result packets

* self review

* add state in live results

* set runtime error in algorithm

* set hostname in job packets

* Set state when algorithm is null

* address review

* address reviews

* set runtime error when algorithm is not available during runtime
2023-01-11 10:54:38 -03:00
Jhonathan Abreu
6ed8cb5cae Backtest progress calculation (#6847)
* Fix backtest progress calculation

* Backtest progress monitor class

* Minor changes

* Lazy calculating the processed days count

* Minor changes

* Minor changes
2023-01-11 10:33:38 -03:00
Jhonathan Abreu
1d1dc07dfb Set DataNormalizationMode on AddSecurity method (#6845)
* Set DataNormalizationMode on AddSecurity method

* Minor changes
2023-01-10 13:03:00 -03:00
Jhonathan Abreu
bddebe279d Algorithm asserting options stategy orders with large quantities (#6843) 2023-01-09 14:21:16 -03:00
Martin-Molinero
81a334c525 Add Leg.Create method (#6842)
- Add Leg.Create method for sugar syntax, specially for python
2023-01-09 14:20:32 -03:00
Martin-Molinero
af26b66481 Update readme.md 2023-01-06 21:10:08 -03:00
Martin-Molinero
d7ead851a1 Update readme.md 2023-01-06 19:27:32 -03:00
Martin-Molinero
f428398900 Update readme.md 2023-01-06 19:22:07 -03:00
Martin-Molinero
19483702f8 Update readme.md 2023-01-06 18:36:42 -03:00
Martin-Molinero
146be2d0ba Update readme.md 2023-01-06 18:09:40 -03:00
Jhonathan Abreu
b54281b262 Combo orders (#6813)
* Feature combo orders

- Add support for combo orders

* Make fill model wait for all grouped orders to emit fills

* Add ComboFill to model multiple fills for combo orders

* Fill combo limit orders

Add some regression algorithms

* Add fill implementation for combo leg limit orders

* Add IFill as common interface for Fill and ComboFill

* Refactor combo orders removing IGroupOrder interface

Move the group order manager to the base Order class

* Update algorithms

* Handle combo order events atomically

* Refactor brokerage transaction event handler

* Refactor combo fill models

* Process fills in batch

* Combo orders fill model tests

* Combo leg limit orders algorithm

* Regression algorithms cleanup

* Fill and combo fill classes cleanup

* Housekeeping

* Refactor equity fill model to derive from base fill model

* Address review changes request

* Handling the new types of orders in the OrderJsonConverter

* Add regression algorithm to test combo orders update/cancel

* Add regression algorithm to test combo orders update/cancel

* Housekeeping

* Address review changes request

* Minor changes

* Security transaction handler method for setting order request id

* Extend public interface for placing combo orders

* Combo order tickets demo algorithm python version

* Tweaks and updates

* Minor fixes

* Minor changes

* Minor fixes

* Address reviews minor fixes

* Minor fixes

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2023-01-06 17:58:43 -03:00
Martin-Molinero
f12e8fc08e CryptoFutures adjustments (#6836)
* CryptoFutures adjustments

- Address reviews of CryptoFutures:
- Add new Slice MarginInterestRates collection
- Add new regression tests asserting funding rate application behaves
  the same no matter the resolution
- Add auxiliary data by type into the security cache
- Revert BuyingPowerModel changes

* Make interest rate application time deterministic
2023-01-05 18:07:01 -03:00
Alexandre Catarino
6b6ca5b460 Saves Dividend Payments to Security Holdings (#6830)
* Saves Dividend Payments to Security Holdings

Saves information about dividend payments to `SecurityHoldings`. This information will be used to factor in dividend payments to the `Profit` and `NetProfit`.
Adds `SecurityPortfolioManager.TotalNetProfit` to sum all the `SecurityHoldings.NetProfit`.

Adds regression and unit tests.

* Addresses Peer-Review

Improves Regression Test.
2023-01-03 18:37:00 -03:00
Martin-Molinero
ab4c3bf55e Live margin interest rate bug (#6833)
* Fix for live MarginInterestRate

* Add unit tests
2023-01-03 14:13:11 -03:00
hsm207
9c69ee5536 Update link to Lean CLI getting started (#6832) 2023-01-02 11:14:06 -03:00
Alexandre Catarino
89493b1546 Adds Pre-Market for LBS (#6831)
The lumber pre-opening window is from 6am to 9am Chicago.
https://www.cmegroup.com/trading-hours.html#foi=F&search=Lumber
2022-12-30 18:00:07 -03:00
Martin-Molinero
ee683933a3 Feature Perpetual Crypto Futures (#6807)
* WIP

* Add base currency cash

* Symbol properties and data processing

* Add basic template algorithm

* Add hourly crypto future algorithm

* Minor fixes after live trading testing

* CoinApiDataQueueHandler CryptoFuture support

* Address reviews

* Fix regression algorithms after update
2022-12-30 13:58:11 -03:00
Martin-Molinero
e87c98def8 Update readme.md 2022-12-28 15:39:59 -03:00
Martin-Molinero
239406ef5c Update ib gateway to latest (#6819) 2022-12-28 15:35:52 -03:00
Martin-Molinero
e13066273c Update readme.md 2022-12-26 17:25:34 -03:00
Martin-Molinero
7677b99bf6 Handle OnOptionNotification race condition (#6821)
- Handle OnOptionNotification race condition to take into account sell
  orders too. Updating unit tests
2022-12-26 17:21:51 -03:00
Ronit Jain
c21dd716ed use data channel property (#6826) 2022-12-26 15:23:18 -03:00
Martin-Molinero
f87eb88f27 Update holidays Christmas New Years 2022/23 (#6824) 2022-12-26 13:58:05 -03:00
Martin-Molinero
1d363e2c35 Fix brokerages tests order id update (#6822)
- Fix for brokerage test brokerage order id update handling
2022-12-22 20:02:35 -03:00
Martin-Molinero
98273097e5 Update readme.md 2022-12-22 10:43:39 -03:00
Martin-Molinero
cbdf25d713 Update readme.md 2022-12-21 21:19:44 -03:00
Martin-Molinero
dcfdbd8c82 Add OnOrderIdChangedEvent (#6816)
* Add OnOrderIdChangedEvent

- Add OnOrderIdChangedEvent so that brokerages can change the brokerage
  order ids on the original order directly

* Fix bug
2022-12-21 20:53:39 -03:00
Louis Szeto
b5b317f490 Basic template algorithm for continuous futures rollover (#6803)
* Basic template algorithm for continuous futures rollover handling

* update regression metric

* Update to multi-contract versions

* SymbolData implementation

* minor bug

* peer review

* order hash

* more abstraction
2022-12-20 11:37:32 -03:00
Martin-Molinero
0eecf5d139 Update gh-actions.yml 2022-12-20 11:12:43 -03:00
Alexandre Catarino
bc513ce0e7 Changes Crumb Location from Yahoo Downloader (#6812)
Yahoo has changed the location from the crumb which is no longer located in "CrumbStore",
2022-12-20 10:33:52 -03:00
Roman Yavnikov
019ce5aa76 TDAmeritrade brokerage fix (#6806)
* remove: support SecurityType.Future

* add SecurityType.Index and IndexOption
fix: error message in orderType support

* Update TDAmeritradeBrokerageModel.cs

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-12-16 19:47:03 -03:00
Martin-Molinero
c4329c4132 More resilient object store file read (#6800) 2022-12-13 15:25:47 -03:00
Roman Yavnikov
9618c376bf Feature tdameritrade brokerage setup (#6791)
* TDAmeritrade LEAN integration

* feature: update order model for TDAmeritrade brokerage
fix: typos

* fix: typo in license

* refactor: remove extra multiple op

* refactor: TDAmeritrade naming api-key

* remove: extra configs

* fix: PR comment

* Rename file

* feature: add to config `SubscriptionDataReaderHistoryProvider`

* remove: extra logic

* Address review

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-12-12 18:14:21 -03:00
Alexandre Catarino
3aabb11315 Allows Market-On-Close Orders Outside Buffer Period (#6769)
* Allows Market-On-Close Orders Outside Buffer Period

Market-On-Close orders can be submitted before and after the buffer period from 15:45 to 16:00 (Tested with TWS) meaning that we can submit MOC when the market is closed and, consequently, use daily resolution data.

* Adds Regression Test with Extended Market Hours

- Removes `nextMarketClose > Time` condition since it's unnecessary. If the algorithm Time is greater than the close of that day, `nextMarektClose` refers to the next day.

* Updates Unit Test

Updates `OrderQuantityConversionTest` because the MOC orders are submitted. They are placed at 7 pm and invalid before this pull request.

* Updates Summary of new Regression Tests
2022-12-08 19:46:58 -03:00
Jhonathan Abreu
4d2723f851 Update CME options scaling factors (#6774) 2022-12-06 16:41:04 -03:00
Jhonathan Abreu
86b74e0a09 Add IB weekly restart time entry to config file (#6773) 2022-12-06 14:52:46 -03:00
Jhonathan Abreu
41a730bc68 OTM option excerise orders improvements (#6767)
* Set fill price to zero in OTM exercise orders.

Improved the OTM exercise orders message.

* Update regression algorithms and unit tests

* Add IsInTheMoney property to OrderEvent

* Update SerializedOrderEvent

* Properly setting the option exercise order price to strike price or zero

* Minor changes

* Minor changes
2022-12-06 14:30:40 -03:00
Jhonathan Abreu
6b2dfb6b8c Update equity default settlement days (#6766) 2022-11-28 13:26:56 -03:00
Jhonathan Abreu
7a4ca7898e Add estimate option to optimizer for optimization estimate (#6763)
* Add 'estimate' option to optimizer launcher

* Add 'estimate' option to optimizer launcher

* Unit tests and minor tweaks

* Minor tweaks
2022-11-25 19:08:28 -03:00
Mathieu Paquette
60028ad48a fix(ToolBox/IQFeed): increase default buffer size (#6762)
fixes #6761
2022-11-25 10:40:52 -03:00
Derek Melchin
e9d690b35a Add missing </summary> tag (#6760) 2022-11-23 10:20:27 -03:00
Alexandre Catarino
db2cb57a3f Handles NaN or Infinity from QLNet Calculations (#6757) 2022-11-18 18:25:13 -03:00
Jhonathan Abreu
3c784e5b04 Revisit futures contract multipliers (#6753) 2022-11-18 18:24:45 -03:00
Jhonathan Abreu
31f8561330 Allow optional selector in classic renko consolidator in Python and C# (#6755) 2022-11-18 17:14:03 -03:00
Martin-Molinero
38b87d941a Update readme.md 2022-11-18 14:36:51 -03:00
Alexandre Catarino
83d59b5f9a Removes Volatility Model Warm Up Requirement (#6752)
* Fixes Regression Algorithm Testing No Warm Up Requirement

* Removes Volatility Model Warm Up Requirement

If the volatiliy model is not ready, we will use the Brenner and Subrahmanyam (1988) approximation (BS88).
Lean will not set the volatility model if the user doesn't, since the BS88 can handle the null model case.
2022-11-18 14:34:56 -03:00
Martin-Molinero
f19d8cb700 Add missing exchanges (#6754)
* Add missing exchanges

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

* Correct calculation for theta, vega, rho

* Add calculation from Black Calculator and peer review

* Address peer review and added unit test

* Update some tests and correct vega/eho

* Fix Unit Test and Improve Comments

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

* Fix regression test and add IV calculation

* refactor and bug fixing on peer review

* refactor and bug fixing on peer review

* for rerun test

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

* update logging

* update logging and description

* Add default option pricing models and unit tests

* address review

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

* refactor structure of interest rate

* Skip Saturday and Sunday

* regression test fix

* peer review

* Fixes Interest Rate Provider Logic

* Minor tweaks

* Fix start date

* Minor test tweak

* Update interest rates

* Fix unit tests

* Add minor log

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

* Minor changes to the algorithm

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

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

* Add regression algorithm

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

* Minor tweaks

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

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

* fix 0.005$ per share fee

* remove PostOnly from Wolverine as its not needed

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

* fix Market Wolverine -> USA

* change config

* Minor tweaks

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

* Calculate data request frequency in data monitor

* Detecting universe data usage in data monitor

* Json data monitor report generation

* Data monitor refactor

* Log and store data monitor report

* Data monitor report tests

* Clean up

* Clean up

* Address changes request

* Address changes request

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

* Minor tweaks

* Some minor tweaks

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

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

* Address review

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

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

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

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

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

* Delegate adding additional paths to pythonpath to PythonInitializer

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

* Add switch to disable BeginAllowThreads in PythonInitializer

* Add switch to disable BeginAllowThreads in PythonInitializer

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

Adds support and documentation to VSCode Dev Container.

* Address Peer Review

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

* Launcher and Task Impromevents

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

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

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

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

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

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

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

* Adds Unit Test to Pandas Indexing

* Log Only Once if TryParseProperties Cannot Parse

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

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

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

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

* docs(VixDualThrustAlpha): `unsubscribe` fixup

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

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

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

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

* docs: `Intialization` -> `Initialization`

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

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

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

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

* Separate GetDataFrame in sub methods to avoid dynamic type resolution

* Housekeeping and unit tests update

* Use all requests in python type method history method

* Address changes request

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

* Update unit tests

* Update unit tests and add comments

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

* Address review

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

- Fix micro crude oil future expiration. Adding unit test

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

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

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

* Minor tweaks and rebase

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

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

* Update regression algorithms stats

* Update regression algorithms stats

* Update expected values in unit tests

* Additional mhdb updates

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

* Fix bug

* Fix bug

* Add dimension test

* Fix test and bug

* Fix python bug

* Address peer review

* Update python workflow

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

* Use algorithm result settings in report generation

* Add unit tests

* Housekeeping

* Changes for live result report

* Housekeeping

* Housekeeping

* Housekeeping

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

* Regression algorithm

* Housekeeping

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

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

* Address reviews

* Simplify implementation

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

* Fix bug

* Adjust storage controls

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

* Models

* Models

* Partial test

* Complete test and fix bug

* Address peer review

* Address review and fix bugs

* Fix regression result

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

- Dynamically adjust wait time on websocket error

* Avoid subscribing multiple times to message events

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

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

* Add 12 month rolling sharpe to report plot

* Housekeeping

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

- Fix python memory leak. Adding unit test

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

* Update regression algorithms stats

* Add futures fill model to allow extended market hours

* Add unit tests

* Update regression algorithms stats

* Update regression algorithms stats

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

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

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

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

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

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

- Update to python38
- Update libraries

* Create latest virtual environment. Add CI unit tests

* Further update python packages

* Virtual env fixes

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

* Adding more python packages

- Adding NBeats, Ax-platform, Riskfolio-Lib

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

* Show live or backtest runtime days in report stats

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

* Unit tests

* Some cleanup

* Fix exchange fees

* Update regression algorithms stats

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

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

* docs: fix `exercising for exercising`

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

* docs: `migth` -> `might`

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

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

* Support extended market hours in AddFutureContract()

* Add C# regression algorithm

* Add Python regression algorithm

* Add regression algorithm for future contracts

* Add regression algorithm checking market hour ranges

* Fixed future regression algorithms to use extended market hours

* Fixed future regression algorithms to use extended market hours

* Fixed future regression algorithms to use extended market hours

* Fixed AddFutureOptionContractFromFutureChainRegressionAlgorithm to use extended market hours

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

* Fixed AddFutureOptionContractDataStreamingRegressionAlgorithm to use extended market hours

* Fixed AddFutureOptionContractFromFutureChainRegressionAlgorithm to use extended market hours

* Fixed AddFutureContractWithContinuousRegressionAlgorithm to use extended market hours

* Fixed BasicTemplateContinuousFutureAlgorithm to use extended market hours

* Fixed BasicTemplateFuturesAlgorithm to use extended market hours

* Fix BasicTemplateFuturesDailyAlgorithm to use extended market hours

* Fixed BasicTemplateFuturesFrameworkAlgorithm to use extended market hours

* Fixed BasicTemplateFuturesHistoryAlgorithm to use extended market hours

* Fixed ContinuousBackMonthRawFutureRegressionAlgorithm to use extended market hours

* Fixed ContinuousFutureBackMonthRegressionAlgorithm to use extended market hours

* Fixed ContinuousFutureHistoryRegressionAlgorithm to use extended market hours

* Fixed ContinuousFutureLimitIfTouchedOrderRegressionAlgorithm to use extended market hours

* Fixed ContinuousFutureRegressionAlgorithm to use extended market hours

* Fixed DelistedFutureLiquidateRegressionAlgorithm to use extended market hours

* Fixed AutomaticIndicatorWarmupDataTypeRegressionAlgorithm to use extended market hours

* Fixed ConsolidateRegressionAlgorithm to use extended market hours

* Fixed DelistingFutureOptionRegressionAlgorithm to use extended market hours

* Fixed EqualWeightingPortfolioConstructionModelFutureRegressionAlgorithm to use extended market hours

* Fixed FutureContractsExtendedMarketHoursRegressionAlgorithm to use extended market hours

* Fixed FutureMarketOpenAndCloseRegressionAlgorithm to use extended market hours

* Fixed FutureMarketOpenConsolidatorRegressionAlgorithm to use extended market hours

* Fixed FutureOptionBuySellCallIntradayRegressionAlgorithm to use extended market hours

* Fixed FutureOptionCallITMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionCallITMGreeksExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionCallOTMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionDailyRegressionAlgorithm to use extended market hours

* Fixed FutureOptionHourlyRegressionAlgorithm to use extended market hours

* Fixed FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm to use extended market hours

* Fixed FutureOptionPutITMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionPutOTMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionShortCallITMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionShortCallOTMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionShortPutITMExpiryRegressionAlgorithm to use extended market hours

* Fixed FutureOptionShortPutOTMExpiryRegressionAlgorithm to use extended market hours

* Fixed FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm to use extended market hours

* Fixed FuturesExpiredContractRegression to use extended market hours

* Fixed FutureSharingTickerRegressionAlgorithm to use extended market hours

* Fixed HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm to use extended market hours

* Fixed HistoryWithDifferentDataMappingModeRegressionAlgorithm to use extended market hours

* Fixed HistoryWithDifferentDataNormalizationModeRegressionAlgorithm to use extended market hours

* Fixed LimitOrdersAreFilledAfterHoursForFuturesRegressionAlgorithm to use extended market hours

* Fixed OpenInterestFuturesRegressionAlgorithm to use extended market hours

* Fixed RegisterIndicatorRegressionAlgorithm to use extended market hours

* Fixed SetHoldingsFutureRegressionAlgorithm to use extended market hours

* Fixed WarmupFutureRegressionAlgorithm to use extended market hours

* Fixed AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm to use extended market hours

* Fixed AlgorithmHistoryTests to use extended market hours for futures

* Fixed AlgorithmTradingTests to use extended market hours for futures

* Fixed BrokerageSetupHandlerTests to use extended market hours for futures

* Fixed TimeRulesTests to use extended market hours for futures

* Fixed FutureOptionMarginBuyingPowerModelTests to use extended market hours for futures

* Fixed FutureMarginBuyingPowerModelTests to use extended market hours for futures

* Fixed FileSystemDataFeedTests to use extended market hours for futures

* Fixed QuantBookHistoryTests to use extended market hours for futures

* Split BasicTemplateContinuousFutureAlgorithm to have an extended market version

* Fixed FutureMarketOpenAndCloseRegressionAlgorithm to use extended market hours

* Split BasicTemplateFuturesAlgorithm to have an extended market version

* Split BasicTemplateFuturesAlgorithm to have an extended market version

* Split BasicTemplateFuturesFrameworkAlgorithm to have an extended market version

* Split BasicTemplateFuturesHistoryAlgorithm to have an extended market version

* Revert AddFutureContractWithContinuousRegressionAlgorithm

* Revert AddFutureOptionContractDataStreamingRegressionAlgorithm and added data

* Revert AddFutureOptionContractFromFutureChainRegressionAlgorithm

* Revert AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm

* Revert ConsolidateRegressionAlgorithm

* Revert Algorithm.CSharp/ContinuousBackMonthRawFutureRegressionAlgorithm.cs

* Revert ContinuousFutureBackMonthRegressionAlgorithm

* Revert ContinuousFutureHistoryRegressionAlgorithm

* Revert ContinuousFutureLimitIfTouchedOrderRegressionAlgorithm

* Revert ContinuousFutureRegressionAlgorithm

* Revert Algorithm.CSharp/DelistedFutureLiquidateRegressionAlgorithm.cs

* Revert EqualWeightingPortfolioConstructionModelFutureRegressionAlgorithm

* Split FutureMarketOpenAndCloseRegressionAlgorithm to have an extended market version

* Split FutureMarketOpenConsolidatorRegressionAlgorithm to have an extended market version

* Revert FutureOptionBuySellCallIntradayRegressionAlgorithm

* Revert FutureOptionCallITMExpiryRegressionAlgorithm

* Revert FutureOptionDailyRegressionAlgorithm

* Revert FutureOptionPutITMExpiryRegressionAlgorithm

* Revert FutureSharingTickerRegressionAlgorithm

* Revert FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm

* Revert FuturesExpiredContractRegression

* Revert HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm

* Revert HistoryWithDifferentDataMappingModeRegressionAlgorithm

* Revert HistoryWithDifferentDataNormalizationModeRegressionAlgorithm

* Revert OpenInterestFuturesRegressionAlgorithm

* Revert RegisterIndicatorRegressionAlgorithm

* Revert SetHoldingsFutureRegressionAlgorithm

* Revert WarmupFutureRegressionAlgorithm

* Revert AutomaticIndicatorWarmupDataTypeRegressionAlgorithm

* Some cleanup

* Address changes request

* Address changes request

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

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

* docs: `porfoltio` -> `portfolio`

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

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

* Improve currency removal from capacity string

Applied this improvement to OptimizationBacktestJsonConverter.WriteJson

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

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

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

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

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

* refactor(BubbleAlgorithm): readability improvements

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

* refactor(OrderTicketDemoAlgorithm): readability improvements

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

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

* Update exposure chart colors and add unit tests

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

* remove default useage

* add tests for verify files are read in order

* add comment

* change reuslt file name

* add comment

* liquidate using given symbol values

* remove redundant

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

* use null leverage

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

* reject the default value of security type

* cleanup

* cleanup

* check if status is not invalid

* cleanup

* abstraction to remove duplication

* fix name

* address reviews

* use counter

* add test to validate symbol/ticker agrumnets

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

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

* Add unit tests

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

* Add unit tests

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

* Update equity readme

* Add quote info

* Fix typo

* Add back QuoteQuant as pre-2007 vendor

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

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

* Fix bug

* Rename

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

* SymbolData class within model

* Address peer review

* fix bug

* revise unit test and fix bug in python model

* revise unit test and fix bug in model

* Revise regression statistics

* Revise regression statistics

* Revise regression statistics

* Revise regression statistics

* Revise regression statistics

* Address peer review

* Updated unit tests according to peer review

* Address peer review
2022-08-04 11:20:11 -03:00
Martin-Molinero
3f7d339463 Fix live result Handler null reference (#6521)
- Fix live result handler null reference, that could happen if the
  algorithm explodes mid initialization. Adding unit test
2022-08-03 19:57:03 -03:00
Martin-Molinero
3f2bcc1784 Add missing CancellationTokenSource dispose (#6512)
- Add missing CancellationTokenSource disposals to avoid memory leaks
2022-08-01 11:12:01 -03:00
Martin-Molinero
30d137e9cc Track CPU usage (#6520)
- Track CPU usage, useful for debugging
2022-08-01 11:10:52 -03:00
Martin-Molinero
ab9ad75c93 Update readme.md 2022-07-29 15:52:57 -03:00
Jhonathan Abreu
1440842d87 Fix LocalMarketHours.GetMarketClose for extended market hours (#6516)
* Fix LocalMarketHours.GetMarketClose to get the actual next market close time with extended market hours

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

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

- Add Lean commands to common project

* Address reviews

- Address reviews, refactor command interfaces and classes

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

* Consider post-market segments when getting market open

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

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

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

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

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

* Update regression algorithms stats

* Fixed regression algorithm and clean up

* Add unit tests

* Fix regression algorithms

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

* Add regression algorithms for delisted futures options with daily resolution

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

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

* Testing improvements

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

* Add more Warmup resolution regression algorithms

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

* Add more warmup regression tests

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

* Fix bug with data rounding

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

* Address reviews

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

* Address reviews

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

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

* Any change

* Add more unit tests

* Nit changes

* Changes requested

* Fix bugs and requested changes

* Requested changes

* More changes

* Check ongoing backtest orders

* Read ongoing backtest does not fail

* nit change

* Fixes for standarized API orders response

- Fixes for a standarized API read orders reponse

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

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

* Address reviews

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

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

* Address reviews

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

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

* Fix removal of continuous futures

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

* Address reviews

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

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

* Fixed for live holdings price rounding

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

* Fix typo

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

* Add regression algorithms

* Using all parameters in History()

* Use private methods to reuse History() code

* Use private methods to reuse History() code

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

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

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

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

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

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

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

* Bump version to pythonnet 2.0.16
2022-06-27 13:04:01 -03:00
Jhonathan Abreu
e9409bf207 Add contractDepthOffset parameter to QCAlgorithm.History() (#6438)
* Add contract depth offset parameter to big History() methods

- Added unit tests
- Added little more ED daily data

* Add C# regression algorithm

* Add Python regression algorithm

* Update regression algorithms stats

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

* Add C# regression algorithm

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

* Add C# regression algorithm

* Add Python regression algorithm

* Cleanup

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

* Fix regression algorithms and add required data

* Fix unit test

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

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

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

- Always call OnWarmupFinished. Adding regression tests

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

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

* Improve QuoteBarConsolidator assertion

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

* Add regression algorithm

* Add Python regression algorithm

* Style changes

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

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

* Updated documentation

* Style and performace changes

* Address changes request

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

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

* choose easy limits to less liquid markets

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

* Add and update option price model tests

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

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

* Update OptionPriceModel regression algorithms to use Lean local data

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

* Update OptionPriceModel regression algorithms to assert that greeks are valid

* Address changes request

* Address changes request

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

* Update OptionPriceModel regression algorithms to use correct test data

* Update OptionPriceModel regression algorithms to throw in OnData

* Address changes request

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

* use use minimumPriceVariation for roundoff

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

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

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

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

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

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

* initial removal

* remove reference

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

Updates LimitIfTouchedRegressionAlgorithm:
- Adds `UpdateTriggerPrice` call that rounds down the `TriggerPrice`.
2022-06-08 10:35:47 -03:00
Martin-Molinero
564d8507c7 Update readme.md 2022-06-07 15:58:45 -03:00
Ronit Jain
c11e24c5b2 Extract Oanda brokerage files and dependencies (#6383)
* use research-object-store-name key from config while creating object store for research notebooks

* remove oanda files
2022-06-07 14:07:24 -03:00
Martin-Molinero
f8c65d886c Update readme.md 2022-06-07 11:26:10 -03:00
Ronit Jain
c162e75bbc Extract bitfinex brokerage files and dependencies (#6382)
* use research-object-store-name key from config while creating object store for research notebooks

* remove bitfinex files

* remove redundant ref

* move test to private repo
2022-06-07 11:07:28 -03:00
Louis Szeto
ca64dd74d5 Update XML documentation comment of LimitPrice (#6381)
* Update OrderField.cs

* Typo
2022-06-07 09:57:37 -03:00
Jhonathan Abreu
5fa9dbad3d Fix Engine not running algorithm when calling Error() from Initialize() (#6379) 2022-06-06 19:33:27 -03:00
Martin-Molinero
3a00b6963c Avoid sending expired symbols to IDQH (#6378)
- Avoid sending expired symbols to the IDQH. This can happen during
  warmup period. Adding unit tests
2022-06-06 19:30:04 -03:00
Martin-Molinero
cde9be8d16 Fix 'OnWarmupFinished' callback (#6377)
- Fix missing 'OnWarmupFinished' callback for python. Adding regression
  algorithms
2022-06-06 11:56:02 -03:00
Louis Szeto
aa1883a140 C# Version of CustomVolatilityModelAlgorithm (#6373) 2022-06-03 19:47:39 -03:00
Martin-Molinero
0c0ee829a2 Warmup state minor fixes (#6367)
* Warmup minor fixes

- Result handler fix
- Centralize and normalize status update during warmup

* Address reviews

* Minor adjustments

* Add console message during warmup period

* Fix warmup percentage update
2022-06-02 18:20:02 -03:00
Jhonathan Abreu
9af7d4a1dc Extended currencies dictionary (#6368)
* Default Currencies.GetCurrencySymbol to the ticker and add ADA symbol

* Extended Currencies dictionary

* Fix failing tests
2022-06-02 17:31:38 -03:00
Martin-Molinero
cabbcf6d81 Move debugpy init log (#6366) 2022-06-02 12:13:13 -03:00
Jhonathan Abreu
df308cc2a7 Make PandasConverter.GetIndicatorDataFrame accept Python dictionary (#6365)
* Overload PandasConverter.GetIndicatorDataFrame to accept a Python dict

* Shared implementation code for PandasConverter.GetIndicatorDataFrame overloads

* Added documentation for private shared methods used by PandasConverter.GetIndicatorDataFrame

* Added unit tests for PandasConverter.GetIndicatorDataFrame

* Added unit tests for PandasConverter.GetIndicatorDataFrame Dictionary overload

* Address change requests

* Address change requests
2022-06-01 19:57:51 -03:00
Ricardo Andrés Marino Rojas
8f3ced7639 Fix bug with Coinbase Pro Stable Pairs (#6362)
* First Commit

* Change Unit tests
2022-06-01 17:19:41 -03:00
Martin-Molinero
e0b9a2735f Warmup fixes (#6293)
* Add regression test reproducing issue

* WIP

* Update regression algorithms

* Improvements

* Cleanup and more fixes

- Clean up BaseDataExchange

* RealTimeHandler fixes

* Address reviews

* More comments, tests and minor tweaks

* Avoid false test failures

* Fixes

* Minor improvements

* Scheduled Event start time fix

* Add warmup option regression algorithm and fix

* Add WarmupFutureRegressionAlgorithm

* Normalize backtesting and live future selection
2022-05-31 10:03:56 -03:00
Martin-Molinero
895dfedf81 User Account currency symbol for fees and capacity (#6359)
* User Account currency symbol for fees and capacity

* Update expected currency symbol stats
2022-05-27 16:36:44 -03:00
Jhonathan Abreu
69dd4fc638 Fixed bug for trailing stop model tracking original security price (#6356)
* Reproduce TrailingStopRiskManagementModel bug with test case

* Fix TrailingStopRiskManagementModel to make it relative to max price

* Adapted old TrailingStopRiskManagementModel test to new implementation

* Fix TrailingStopRiskManagementModel Python version

* Fixed TrailingStopRiskFrameworkAlgorithm regression tests data

* Handling both long and short positions in TrailingStopRiskManagementModel

* Traking holdings value instead of unrealized profit in TrailingStopRiskManagementModel

* Checking for position side change in TrailingStopRiskManagementModel

* Handling immediate liquidation in TrailingStopRiskManagementModel
2022-05-26 19:50:54 -03:00
Ronit Jain
fd20b5377d use research-object-store-name key from config while creating object store for research notebooks (#6355) 2022-05-26 18:12:13 -03:00
Ricardo Andrés Marino Rojas
e78c3e1eb7 Solve bug when plotting Python indicators (#6347)
* First commit

* Add unit test

* Change implementation

* Add unit tests

* Nit change

* nit change

* Remove unnecessary methods

* Add more unit tests

* Revert "Add more unit tests"

This reverts commit 1ba2ab7454.

* Add more unit tests

* Add more unit tests

* Improve Implementation

* Change unit tests

* Remove unit tests

Remove unit tests from AlgorithmRegisterIndicatorTests.cs
2022-05-26 13:03:42 -03:00
Martin-Molinero
0fbbc0e612 Revert "Coarse fine flag improvement (#6349)" (#6353)
This reverts commit fb90f118c9.
2022-05-25 16:51:33 -03:00
Martin-Molinero
fb90f118c9 Coarse fine flag improvement (#6349)
* Coarse fine flag improvement

- Coarse will check global data folder for fine existance if it's
  different than the given path to check

* Update readme.md
2022-05-24 19:46:37 -03:00
Derek Melchin
d7558406c8 Set default constructor values to match those in Python (#6348)
The Python implementation of this Alpha model sets some default values for `lookback` and `resolution`.
aaba566954/Algorithm.Framework/Alphas/PearsonCorrelationPairsTradingAlphaModel.py (L23-L24)
2022-05-23 21:31:48 -03:00
Martin-Molinero
00dd3dbd2c Bump to pythonNet 2.0.15 (#6342) 2022-05-18 13:09:45 -03:00
Martin-Molinero
cb2062debd Expand GetSecondUnevenWait usages (#6340)
* Reduce Live CPU usage

* Address selfreview
2022-05-16 20:12:22 -03:00
Martin-Molinero
4b86c78df0 Add unit test showcasing feature (#6339) 2022-05-13 20:21:08 -03:00
Jhonathan Abreu
17d57cb578 True Strength Index indicator (#6332)
* TrueStrengthIndex indicator

* TrueStrengthIndex indicator signal line

* Address change requests
2022-05-13 15:55:28 -03:00
Martin-Molinero
284b26a9bd Performance improvements and fixes (#6330)
* Reuse GUID

* Reduce Lean task usage

* Reduce CPU usage

* Address reviews
2022-05-13 15:04:09 -03:00
Martin-Molinero
0bc087954e Fix for arm image research (#6333) 2022-05-12 12:42:38 -03:00
Martin-Molinero
f5dd997ca0 Minor fix for FuncPeriodSpecification (#6334)
- Minor fix for FuncPeriodSpecification so it always uses the same
  DateTime to assert the given function. Improve documentation and
  exception message being thrown
2022-05-12 12:37:08 -03:00
Martin-Molinero
33616a44b0 Avoid coding with exceptions (#6327)
- Avoid relying on exception throwing for coding logic.
2022-05-09 10:34:50 -03:00
Derek Melchin
9bd6b46160 Fix CustomIndicatorAlgorithm (#6324) 2022-05-09 10:19:31 -03:00
Martin-Molinero
eb995b86ea Update to pythonNet 2.0.14 (#6322)
* Update to pythonNet 2.0.14

* Add unit test reproducing issue
2022-05-06 17:29:55 -03:00
Martin-Molinero
59a3912f68 Update recyclable memory nuget (#6321) 2022-05-06 11:04:19 -03:00
Martin-Molinero
1be6cccbd4 Update readme.md 2022-05-05 14:45:46 -03:00
Martin-Molinero
a658beb31e Update readme.md 2022-05-05 13:03:17 -03:00
Martin-Molinero
8cf6e073af Update readme.md 2022-05-04 16:43:01 -03:00
Martin-Molinero
2f39ac7d83 Fix research test setup (#6318) 2022-05-03 18:55:48 -03:00
Martin-Molinero
ea25e76faa Update readme.md 2022-05-03 12:18:55 -03:00
Martin-Molinero
b7a21ce4be Update to net6 (#6311)
* Update to net6

* Bump pythonNet to 2.0.13
2022-05-03 11:45:55 -03:00
Martin-Molinero
b9d3d99917 Bump pythonNet version 2.0.12 (#6310)
* Updates after pythonNet rebase

* Bump pythonNet version 2.0.12

* Fix exception types being thrown
2022-05-02 14:38:50 -03:00
Martin-Molinero
64125668db Catch expected test exception (#6317) 2022-05-02 12:44:18 -03:00
Martin-Molinero
06228a8de8 Improve python stack trace parsing (#6316)
- Improve python stack trace parsing removing base Lean path directory.
  Adding unit test
2022-05-02 11:42:36 -03:00
Martin-Molinero
813412afb2 Persist and order runtime statistics (#6314) 2022-04-29 20:59:40 -03:00
Ricardo Andrés Marino Rojas
e0d29e1da7 Charge correct fees for Coinbase Pro stable pairs (#6312)
* First commit

* Improve implementation

* Improve implementation
2022-04-29 16:29:21 -03:00
Ronit Jain
41b7ff58cf consider null cases for cloud brokerageData (#6308) 2022-04-28 13:42:11 -03:00
Ricardo Andrés Marino Rojas
6d181cc452 Fix bug with SetBenchmark() using custom data (#6304)
* First commit

* Solve the easy case

* Solve bugs

* Solve bugs

* Requested changes

* Requested changes
2022-04-27 13:58:10 -03:00
Ronit Jain
b8c8460c7a Update Tradier sandbox config as string with backwards compatibility for bool (#6306)
* add new config

* make case in-sensitive

* use string.IsnullOrEmpty
2022-04-27 13:58:00 -03:00
Louis Szeto
9fe018390e Update OrderResponseErrorCode.cs (#6303) 2022-04-26 10:36:02 -03:00
Nicholas Konovalenko
427f2a70fe Relative Moving Average Indicator (#6297)
* RelativeMovingAverage Indicator #5958

* RelativeMovingAverage #5958

Creation of the RelativeMovingAverage (RMA) indicator, based on the following equation: https://www.hybrid-solutions.com/plugins/client-vtl-plugins/free/rma.html

* Address self review

* Fix unit test

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-04-25 13:13:20 -03:00
code-review-doctor
32f49f1f92 Fix issue probably-meant-fstring found at https://codereview.doctor (#6301) 2022-04-25 10:48:58 -03:00
Martin-Molinero
b3c2303111 Zip data cache provider improvements (#6296)
- Throw on failure to store. Add unit test
- Fix handle leak
2022-04-22 13:52:30 -03:00
Martin-Molinero
fc008fe906 Update readme.md 2022-04-21 16:48:12 -03:00
Martin-Molinero
bbcf5d71a2 Update readme.md 2022-04-20 12:48:25 -03:00
Martin-Molinero
482d86a44a Update readme.md 2022-04-20 12:42:00 -03:00
Martin-Molinero
6eab53f619 Update readme.md 2022-04-19 15:04:29 -03:00
Ricardo Andrés Marino Rojas
f617d25af9 Add missing StableCoins pairs in Crypto Exchanges (#6259)
* Add missing stablecoins

* Fix bugs

* Remove MIMUSD stablecoin pair

That pair is already in the SPDB

* Add more stablecoins pairs

- Add SUSD and IDRT

* Fix bug

* Requested changes

The algorithm posted in the GH was failing because when finding a conversion between currencies BTC to USD, it wasn't taking into account BTCUSDT and that USD = USDT because is a stablecoin

* Solve bugs

* Nit changes and more tests

* Requested changes

* Nit changes

* Requested changes

* Nit change
2022-04-12 18:10:37 -03:00
Martin-Molinero
a8e104f696 Allow LeanDataWriter to merge existing ticks if desired (#6284)
* Allow DataWriter to merge existing ticks if desired

- Optionally allow lean data writer to merge new ticks with existing
- Adjust ZipStreamWriter
- Fix bug in compression lib that was leaving files open. Reproduced by
  added tests.

* Address reviews

- Define new WritePolicy to configure the behavior of the LeanDataWriter
  regarding how it should handle writing to a file: merge, overwrite,
  append
2022-04-08 18:20:23 -03:00
Ronit Jain
d1ff914e5a fix docs (#6285) 2022-04-08 17:44:01 -03:00
Martin-Molinero
574d685647 Update readme.md 2022-04-07 15:55:51 -03:00
Martin-Molinero
fbd12c7eb1 Update readme.md 2022-04-07 15:29:26 -03:00
Ronit Jain
49562c712f Extract IB brokerage files and dependencies (#6283)
* make public safe to expose test properties

* extract ib files

* remove dependencies

* refactor to use ib reference as string

* remove un-used dependencies

* remove redundant refrences
2022-04-07 14:48:10 -03:00
maciek231
73fa0461ed Added checking if algorithm is stopped in initialize method (#6282)
* Added checking if algorithm is stopped in initialize method

* Quit on initialize adjusment

- Minor adjustments to solution. Adding more regression algorithms

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-04-06 19:56:18 -03:00
Martin-Molinero
6cf537b26f Tradier handle unsupported order durations (#6281)
- Tradier will correctly handle closed orders with unsupported order
  durations. Adding unit test
2022-04-04 18:36:22 -03:00
quantify-cflynn
a374ce9b6e Update Tick.cs Time parsing (#6280)
* Update Tick.cs Time parsing

* Adjust equity tick millisecond read

* Fix tick sub millisecond precision

- DateTime.AddMilliseconds will rount to the nearest integer. So instead
  use AddTicks

* Avoid sporadic test failure

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-04-04 17:36:57 -03:00
Ronit Jain
ad34429014 Refactor changes required for brokerages extraction (#6279)
* set price currency for open orders from brokerage setup handler, remove setters from brokerage

* order already has price currency being set by brokerage transcation handler

* remove as overwritten by BrokerageSetupHandler.GetOpenOrders

* refactor because can't use internal setters in private repos

* refactor, use ctor to set attributes

* remove redundant broker dependency

(cherry picked from commit 57b071eb174ca9fe857021ebffa7a546834e86f7)

* check limit price for limit order instead for checking price

* add price agrument for MarketOrder

* remove, not required anymore

* AddUnrequestedSecurity should not return null

* assert string in not null cases
2022-04-04 17:01:36 -03:00
Martin-Molinero
cc1c305432 Update readme.md 2022-04-01 20:09:46 -03:00
Martin-Molinero
caaa506c56 Update readme.md 2022-04-01 18:45:14 -03:00
kulaj
29e426c2b6 Add localization for CSV export delimiters in CoarseUniverseGeneratorProgram (#6228) (#6275)
* Add localization for CSV export delimiters (#6228)

* Use invariant string decimal for coarse

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-04-01 18:12:47 -03:00
Ricardo Andrés Marino Rojas
368cfe0f5d SecurityExchangeHours::GetMarketHours(DateTime) check early closes and late opens (#6278)
* Update GetMarketHours()

* Nit changes

* Requested changes

* Fix bug

* Add more unit tests

* Address reviews

* Minor tweak

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-04-01 18:02:41 -03:00
Martin-Molinero
06c05c4274 Fully reset security cache (#6277)
- Fully reset the security cache when it's finally removed from the algorithm.
   Adding regression algorithm reproducing issue
- Updating regression algorithms which would trade based on data
  previously available
2022-04-01 15:00:29 -03:00
Ricardo Andrés Marino Rojas
cde4743ca7 Warm up EmaCrossAlphaModel indicators (#6270)
* Warm up EmaCrossAlphaModel

Warm Up EmaCrossAlphaModel indicators

* Fix regression test bug

When using the default `EmaCrossAlphaModel()` the period of both indicators to be ready is bigger than the difference between the start date and the end date of the algorithm. Then, as the algorithm didn't warm up the data both indicators of EmaCrossAlpha never were ready, but now as the model warms up the data both indicators are ready so we get different statistics

* Requested change

* Fix unit tests

As there wasn't items in `AddedSecurities`, when trying to remove the items in ´RemovedSecurities´ there was nothing to remove because there was never a security in `_symbolDataBySymbol`. That's why, in order to test, the behavior of `EmaCrossAlphaModel` when removing a security we need to first add one to then remove it.

* Requested changes in Python

- Requested changes in Python
- Nit changes

* Nit change

* Requested Changes

* Add RemoveConsolidators() method in Python version
2022-04-01 12:15:35 -03:00
maciek231
58e89872c1 Fix HttpClient request timeout (#6273)
* Fix HttpClient request timeout

* Update LiveOptionChainProvider.cs

Remove unrequired accepted encoding specification

Co-authored-by: maciej.tromiczak <maciej.tromiczak@96volt.com>
Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-03-30 17:34:02 -03:00
Ricardo Andrés Marino Rojas
85eb1fca9a Add History method overload For Python (#6265)
* Add requested History overload

* Add more regression tests

* Revert "Add more regression tests"

This reverts commit 71b279e917.

* Add more regression tests
2022-03-30 16:18:36 -03:00
Jovad Uribe
cc18e47cd6 Added get/set and tests (#6258)
Co-authored-by: Jovad Uribe <jovuribe@gmail.com>
2022-03-18 10:47:55 -07:00
Ronit Jain
15066ae5e1 Feature improve regression tests (#6245)
* add data count properties

* 'add history count property

* assert data counts

* update missing override

* consider override/virtual cases

* implement data count

* add message handler for regression tests

* use regression test message handler

* set algorithm manager for regression test message handler

* update data count

* check if stats are present, check if algo manager is not null

* update

* add c# algo

* make same as c# algo

* use new line

* logic shifted to RegressionTestMessageHandler

* cleanup

* auto cleanup

* skip non deterministic data count

* change data count

* use inheritance

* improve stats

* update couht

* add sma indicator to c# and customSMA to python

* call base method before executing further

* skip test

* revert to original

* add duplicate sma

* skip regression test
2022-03-15 16:51:15 -03:00
Jovad Uribe
1dc118304f Feature #6233 adds super trend getter (#6251)
* Updates SuperTrend and tests

* Requested Changes

* Address selfreviews

Co-authored-by: Jovad Uribe <jovuribe@gmail.com>
Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-03-14 15:01:07 -03:00
Martin-Molinero
de57cedc5a Make continuous future untradable (#6252)
* Make continuous futures untradable

- To match live trading behavior. Adjust continuous futures securities
  to be untradable

* Set ContinuousFuture as non tradable

- Set continuous futures as non tradable. Update regression algorithms
- Fixes for symbol capacity calculation
2022-03-14 14:23:26 -03:00
Louis Szeto
6273671eb7 Update readme.md (#6250)
Enclose the opened string
2022-03-11 11:44:24 -03:00
Louis Szeto
cece811cce Remove extra ; at Python files (#6248)
Co-authored-by: LouisSzeto <hke0073@hotmail.com>
2022-03-10 11:09:33 -03:00
Alexandre Catarino
0c9c8c45e5 Fixes WarmUpIndicator Overload Inconsistency (#6246)
`WarmUpIndicator` for Python indicators doesn't return the indicator anymore after #6027. So all overloads should return `void`.

Fixes `SmaCrossUniverseSelectionAlgorithm` [C# and Py].
2022-03-10 10:59:16 -03:00
Ronit Jain
7e64bd0265 add end date (#6242) 2022-03-07 19:24:16 -03:00
Ronit Jain
48a7ba77ef Feature support CI of research environment for LEAN (#6237)
* initial commit

* temp commit

* checkout master

* update files

* copy to output directory

* checkout master

* automatically update expected output

* revert

* use correct dotnet interactive version

* clean escape char before assert

* add remark

* update namespace

* remove pythonnet

* use GetExportedTypes

* update notebook result during test run

* remove dispensable escape sequences from expected output

* change location

* update summary

* docs

* docs

* update paths

* use multiple lines for output

* update paths

* suport different python location

* check if notebook are run

* update comment

* remove

* help proper debugging

* assert output first

* add comment
2022-03-04 17:40:41 -03:00
Martin-Molinero
b6de0e7222 Update readme.md 2022-03-04 16:23:57 -03:00
Martin-Molinero
7732a27c1b Nugets will copy content files to output (#6239) 2022-03-04 16:18:46 -03:00
chriscdev
adb6afc4f1 Feature 6208 add nyseliffe exchange to interactive brokers (#6209)
* Added NYSELIFFE exchange support to Interactive Brokers brokerage.

* Fixed unit test AddSecurityWithSymbol by adding market hours for Equity-nyseliffe-[*], Index-nyseliffe-[*], Option-nyseliffe-[*].

* Added NYSELIFFE exchange support to Interactive Brokers brokerage.

* Fixed unit test AddSecurityWithSymbol by adding market hours for Equity-nyseliffe-[*], Index-nyseliffe-[*], Option-nyseliffe-[*].

* Added NYSELIFFE exchange support to Interactive Brokers brokerage.

* Fixed unit test AddSecurityWithSymbol by adding market hours for Equity-nyseliffe-[*], Index-nyseliffe-[*], Option-nyseliffe-[*].

* - Added NYSELIFFE futures to Futures.cs
- Added method GetGoodFriday() to calculate Good Friday to FuturesExpiryUtilityFunctions.cs.
- Added unit tests for GetGoodFriday().
- Added NYSELIFFE futures expiries to FuturesExpiryFunctions.cs which uses GetGoodFriday() instead of hardcoding the date of Good Friday in the market-hours-database.json.
 - Added unit tests for NYSELIFFE futures expiry.
- Added NYSELIFFE to Exchange.cs
- Removed Equity-nyseliffe-[*] and Index-nyseliffe-[*] from market-hours-database.json
- Updated Option-nyseliffe-[*] to FutureOption-nyseliffe-[*] on market-hours-database.json
- Added the supported NYSELIFFE futureoptions to symbol-properties-database.csv.

* Removed blanks after India tuple

* Added the dates for 2022 and 2023 to the market-hours-database.json.
Removed "FutureOption-nyseliffe-[]" from market-hours-database.json.
Added to FuturesOptionsSymbolMappings.cs:
{ "YG", "OYG" },
{ "ZG", "OZG" },
{ "ZI", "OZI" }

* Minor tweaks for nyseliffe FOPs

Co-authored-by: Chris Coetzee <chris@polidata.ai>
Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-03-04 15:24:17 -03:00
Martin-Molinero
29588095ed Remove Atreyu order exchange destination (#6232)
- Remove Atreyu order exchange destination no longer supported. Updating
  regression test
2022-03-04 15:22:29 -03:00
Martin-Molinero
e7043bfc7e Re add ptvsd python debugger (#6236) 2022-03-01 22:11:23 -03:00
Colton Sellers
a44d7b2f92 VSCode Project Changes (#6129)
* Deprecate breakpoints

Drop Watchlist

Remove breakpoints from lean

Prep install of NetCoreDbg

Cleanup

* Install NetCoreDbg

* Update Research Images with Newer Jupyter
2022-03-01 17:41:44 -03:00
Adalyat Nazirov
18b99338fc Implement Binance US exchange (#6222)
* Binance.US base changes

* biniance exchange info update

* Binance US uses same fee rates as main Binance

* binance us brokerage model tests

* use base implementation of GetBuyingPowerModel method
2022-02-22 13:32:59 -03:00
Ronit Jain
f129ab1a09 Feature implement ExchangeInfoDownloader (#6213)
* add gdax exchange info downloader

* add downloader method to program]

* fetch currency description

* change definition to include headers

* use extension method to make request

* remove log from test

* replace WebRequest

* cleanup

* use relevant name

* implement IExchangeInfoDownloader for bitfinex, initial commit

* add default values

* use default market value

* use correct attribute for lotsize

* don't skip missing values

* handle multiple downloaders

* add gdax and bitfinex exchange downloader

* follow LEAN data directory structure

* update SPDB

* order tickers

* order tickers

* add exchange info downloader test template

* delete files

* update SPDB

* use currency mapping

* update bitfinex symbols

* update currency mapping

* sort result after old currency symbols are used

* use market of the respective brokerage

* no more unknown symbol

* change minimum order size value

* direct conversion possible

* update bitfinex symbols

* change user-agent

* add test for indirect conversion

* update stats
2022-02-22 13:00:54 -03:00
Ronit Jain
f86926bf7a Fixes HistoryProviderManager slice merging by using algortime for all slices (#6226)
* remove un-used

* use utc time for slice sync

* use utc time

* refactor

* add regression test

* use utc time

* use utc time

* make utctime required parameter

* add utcTime in slice creation

* assert warm up complete

* check if algorithm is still warmingup

* use exchange tz
2022-02-18 20:43:33 -03:00
Louis Szeto
68c046fc7b Update SamcoFeeModel.cs (#6220)
* Update SamcoFeeModel.cs

https://www.samco.in/charge-list-equities-and-equity-derivatives

* Update SamcoFeeModelTests.cs

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-02-17 20:05:31 -03:00
Alexandre Catarino
3e52816f6e Fixes GetBuyingPowerModel Method of DefaultBrokerageModel (#6215)
`CashBuyingPowerModel`, which reflected on `AlphaStreamBrokerageModel`, a margin-only brokerage.

It also didn't consider the account type, so `InteractiveBrokersBrokerageModel` was using the margin model even if `AccountType.Cash` was selected.

Removes `GetBuyingPowerModel` method from other Brokerage Models when their cases are covered by `DefaultBrokerageModel`

Fixes some typoes in `TradierBrokerageModel`

Fixes unit and regression tests. For the regression tests, we have explicitly set the brokerage model.
2022-02-17 19:41:55 -03:00
Jasper van Merle
c598a8d260 Add support for array history-provider values to QuantBook (#6219) 2022-02-17 11:24:20 -03:00
Martin-Molinero
e63bfc9127 Adjust virtual position in margin accounts (#6214)
- The BrokerTransactionHandler will also adjust virtual positions for
  margin accounts when fees are in base currency and the asset is a
  crypto or forex pair. Adding new regression tests reproducing issue
2022-02-16 15:25:47 -03:00
Martin-Molinero
e316f12394 Refactor MarginRequirementEntry. Update margins (#6210)
* Fix master

* Refactor MarginRequirementEntry to it's own file

* Update margin files

* Remove duplicate dates cases

* Update margins after fix
2022-02-15 20:24:28 -03:00
Martin-Molinero
306298a16f Update HistoryProviderManagerTests.cs 2022-02-15 12:34:00 -03:00
Adalyat Nazirov
e8160f33d5 Binance extraction (#6193)
* extract binance brokerage

* remove binance tools from main toolbox app

* modify OrderTestParameters constructor

* fix BinanceBrokerage ref config.json

* update symbol properties

* move BinanceFeeModel tests to the right place
2022-02-15 12:05:47 -03:00
Ronit Jain
ce3cb8e1a3 fix max leverage (#6207) 2022-02-14 16:42:05 -03:00
Ronit Jain
2d644d7879 Feature handle multiple history providers (#6187)
* initial commit

* get history from data providers

* merge history from history providers

* merge slice

* Add merge function in slice

* Update test

* merge aux data

* add data points in _data

* append new data points in original list

* Add test suite for HistoryProviderManager

* reduce complexity

* setup once

* add fake history provider

* doesn't count aux data

* add tests for options

* style changes

* add custom data

* merge rawDataList

* use array of history providers

* optimize

* fix formatting error

* add comment

* add tests

* simplify

* use list

* use abstraction

* split tests

* add test

* use abstraction to create generic enumertor class

* refactor

* accept list of type T

* sync history slices

* use SubscriptionDataReaderHistoryProvider for live

* rename test file

* return empty

* add tests

* cleanup

* address reviews

* optimize

* Fix method definition

* use initial time for basedata

* refactor

* re-use collection

* inherit HistoryProviderBase

* always return HistoryProviderManager

* add tests

* update rawDataList

* reset composer

* consider null elements

* add tests for binary search method

* Follow lean coding style

* revert

* remove binary search method

* convert to field
2022-02-14 11:58:00 -03:00
Colton Sellers
b80e274d4f Rename OptionsPositions.None -> Empty (#6204) 2022-02-11 19:11:30 -03:00
Martin-Molinero
9a355c9be5 Adjust INR/USD micro future scale to usd dollars (#6203) 2022-02-11 17:01:01 -03:00
Kieran Anderson
303b95ab50 Fix typo (#6201)
"buisness" --> "business"
2022-02-10 21:16:18 -03:00
Colton Sellers
d826d267f4 Update CI script with fixes for using env var (#6200) 2022-02-10 20:13:39 -03:00
Ricardo Andrés Marino Rojas
eb55311052 Feature 5157 micro futures update (#6190)
* Update MHDB and SPDB

Update MHDB and SPDB with micro futures

* Fix bugs

* Add more FutureExpiryFunctions

* Requested changes

* Nit changes

* Nit changes

- Fix some future values in SPDB
- Test LastFriday() method
- Apparently Micro CHF/USD Futures(MSF) refers to the micro of Swiss Franc Futures (6S). The same happens with Micro JPY/USD (MJY) Futures and Japanese Yen Futures (6J)

* Fix bugs

* Micro futures MultipleFactor

* Fix some futures MultipleFactor
2022-02-10 17:45:07 -03:00
Colton Sellers
27d18fa2e8 Include DataSource repos in stub generation (#6195)
* Include DataSource repos in stub generation

* Remove C# import from AlgorithmImports

* Directly import the Algorithm.CSharp namespace

* Update ci_build_stubs.sh

Case-sensitive typo

Co-authored-by: Jasper van Merle <jaspervmerle@gmail.com>

Co-authored-by: Jasper van Merle <jaspervmerle@gmail.com>
2022-02-10 15:09:08 -03:00
Adalyat Nazirov
bb0c671e7c Accept OrderSubmissionData in constructor (#6194)
* modify OrderTestParameters constructor

* add other types
2022-02-08 19:27:22 -03:00
Martin-Molinero
c8dc343c13 GetLastKnownPrices python data (#6191)
* Adding unit tests reproducing issue.

* Fix a couple of minor bugs

- IsMarketOpen will work correctly when used with daily and hourly
  resolution.
- slice.Get will work correctly with python custom data
- ExtendedDictionary will be able to dinamically access methods,
  required for python and private C# data types

* Refactor solution. Add more tests

* Remove unrequired import statement
2022-02-08 15:37:05 -03:00
Alexander Myltsev
b6815d22de Exante Brokerage initial setup (#6018)
* Exante Brokerage initial setup

* Minor exante adjustment. Address review

* Add comments to Exante config section

* Exante `GetLeverage`: handle `SecurityType.Forex`

* Exante `GetLeverage`: return 1.0 for the default case

* Cover Exante `BrokerageModel` and `FeeModel` with tests

* Add missing configurations at config.json

Fixes https://github.com/QuantConnect/Lean/pull/6018#discussion_r799527521

* Fix spaces typos

https://github.com/QuantConnect/Lean/pull/6018#discussion_r799528112

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-02-07 19:53:22 -03:00
Martin-Molinero
459f60603b Fees is base currency subtracted from quote currency (#6188)
* WIP

* Fix fees in base currency not being subtracted

- Fix fees in base currency not being subtracted from the quote currency
  for crypto cash accounts. Updating regression tests to assert
  portfolio, cashbook state and holdings state.

* Fix unit test race condition
2022-02-07 14:57:40 -03:00
Martin-Molinero
1aaaa20c61 Fix daily auxiliary data points emission time (#6186)
* Use GC server mode for tests

* Fix daily auxiliary data points emission time

- Due to fillforwarding, in some cases with daily resolution symbol
  change events (generically any auxiliary data) would arrive late.
  Updating regression test to reproduce the issue. Adding unit test
- Some refactoring and logging improvements

* Address reviews

* Remove old xml docs param
2022-02-04 21:06:45 -03:00
Adalyat Nazirov
07b6572bf9 Support Binance Margin trading (#6173)
* change BinanceBrokerageModel

* supply spot vs margin endpoint as parameter

* wip

* send margin order for margin account

* "NEW" means that the order has been accepted by the Binance engine.

* fix cash balance

* use JsonConverters for account parsing

* unit tests

* fixup

* lazy connect

* fix connection

* allow api client to be null if DQH only

* make method private

* more unit tests

* fix Dispose

* fix tests

* fix IsConnected condition

* run test as additional

* add some comments

* improve unit tests

* improve null checks

* tidy up the code
2022-02-04 17:30:39 -03:00
Ricardo Andrés Marino Rojas
a675aca7e5 Refactor GetFilePath() (#6164)
* Refactor `GetFilePath()`
Add also useful methods to use with this one

* Nit changes

* Requested changes

* Requested changes

* Restore SaveString()

* Nit changes

* Address self review

* Test improvements

* Adjust example KerasNeuralNetworkAlgorithm

* Minor tweak for KerasNeuralNetworkAlgorithm.py

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-02-04 16:58:25 -03:00
Martin-Molinero
87db3fe379 Performance improvements (#6182)
- User server mode for GC
- Remove SecurityType cache type check
2022-02-02 19:52:45 -03:00
Ricardo Andrés Marino Rojas
74321d1727 Update CME future holidays and early closes in MHDB (#6181)
* CME Futures update in MHDB

* Fix indent spaces nit errors

* Revert "Fix indent spaces nit errors"

This reverts commit 6ebb8614c0.

* Fix tabs errors

* Update MHDB with 2022 holidays

* Fix bugs

* Remove earlyOpens
2022-02-02 19:28:21 -03:00
Martin-Molinero
9fd50a302e Update or remove SharpZipLib dependency (#6180) 2022-02-02 13:28:24 -03:00
Martin-Molinero
fc0b2f3fa4 Fix for Add & Remove option contract case (#6172) 2022-01-28 14:13:21 -03:00
Martin-Molinero
c4a2d6eef4 Crypto base currency fees handled correctly (#6166)
* Binance fees deducted from fill quantity accordengly

- For Binance cash accounts while buying, if fees are from the base
  currency of leans virtual position, we need to deduct the fee from the
  fill quantity, else we can end with a position bigger that it actually
  is and not be able to liquidate

* Refactor solution

- Refactor solution into a more generic approach solving fees in base
  currency at the BrokerageTransactionHandler level, covering all
  brokerages that require it. Adding regression algorithm reproducing
  issue.
- Update Bitfinex and Binance fee models to correctly reflact reality

* Log fill quantity adjusment once
2022-01-28 13:02:58 -03:00
Martin-Molinero
c2b60e4e48 Fix empty parameter set deserialization (#6171)
- Fix empty ParameterSet deserialization. Adding unit test
2022-01-27 20:18:47 -03:00
Martin-Molinero
ca9e55fda6 Add null check for Tradier GetQuotes (#6170)
- Fixing bug where tradier GetQuotes could return null in cases where
  the provided symbol would not match any. Adding unit test.
2022-01-26 19:55:27 -03:00
Martin-Molinero
b698641c90 Minor tweak for ApiDataProvider to support India (#6169)
- Minor tweaks for the ApiDataProvider to better support India market
2022-01-24 21:27:22 -03:00
Ronit Jain
e5c709ee29 Extract zerodha brokerage out of LEAN (#6163)
* Remove zerodha brokerage

* use different brokerage for tests

* remove zerodha files with conflict

* remove redundant dependecies
2022-01-24 18:43:12 -03:00
Martin-Molinero
ca787d0a25 Add support for live price scaling (#6104)
* Add support for live price scaling

- Add support for live trading price scaling for continuous futures.
  Adding unit tests

* Move live price scale application. Updating unit tests

- Live trading application of price scaling will happen before fill
  forwarding and updating securities real time price. Updating unit
  tests to reproduce issue
2022-01-24 18:02:24 -03:00
Martin-Molinero
b1a1277eca Fix GetLastKnownPrices resolution usage (#6165)
- GetLastKnownPrices will no longer guess which resolution to use but
  rely on other methods implementation/
- Updating basic template future algorithms to warmup contracts and
  assert it
- Minor improvements for FunSecurityInitializer and FuncSecuritySeeder
2022-01-21 18:00:53 -03:00
Martin-Molinero
30d7fb042b Always reuse aggregator instance if any (#6161)
* Always reuse aggregator instance if any

- When fetching a IDataAggregator instance from the composer, do not
  enfore type name on existing instances

* Fix unit tests
2022-01-20 18:52:22 -03:00
Ronit Jain
d1bb70fbb7 Add account currency and IRegressionAlgorithmDefinition (#6159)
* Add account currency

* update stats

* use market order, same as c#
2022-01-19 18:25:57 -03:00
Ricardo Andrés Marino Rojas
0946bfc2fb Enable users to use symbol tickers when using Toolkit (#6158)
* If the market ticker has a ":" the user can use the symbol ticker

* Nit change
2022-01-19 15:42:21 -03:00
Ronit Jain
f34be8e3ff Feature add India index algorithms and data (#6145)
* add data

(cherry picked from commit 814011d89e5316d150f88ffca5f48d8d5f0ea7d9)

* update market hours for index

(cherry picked from commit edac40732c120eb84d27de00594b59eebb4983f5)

* add index algorithms

(cherry picked from commit b22d27b4fa98172c435f7c26de4a3a297c49a6b7)

* update statistics

* add cash

* Add india market

* add leverage for index

* can subscribe to index

* update format

* fix wrong cash

* fix ticker names

* update data

* update ticker and stats

* update docs
2022-01-19 12:14:48 -03:00
Martin-Molinero
e1d1e28bb8 Fix for Tick subscription history requests (#6156)
- Fix for history requests != Tick for existing subscriptions with Tick
  resolution. Adding unit test reproducing issue
2022-01-18 17:36:27 -03:00
Colton Sellers
5ea9f04b10 Deprecate PTVSD for DebugPy (#6153)
* Deprecate PTVSD for DebugPy

* Replace all references to PTVSD with debugpy

* Address review
2022-01-13 09:45:12 -03:00
Adalyat Nazirov
2529ba124d FTX API endpoint is cinfigurable (#6026)
* specify enpoint url of ftx api (can be FTX pr FTX.US)

* more metadata for ftxus

* tidy up code

* tests

* more tests

* fix tests

* fix us fee rates

* add account tier

* update symbol props

* typo

* typo-2

* update symbol properties

* use FTXUS fee model

* minor tweaks
2022-01-12 13:51:18 -03:00
Ricardo Andrés Marino Rojas
472f78cc53 Remove Quandl from LEAN (#6110)
* Remove Quandl from LEAN

* Nit changes and CustomLiveDataFeedTests.cs

* Resolve conflicts

* Remove files related with Quandl

* Fix bug

* Fix QuantBookHistoryTests.cs

* Fix bug

* Fix bug

* Fix unit tests

* Try fix regression tests

* Nit changes

* Fix bug

* Some of the requested changes

* The missing changes

* Requested changes

* Nit changes

* Revert "Nit changes"

This reverts commit 9800bc5c34.

* Nit changes

* Fix bug

* Requested changes

* Missing file using Quandl to be removed

* Nit changes

* Not applied nit change

* Nit change

* Nit change

* Add nasdaq-auth-code parameter in config.json

* Remove 'quandl-auth-token' from config.json

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-01-12 12:10:20 -03:00
Adalyat Nazirov
0c26d42561 Feature 2839 black scholes data generator (#6135)
* replace to local functions as they are more performant

* fix random generator upper bound

Next() includes minValue, but not maxValue, so we increment it +1

* introduce abstract layers

* refactoring

* fix tets

* adapt tests

* fixup

* implement blackschole price model for options

* use risk free rate

* use ql price model

* wip

* change interface

* fix

* tidy up the code

* wip

* iterate groupped symbols

* wip

* wip

* fix

* allow symbol of different types

* improve settings

* wip

* iterate full range

* fix issue with negative option

* fix

* fixup

* use StandardDeviationOfReturnsVolatilityModel

* re-use existing tick types per security type

* parametrize underlying security type

* use default option style

* dynamic option price model

* fix enumeration

* test

* fix unit tests

* refactor code

* remove unused file

* minor tweaks and refactoring

* rename symbol generator class

* fix interface

* add comments

* more comments and unit tests

* more tests

* add disclaimer

* more tests

* more comments and tests

* split tests into different files

* tidy up the code

* tidy up the code; more tests

* refactor TickGenerator => use security price directly on each iteration

* remove dupe; reuse main constructor

* use SecurityManager, refactor code

* bugfix: save ticks in history array

* check volatility warm up & tests

* more unit tests

* describe volatility period span in settings

* rename command line option

* Minor adjusments. Address review

- Use Lean log handler instead of writting directly to console
- Rename BlackShcolesPriceGenerator to generically OptionPriceModelPriceGenerator
- Minor format clean up & standarization
- Add support for specifying the option chain size

* Rename TickGenerator private fields

* Fix unit tests

* fix tests class name

* Support tickers being specified

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2022-01-10 17:21:03 -03:00
Martin-Molinero
4b94f50754 Option selection improvements (#6144)
- Zip entries will be sourced from cache provider
- Option underlying will use SubscriptionDataSource to fetch it's data.
  Fixing bug where it would let through an old data point, or miss
  sending data through.
2022-01-10 11:18:28 -03:00
Martin-Molinero
5bdc60b137 Fix for warmup history requests when internal subscriptions present (#6146) 2022-01-10 11:10:44 -03:00
Ronit Jain
3837c32b36 Add India market local data and regression algorithm (#6088)
* Add india market data

* use local data for algo

* Add India market regression algo

* update india market data

* Update readme

* add python algo for BasicTemplateIndiaAlgorithm

* Add India data regression python algo

* data india data files

* update tickers

* Fix algo template

* remove data

* fix stats

* update stats

* remove unused data
2022-01-06 18:24:32 -03:00
Ronit Jain
0e298edcb2 use compression library (#6142) 2022-01-05 15:19:41 -03:00
Martin-Molinero
7a753bfa3f Live mapped subscription will clone the underlying (#6141)
- Live subscription enumerator will clone the underlying data set when
  live mapping is being done. To avoid issues where IDQH implementations
  could reuse a data point with same configurations. Adjusting unit test
  to reproduce issue
2022-01-05 13:45:52 -03:00
Martin-Molinero
8e2554b110 Add continuous futures MHDB always. Adding unit tests (#6139) 2022-01-04 20:31:31 -03:00
Martin-Molinero
bfa58b4692 Fix IB Hong Kong Future Exchanges fees (#6133)
* Fix IB HongKongFutureExchanges fees. Adding test

* Minor self review tweak
2021-12-28 20:12:59 -03:00
Martin-Molinero
e3375bc45e Pin conda and pip foundation versions (#6134) 2021-12-28 18:14:17 -03:00
Martin-Molinero
ac8b500ba2 Foundation update: Ray, H2o & IB (#6126)
* Foundation remove Ray update H2o

* Update IB version to 10.12.2d
2021-12-28 16:17:52 -03:00
Omid K. Rad
2557a36feb Bug: Config.TryGetValue returns true if key is not found (#6128)
* Fix typo

* Fix TryGetValue to return false if key is not found

* Revert "Fix TryGetValue to return false if key is not found"

This reverts commit b85b7b579a.

* Update documentation for TryGetValue
2021-12-28 12:19:46 -03:00
Martin-Molinero
55cb3bdaff ApiDataProvider Support Future map & factor files (#6132)
- Add support for the ApiDataProvider to handle future map and factor
  files downloads. Adding unit test
2021-12-27 21:52:51 -03:00
Martin-Molinero
10bb627fc2 Update to pythonNet 2.0.11 (#6131) 2021-12-27 15:49:24 -03:00
Alexandre Catarino
3d3733c0fb Adds Market.HKFE to InteractiveBrokersFeeModel (#6127)
Adds `Market.HKFE` to `InteractiveBrokersFeeModel` in the Futures Options case.
2021-12-22 19:32:07 -03:00
Martin-Molinero
1303ccf843 Update readme.md 2021-12-22 17:16:41 -03:00
Martin-Molinero
3b5f3fcf42 Update readme.md 2021-12-22 16:18:09 -03:00
Andreas Sundebo
e2de241c2b Feature 5090 add api optimization methods (#6108)
* Move Optimizer-related DTOs and JSON converters into Common/Optimizer

* Add REST methods for Optimization

* Move OptimizationStatus into Common

* Change optimizationId parameter type to string

* Update Optimization and add lightweight optimization object

* Rename lightweight optimization to BaseOptimization and remove unneccessary properties

* Remove snapshotId from Optimization, add ParameterSet to Backtest

* Add missing IApi.cs method signatures

* Move ParameterSet into Common

* Replace Backtest with OptimizationBacktest

* Update UpdateOptimization to not include null or empty name and layout params in the request

* Change Objective targetTemplate regex pattern from ['(.+)'] to (.+) to prevent escaping target strings without whitespace

* Return Estimate object when calling EstimateOptimization

* Use DefaultNamingStrategy when serializing constraint operators

* Revert "Change Objective targetTemplate regex pattern from ['(.+)'] to (.+) to prevent escaping target strings without whitespace"

This reverts commit fbe7de0fd7.

* Update Api method signatures

* Add unit tests

* Fix XML comment referring to the old class name

* Fix XML summary for OptimizationResponseWrapper

* Address review feedback
- Remove unused testOrganizationId
- Change NodeType from string to NodeType enum
- Clarify unit types for Estimate time and balance
- Simplify JsonConverter classes

* Add accessors to Common/Api classes

* Define performance metrics names in PerformanceMetrics class

* Remove unnecessary branching logic from GetSeriesValues method

* Add crefs and examples to XML comments in the Api class

* Revert "Change NodeType from string to NodeType enum"

* Remove layout param from UpdateOptimization method

* Backtest property ParameterSet should be of type ParameterSet

* Add asserts for deserialization in OptimizationBacktestJsonConverterTests

* Replace the three target-related properties with Criterion

* Add serialization and deserialization tests for Optimization

* Remove Optimization Serialization test

* Add EstimateDeserialization test

* Add asserts for integration tests

* Address self review

* Revert test case

* Update Nodes.cs

* Update Nodes.cs

* Set Aborted status when Optimization fails to start

* Add ParameterSetJsonConverter and ParameterSetJsonConverterTests

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-12-22 13:14:56 -03:00
Martin-Molinero
68e2a9170a Do not send internal SecurityChanges to Algorithm (#6118)
* Do not send internal SecurityChanges to Algorithm

- Will not send internal security changes to the Algorithm by default.
  Following custom security changes filter pattern. Updating regression
  algorithms to assert behavior.
- The universe member will know wether it was added with internal
  configurations or not

* Address reviews use a separate collection for internals

* Refactor solution. Adding security changes constructor class
2021-12-21 20:24:32 -03:00
Adalyat Nazirov
d395f704b3 Bug 6115 adjust dates (#6124)
* GH-6115: adjust dates

* fix

* use another approach

* Add lean data writter multiple days data unit test

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-12-21 17:33:36 -03:00
Martin-Molinero
4d1fc7e05a Handle security added and removed in the same loop (#6120)
* Handle security added and removed in the same loop

- Correctly handle adding and removing a security in the same loop.
  Adding regression test

* Adding comments
2021-12-21 11:59:45 -03:00
Martin-Molinero
e3a562d3c9 Add file and line number to documentation attribute (#6122) 2021-12-20 17:30:04 -08:00
Martin-Molinero
4fdd60d146 Use 64 when saving zips update dotnetZip (#6114) 2021-12-20 16:39:06 -03:00
Martin-Molinero
abbb50e209 Minor improvements for data reading and caching (#6113)
* Minor improvements for data reading and caching

* Address reviews

* Adjust zip cache error check
2021-12-16 19:58:37 -03:00
Alexandre Catarino
0e1cc288a6 Change Default Market of CFD to OANDA (#6107)
Oanda is currently the only provider.
2021-12-13 17:58:57 -03:00
Martin-Molinero
3b826535c7 Fix for ConcurrentDictionary Thread Safety (#6105)
- ConcurrentDictionary with OrderBy is not thread safe, adding thread
  safe extension method. Adding unit tests
2021-12-13 10:45:58 -03:00
Martin-Molinero
59da486e30 IB will correctly create non USD currency contract (#6103)
- IB will create contract based on SPDB entry for symbol. Adding unit
  test
2021-12-10 13:56:32 -03:00
Martin-Molinero
f42d7bb3a2 Align universe security and configuration TZ (#6102)
* Align universe security and configuration TZ

- Make sure universe security and configuration tz are aligned always.
  Adding unit test reproducing issue

* Address review UserDefinedUniverse will use UTC TZ
2021-12-09 15:53:56 -03:00
Martin-Molinero
87bd0d7792 CompositeDataQueueHandler handles duplicate configs (#6101)
* CompositeDataQueueHandler handles duplicate configs

- CompositeDataQueueHandler will handle duplicate subscriptions sharing
  the same config. Adding unit tests

* Refactor bug solution after review

- LiveSubscriptionEnumerator will not long perform any symbol mapping
  but will just trigger a new subscription call when remapped.
- CompositeDHQ will handling symbol mapping and keep track of these
  mapped configs to trigger unsubscribe accordengly. Adding unit tests

* Adjust solution after review

- To avoid breaking uniqueness of SubscriptionDataConfig will be adding
  a private `mapped` property that will change equality of mapped
  configs to avoid them clashing. Adding unit tests

* Rename IDQH subscription extension methods
2021-12-09 14:53:04 -03:00
Louis Szeto
8ca9258e70 API Reference for docs v2 (#6098)
API Reference for docs v2 

Co-authored-by: Alexandre Catarino <AlexCatarino@users.noreply.github.com>
2021-12-08 16:25:36 -08:00
Martin-Molinero
72105539fc Minor Exchanges cleanup (#6100) 2021-12-06 19:27:27 -03:00
Anuj Patel
589e8a9293 fix Kraken fee model (#6096)
* Update KrakenFeeModel.cs

* Update KrakenFeeModelTests.cs

Co-authored-by: Anuj Patel <91538343+anuj-mitul-patel@users.noreply.github.com>
2021-12-06 11:59:20 -03:00
Martin-Molinero
dd27a382f7 Composite data queue handler IUniverseProvider (#6097)
* Minor performance improvements

* CompositeDataQueueHandler is UniverseProvider

- CompositeDataQueueHandler implements the UniverseProvider interface.
  Adding unit tests
2021-12-06 10:27:18 -03:00
Jovad Uribe
62a8aee38c Kaufman Efficiency Ratio Indicator (#6050)
* Indicator

* Fixed logic error

* Removed old files, added KER into KAMA

* Removed old comments

* Added requested changes

* Minor clean up

* Refactors KaufmanEfficiencyRatio and KaufmanAdaptiveMovingAverage

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
Co-authored-by: Alexandre Catarino <AlexCatarino@users.noreply.github.com>
2021-12-04 18:55:09 -03:00
Alexandre Catarino
7e7c27416b Updates KeltnerChannels to Update MiddleBand with EndTime (#6084)
* Updates KeltnerChannels to Update MiddleBand with EndTime

* Adds Unit Test

This unit test shows that the timestamp of the MiddleBand and the indication are aligned as expected.
2021-12-03 19:43:32 -03:00
Martin-Molinero
26f2f88c67 Add documentation attribute default value (#6095) 2021-12-03 18:47:47 -03:00
Martin-Molinero
c08c129860 Add documentation attribute (#6094) 2021-12-03 18:23:06 -03:00
Martin-Molinero
bae10389ae Update readme.md 2021-12-03 17:15:58 -03:00
Martin-Molinero
4301d7cead Update readme.md 2021-12-03 17:08:06 -03:00
Martin-Molinero
d49f1d0d6c Update readme.md 2021-12-03 16:34:47 -03:00
Ronit Jain
264c3c8374 Composite IDQH - Support multiple live data feeds (#6047)
* initial commit

* Follow IDQH implementation

* Expect a list of data handlers from LiveNodePacket

* Return null if can not subscribe

* refctor to add check for subscription

* initialze null

* Add tests

* Check subscribe retuns null/not-null

* cleanup

* Read all required IDQH credentails to job

* Use CDQH to handle all IDQH instances

* constructor abstraction to call from setjob

* use flag

* remove redundant because derived will call initialize on it

* abstract and initialize from setjob

* handle null enumerators

* get creds from data handlers

* handle single data handler value from data-queue-handler

* Fix to support a json array

* Fix missed constructor call

* change access modifier to access from Tests files

* Add test to get brokerageFactory from dataQueueHandler

* Fix init flag to handle all conditions

* Add docs

* initialize from setjob

* Check if websocket open before using

* change defination of initialzie to include tradier

* clean up

* change defination

* fix wrong api key name

* return empty enumerator

* check websocket open before sending request

* check connection before subscribing

* fix to include more cases

* check websocket open before sending request

* Minor refactoring

* reafctor and use IsConnected

* remove unused

* clean up

* Fix test cases

* reverse change

* include config changes

* connect to websocket from setjob

* check websocket connection from setjob

* clean up

* include condition for IDQH that are not brokerage

* Address review

* Add market check condition before subscribe

* Remove deprecated

* Minor fix for deserializing data queue handler

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-12-03 16:18:41 -03:00
Martin-Molinero
8a1f67edfc Minor fixes (#6093)
- Update Atreyu fees
- Remove redundant check in AlphaStreamBrokerageModel
- Fix option contract removal and second addition. Adding unit test
2021-12-03 12:54:49 -03:00
Martin-Molinero
5f434f2fa5 SetupHandlers will exit if errors on initialize (#6092)
- SetupHandlers will exit right away if detect errors on initialize.
  Adding unit tests
2021-12-02 19:24:51 -03:00
Martin-Molinero
e37f8ae878 Fix for adding continuous future and future contract at the same time (#6091)
- Fix for adding continuous future and manually adding contract at the
  same time. Continuous future was using the user defined universe
  symbol and caused clashes. Adding regression test reproducing the issue.
2021-12-02 18:13:52 -03:00
Martin-Molinero
b4e95209f6 Fix for IB Option position race condition (#6090)
- Fix for IB option position update race condition, where the BTH would
  incorrectly assume it should trigger an early option assignment. Adding unit tests
2021-12-02 17:09:50 -03:00
Martin-Molinero
ea65c61dc8 Minor InteractiveBrokers fix (#6089)
- IB needs to notify the `DefaultBrokerageMessageHandler` we have re
  connected else it might kill the algorithm
2021-12-01 19:26:25 -03:00
Ricardo Andrés Marino Rojas
6bf6ff1a6a Fix bug in ConsumeMultipleMinutes() test (#6083)
* Give `code()` more time per iteration

* Another proposed solution

* Revert "Another proposed solution"

This reverts commit 29bf5a7554.

* Add an AutoResetEvent field in `TimeConsumer()`

* Avoid change TimeMonitor implementation

* Remove changes in `TimeConsumer.cs`

* Requested changes

* Avoid re-implementation
2021-11-30 21:44:42 -03:00
Martin-Molinero
d1a35e6281 Continuous Futures Refactor. Live Mappings (#6076)
* Continuous Futures Refactor. Live Mappings

- Adding support for live mappings. LiveTradingDataFeed will handle any
  symbol mapping at the configuration layer and resubscribe through the
  IDQH
- Refactoring continuous futures adding ContinuousFutureUniverse that
  will select the currently mapped security

* Minor fixes

- Remove addition of configurations in UniverseSelection step, leave
  resposability for universe.
- LiveTradingDF future unit test will only assert slice data for non
  internal feeds.
- ContinuousContractUniverse will respect internal option interest
  subscription

* Address review
2021-11-30 21:38:50 -03:00
Martin-Molinero
fed1fa929b Fix low resolution index TradeBar parsing (#6081)
- Fix low resolution Index TradeBar parsing. Updating unit tests. Adding
  unit tests
2021-11-29 12:59:16 -03:00
Ricardo Andrés Marino Rojas
9e7962f5a2 Add Overload in SecurityTransactionManager Methods to Support Python Functions (#6068)
* Add PyObject overload

* Nit changes and unit tests

* Regression tests

* Nit changes

* Requested changes

* Requested changes

* Handle null parameter cases
2021-11-26 16:15:54 -03:00
Andreas Sundebo
3e66733413 Properly handle pending CancelOrderRequests during backtesting (#6021)
* Properly handle pending CancelOrderRequests

To avoid unneccessary "Insufficient buying power to complete order" errors showing up as Invalid orders we need to skip further processing of pending CancelOrderRequests in the BacktestingBrokerage and instead let them be properly removed during the next transaction handler run.

* Update BacktestingBrokerage.cs
2021-11-26 14:47:30 -03:00
Colton Sellers
c11a09e08a Feature Index Option Low Resolution Support (#6075)
* Activate Index and IndexOptions low res

* Add Index and IndexOption low res data

* Add IndexOption regressions

* Fix bug with IndexOption QuoteBar data not being scaled

* nit - update comment for _scaleFactor

* Update data and regressions to reflect fix in data

* Tweak regressions
2021-11-26 13:11:35 -03:00
Anuj Patel
f06bab944d fix incorrect Kraken and Coinbase Pro fee values (#6071)
* fix Coinbase Pro fee values

fee values changed to reflect most recent fee schedule, see 
* https://blog.coinbase.com/updates-to-coinbase-pro-fee-structure-b3d9ee586108
* https://help.coinbase.com/en/pro/trading-and-funding/trading-rules-and-fees/fees
* https://pro.coinbase.com/fees

* fix Kraken fee values

all fee values multiplied by 1/100 to correct inaccuracy, see
* https://www.kraken.com/features/fee-schedule#kraken-pro

* changes time to after latest fees have been set and replaces old expected values
2021-11-24 16:57:20 -03:00
Ricardo Andrés Marino Rojas
df63b6f5d6 Renaming requested changes (#6072) 2021-11-24 09:58:37 -03:00
Colton Sellers
1358bd8115 Future and FutureOption low res support (#6069)
* Fixes for FutureOptions support in LeanData

* Add CreateCanonicalOption() utility function for Symbol.cs

* Add aggregated Futures/FuturesOptions data to Lean

* Add FutureOptions regressions for daily/hourly data

* Allow Futures to be added with low resolution

* Add Future regressions using hour/daily data

* Nit - Python Class names

* Add reviews

* Add alias into CreateCanonicalOption
2021-11-24 09:53:21 -03:00
Martin-Molinero
40cc7a808a Skip subscribing to canonical symbols (#6070) 2021-11-22 21:00:45 -03:00
Martin-Molinero
e3a4fa1838 Update readme.md 2021-11-22 12:54:51 -03:00
bmello4688
1d8243ecac Add tick type to data downloader get (price data) call in order for a… (#6057)
* Add tick type to data downloader get (price data) call in order for api's with rate limits to handle not making an api call at all.

* Added DTO object to pass into data downloader get

* Added missing header for new file

* Address review. Minor tweaks

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-11-22 12:00:16 -03:00
Martin-Molinero
a8c81cad2a Fixes for continuous futures history requests (#6067)
* Fixes for continuous futures history requests

- Fixes for continuous future history requests and warmup. Adding
  regression test

* Address reviews
2021-11-19 20:52:15 -03:00
Martin-Molinero
5f95a9ba77 Bug fix python history requests enumerable data (#6066)
* Fix for python enumerable data history request

- Fix for python enumerable type data history request. Adding unit test.

* Add methods for adding data points into a baseDataCollection
2021-11-19 14:58:48 -03:00
Ricardo Andrés Marino Rojas
a9b914c9ef Fix: IB Subscribe Cannot Find HangSeng Futures (#6064)
* Fix Bug

* Nit change

* Change `LookupSymbols()` method implementation

* Nit change

* Revert "Nit change"

This reverts commit 7bad6d195d.

* Nit change
2021-11-18 20:56:22 -03:00
Martin-Molinero
5436275901 Remove comments from MHDB json file (#6065) 2021-11-18 20:41:02 -03:00
Martin-Molinero
0a315b0ae6 Update readme.md 2021-11-17 19:59:03 -03:00
Colton Sellers
33599b473d Refactor Delistings Processing (#6059)
* Move processing of delistings to Brokerage

* Deal with case that exchange is not open on OptionSymbol.ID.Date

* Refactor solution to use DelistingNotification event

* Adjust some regression expected liquidation time

* Mark some todos on deprecated functions

* Update expected liqudation time for Py regressions

* Update regressions that have been validated

* Use HandlePositionAssigned for assignment orders

* Update regressions

* Update some missed unit tests; remove one that is already covered by regression

* Cleanup deprecated backend functions

* nit - small cleanup adjustment

* Post rebase fix

* Address review

* Minor tweak to py regression
2021-11-17 17:43:35 -03:00
Jovad Uribe
325e788728 Super Trend Indicator (#6013)
* Super Trend Indicator #4653

* Updated test data

Previous test data was wrong

* Reduced if statement

* Updated tests

Replacing spy test data with dwac test data from trading view.

* Minor comment update

* Minor tweaks

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-11-17 12:19:26 -03:00
Martin-Molinero
57ac4d6497 Add import for System.Drawing (#6063) 2021-11-17 11:28:09 -03:00
Martin-Molinero
664dca2236 Tradier websocket bug fix (#6061)
- Tradier brokerage will use BaseWebsocketsBrokerage which handled
  websocket resubscription. Minor API changes
2021-11-16 18:44:38 -03:00
Ricardo Andrés Marino Rojas
5415fe6bc0 Beta indicator (#6042)
* First BetaIndicator prototype
- In construction

* Fist BetaIndicator version and unit tests

* More unit tests and regression test

* Nit change

* Requested changes

* Nit changes

* Requested changes

* Adjust beta formula slightly and nit changes

* Nit change
2021-11-15 15:57:24 -03:00
Martin-Molinero
b2517cbbb4 Fix DiskDataCacheProvider. Expanding unit test (#6058) 2021-11-15 15:57:09 -03:00
Martin-Molinero
b8b0d18993 Continuous futures (#6034)
* Continuous Future Contracts

* Mapping approach

* Tweaks WIP

* Live mapping

* Live mapping

- Add support for live mapping, refreshing mapfiles
- Fix future expiration functions
- Adding unit tests

* Update moq test package

* Continuous futures price scaling

* Refactor price factors scaling

* Factor file related renames

* Address reviews
2021-11-15 14:44:30 -03:00
Martin-Molinero
ad865e2a53 Add new CustomWeight, AlphaModel for AlphaStreams (#6052)
- Add new CustomWeight PCM for alpha streams
- Add new AlphaStreams AlphaModule that will handle security additions
  and removals, removing this logic from AlphaStreamsBasicTemplateAlgo
2021-11-15 14:33:16 -03:00
Martin-Molinero
57f0d17c5d Remove user plan enum (#6055)
* Remove user plan enum

- Get maximum order and runtime from job controls
- Remove user plan enum definitions

* Add log for BacktestingSetupHandler maximums
2021-11-12 19:37:23 -03:00
Ricardo Andrés Marino Rojas
d234d69abc Give timer more time (#6053) 2021-11-12 13:41:56 -03:00
Colton Sellers
dd4da7ba95 Feature Daily/Hourly Options Support (#6017)
* Create generic writing for LeanDataWriter, + notes on todos

* Make Options Daily/Hourly data store by year

* Refactor Generic Write

* Permit hour and daily resolutions for options

* Refactor writer to merge when needed with other files

* Cleanup redundancies, run write tasks in parallel

* Make needed classes/vars available

* Update tests to reflect new naming convention for daily hourly options data

* Add Byte[] overloads for ZipData functions in compression

* Implemented Store() for ZipDataCacheProvider

* Have LeanDataWriter use a DataCacheProvider

* ZipDataCacheProvider cleanup

* ZipDataCacheProvider tweaks, doesn't support storing non-zips

* Test adjustments

* Update LeanDataWriter to use Write instead of SaveDailyHourly/SaveMinuteSecond

* Implement tests to verify DownloadAndSave behavior

* Nit cleanup on DownloadAndSave tests

* Fix for options daily/hourly underlying equity subscription read

* Add daily/hourly options data and regressions

* Add missing open interest for hourly

* Fix writing of OpenInterest Daily/Hourly data

* Update data

* Fix Date typo in regression

* Use daily algorithm to test delisting

* Revisions part 1

* Expand test for DataCacheProviders; refactor DiskDataCacheProvider

* nit - test adjustments

* ZipDataCacheProvider test setup refactor

* Adjust multithreaded read/write test; fixes for ZipDataCacheProvider

* Move DiskDataCacheProvider to its own file and add write test

* Remove _appendToZips; always overwrite entry or create zip

* Add mapping regression for daily options

* nit - add license to regression

* Fix Tick write case where more than one data point for a DateTime

* Fix data issue

* Address review

* Tweaks for tests

* Stop Store() early if no entry name is given
2021-11-11 20:05:31 -03:00
Martin-Molinero
27f5223cd2 Pin dotnet interactive version for net5 (#6048) 2021-11-10 13:00:59 -03:00
Adalyat Nazirov
b3d3df3a3c rate limit is dependent on Account Tier, Tier1 by default (#6046) 2021-11-09 16:44:29 -03:00
Ricardo Andrés Marino Rojas
3c1ddb7b96 Enable Warm Up process in MacdAlphaModel (#6037)
* Warm up MACD indicators
- When a security is added in the MACD alpha model, it's warm up at once

* Add unit tests

* Nit change

* Code style and nit changes
2021-11-04 12:15:32 -03:00
Ronit Jain
926ac3879a Add try-catch and null check (#6038) 2021-11-03 20:07:47 -03:00
Martin-Molinero
0327b2012c Add default value for Exchange security types (#6032) 2021-11-01 12:05:15 -03:00
Martin-Molinero
cd5e1d9c54 Can serialize unknown exchange. Adding test (#6031) 2021-10-29 09:13:52 -07:00
Ricardo Andrés Marino Rojas
fc6ddc2120 Feature 5988 WarmUpIndicator() method for indicators written in Python (#6027)
* Implement IIndicatorWarmUpPeriodProvider
- Implement IIndicatorWarmUpPeriodProvider in PythonIndicator.cs
- Make a unit test to check whether the WarmUpPeriod is working as expected
- Make a regression test to check the new feature at a system level

* Nit change

* Change Period parameter for WarmUpPeriod parameter
- Change regression test to check if the new parameter keep backwards compatibility with indicators that do not set WarmUpPeriod

* Documentation change

* Fix tests bugs
- In CommonIndicatorTests.cs before finish the test it checks the period.value with the number of samples but for default the period.value was set to -1

* Change names

* Change WarmUp and RegisterIndicator methods
- Lean WarmUp indicator skip custom python indicators that don't define WarmUpPeriod parameter

* Call WarmUpIndicator manually
- Add a new "bridge" method called WarmUpIndicator in QCAlgorithm.Python.cs to set up everything to call WarmUpIndicator in QCAlgorithm.Indicators.cs
- Change the regression algorithm to warm up the indicators manually

* Remove unnecessary code and add more tests

* Nit change

* Revert "Nit change"

This reverts commit da411f59c9.

* Fix bugs

* Try fix bugs

* Add C# regression test
- More nit changes
- Fix bugs

* Requested changes

* Remove unnecessary code

* Requested changes

* Nit changes
- Add new Python class to check a custom indicator, which doesn't inherits from PythonIndicator, warms up properly

* Reduce redundant code

* Fix bug and add more unit and regression tests

* - Add more unit tests

* Nit change

* Test cleanup

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-10-28 20:29:22 -03:00
Ricardo Andrés Marino Rojas
013b9ea850 Set WarmUpPeriod value in MarketProfile constructor (#6029)
- Remove unnecessary attribute `_period` in MarketProfile
- Set the value of WarmUpPeriod to the period in MarketProfile constructor
- Fix unit test to check VolumeProfile and TimeProfile indicators are being warmed up properly and its WarmUpPeriod parameter isn't zero
2021-10-28 19:54:11 -03:00
Martin-Molinero
9f29e3bf4e Some performance improvements for IndexOptions (#6025)
- Some performance improvements for IndexOptions specially affects
  debugging C# algorithms.
2021-10-27 20:26:51 -03:00
Alexandre Catarino
4ecdf14ce8 Include Security Master Url to ApiDataProvider Error Message (#6023) 2021-10-27 14:58:15 -03:00
Martin-Molinero
ede2d4a5e4 Lazy loading of the SecurityDefinition file (#6024)
- Perform a lazy loading of the security definitions file. Adding unit
  tests
2021-10-27 14:57:50 -03:00
Martin-Molinero
8c71dbc8ba Revert "Feature 5988 IIndicatorWarmUpPeriodProvider for custom PythonIndicator (#5992)" (#6022)
This reverts commit 995f598999.
2021-10-26 22:07:22 -03:00
Martin-Molinero
d17865b2cf CoinApi read previous date file (#6019)
- If available, CoinApi converter will read previous date files to
  rescue initial midnight ticks for the processing date. Also make sure
  to drop ticks from tomorrow
2021-10-25 20:26:12 -03:00
Martin-Molinero
7b3b560dea Foundation update CVXPY 1.1.15 (#6020)
- Update cvxpy python package version to latest 1.1.15. To avoid
  installation issue `error in cvxpy setup command: use_2to3 is invalid`
2021-10-25 18:45:07 -03:00
Ricardo Andrés Marino Rojas
995f598999 Feature 5988 IIndicatorWarmUpPeriodProvider for custom PythonIndicator (#5992)
* Implement IIndicatorWarmUpPeriodProvider
- Implement IIndicatorWarmUpPeriodProvider in PythonIndicator.cs
- Make a unit test to check whether the WarmUpPeriod is working as expected
- Make a regression test to check the new feature at a system level

* Nit change

* Change Period parameter for WarmUpPeriod parameter
- Change regression test to check if the new parameter keep backwards compatibility with indicators that do not set WarmUpPeriod

* Documentation change

* Fix tests bugs
- In CommonIndicatorTests.cs before finish the test it checks the period.value with the number of samples but for default the period.value was set to -1

* Change names

* Change WarmUp and RegisterIndicator methods
- Lean WarmUp indicator skip custom python indicators that don't define WarmUpPeriod parameter

* Call WarmUpIndicator manually
- Add a new "bridge" method called WarmUpIndicator in QCAlgorithm.Python.cs to set up everything to call WarmUpIndicator in QCAlgorithm.Indicators.cs
- Change the regression algorithm to warm up the indicators manually

* Remove unnecessary code and add more tests

* Nit change

* Revert "Nit change"

This reverts commit da411f59c9.

* Fix bugs

* Try fix bugs

* Add C# regression test
- More nit changes
- Fix bugs

* Requested changes

* Remove unnecessary code

* Requested changes

* Nit changes
- Add new Python class to check a custom indicator, which doesn't inherits from PythonIndicator, warms up properly

* Reduce redundant code
2021-10-25 18:08:57 -03:00
Martin-Molinero
43c271a568 Atreyu template algorithm change traget SPY exchange (#6016) 2021-10-25 15:43:35 -03:00
IlshatGaripov
2e4252c92b LiveTradingResultHandler -> changes access modifier of SetNextStatusUpdate (#6015) 2021-10-25 11:17:35 -03:00
Adalyat Nazirov
0f189aa2b4 FTX brokerage rejects STOP order if market price missed (#6009)
* cannot submit stop orders with bad trigger price

* unit tests

* expect price data
2021-10-25 11:14:41 -03:00
IlshatGaripov
f55588e4c6 SecurityHolding -> impl. ToString() (#6014) 2021-10-25 11:07:34 -03:00
Martin-Molinero
58ccdee1b1 PythonNet version bump 2.0.10 (#6010) 2021-10-22 20:27:38 -03:00
Colton Sellers
6bd2859f64 Update to PythonNet 2.0.9 (#6004) 2021-10-21 20:06:38 -03:00
Alexandre Catarino
3ff7882dbf Round AverageLoss to Avoid Very Small Numbers (#6003) 2021-10-21 17:00:31 -03:00
Martin-Molinero
dace6d7ee1 Fix index live target exchange (#6000) 2021-10-20 17:26:25 -03:00
Colton Sellers
71d9eed07e BuyingPowerModel Fixes (#5996)
* Refactor error message for reproducability

* WIP Refactor GetMaximumOrderQuantityForTargetBuyingPower

* Additional tweaks and tests

* Address shorted margin case

* Reinstate tests with new modified function

* Update regression

* Some cleanup

* Expand test set

* Refactor solution

* Address review

* Final adjustments and cleanup

* Expand error message for GetAmountToOrder for safety and reproducibility

* Address reviews
2021-10-20 16:37:20 -03:00
Stas Kotykhin
c4a4550a66 Override History provider in kraken environment (#5998)
* add history-provider field to config.json

* Add comment
2021-10-20 16:36:34 -03:00
bmello4688
67081a8a05 Add virtual overrides for pivotpointshighlow computations (#5987)
* Add base class for pivotpointshighlow

* abstracts do not work well with python switch to virtuals and use pivotpointhighlow as base implementation

* added missing documentatino header

* moved reset back to original location
2021-10-19 21:45:18 -03:00
alexgallotta
a567053404 fix build command with dotnet (#5990) 2021-10-18 16:55:56 -03:00
Martin-Molinero
56b8ccc4b4 CoinApi log error on duplicate symbol (#5989) 2021-10-15 20:31:55 -03:00
Martin-Molinero
5f65677ede Add suuport for coinApi kraken ftx exchanges (#5985) 2021-10-15 11:24:30 -03:00
Ricardo Andrés Marino Rojas
def916aed1 Add IIndicatorWarmUpPeriodProvider for WindowIndicator.cs and Identity.cs indicators (#5984)
- Implement IIndicatorWarmUpPeriodProvider interface in both indicators
- Add test to check the new functionality is working as expected. To test WindowIndicator IIndicatorWarmUpPeriodProvider there was used WindowIdentity indicator tests because that indicator only inherits from it
2021-10-15 11:10:59 -03:00
Adalyat Nazirov
46ce138fa1 move methods for further usage across other brokerages (#5981) 2021-10-14 17:08:11 -03:00
Martin-Molinero
b8768ae274 Add FOPs price magnifier (#5979)
* Add FOPs price magnifier

* Improve unit tests
2021-10-14 11:57:48 -03:00
Ricardo Andrés Marino Rojas
db04b5e110 Feature 5930 price magnifier (#5977)
* Update SPDB with price magnifier parameter
- Add a new column for new parameter in symbol-properties-database.csv
- Change InteractiveBrokersBrokerage.cs implementation of GetContractPriceMagnifier() method in order to get the parameter directly from the SPDB
- Add test in SymbolPropertiesDatabaseTests.cs to check if the new parameter is loading properly

* Change GetContractPriceMagnifier() method name and implementation
- Change NormalizePriceToLean() and NormalizePriceToBrokerage() methods

* Nit change in GetSymbolPriceMagnifier() method

* Remove GetSymbolPriceMagnifier() method
- Remove redundant and unnecessary parameters in NormalizePriceToLean() and NormalizePriceToBrokerage()

* Requested changes and SPDB update
- Update SPDB with minimum order size parameter for futures in cents. The minimum order size parameter was extracted from the CME group API

* Address reviews. Adding unit test for failing case

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-10-14 11:16:23 -03:00
Colton Sellers
cff3640f15 Update to PythonNet 2.0.8 (#5978) 2021-10-13 20:19:06 -03:00
Martin-Molinero
b5574a7986 Do not emit zero quantity Exercise Order events (#5976)
- BrokerateTransactionHandler will not emit zero quantity Exercise order
  events. Updating unit tests
2021-10-12 19:38:37 -03:00
Martin-Molinero
c638f82337 Adjust Bitfinex currency fee error message (#5975) 2021-10-12 17:05:27 -03:00
Adalyat Nazirov
3a591c3a72 Fix Binance ExchangeInfo downloader (#5965)
* fix exchangeinfo downloader

* normalize data, update symbol properties

* min ordersize should be in base currency

* check min order size using quote currency price

* check order size in quote currency

* improve checks

* improve code; more unit tests

* more description

* fix failing test
2021-10-11 12:36:41 -03:00
Martin-Molinero
fdfb1b54c0 Add Binance debugging logs (#5974) 2021-10-11 11:55:12 -03:00
Adalyat Nazirov
7cfdd1243f FTX brokerage essentials (#5963)
* FTX config boilerplate

fixup

* required

* order props

* make orger props setter public

* add market props

* brokerage model

* deny modify order directly

* update markets

* unit tests

* fix market properties

* add comments

* return security benchmark

* fix fee calculation

* dont change access modifiers

* check brokerage CanSubmitOrder using min order quantity

* fix ticker values - use lean notation

* fix fee model

* fix error message
2021-10-08 19:16:38 -03:00
Stas Kotykhin
3fc042af33 Move bar aggregators to utils, add time overloads & add check of orderType for Kraken (#5969)
* Move Aggregate Quote and Trade Bars to utils

* Add decimal and long overload to UnixTimeStampToDateTime

* Add Kraken OrderType check in CanSubmitOrder

* PR !5969 review fixes
2021-10-08 17:59:32 -03:00
Martin-Molinero
1d6fed8843 Update python to 2.0.7 (#5968) 2021-10-08 12:55:14 -03:00
Colton Sellers
2109394060 Add subset test after dropping 'symbol' (#5966) 2021-10-06 18:21:33 -03:00
Colton Sellers
d2d99b1f10 Algorithm Sampling and Statistics Fixes (#5936)
* Implement scheduled event sampling solution

* Use UTC time, only update daily portfolio value once a day

* For daily resolutions sample chart always

* Cleanup

* Drop resample daily all together

* Force final sample

* Regression updates

* FIx LiveResultHandler to update portfolio and benchmark values outside of sampling event

* Name the daily sampling event

* Address review pt 1

* Drop force and use reference wrapper

* Adjust tests

* Fix warning for Benchmark Timezone Misalignment and also add test

* Fix for daily resolution orders and test adjustments

* Also warn on universe settings with daily resolution

* Update missed regression

* Fix reference wrapper use

* Update regression after rebase

* Add values back in for Daylight Algo

* Have statistics builder skip day 1 performance

* Regression adjustments

* Test adjustments

* Update regression unit test

* Adjust some regressions starts to show performance values

* Add hourly algorithm for beta comparison

* Address missing Python regression changes

* Remove null comment
2021-10-05 19:31:25 -03:00
Martin-Molinero
659735946a Bitfinex fees cash accounts (#5957)
* Bitfinex Fee adjustment

- Fix for bitfinex fee adjustment for cash account type only happen if
  the currencies are the expected ones, else log message.

* Adjust error handling to terminate algorithm

* Add bitfinex TESTBTCTESTUSD

* Minor improvements

- Add bitfinex test symbols to the SPDB
- Make SecurityDefinitionSymbolResolver log using trace
- Minor tweak for Bitfinex DQH lock contention
2021-10-04 18:15:32 -03:00
Stefano Raggi
29294cb1f4 Transaction handlers - minor updates (#5956)
- Move debug logging of order events from Brokerage to BrokerageTransactionHandler
- Override CurrentTimeUtc in BacktestingTransactionHandler
2021-10-01 19:09:08 -03:00
Ronit Jain
4546bbe9b1 Fix missing reference price when creating last entry (#5952)
* Fix code styling changes

* Cosmetic change

* Add reference price 1 for last entry

* Fix refernece price
2021-10-01 11:37:58 -03:00
Ricardo Andrés Marino Rojas
af958f0ce4 Bug 5904 minimum order size rejected order (#5949)
* - Update symbol-properties-database.csv, SymbolPropertiesDatabase.cs and SymbolProperties.cs with a new column for MinimumOrderSize parameter for Crypto type
- Change CanSubmitOrder() method implementation in GDAXBrokerageModel.cs to get the MinimumOrderSize from the security SymbolProperties directly
- Add CanSubmitOrder() method in Binance, Bitfinex and Kraken Brokerages models
- Add tests to check if CanSubmitOrder() method is working as expected in Binance, Bitfinex, Kraken and GDAX brokerages models
- Add tests to check if MinimumOrderSize parameter is loading correctly from symbol-properties-database.csv

* Revert "- Update symbol-properties-database.csv, SymbolPropertiesDatabase.cs and SymbolProperties.cs with a new column for MinimumOrderSize parameter for Crypto type"

This reverts commit e0fd66a5fa.

* Revert "Revert "- Update symbol-properties-database.csv, SymbolPropertiesDatabase.cs and SymbolProperties.cs with a new column for MinimumOrderSize parameter for Crypto type""

This reverts commit b0f37935fc.

* Requested changes in Crypto brokerage models
- Remove unnecessary commas in symbols-properties-database.csv
- Add TestHelpers class to reuse GetSecurity() method
- Add IsValidOrderSize() method in DefaultBrokerageModel class
- Remove unnecessary classes for brokerage models test helpers

* Nit change
- Remove unnecessary attribute from DefaultBrokerageModel.cs

* Nit change

* Nit changes and Regression test
- Add Bitfinex BTCUSD hourly data for 2 days
- Add regression test BuyBTCWithLessThanOneDollarAlgorithm.cs to test that the order size is taking into account when placing or updating an order
- Nit changes

* Change CanUpdateOrder() implementation
- CanUpdateOrder() now checks if the requested quantity value is valid

* Requested Changes
- Change regression algorithm BuyBTCWithLessThanOneDollar.cs name and implementation

* Nit changes
2021-09-30 18:30:04 -03:00
Stefano Raggi
6c42a266be IB brokerage - Update option positions at contract expiration (#5880)
* IB brokerage - Update option positions at contract expiration

* Add handling of live option expiration events

* Address review

- Nits

* Refactor option notification events [WIP]

* Add early exercise+assignment unit tests

* Fix sign bug in IB ExerciseOrder

* Address review

- log unexpected position
- add unit test cases for partial exercise/assignment
2021-09-30 13:48:41 -03:00
José Emiliano Cabrera Blancas
8b7da686ea Fix MovingAverageType in KeltnerChannels Indicator (#5954)
The Simple Moving Average was always used instead of the one passed to
the KeltnerChannels constructor.
2021-09-29 20:48:07 -03:00
Martin-Molinero
d3280c5e60 Move VX margin files (#5948) 2021-09-28 14:21:07 -03:00
Stas Kotykhin
fe1f22543f Add NonUpdateableLimitIfTouchedOrderTestParameters class (#5947) 2021-09-28 13:16:04 -03:00
Stefano Raggi
57ddbbbf05 IBAutomater updates (#5946) 2021-09-28 11:45:05 -03:00
Martin-Molinero
9579c4263b Fix history requests so they ignore internal subscriptions (#5945)
- Fix for history requests so that they ignore internal subscriptions
  accordengly. Adding regression test reproducing issue
2021-09-27 20:31:05 -03:00
Martin-Molinero
f082a40f34 Add missing comments (#5944) 2021-09-27 18:48:53 -03:00
Martin-Molinero
d739873daa Add aggregator reader (#5942)
* Add BaseDataCollectionAggregatorReader

- Add enumerable for BaseDataCollection
- Add BaseDataCollectionAggregatorReader
- Clean up CollectionSubscriptionDataSourceReader

* Address reviews

- Add new FileFormat that will be handled by the new Reader
- Adding unit tests for the new BaseDataCollectionAggregatorReader
- Some DataSourceReader duplication cleaning up

* Minor adjustment after some live trading tests
2021-09-27 17:25:23 -03:00
Martin-Molinero
0f7dfe8ec8 Fix live ETF universe selection (#5938)
- ETF live universe selection will behave the same as Coarse selection.
  Adding unit test
2021-09-23 15:11:35 -03:00
Alexandre Catarino
58968bf05f Adds Warnings to MOO and MOO using Tick Data (#5937)
Adds Warnings to MOO and MOO using Tick Data
These warnings are meant to let the user know that it was not possible to find ticks marked with the `OfficialOpen`, `OfficialClose`, `OpeningPrints` or `ClosingPrints` flags.
2021-09-22 19:17:18 -03:00
Stefano Raggi
627f280100 IB brokerage updates (#5933)
* Disconnect from IB API before waiting for restart

* Update IBAutomater to v2.0.62

* Update IBAutomater to v2.0.63
2021-09-22 18:52:00 -03:00
Alexandre Catarino
9ca57c2de9 Fixes Market On Close Fill of Equity Fill Model (#5913)
* Fixes Market On Close Fill of Equity Fill Model

Only use trade data (`Tick` with `TickTrade` type or `TradeBar`) to get the closing price, since MOC is filled with the closing price.

- Fix unit tests to show that the new implementation only fills with trade data from the current open market.
- Change regression tests to reflect the bug fix. All other changes are the consequence of using `TradeBar` instead of `QuoteBar`.

* Address Peer-Review

Fixes the logic with tick data: looking for the OfficalClose or ClosingPrints only apply if data from the extended market hours is included.
Adds additional logic to handle missing trade data.

* Refactors Timeout Logic and Adds It to MarketOnOpenFIll

-Refactors timeout logic to address peer-review and adds it to MOO fill too.
- Adds unit tests
2021-09-21 17:51:35 -03:00
Martin-Molinero
35c2951abb Tradier add retry logic. Clean up rate gate (#5935)
- Add Tradier retry logic in case of an unexpected execution failure
- Clean up rate gate logic to use RateGate class
2021-09-21 17:40:54 -03:00
Simon Judd
2c237b7f84 IB Brokerage - fix for futures contracts priced in cents (#5930)
* Fix IB futures prices where PriceMagnifier != 1

* Fix deadlock in GetOpenOrdersInternal by moving ConvertOrder call out of event handler;
Minor refactor to combine NormalizePrice and ConvertPrice methods

* IB future and future options price magnifier

* Address review. IB API clean up

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-09-20 16:17:25 -03:00
Martin-Molinero
4e6e0c85c6 Lean exchange improvements (#5932)
* Lean exchanges improvements

- Adding new Exchange class to avoid exchange code clash.
  Adding and updating unit test

* Add Market for MapFile API

* Self review
2021-09-20 13:50:15 -03:00
Colton Sellers
a2ac956d53 Move WickedRenkoConsolidator to RenkoConsolidator as Default (#5931)
* Rename Renko to ClassicRenko

* Rename WickedRenko to Renko

* Adjust tests and usages

* Backwards support WickedRenkoConsolidator

* Renames for consistency
2021-09-17 16:32:01 -03:00
Colton Sellers
5fecb77c8a Composite Indicator Fixes (#5929)
* Refactor for two types in composite indicator

* Fixes for unit tests

* Non generic indicator base

* Further seperate non-generic indicator base and generic input base

* Adjustments

* Remove generic CompositeIndicator

* Add test suite

* Make each method an individual case

* Address review

* Testing cleanup

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-09-16 17:58:10 -03:00
Stefano Raggi
3e8f15a62f Fix IB restarts during weekends (#5926)
* Fix IB restarts during weekends

* Address review

- Task.Delay usage
- update default delay from 10s to 5m
2021-09-15 19:16:34 -03:00
Martin-Molinero
0931ae868a Fix multiple coarse selection algorithms (#5927)
- Fix for live trading multiple coarse selections. Adding unit test
  reproducing issue.
2021-09-14 20:27:09 -03:00
Martin-Molinero
e13df5c901 Fix null reference loading existing holdings and cash balance (#5925) 2021-09-14 11:20:03 -03:00
Martin-Molinero
7be1b7db1a Algorithm Language can be case insensitive (#5924) 2021-09-13 10:31:31 -03:00
Gerardo Salazar
024d416ddd Adds support for getting a Lean symbol based on FIGI, CUSIP, ISIN, SEDOL (#5922)
* Adds support for getting a Lean symbol based on FIGI, CUSIP, ISIN, SEDOL

* Address review: bug fixes for mapping, improve docs, cleanup & refactor

  * Make LocalZipMapFileProvider and LocalZipFactorFileProvider only
    initialize if they haven't been initialized yet.

* Address review: makes ISIN, SEDOL, CUSIP case-insensitive

  * Cleans up map file provider in SecurityDefinitionSymbolResolver
  * Modifies some test cases to test for case-insensitivity

* Add null check for SecurityDefinitions

* Fix unit tests

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-09-10 19:16:18 -07:00
Martin-Molinero
eb2dbe2af7 Fix FuncSecuritySeeder for python (#5923)
- Fix funcSecuritySeeder for python. Adding regression algorithm
2021-09-10 19:28:49 -03:00
Colton Sellers
8358c394e1 Support all security types for benchmarks (#5919)
* Adjust benchmark subscription to dynamically determine best resolution

* Get types from SM

* Add red/green test set for security types
2021-09-10 16:58:31 -03:00
Stefano Raggi
d7c7adbd0d Update IBAutomater to v2.0.57 (#5920) 2021-09-10 12:36:34 -03:00
Martin-Molinero
1ab1f90e27 Add research import QuantConnect.AlphaStream (#5918) 2021-09-09 15:12:42 -03:00
Martin-Molinero
bf2ef35ada Update readme.md 2021-09-09 12:14:46 -03:00
Colton Sellers
2001f9a181 Tradier Options History Support (#5912)
* Implement options support for history requests

* Address review
2021-09-09 11:19:12 -03:00
Stas Kotykhin
8026785116 Feature kraken brokerage setup (#5896)
* Kraken Brokerage initial setup

* Fix naming in config

* Add license messages

* Add fees for stablecoins

* add kraken databases

* Review fixes, tests added

* Remove redundant field and using

* add CanUpdateOrder & summary

* Remove null

* Change to equal

* complete xml comments
2021-09-08 12:49:13 -03:00
Ronit Jain
5083433f68 Inital brokerage setup commit (#5905) 2021-09-07 22:05:36 -03:00
quantify-cflynn
5d4f428906 Add ValueAreaVolumePercentage Parameter (#5908)
* Add ValueAreaVolumePercentage Parameter

Remove hard coding of parameter and set it to optional parameter for the user.

* Update TimeProfile.cs to include valueAreaVolumePercentage parameter

* Update TimeProfile definition in QCAlgorithm.Indicators.cs
2021-09-07 12:17:23 -03:00
Ricardo Andrés Marino Rojas
da60daa60d Market profile indicator (#5891)
* Create Market Profile indicator.

* - Requested changes in MarketProfile indicator made it.
- TimeProfile and VolumeProfile created and tested.
- tp_datatest.csv and vp_datatest.csv extracted from https://github.com/bfolkens/py-market-profile

* Final potential Market Profile Indicator.
All unit test made it and the indicator is passing all of them
Test cases made it with python library from GH issue

* Code styling request changes

* Minor suggestions

* Minor renaming tweaks

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-09-03 20:18:44 -03:00
Martin-Molinero
7d88b5040b Update readme.md 2021-09-03 19:20:11 -03:00
Martin-Molinero
d76106b444 Fix foundation build failure (#5902) 2021-09-03 17:41:58 -03:00
Martin-Molinero
de09ec0933 Update readme.md 2021-09-03 17:27:36 -03:00
Martin-Molinero
c3874bc618 Mapping Extensions will try get custom data from symbol (#5901) 2021-09-03 17:08:02 -03:00
Stefano Raggi
0e1e497fbf Update IBAutomater to v2.0.56 (#5900)
* Update IBAutomater to v2.0.55

* Update IBAutomater to v2.0.56
2021-09-03 10:31:22 -03:00
Martin-Molinero
8eb023e854 Remove duplicate market hours segments (#5897) 2021-09-02 19:09:51 -03:00
Martin-Molinero
b251cffc2f Alpha Streams improvements (#5887)
* Few improvements

- Alpha Streams algorithm will add target securities right away
- If algorithm is warming up PortfolioTargetCollection will emit not
  insight
- Fix local disk factor file provider to use local cache instead of data
  folder
- EWAS PCM will not emit targets for securities which have not been
  added by the algorithm yet, to avoid runtime exception

* Fix GetLastKnownPrice default order adding more unit tests
2021-09-01 13:12:26 -03:00
Stefano Raggi
1d904e716c Add new Market.CFE (#5391)
As most brokers use separate exchange codes for CBOE and CFE, we added the new Market.CFE (previously Market.CBOE was used for both exchanges). This change also avoids hacky code in symbol mappers.
2021-08-31 19:34:14 -03:00
Ronit Jain
df57428bd7 Fix zerodha async order event (#5878)
* Fix zerodha async order event

consider fillQuantity as total filled quantity

cover edge case of fully filled

fix async events received from zerodha

indentation fix

* Fix coding style

* keep order in only CachedOrderIDs
2021-08-30 19:32:40 -03:00
Stefano Raggi
9d734c4d8f Update IBGateway install path (#5885) 2021-08-30 17:11:12 -03:00
Martin-Molinero
765ce87df1 Remove unrequired link library (#5884) 2021-08-27 21:45:30 -03:00
Martin-Molinero
8a5766fa39 Update foundation base image to ubuntu 20.04 (#5882)
- Update amd64 and ARM foundatio base image to ubuntu 20.04
2021-08-27 19:47:20 -03:00
Martin-Molinero
933e5ce6ca Alpha Streams improvements (#5876)
* Alpha Streams improvements

- Warmup added securities so we can trigger an order right away
- Fix bug where AddSecurity returned a security which was not the one
  being used
- Fix bug where EWAS PCM would remove from a dictionary while iterating
  over it

* Fix unit tests

* Add QCAlgorithm.GetLastKnownPrices API

- Add new GetLastKnownPrices that will return the last known data point
  for all subscribed data types.
- Fix for MHDB GetDataTimeZone which was using an invalid entry key
  format for custom data.
- Fix for using GetLastKnownPrice/s to seed a security during creation,
  when it's not added in the Algorithm.Securities collection

* Adding more unit tests for GetLastKnownPrice

* Address reviews

- Refactor GetLastKnownPrice/s to perform a single history request for
  all data types
2021-08-27 13:50:45 -03:00
Gerardo Salazar
dc433493b7 Add support for specifying CoinAPI market to process (#5877)
* Add support for specifying CoinAPI market to process

* Address review: improve CoinAPI stability by making inputted market lowercase
2021-08-27 13:26:55 -03:00
Martin-Molinero
9acf68ad19 Bump pythonNet to 2.0.6 (#5881) 2021-08-26 18:01:05 -03:00
2601 changed files with 165172 additions and 150092 deletions

8
.devcontainer/Dockerfile Normal file
View File

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

View File

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

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

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

View File

@@ -19,7 +19,7 @@ jobs:
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\"\)
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --blame-hang-timeout 300seconds --blame-crash --filter "TestCategory!=TravisExclude&TestCategory!=ResearchRegressionTests" -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\)
- name: Generate & Publish python stubs
if: startsWith(github.ref, 'refs/tags/')
@@ -28,3 +28,5 @@ jobs:
./ci_build_stubs.sh -t -g -p
env:
PYPI_API_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
ADDITIONAL_STUBS_REPOS: ${{ secrets.ADDITIONAL_STUBS_REPOS }}
QC_GIT_TOKEN: ${{ secrets.QC_GIT_TOKEN }}

View File

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

View File

@@ -0,0 +1,35 @@
name: Research 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: install dependencies
run: |
pip3 install papermill==2.4.0 clr-loader==0.1.6
- name: install kernel
run: dotnet tool install --global Microsoft.dotnet-interactive --version 1.0.340501
- name: Add dotnet tools to Path
run: echo "$HOME/.dotnet/tools" >> $GITHUB_PATH
- name: activate kernel for jupyter
run: dotnet interactive jupyter install
- 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=ResearchRegressionTests -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\) TestRunParameters.Parameter\(name=\"reduced-disk-size\", value=\"true\"\)

View File

@@ -0,0 +1,70 @@
name: Python Virtual Environments
on:
push:
branches: ['*']
tags: ['*']
pull_request:
branches: [master]
jobs:
build:
runs-on: ubuntu-20.04
container:
image: quantconnect/lean:foundation
steps:
- uses: actions/checkout@v2
- name: Build
run: dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
- name: Python Virtual Environment System Packages
run: python -m venv /lean-testenv --system-site-packages && . /lean-testenv/bin/activate && pip install --no-cache-dir lean==1.0.99 && deactivate
- name: Run Virtual Environment Test System Packages
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonVirtualEnvironmentTests.AssertVirtualEnvironment"
- name: Python Virtual Environment
run: rm -rf /lean-testenv && python -m venv /lean-testenv && . /lean-testenv/bin/activate && pip install --no-cache-dir lean==1.0.99 && deactivate
- name: Run Virtual Environment Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonVirtualEnvironmentTests.AssertVirtualEnvironment"
- name: Run Python Package Tests
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests" --blame-hang-timeout 120seconds --blame-crash
- name: Run Pomegranate & Tigramite Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.PomegranateTest|Tigramite" --blame-hang-timeout 120seconds --blame-crash
- name: Run StableBaselines Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.StableBaselinesTest" --blame-hang-timeout 120seconds --blame-crash
- name: Run AxPlatform Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.AxPlatformTest" --blame-hang-timeout 120seconds --blame-crash
- name: Run NBeats Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.NBeatsTest" --blame-hang-timeout 120seconds --blame-crash
- name: Run TensorlyTest Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorlyTest" --blame-hang-timeout 120seconds --blame-crash
- name: Run NeuralTangents, Ignite Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.NeuralTangentsTest|IgniteTest" --blame-hang-timeout 120seconds --blame-crash
- name: Run TensorflowTest
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorflowTest" --blame-hang-timeout 120seconds --blame-crash
- name: Run TensorflowProbability
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorflowProbabilityTest" --blame-hang-timeout 120seconds --blame-crash
- name: Run Hvplot Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.HvplotTest" --blame-hang-timeout 120seconds --blame-crash
- name: Run Hvplot Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.StellargraphTest" --blame-hang-timeout 120seconds --blame-crash
- name: Run Keras Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.KerasTest" --blame-hang-timeout 120seconds --blame-crash
- name: Run Keras Python Package Test
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.ScikerasTest" --blame-hang-timeout 120seconds --blame-crash

View File

@@ -18,10 +18,10 @@ To use Lean CLI follow the instructions for installation and tutorial for usage
<h2>Option 2: Install Locally</h2>
1. Install [.Net 5](https://dotnet.microsoft.com/download) for the project
1. Install [.Net 6](https://dotnet.microsoft.com/download) for the project
2. (Optional) Get [Python 3.6.8](https://www.python.org/downloads/release/python-368/) for running Python algorithms
- Follow Python instructions [here](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#installing-python-36) for your platform
2. (Optional) Get [Python 3.8.13](https://www.python.org/downloads/release/python-3813/) for running Python algorithms
- Follow Python instructions [here](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#installing-python-38) for your platform
3. Get [Visual Studio](https://visualstudio.microsoft.com/vs/)

10
.vscode/launch.json vendored
View File

@@ -3,13 +3,13 @@
VS Code Launch configurations for the LEAN engine
Launch:
Builds the project with dotnet 5 and then launches the program using coreclr; supports debugging.
In order to use this you need dotnet 5 on your system path, As well as the C# extension from the
Builds the project with dotnet 6 and then launches the program using coreclr; supports debugging.
In order to use this you need dotnet 6 on your system path, As well as the C# extension from the
marketplace.
Attach to Python:
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",
Will attempt to attach to LEAN running locally using DebugPy. Requires that the process is
actively running and config is set: "debugging": true, "debugging-method": "DebugPy",
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
@@ -26,7 +26,7 @@
"program": "${workspaceFolder}/Launcher/bin/Debug/QuantConnect.Lean.Launcher.dll",
"args": [
"--config",
"${workspaceFolder}/Launcher/config.json"
"${workspaceFolder}/Launcher/bin/Debug/config.json"
],
"cwd": "${workspaceFolder}/Launcher/bin/Debug/",
"stopAtEntry": false,

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

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

55
.vscode/readme.md vendored
View File

@@ -4,6 +4,8 @@ This document contains information regarding ways to use Visual Studio Code to w
- Using Lean CLI -> A great tool for working with your algorithms locally, while still being able to deploy to the cloud and have access to Lean data. It is also able to run algorithms locally through our official docker images **Recommended for algorithm development.
- Using a Lean Dev container -> A docker environment with all dependencies pre-installed to allow seamless Lean development across platforms. Great for open source contributors.
- Locally installing all dependencies to run Lean with Visual Studio Code on your OS.
<br />
@@ -12,32 +14,63 @@ This document contains information regarding ways to use Visual Studio Code to w
<h2>Option 1: Lean CLI</h2>
To use Lean CLI follow the instructions for installation and tutorial for usage in our [documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli)
To use Lean CLI follow the instructions for installation and tutorial for usage in our [documentation](https://www.quantconnect.com/docs/v2/lean-cli/key-concepts/getting-started)
<br />
<h2>Option 2: Install Dependencies Locally</h2>
<h2>Option 2: Lean Development Container</h2>
1. Install [.Net 5](https://dotnet.microsoft.com/download) for the project
Before anything we need to ensure a few things have been done for either option:
2. (Optional) Get [Python 3.6.8](https://www.python.org/downloads/release/python-368/) for running Python algorithms
- Follow Python instructions [here](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#installing-python-36) for your platform
1. Get [Visual Studio Code](https://code.visualstudio.com/download)
- Get [Remote Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) Extension
2. Get [Docker](https://docs.docker.com/get-docker/):
- Follow the instructions for your Operating System
- New to Docker? Try [docker getting-started](https://docs.docker.com/get-started/)
3. Pull Leans latest research image from a terminal
- `docker pull quantconnect/research:latest`
4. Get Lean into VS Code
- Download the repo or clone it using: `git clone [https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)`
- Open the folder using VS Code
5. Open Development Container
- In VS Code, either:
- Select "Reopen in Container" from pop up box.
OR
- Ctrl+Shift+P (Command Palette) and select "Remote-Containers: Rebuild and Reopen in Container"
You should now be in the development container, give VS Code a moment to prepare and you will be ready to go!
If you would like to mount any additional local files to your container, checkout [devcontainer.json "mounts" section](https://containers.dev/implementors/json_reference/) for an example! Upon any mount changes you must rebuild the container using Command Palette as in step 5.
<br />
<h2>Option 3: Install Dependencies Locally</h2>
1. Install [.NET 6](https://dotnet.microsoft.com/en-us/download/dotnet/6.0) for the project
2. (Optional) Get [Python 3.8.13](https://www.python.org/downloads/release/python-3813/) for running Python algorithms
- Follow Python instructions [here](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#installing-python-38) for your platform
3. Get [Visual Studio Code](https://code.visualstudio.com/download)
- Get the Extension [C#](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp) for C# Debugging
- Get the Extension [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) for Python Debugging
4. Get Lean into VS Code
- Download the repo or clone it using: _git clone [https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)_
- Download the repo or clone it using: `git clone [https://github.com/QuantConnect/Lean](https://github.com/QuantConnect/Lean)`
- Open the folder using VS Code
Your environment is prepared and ready to run lean
Your environment is prepared and ready to run Lean.
<br />
<h1>How to use Lean</h1>
This section will cover configuring, building, launching and debugging lean. This is only applicable to option 2 from above. This does not apply to Lean CLI, please refer to [CLI documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli)
This section will cover configuring, building, launching and debugging lean. This is only applicable to option 2 from above. This does not apply to Lean CLI, please refer to [CLI documentation](https://www.quantconnect.com/docs/v2/lean-cli/key-concepts/getting-started)
<br />
@@ -73,7 +106,6 @@ In VS Code run build task (Ctrl+Shift+B or "Terminal" dropdown); there are a few
- __Build__ - basic build task, just builds Lean once
- __Rebuild__ - rebuild task, completely rebuilds the project. Use if having issues with debugging symbols being loaded for your algorithms.
- __Autobuilder__ - Starts a script that builds then waits for files to change and rebuilds appropriately
- __Clean__ - deletes out all project build files
<br />
@@ -95,7 +127,7 @@ Python algorithms require a little extra work in order to be able to debug them.
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:
"debugging": true,
"debugging-method": "PTVSD",
"debugging-method": "DebugPy",
In setting this we are telling Lean to expect a debugger connection using Python Tools for Visual Studio Debugger. Once this is set Lean will stop upon initialization and await a connection to the debugger via port 5678.
@@ -123,5 +155,6 @@ _Figure 2: Python Debugger Messages_
<h1>Common Issues</h1>
Here we will cover some common issues with setting this up. This section will expand as we get user feedback!
- 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")
- The "project file cannot be loaded" and "nuget packages not found" errors occurs when the project files are open by another process in the host. Closing all applications and/or restarting the computer solve the issue.
- Autocomplete and reference finding with omnisharp can sometimes be buggy, if this occurs use the command palette to restart omnisharp. (Ctrl+Shift+P "OmniSharp: Restart OmniSharp")
- Any error messages about building in VSCode that point to comments in JSON. Either select **ignore** or follow steps described [here](https://stackoverflow.com/questions/47834825/in-vs-code-disable-error-comments-are-not-permitted-in-json) to remove the errors entirely.

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

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

12
.vscode/tasks.json vendored
View File

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

View File

@@ -69,6 +69,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 3943;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -96,25 +106,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Fees", "$199.00"},
{"Estimated Strategy Capacity", "$26000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "-22.493"},
{"Return Over Maximum Drawdown", "-77.93"},
{"Portfolio Turnover", "1.211"},
{"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", "$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%"},
{"Portfolio Turnover", "119.89%"},
{"OrderListHash", "3c4c4085810cc5ecdb927d3647b9bbf3"}
};
}

View File

@@ -105,6 +105,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 58;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -117,40 +127,22 @@ namespace QuantConnect.Algorithm.CSharp
{"Drawdown", "1.700%"},
{"Expectancy", "1.781"},
{"Net Profit", "1.442%"},
{"Sharpe Ratio", "4.017"},
{"Probabilistic Sharpe Ratio", "59.636%"},
{"Sharpe Ratio", "4.86"},
{"Probabilistic Sharpe Ratio", "59.497%"},
{"Loss Rate", "33%"},
{"Win Rate", "67%"},
{"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"},
{"Alpha", "4.181"},
{"Beta", "-1.322"},
{"Annual Standard Deviation", "0.321"},
{"Annual Variance", "0.103"},
{"Information Ratio", "-0.795"},
{"Tracking Error", "0.532"},
{"Treynor Ratio", "-1.18"},
{"Total Fees", "$14.78"},
{"Estimated Strategy Capacity", "$47000000.00"},
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
{"Fitness Score", "0.408"},
{"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"},
{"Total Insights Analysis Completed", "3"},
{"Long Insight Count", "0"},
{"Short Insight Count", "3"},
{"Long/Short Ratio", "0%"},
{"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%"},
{"Portfolio Turnover", "41.18%"},
{"OrderListHash", "9da9afe1e9137638a55db1676adc2be1"}
};
}

View File

@@ -82,6 +82,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 24;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -103,31 +113,13 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Information Ratio", "-9.486"},
{"Tracking Error", "0.008"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"Portfolio Turnover", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}

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;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm reproducing GH issue #5971 where we add and remove an option in the same loop
/// </summary>
public class AddAndRemoveSecuritySameLoopRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _contract;
private bool _hasRemoved;
public override void Initialize()
{
SetStartDate(2014, 06, 06);
SetEndDate(2014, 06, 09);
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero;
var aapl = AddEquity("AAPL").Symbol;
_contract = OptionChainProvider.GetOptionContractList(aapl, Time)
.OrderBy(symbol => symbol.ID.Symbol)
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American);
}
public override void OnData(Slice slice)
{
if (_hasRemoved)
{
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
}
_hasRemoved = true;
AddOptionContract(_contract);
// changed my mind!
RemoveOptionContract(_contract);
RemoveSecurity(_contract.Underlying);
RemoveSecurity(AddEquity("SPY", Resolution.Daily).Symbol);
}
public override void OnEndOfAlgorithm()
{
if (!_hasRemoved)
{
throw new Exception("We did not remove the option contract!");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 24;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-9.486"},
{"Tracking Error", "0.008"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

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;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression test to explain how Beta indicator works
/// </summary>
public class AddBetaIndicatorRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Beta _beta;
private SimpleMovingAverage _sma;
private decimal _lastSMAValue;
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 15);
SetCash(10000);
AddEquity("IBM");
AddEquity("SPY");
EnableAutomaticIndicatorWarmUp = true;
_beta = B("IBM", "SPY", 3, Resolution.Daily);
_sma = SMA("SPY", 3, Resolution.Daily);
_lastSMAValue = 0;
if (!_beta.IsReady)
{
throw new Exception("_beta indicator was expected to be ready");
}
}
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
var price = data["IBM"].Close;
Buy("IBM", 10);
LimitOrder("IBM", 10, price * 0.1m);
StopMarketOrder("IBM", 10, price / 0.1m);
}
if (_beta.Current.Value < 0m || _beta.Current.Value > 2.80m)
{
throw new Exception($"_beta value was expected to be between 0 and 2.80 but was {_beta.Current.Value}");
}
Log($"Beta between IBM and SPY is: {_beta.Current.Value}");
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
var order = Transactions.GetOrderById(orderEvent.OrderId);
var goUpwards = _lastSMAValue < _sma.Current.Value;
_lastSMAValue = _sma.Current.Value;
if (order.Status == OrderStatus.Filled)
{
if (order.Type == OrderType.Limit && Math.Abs(_beta.Current.Value - 1) < 0.2m && goUpwards)
{
Transactions.CancelOpenOrders(order.Symbol);
}
}
if (order.Status == OrderStatus.Canceled)
{
Log(orderEvent.ToString());
}
}
/// <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 virtual Language[] Languages { get; } = { Language.CSharp};
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 10977;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 11;
/// <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", "12.939%"},
{"Drawdown", "0.300%"},
{"Expectancy", "0"},
{"Net Profit", "0.289%"},
{"Sharpe Ratio", "4.233"},
{"Probabilistic Sharpe Ratio", "68.349%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.035"},
{"Beta", "0.122"},
{"Annual Standard Deviation", "0.024"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-3.181"},
{"Tracking Error", "0.142"},
{"Treynor Ratio", "0.842"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$35000000.00"},
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
{"Portfolio Turnover", "1.51%"},
{"OrderListHash", "bd88c6a0e10c7e146b05377205101a12"}
};
}
}

View File

@@ -0,0 +1,157 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using System.Collections.Generic;
using QuantConnect.Securities.Future;
using QuantConnect.Data.UniverseSelection;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Continuous Futures Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
/// and a future contract at the same time
/// </summary>
public class AddFutureContractWithContinuousRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _currentMappedSymbol;
private Future _continuousContract;
private Future _futureContract;
private bool _ended;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 6);
SetEndDate(2013, 10, 10);
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
dataMappingMode: DataMappingMode.LastTradingDay,
contractDepthOffset: 0
);
_futureContract = AddFutureContract(FutureChainProvider.GetFutureContractList(_continuousContract.Symbol, Time).First());
}
/// <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 (_ended)
{
throw new Exception($"Algorithm should of ended!");
}
if (data.Keys.Count > 2)
{
throw new Exception($"Getting data for more than 2 symbols! {string.Join(",", data.Keys.Select(symbol => symbol))}");
}
if (UniverseManager.Count != 3)
{
throw new Exception($"Expecting 3 universes (chain, continuous and user defined) but have {UniverseManager.Count}");
}
if (!Portfolio.Invested)
{
Buy(_futureContract.Symbol, 1);
Buy(_continuousContract.Mapped, 1);
RemoveSecurity(_futureContract.Symbol);
RemoveSecurity(_continuousContract.Symbol);
_ended = true;
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Status == OrderStatus.Filled)
{
Log($"{orderEvent}");
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
Debug($"{Time}-{changes}");
if (changes.AddedSecurities.Any(security => security.Symbol != _continuousContract.Symbol && security.Symbol != _futureContract.Symbol)
|| changes.RemovedSecurities.Any(security => security.Symbol != _continuousContract.Symbol && security.Symbol != _futureContract.Symbol))
{
throw new Exception($"We got an unexpected security changes {changes}");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 63;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "-0.03%"},
{"Compounding Annual Return", "-2.594%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.034%"},
{"Sharpe Ratio", "-7.854"},
{"Probabilistic Sharpe Ratio", "1.216%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.022"},
{"Beta", "0.004"},
{"Annual Standard Deviation", "0.003"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.768"},
{"Tracking Error", "0.241"},
{"Treynor Ratio", "-4.689"},
{"Total Fees", "$8.60"},
{"Estimated Strategy Capacity", "$5500000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Portfolio Turnover", "66.80%"},
{"OrderListHash", "802a335b5c355e83b8cd2174f053c1b9"}
};
}
}

View File

@@ -40,8 +40,8 @@ namespace QuantConnect.Algorithm.CSharp
public override void Initialize()
{
SetStartDate(2020, 1, 5);
SetEndDate(2020, 1, 6);
SetStartDate(2020, 1, 4);
SetEndDate(2020, 1, 8);
_es20h20 = AddFutureContract(
QuantConnect.Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 3, 20)),
@@ -51,8 +51,9 @@ namespace QuantConnect.Algorithm.CSharp
QuantConnect.Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)),
Resolution.Minute).Symbol;
var optionChains = OptionChainProvider.GetOptionContractList(_es20h20, Time)
.Concat(OptionChainProvider.GetOptionContractList(_es19m20, Time));
// Get option contract lists for 2020/01/05 (Time.AddDays(1)) because Lean has local data for that date
var optionChains = OptionChainProvider.GetOptionContractList(_es20h20, Time.AddDays(1))
.Concat(OptionChainProvider.GetOptionContractList(_es19m20, Time.AddDays(1)));
foreach (var optionContract in optionChains)
{
@@ -160,6 +161,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 311879;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -168,45 +179,27 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "217.585%"},
{"Drawdown", "0.600%"},
{"Compounding Annual Return", "5512.811%"},
{"Drawdown", "1.000%"},
{"Expectancy", "0"},
{"Net Profit", "0.635%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Net Profit", "5.333%"},
{"Sharpe Ratio", "64.137"},
{"Probabilistic Sharpe Ratio", "95.977%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-14.395"},
{"Tracking Error", "0.043"},
{"Treynor Ratio", "0"},
{"Total Fees", "$7.40"},
{"Estimated Strategy Capacity", "$28000000.00"},
{"Alpha", "25.72"},
{"Beta", "2.914"},
{"Annual Standard Deviation", "0.423"},
{"Annual Variance", "0.179"},
{"Information Ratio", "66.11"},
{"Tracking Error", "0.403"},
{"Treynor Ratio", "9.315"},
{"Total Fees", "$8.60"},
{"Estimated Strategy Capacity", "$22000000.00"},
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
{"Fitness Score", "1"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "3.199"},
{"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", "35738733ff791eeeaf508faec804cab0"}
{"Portfolio Turnover", "122.11%"},
{"OrderListHash", "e7021bd385f366771ae00abd3a46a22e"}
};
}
}

View File

@@ -0,0 +1,134 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using System.Collections.Generic;
using System.Linq;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regression algorithm tests we can add future option contracts from contracts in the future chain
/// </summary>
public class AddFutureOptionContractFromFutureChainRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private bool _addedOptions;
public override void Initialize()
{
SetStartDate(2020, 1, 4);
SetEndDate(2020, 1, 6);
var es = AddFuture(Futures.Indices.SP500EMini, Resolution.Minute, Market.CME);
es.SetFilter((futureFilter) =>
{
return futureFilter.Expiration(0, 365).ExpirationCycle(new[] { 3, 6 });
});
}
public override void OnData(Slice data)
{
if (!_addedOptions)
{
_addedOptions = true;
foreach (var futuresContracts in data.FutureChains.Values)
{
foreach (var contract in futuresContracts)
{
var option_contract_symbols = OptionChainProvider.GetOptionContractList(contract.Symbol, Time).ToList();
if(option_contract_symbols.Count == 0)
{
continue;
}
foreach (var option_contract_symbol in option_contract_symbols.OrderBy(x => x.ID.Date)
.ThenBy(x => x.ID.StrikePrice)
.ThenBy(x => x.ID.OptionRight).Take(5))
{
AddOptionContract(option_contract_symbol);
}
}
}
}
if (Portfolio.Invested)
{
return;
}
foreach (var chain in data.OptionChains.Values)
{
foreach (var option in chain.Contracts.Keys)
{
MarketOrder(option, 1);
MarketOrder(option.Underlying, 1);
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 12164;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "20"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "386219349.202%"},
{"Drawdown", "5.200%"},
{"Expectancy", "0"},
{"Net Profit", "11.912%"},
{"Sharpe Ratio", "1604181.92"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "2144881.34"},
{"Beta", "31.223"},
{"Annual Standard Deviation", "1.337"},
{"Annual Variance", "1.788"},
{"Information Ratio", "1657259.526"},
{"Tracking Error", "1.294"},
{"Treynor Ratio", "68696.045"},
{"Total Fees", "$35.70"},
{"Estimated Strategy Capacity", "$2600000.00"},
{"Lowest Capacity Asset", "ES 31C3JQS9D84PW|ES XCZJLC9NOB29"},
{"Portfolio Turnover", "495.15%"},
{"OrderListHash", "64221a660525c4259d5bd852eef1299c"}
};
}
}

View File

@@ -42,8 +42,8 @@ namespace QuantConnect.Algorithm.CSharp
public override void Initialize()
{
SetStartDate(2020, 1, 5);
SetEndDate(2020, 1, 6);
SetStartDate(2020, 1, 4);
SetEndDate(2020, 1, 8);
_es = AddFuture(Futures.Indices.SP500EMini, Resolution.Minute, Market.CME);
_es.SetFilter((futureFilter) =>
@@ -164,8 +164,6 @@ namespace QuantConnect.Algorithm.CSharp
public override void OnEndOfAlgorithm()
{
base.OnEndOfAlgorithm();
if (!_optionFilterRan)
{
throw new InvalidOperationException("Option chain filter was never ran");
@@ -219,6 +217,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 612882;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -227,45 +235,27 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-15.625%"},
{"Drawdown", "0.200%"},
{"Compounding Annual Return", "347.065%"},
{"Drawdown", "0.900%"},
{"Expectancy", "0"},
{"Net Profit", "-0.093%"},
{"Sharpe Ratio", "-11.181"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Net Profit", "1.951%"},
{"Sharpe Ratio", "15.548"},
{"Probabilistic Sharpe Ratio", "95.977%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.002"},
{"Beta", "-0.016"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-14.343"},
{"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"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-185.654"},
{"Portfolio Turnover", "0.821"},
{"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", "9347e3b610cfa21f7cbd968a0135c8af"}
{"Alpha", "1.885"},
{"Beta", "1.066"},
{"Annual Standard Deviation", "0.155"},
{"Annual Variance", "0.024"},
{"Information Ratio", "13.528"},
{"Tracking Error", "0.142"},
{"Treynor Ratio", "2.258"},
{"Total Fees", "$3.57"},
{"Estimated Strategy Capacity", "$760000.00"},
{"Lowest Capacity Asset", "ES XCZJLDQX2SRO|ES XCZJLC9NOB29"},
{"Portfolio Turnover", "32.31%"},
{"OrderListHash", "738240babf741f1bf79f85ea5026ec4c"}
};
}
}

View File

@@ -114,6 +114,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 37597;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -126,41 +136,23 @@ namespace QuantConnect.Algorithm.CSharp
{"Drawdown", "0.300%"},
{"Expectancy", "-0.042"},
{"Net Profit", "-0.332%"},
{"Sharpe Ratio", "-3.7"},
{"Probabilistic Sharpe Ratio", "0.563%"},
{"Sharpe Ratio", "-3.149"},
{"Probabilistic Sharpe Ratio", "0.427%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.92"},
{"Alpha", "-0.021"},
{"Beta", "-0.011"},
{"Annual Standard Deviation", "0.006"},
{"Alpha", "-0.015"},
{"Beta", "-0.012"},
{"Annual Standard Deviation", "0.005"},
{"Annual Variance", "0"},
{"Information Ratio", "-3.385"},
{"Tracking Error", "0.058"},
{"Treynor Ratio", "2.117"},
{"Information Ratio", "-2.823"},
{"Tracking Error", "0.049"},
{"Treynor Ratio", "1.372"},
{"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"},
{"Sortino Ratio", "-43.418"},
{"Return Over Maximum Drawdown", "-14.274"},
{"Portfolio Turnover", "0.007"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "b006bb7864c0b2f1a6552fb2aa7f03b8"}
{"Estimated Strategy Capacity", "$67000000.00"},
{"Lowest Capacity Asset", "AOL VRKS95ENLBYE|AOL R735QTJ8XC9X"},
{"Portfolio Turnover", "0.55%"},
{"OrderListHash", "568fe7c2a11960436660db1231f2cfd2"}
};
}
}

View File

@@ -166,6 +166,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 5797;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -193,25 +203,7 @@ namespace QuantConnect.Algorithm.CSharp
{"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"},
{"Sortino Ratio", "-19.883"},
{"Return Over Maximum Drawdown", "-67.224"},
{"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%"},
{"Portfolio Turnover", "1.14%"},
{"OrderListHash", "ae0b430e9c728966e3736fb352a689c6"}
};
}

View File

@@ -0,0 +1,157 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm reproducing GH issue #6073 where we remove and re add an option and expect it to work
/// </summary>
public class AddOptionContractTwiceRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _contract;
private bool _hasRemoved;
private bool _reAdded;
public override void Initialize()
{
SetStartDate(2014, 06, 06);
SetEndDate(2014, 06, 09);
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero;
UniverseSettings.FillForward = false;
AddEquity("SPY", Resolution.Daily);
var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
_contract = OptionChainProvider.GetOptionContractList(aapl, Time)
.OrderBy(symbol => symbol.ID.Symbol)
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American);
AddOptionContract(_contract);
}
public override void OnData(Slice slice)
{
if (_hasRemoved)
{
if (!_reAdded && slice.ContainsKey(_contract) && slice.ContainsKey(_contract.Underlying))
{
throw new Exception("Getting data for removed option and underlying!");
}
if (!Portfolio.Invested && _reAdded)
{
var option = Securities[_contract];
var optionUnderlying = Securities[_contract.Underlying];
if (option.IsTradable && optionUnderlying.IsTradable
&& slice.ContainsKey(_contract) && slice.ContainsKey(_contract.Underlying))
{
Buy(_contract, 1);
}
}
if (!Securities[_contract].IsTradable
&& !Securities[_contract.Underlying].IsTradable
&& !_reAdded)
{
// ha changed my mind!
AddOptionContract(_contract);
_reAdded = true;
}
}
if (slice.ContainsKey(_contract) && slice.ContainsKey(_contract.Underlying))
{
if (!_hasRemoved)
{
RemoveOptionContract(_contract);
RemoveSecurity(_contract.Underlying);
_hasRemoved = true;
}
}
}
public override void OnEndOfAlgorithm()
{
if (!_hasRemoved)
{
throw new Exception("We did not remove the option contract!");
}
if (!_reAdded)
{
throw new Exception("We did not re add the option contract!");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 4677;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.05%"},
{"Compounding Annual Return", "-4.548%"},
{"Drawdown", "0.100%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.051%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-9.486"},
{"Tracking Error", "0.008"},
{"Treynor Ratio", "0"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$30000.00"},
{"Lowest Capacity Asset", "AAPL VXBK4Q9ZIFD2|AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "0.07%"},
{"OrderListHash", "546b6182e1df2d222178454d8f311566"}
};
}
}

View File

@@ -0,0 +1,129 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Algorithm asserting that using OnlyApplyFilterAtMarketOpen along with other dynamic filters will make the filters be applied only on market
/// open, regardless of the order of configuration of the filters
/// </summary>
public class AddOptionWithOnMarketOpenOnlyFilterRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2014, 6, 5);
SetEndDate(2014, 6, 10);
// OnlyApplyFilterAtMarketOpen as first filter
AddOption("AAPL", Resolution.Minute).SetFilter(u =>
u.OnlyApplyFilterAtMarketOpen()
.Strikes(-5, 5)
.Expiration(0, 100)
.IncludeWeeklys());
// OnlyApplyFilterAtMarketOpen as last filter
AddOption("TWX", Resolution.Minute).SetFilter(u =>
u.Strikes(-5, 5)
.Expiration(0, 100)
.IncludeWeeklys()
.OnlyApplyFilterAtMarketOpen());
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
// This will be the first call, the underlying securities are added.
if (changes.AddedSecurities.All(s => s.Type != SecurityType.Option))
{
return;
}
var changeOptions = changes.AddedSecurities.Concat(changes.RemovedSecurities)
.Where(s => s.Type == SecurityType.Option);
// Susbtract one minute to get the actual market open. If market open is at 9:30am, this will be invoked at 9:31am
var expectedTime = Time.TimeOfDay - TimeSpan.FromMinutes(1);
var allOptionsWereChangedOnMarketOpen = changeOptions.All(s =>
{
var firstMarketSegment = s.Exchange.Hours.MarketHours[Time.DayOfWeek].Segments
.First(segment => segment.State == MarketHoursState.Market);
return firstMarketSegment.Start == expectedTime;
});
if (!allOptionsWereChangedOnMarketOpen)
{
throw new Exception("Expected options filter to be run only on market open");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all time slices of algorithm
/// </summary>
public long DataPoints => 6023980;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-10.144"},
{"Tracking Error", "0.033"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -40,8 +40,8 @@ namespace QuantConnect.Algorithm.CSharp
private int _expectedContractIndex;
private readonly List<Symbol> _expectedContracts = new List<Symbol>
{
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00750000"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00747500"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00750000"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00752500")
};
@@ -109,6 +109,11 @@ namespace QuantConnect.Algorithm.CSharp
var googOptionChain = AddOption(UnderlyingTicker);
googOptionChain.SetFilter(u =>
{
// we added the universe at 10, the universe selection data should not be from before
if (u.Underlying.EndTime.Hour < 10)
{
throw new Exception($"Unexpected underlying data point {u.Underlying.EndTime} {u.Underlying}");
}
// find first put above market price
return u.IncludeWeeklys()
.Strikes(+1, +1)
@@ -205,6 +210,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 200618;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -231,27 +246,9 @@ namespace QuantConnect.Algorithm.CSharp
{"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"},
{"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", "1e7b3e90918777b9dbf46353a96f3329"}
{"Lowest Capacity Asset", "GOOCV 305RBR0BSWIX2|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "1.19%"},
{"OrderListHash", "550a99c482106defd8ba15f48183768e"}
};
}
}

View File

@@ -0,0 +1,124 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using System.Collections.Generic;
using QuantConnect.Orders;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm making sure the securities cache is reset correctly once it's removed from the algorithm
/// </summary>
public class AddRemoveSecurityCacheRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 07); //Set Start Date
SetEndDate(2013, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
AddEquity("SPY", Resolution.Minute, extendedMarketHours: true);
}
/// <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("SPY", 1);
}
if (Time.Day == 11)
{
return;
}
if (!ActiveSecurities.ContainsKey("AIG"))
{
var aig = AddEquity("AIG", Resolution.Minute);
var ticket = MarketOrder("AIG", 1);
if (ticket.Status != OrderStatus.Invalid)
{
throw new Exception("Expected order to always be invalid because there is no data yet!");
}
}
else
{
RemoveSecurity("AIG");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 11202;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "19"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "271.720%"},
{"Drawdown", "2.500%"},
{"Expectancy", "-1"},
{"Net Profit", "1.754%"},
{"Sharpe Ratio", "11.994"},
{"Probabilistic Sharpe Ratio", "74.160%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.618"},
{"Beta", "0.81"},
{"Annual Standard Deviation", "0.185"},
{"Annual Variance", "0.034"},
{"Information Ratio", "3.961"},
{"Tracking Error", "0.061"},
{"Treynor Ratio", "2.746"},
{"Total Fees", "$21.45"},
{"Estimated Strategy Capacity", "$830000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "20.49%"},
{"OrderListHash", "6ee62edf1ac883882b0fcef8cb3e9bae"}
};
}
}

View File

@@ -106,6 +106,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 7063;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -133,25 +143,7 @@ namespace QuantConnect.Algorithm.CSharp
{"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", "372.086"},
{"Portfolio Turnover", "0.374"},
{"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%"},
{"Portfolio Turnover", "29.88%"},
{"OrderListHash", "ac3f4dfcdeb98b488b715412ad2d6c4f"}
};
}

View File

@@ -59,6 +59,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 3943;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -86,25 +96,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Fees", "$10.33"},
{"Estimated Strategy Capacity", "$38000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.747"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "107.013"},
{"Portfolio Turnover", "0.747"},
{"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", "$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%"},
{"Portfolio Turnover", "59.74%"},
{"OrderListHash", "af3a9c98c190d1b6b36fad184e796b0b"}
};
}

View File

@@ -0,0 +1,142 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm reproducing issue where underlying option contract would be removed with the first call
/// too RemoveOptionContract
/// </summary>
public class AddTwoAndRemoveOneOptionContractRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _contract1;
private Symbol _contract2;
private bool _hasRemoved;
public override void Initialize()
{
SetStartDate(2014, 06, 06);
SetEndDate(2014, 06, 06);
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero;
var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
var contracts = OptionChainProvider.GetOptionContractList(aapl, Time)
.OrderBy(symbol => symbol.ID.Symbol)
.Where(optionContract => optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American)
.Take(2)
.ToList();
_contract1 = contracts[0];
_contract2 = contracts[1];
AddOptionContract(_contract1);
AddOptionContract(_contract2);
}
public override void OnData(Slice slice)
{
if (slice.HasData)
{
if (!_hasRemoved)
{
RemoveOptionContract(_contract1);
_hasRemoved = true;
}
else
{
var subscriptions =
SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs("AAPL");
if (subscriptions.Count == 0)
{
throw new Exception("No configuration for underlying was found!");
}
if (!Portfolio.Invested)
{
Buy(_contract2, 1);
}
}
}
}
public override void OnEndOfAlgorithm()
{
if (!_hasRemoved)
{
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1578;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "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", "$2.00"},
{"Estimated Strategy Capacity", "$230000.00"},
{"Lowest Capacity Asset", "AAPL VXBK4QQIRLZA|AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "0.25%"},
{"OrderListHash", "228194dcc6fd8689a67f383577ee2d85"}
};
}
}

View File

@@ -78,6 +78,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 53;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -90,40 +100,22 @@ namespace QuantConnect.Algorithm.CSharp
{"Drawdown", "3.300%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.168%"},
{"Sharpe Ratio", "-0.126"},
{"Probabilistic Sharpe Ratio", "45.081%"},
{"Sharpe Ratio", "62.513"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-2.896"},
{"Beta", "0.551"},
{"Annual Standard Deviation", "0.385"},
{"Annual Variance", "0.148"},
{"Information Ratio", "-13.66"},
{"Tracking Error", "0.382"},
{"Treynor Ratio", "-0.088"},
{"Alpha", "1.118"},
{"Beta", "1.19"},
{"Annual Standard Deviation", "0.213"},
{"Annual Variance", "0.046"},
{"Information Ratio", "70.862"},
{"Tracking Error", "0.043"},
{"Treynor Ratio", "11.209"},
{"Total Fees", "$23.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.352"},
{"Portfolio Turnover", "0.269"},
{"Total Insights Generated", "15"},
{"Total Insights Closed", "12"},
{"Total Insights Analysis Completed", "12"},
{"Long Insight Count", "15"},
{"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%"},
{"Portfolio Turnover", "26.96%"},
{"OrderListHash", "a7a0983c8413ff241e7d223438f3d508"}
};
}

View File

@@ -89,6 +89,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 234018;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -101,40 +111,22 @@ namespace QuantConnect.Algorithm.CSharp
{"Drawdown", "5.800%"},
{"Expectancy", "-0.731"},
{"Net Profit", "-5.588%"},
{"Sharpe Ratio", "-3.272"},
{"Probabilistic Sharpe Ratio", "5.825%"},
{"Sharpe Ratio", "-3.252"},
{"Probabilistic Sharpe Ratio", "5.526%"},
{"Loss Rate", "86%"},
{"Win Rate", "14%"},
{"Profit-Loss Ratio", "0.89"},
{"Alpha", "-0.594"},
{"Beta", "0.707"},
{"Annual Standard Deviation", "0.203"},
{"Annual Variance", "0.041"},
{"Information Ratio", "-2.929"},
{"Tracking Error", "0.193"},
{"Treynor Ratio", "-0.942"},
{"Alpha", "-0.499"},
{"Beta", "1.483"},
{"Annual Standard Deviation", "0.196"},
{"Annual Variance", "0.039"},
{"Information Ratio", "-3.844"},
{"Tracking Error", "0.142"},
{"Treynor Ratio", "-0.43"},
{"Total Fees", "$37.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.469"},
{"Return Over Maximum Drawdown", "-13.057"},
{"Portfolio Turnover", "0.084"},
{"Total Insights Generated", "33"},
{"Total Insights Closed", "30"},
{"Total Insights Analysis Completed", "30"},
{"Long Insight Count", "33"},
{"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%"},
{"Portfolio Turnover", "7.34%"},
{"OrderListHash", "f837879b96f5e565b60fd040299d2123"}
};
}

View File

@@ -30,7 +30,7 @@ namespace QuantConnect.Algorithm.CSharp
{
private Symbol _aapl;
private const string Ticker = "AAPL";
private FactorFile _factorFile;
private CorporateFactorProvider _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,
@@ -56,7 +56,7 @@ namespace QuantConnect.Algorithm.CSharp
factorFileProvider.Initialize(mapFileProvider, dataProvider);
_factorFile = factorFileProvider.Get(_aapl);
_factorFile = factorFileProvider.Get(_aapl) as CorporateFactorProvider;
}
/// <summary>
@@ -83,7 +83,7 @@ namespace QuantConnect.Algorithm.CSharp
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 dayFactor = _factorFile.GetPriceScale(aaplData.Time, DataNormalizationMode.SplitAdjusted);
var probableAdjustedVolume = aaplData.Volume / dayFactor;
if (_expectedAdjustedVolume.Current == probableAdjustedVolume)
@@ -107,7 +107,7 @@ namespace QuantConnect.Algorithm.CSharp
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 dayFactor = _factorFile.GetPriceScale(aaplQuoteData.Time, DataNormalizationMode.SplitAdjusted);
var probableAdjustedAskSize = aaplQuoteData.LastAskSize / dayFactor;
if (_expectedAdjustedAskSize.Current == probableAdjustedAskSize)
@@ -126,7 +126,7 @@ namespace QuantConnect.Algorithm.CSharp
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 dayFactor = _factorFile.GetPriceScale(aaplQuoteData.Time, DataNormalizationMode.SplitAdjusted);
var probableAdjustedBidSize = aaplQuoteData.LastBidSize / dayFactor;
if (_expectedAdjustedBidSize.Current == probableAdjustedBidSize)
@@ -153,6 +153,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 795;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -180,25 +190,7 @@ namespace QuantConnect.Algorithm.CSharp
{"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%"},
{"Portfolio Turnover", "99.56%"},
{"OrderListHash", "18e41dded4f8cee548ee02b03ffb0814"}
};
}

View File

@@ -186,6 +186,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 35410;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -198,40 +208,22 @@ namespace QuantConnect.Algorithm.CSharp
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0.192%"},
{"Sharpe Ratio", "31.331"},
{"Probabilistic Sharpe Ratio", "88.448%"},
{"Sharpe Ratio", "231.673"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.138"},
{"Beta", "0.04"},
{"Annual Standard Deviation", "0.004"},
{"Alpha", "0.163"},
{"Beta", "-0.007"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "4.767"},
{"Tracking Error", "0.077"},
{"Treynor Ratio", "3.223"},
{"Information Ratio", "4.804"},
{"Tracking Error", "0.098"},
{"Treynor Ratio", "-22.526"},
{"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%"},
{"Portfolio Turnover", "10.61%"},
{"OrderListHash", "0069f402ffcd2d91b9018b81badfab81"}
};
}

View File

@@ -13,13 +13,12 @@
* limitations under the License.
*/
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using System.Collections.Generic;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Data.Custom.AlphaStreams;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
@@ -30,8 +29,6 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public class AlphaStreamsBasicTemplateAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Dictionary<Symbol, HashSet<Symbol>> _symbolsPerAlpha = new Dictionary<Symbol, HashSet<Symbol>>();
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
@@ -40,9 +37,12 @@ namespace QuantConnect.Algorithm.CSharp
SetStartDate(2018, 04, 04);
SetEndDate(2018, 04, 06);
SetAlpha(new AlphaStreamAlphaModule());
SetExecution(new ImmediateExecutionModel());
Settings.MinimumOrderMarginPortfolioPercentage = 0.01m;
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
SetSecurityInitializer(new BrokerageModelSecurityInitializer(BrokerageModel,
new FuncSecuritySeeder(GetLastKnownPrices)));
foreach (var alphaId in new [] { "623b06b231eb1cc1aa3643a46", "9fc8ef73792331b11dbd5429a" })
{
@@ -50,59 +50,11 @@ namespace QuantConnect.Algorithm.CSharp
}
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
foreach (var portfolioState in data.Get<AlphaStreamsPortfolioState>().Values)
{
var alphaId = portfolioState.Symbol;
var currentSymbols = _symbolsPerAlpha[alphaId];
var newSymbols = new HashSet<Symbol>(currentSymbols.Count);
foreach (var symbol in portfolioState.PositionGroups?.SelectMany(positionGroup => positionGroup.Positions).Select(state => state.Symbol) ?? Enumerable.Empty<Symbol>())
{
// only add it if it's not used by any alpha (already added check)
if (newSymbols.Add(symbol) && !UsedBySomeAlpha(symbol))
{
AddSecurity(symbol, resolution: UniverseSettings.Resolution);
}
}
_symbolsPerAlpha[alphaId] = newSymbols;
foreach (var symbol in currentSymbols.Where(symbol => !UsedBySomeAlpha(symbol)))
{
RemoveSecurity(symbol);
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
Log($"OnOrderEvent: {orderEvent}");
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
changes.FilterCustomSecurities = false;
foreach (var addedSecurity in changes.AddedSecurities)
{
if (addedSecurity.Symbol.IsCustomDataType<AlphaStreamsPortfolioState>())
{
_symbolsPerAlpha[addedSecurity.Symbol] = new HashSet<Symbol>();
}
}
Log($"OnSecuritiesChanged: {changes}");
}
private bool UsedBySomeAlpha(Symbol asset)
{
return _symbolsPerAlpha.Any(pair => pair.Value.Contains(asset));
}
/// <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>
@@ -113,6 +65,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 890;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 12;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -140,25 +102,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$83000.00"},
{"Lowest Capacity Asset", "BTCUSD XJ"},
{"Fitness Score", "0.017"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-138.588"},
{"Portfolio Turnover", "0.034"},
{"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%"},
{"Portfolio Turnover", "2.31%"},
{"OrderListHash", "2b94bc50a74caebe06c075cdab1bc6da"}
};
}

View File

@@ -41,52 +41,44 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 6202;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 61;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.84%"},
{"Compounding Annual Return", "-78.502%"},
{"Average Win", "0.01%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-78.519%"},
{"Drawdown", "3.100%"},
{"Expectancy", "-1"},
{"Expectancy", "7.797"},
{"Net Profit", "-1.134%"},
{"Sharpe Ratio", "-2.456"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.008"},
{"Beta", "1.012"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "16.59"},
{"Alpha", "0.006"},
{"Beta", "1.011"},
{"Annual Standard Deviation", "0.343"},
{"Annual Variance", "0.117"},
{"Information Ratio", "-0.57"},
{"Information Ratio", "-0.859"},
{"Tracking Error", "0.004"},
{"Treynor Ratio", "-0.831"},
{"Total Fees", "$2.89"},
{"Estimated Strategy Capacity", "$8900000000.00"},
{"Treynor Ratio", "-0.832"},
{"Total Fees", "2.89"},
{"Estimated Strategy Capacity", "8900000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.506"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0.506"},
{"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%"},
{"Portfolio Turnover", "33.78%"},
{"OrderListHash", "a9dd0a0ab6070455479d1b9caaa4e69c"}
};
}

View File

@@ -14,9 +14,11 @@
*/
using System;
using QuantConnect.Interfaces;
using System.Collections.Generic;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Data.Custom.AlphaStreams;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Selection;
@@ -26,7 +28,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Example algorithm consuming an alpha streams portfolio state and trading based on it
/// </summary>
public class AlphaStreamsUniverseSelectionTemplateAlgorithm : AlphaStreamsBasicTemplateAlgorithm
public class AlphaStreamsUniverseSelectionTemplateAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
@@ -36,6 +38,7 @@ namespace QuantConnect.Algorithm.CSharp
SetStartDate(2018, 04, 04);
SetEndDate(2018, 04, 06);
SetAlpha(new AlphaStreamAlphaModule());
SetExecution(new ImmediateExecutionModel());
Settings.MinimumOrderMarginPortfolioPercentage = 0.01m;
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
@@ -65,23 +68,55 @@ namespace QuantConnect.Algorithm.CSharp
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 893;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 2;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
get
{
var result = base.ExpectedStatistics;
result["Compounding Annual Return"] = "-13.200%";
result["Information Ratio"] = "2.827";
result["Tracking Error"] = "0.248";
result["Fitness Score"] = "0.011";
result["Return Over Maximum Drawdown"] = "-113.513";
result["Portfolio Turnover"] = "0.023";
return result;
}
}
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.12%"},
{"Compounding Annual Return", "-13.200%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.116%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "2.474"},
{"Tracking Error", "0.339"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$83000.00"},
{"Lowest Capacity Asset", "BTCUSD XJ"},
{"Portfolio Turnover", "2.31%"},
{"OrderListHash", "2b94bc50a74caebe06c075cdab1bc6da"}
};
}
}

View File

@@ -27,7 +27,6 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public class AlphaStreamsWithHoldingsBasicTemplateAlgorithm : AlphaStreamsBasicTemplateAlgorithm
{
private decimal _initialCash = 100000;
private decimal _expectedSpyQuantity;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
@@ -36,7 +35,7 @@ namespace QuantConnect.Algorithm.CSharp
{
SetStartDate(2018, 04, 04);
SetEndDate(2018, 04, 06);
SetCash(_initialCash);
SetCash(100000);
SetExecution(new ImmediateExecutionModel());
UniverseSettings.Resolution = Resolution.Hour;
@@ -46,23 +45,23 @@ namespace QuantConnect.Algorithm.CSharp
// AAPL should be liquidated since it's not hold by the alpha
// This is handled by the PCM
var aapl = AddEquity("AAPL", Resolution.Hour);
aapl.Holdings.SetHoldings(100, 10);
aapl.Holdings.SetHoldings(40, 10);
// SPY will be bought following the alpha streams portfolio
// This is handled by the PCM + Execution Model
var spy = AddEquity("SPY", Resolution.Hour);
spy.Holdings.SetHoldings(100, -10);
spy.Holdings.SetHoldings(246, -10);
AddData<AlphaStreamsPortfolioState>("94d820a93fff127fa46c15231d");
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (_expectedSpyQuantity == 0 && orderEvent.Symbol == "SPY")
if (_expectedSpyQuantity == 0 && orderEvent.Symbol == "SPY" && orderEvent.Status == OrderStatus.Filled)
{
var security = Securities["SPY"];
var priceInAccountCurrency = security.AskPrice * security.QuoteCurrency.ConversionRate;
_expectedSpyQuantity = (_initialCash * (1 - Settings.FreePortfolioValuePercentage) - priceInAccountCurrency) / priceInAccountCurrency;
var priceInAccountCurrency = Portfolio.CashBook.ConvertToAccountCurrency(security.AskPrice, security.QuoteCurrency.Symbol);
_expectedSpyQuantity = (Portfolio.TotalPortfolioValue - Settings.FreePortfolioValue) / priceInAccountCurrency;
_expectedSpyQuantity = _expectedSpyQuantity.DiscretelyRoundBy(1, MidpointRounding.ToZero);
}
@@ -76,7 +75,8 @@ namespace QuantConnect.Algorithm.CSharp
throw new Exception("We should no longer hold AAPL since the alpha does not");
}
if (Securities["SPY"].Holdings.Quantity != _expectedSpyQuantity)
// we allow some padding for small price differences
if (Math.Abs(Securities["SPY"].Holdings.Quantity - _expectedSpyQuantity) > _expectedSpyQuantity * 0.03m)
{
throw new Exception($"Unexpected SPY holdings. Expected {_expectedSpyQuantity} was {Securities["SPY"].Holdings.Quantity}");
}
@@ -92,23 +92,33 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 2313;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 1;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-1.03%"},
{"Average Win", "0.01%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-87.617%"},
{"Drawdown", "3.100%"},
{"Expectancy", "-1"},
{"Expectancy", "8.518"},
{"Net Profit", "-1.515%"},
{"Sharpe Ratio", "-2.45"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "18.04"},
{"Alpha", "0.008"},
{"Beta", "1.015"},
{"Annual Standard Deviation", "0.344"},
@@ -119,25 +129,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Fees", "$3.09"},
{"Estimated Strategy Capacity", "$8900000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.511"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "6113.173"},
{"Portfolio Turnover", "0.511"},
{"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%"},
{"Portfolio Turnover", "34.12%"},
{"OrderListHash", "788eb2c74715a78476ba0db3b2654eb6"}
};
}

View File

@@ -1,162 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Orders.Fees;
using QuantConnect.Data.Custom;
using System.Collections.Generic;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Algorithm.Framework.Selection;
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
/// sourced so the community and client funds can see an example of an alpha.
///</summary>
public class MortgageRateVolatilityAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2017, 1, 1); //Set Start Date
SetCash(100000); //Set Strategy Cash
UniverseSettings.Resolution = Resolution.Daily;
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();
SetUniverseSelection(new ManualUniverseSelectionModel(realEstateETFs));
SetAlpha(new MortgageRateVolatilityAlphaModel(this));
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
SetExecution(new ImmediateExecutionModel());
SetRiskManagement(new NullRiskManagementModel());
}
private class MortgageRateVolatilityAlphaModel : AlphaModel
{
private readonly int _indicatorPeriod;
private readonly Resolution _resolution;
private readonly TimeSpan _insightDuration;
private readonly int _deviations;
private readonly double _insightMagnitude;
private readonly Symbol _mortgageRate;
private readonly SimpleMovingAverage _mortgageRateSma;
private readonly StandardDeviation _mortgageRateStd;
public MortgageRateVolatilityAlphaModel(
QCAlgorithm algorithm,
int indicatorPeriod = 15,
double insightMagnitude = 0.0005,
int deviations = 2,
Resolution resolution = Resolution.Daily
)
{
// Add Quandl data for a Well's Fargo 30-year Fixed Rate mortgage
_mortgageRate = algorithm.AddData<QuandlMortgagePriceColumns>("WFC/PR_GOV_30YFIXEDVA_APR").Symbol;
_indicatorPeriod = indicatorPeriod;
_resolution = resolution;
_insightDuration = resolution.ToTimeSpan().Multiply(indicatorPeriod);
_insightMagnitude = insightMagnitude;
_deviations = deviations;
// Add indicators for the mortgage rate -- Standard Deviation and Simple Moving Average
_mortgageRateStd = algorithm.STD(_mortgageRate, _indicatorPeriod, resolution);
_mortgageRateSma = algorithm.SMA(_mortgageRate, _indicatorPeriod, resolution);
// Use a history call to warm-up the indicators
WarmUpIndicators(algorithm);
}
public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
{
var insights = new List<Insight>();
// Return empty list if data slice doesn't contain monrtgage rate data
if (!data.Keys.Contains(_mortgageRate))
{
return insights;
}
// Extract current mortgage rate, the current STD indicator value, and current SMA value
var rate = data[_mortgageRate].Value;
var deviation = _deviations * _mortgageRateStd;
var sma = _mortgageRateSma;
// Loop through all Active Securities to emit insights
foreach (var security in algorithm.ActiveSecurities.Keys)
{
// Mortgage rate Symbol will be in the collection, so skip it
if (security == _mortgageRate)
{
return insights;
}
// If volatility in mortgage rates is high, then we emit an Insight to sell
if ((rate < sma - deviation) || (rate > sma + deviation))
{
insights.Add(Insight.Price(security, _insightDuration, InsightDirection.Down, _insightMagnitude));
}
// If volatility in mortgage rates is low, then we emit an Insight to buy
if ((rate < sma - (decimal)deviation/2) || (rate > sma + (decimal)deviation/2))
{
insights.Add(Insight.Price(security, _insightDuration, InsightDirection.Up, _insightMagnitude));
}
}
return insights;
}
private void WarmUpIndicators(QCAlgorithm algorithm)
{
// Make a history call and update the indicators
algorithm.History(new[] { _mortgageRate }, _indicatorPeriod, _resolution).PushThrough(bar =>
{
_mortgageRateSma.Update(bar.EndTime, bar.Value);
_mortgageRateStd.Update(bar.EndTime, bar.Value);
});
}
}
public class QuandlMortgagePriceColumns : Quandl
{
public QuandlMortgagePriceColumns()
// Rename the Quandl object column to the data we want, which is the 'Value' column
// of the CSV that our API call returns
: base(valueColumnName: "Value")
{
}
}
}
}

View File

@@ -82,6 +82,16 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 0;
/// </summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -195,4 +205,4 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
UltraShort = ultraShort;
}
}
}
}

View File

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

View File

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

View File

@@ -73,6 +73,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1893;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 100;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -85,40 +95,22 @@ namespace QuantConnect.Algorithm.CSharp
{"Drawdown", "0.100%"},
{"Expectancy", "3.321"},
{"Net Profit", "0.089%"},
{"Sharpe Ratio", "0.868"},
{"Probabilistic Sharpe Ratio", "44.482%"},
{"Sharpe Ratio", "0.798"},
{"Probabilistic Sharpe Ratio", "40.893%"},
{"Loss Rate", "24%"},
{"Win Rate", "76%"},
{"Profit-Loss Ratio", "4.67"},
{"Alpha", "0.001"},
{"Beta", "-0"},
{"Alpha", "-0.001"},
{"Beta", "0.008"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.148"},
{"Tracking Error", "0.101"},
{"Treynor Ratio", "-4.168"},
{"Information Ratio", "-1.961"},
{"Tracking Error", "0.092"},
{"Treynor Ratio", "0.08"},
{"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%"},
{"Portfolio Turnover", "0.02%"},
{"OrderListHash", "cf43585a8d1781f04b53a4f1ee3380cb"}
};
}

View File

@@ -35,7 +35,7 @@ namespace QuantConnect.Algorithm.CSharp
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
EnableAutomaticIndicatorWarmUp = true;
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 09);
SetEndDate(2013, 10, 10);
var SP500 = QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME);
_symbol = FutureChainProvider.GetFutureContractList(SP500, StartDate).First();
@@ -67,7 +67,7 @@ namespace QuantConnect.Algorithm.CSharp
// Test case: custom IndicatorBase<QuoteBar> indicator using Future subscribed symbol
var indicator = new CustomIndicator();
var consolidator = CreateConsolidator(TimeSpan.FromMinutes(1), typeof(QuoteBar));
var consolidator = CreateConsolidator(TimeSpan.FromMinutes(2), typeof(QuoteBar));
RegisterIndicator(_symbol, indicator, consolidator);
AssertIndicatorState(indicator, isReady: false);
@@ -143,6 +143,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 6426;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 84;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -151,45 +161,27 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-99.999%"},
{"Drawdown", "16.100%"},
{"Compounding Annual Return", "733913.744%"},
{"Drawdown", "15.900%"},
{"Expectancy", "0"},
{"Net Profit", "-6.366%"},
{"Sharpe Ratio", "1.194"},
{"Net Profit", "6.828%"},
{"Sharpe Ratio", "203744786353.302"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "5.56"},
{"Beta", "-71.105"},
{"Annual Standard Deviation", "0.434"},
{"Annual Variance", "0.188"},
{"Information Ratio", "1.016"},
{"Tracking Error", "0.44"},
{"Treynor Ratio", "-0.007"},
{"Total Fees", "$20.35"},
{"Estimated Strategy Capacity", "$19000000.00"},
{"Alpha", "456382350698.561"},
{"Beta", "9.229"},
{"Annual Standard Deviation", "2.24"},
{"Annual Variance", "5.017"},
{"Information Ratio", "228504036840.953"},
{"Tracking Error", "1.997"},
{"Treynor Ratio", "49450701625.718"},
{"Total Fees", "$23.65"},
{"Estimated Strategy Capacity", "$200000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.138"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-1.727"},
{"Return Over Maximum Drawdown", "-12.061"},
{"Portfolio Turnover", "4.916"},
{"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", "7c841ca58a4385f42236838e5bf0c382"}
{"Portfolio Turnover", "351.80%"},
{"OrderListHash", "dd38e7b94027d20942a5aa9ac31a9a7f"}
};
}
}

View File

@@ -105,6 +105,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 3943;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 40;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -132,25 +142,7 @@ namespace QuantConnect.Algorithm.CSharp
{"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.728"},
{"Portfolio Turnover", "0.248"},
{"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%"},
{"Portfolio Turnover", "19.93%"},
{"OrderListHash", "9e4bfd2eb0b81ee5bc1b197a87ccedbe"}
};
}

View File

@@ -293,6 +293,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1341291;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -305,41 +315,23 @@ namespace QuantConnect.Algorithm.CSharp
{"Drawdown", "0.400%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.329%"},
{"Sharpe Ratio", "-11.083"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Sharpe Ratio", "-7.887"},
{"Probabilistic Sharpe Ratio", "1.216%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.003"},
{"Alpha", "-0.001"},
{"Beta", "0.097"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "9.742"},
{"Tracking Error", "0.021"},
{"Treynor Ratio", "-0.26"},
{"Information Ratio", "7.39"},
{"Tracking Error", "0.015"},
{"Treynor Ratio", "-0.131"},
{"Total Fees", "$2.00"},
{"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"}
{"Portfolio Turnover", "17.02%"},
{"OrderListHash", "85cbf92f01c2c91b5f710b7eeefecbe1"}
};
}
}

View File

@@ -0,0 +1,95 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Abstract regression framework algorithm for multiple framework regression tests
/// </summary>
public abstract class BaseFrameworkRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2014, 6, 1);
SetEndDate(2014, 6, 30);
UniverseSettings.Resolution = Resolution.Hour;
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
var symbols = new[] { "AAPL", "AIG", "BAC", "SPY" }
.Select(ticker => QuantConnect.Symbol.Create(ticker, SecurityType.Equity, Market.USA))
.ToList();
// Manually add AAPL and AIG when the algorithm starts
SetUniverseSelection(new ManualUniverseSelectionModel(symbols.Take(2)));
// At midnight, add all securities every day except on the last data
// With this procedure, the Alpha Model will experience multiple universe changes
AddUniverseSelection(new ScheduledUniverseSelectionModel(
DateRules.EveryDay(), TimeRules.Midnight,
dt => dt < EndDate.AddDays(-1) ? symbols : Enumerable.Empty<Symbol>()));
SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(31), 0.025, null));
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
SetExecution(new ImmediateExecutionModel());
SetRiskManagement(new NullRiskManagementModel());
}
public override void OnEndOfAlgorithm()
{
// The base implementation checks for active insights
var insightsCount = Insights.GetInsights(insight => insight.IsActive(UtcTime)).Count;
if (insightsCount != 0)
{
throw new Exception($"The number of active insights should be 0. Actual: {insightsCount}");
}
}
/// <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 virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 765;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public abstract Dictionary<string, string> ExpectedStatistics { get; }
}
}

View File

@@ -14,6 +14,7 @@
*/
using System.Collections.Generic;
using QuantConnect.Brokerages;
using QuantConnect.Data;
using QuantConnect.Interfaces;
@@ -33,6 +34,7 @@ namespace QuantConnect.Algorithm.CSharp
{
SetStartDate(2018, 04, 04); //Set Start Date
SetEndDate(2018, 04, 04); //Set End Date
SetBrokerageModel(BrokerageName.GDAX, AccountType.Cash);
//Before setting any cash or adding a Security call SetAccountCurrency
SetAccountCurrency("EUR");
SetCash(100000); //Set Strategy Cash
@@ -63,6 +65,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 4319;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 120;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -87,29 +99,11 @@ namespace QuantConnect.Algorithm.CSharp
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$85000.00"},
{"Total Fees", "€298.35"},
{"Estimated Strategy Capacity", "85000.00"},
{"Lowest Capacity Asset", "BTCEUR XJ"},
{"Fitness Score", "0.506"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-14.148"},
{"Portfolio Turnover", "1.073"},
{"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", "18dc611407abec4ea47092e71f33f983"}
{"Portfolio Turnover", "107.64%"},
{"OrderListHash", "2ba443899dcccc79dc0f04441f797bf9"}
};
}
}

View File

@@ -72,6 +72,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 3943;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -99,25 +109,7 @@ namespace QuantConnect.Algorithm.CSharp
{"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.728"},
{"Portfolio Turnover", "0.248"},
{"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%"},
{"Portfolio Turnover", "19.93%"},
{"OrderListHash", "9e4bfd2eb0b81ee5bc1b197a87ccedbe"}
};
}

View File

@@ -43,9 +43,6 @@ namespace QuantConnect.Algorithm.CSharp
DefaultOrderProperties = new AtreyuOrderProperties
{
// Can specify the default exchange to execute an order on.
// If not specified will default to the primary exchange
Exchange = Exchange.NASDAQ,
// Currently only support order for the day
TimeInForce = TimeInForce.Day
};
@@ -59,10 +56,8 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!Portfolio.Invested)
{
// will set 25% of our buying power with a market order that will be routed to exchange set in the default order properties (NASDAQ)
// will set 25% of our buying power with a market order
SetHoldings("SPY", 0.25m);
// will increase our SPY holdings to 50% of our buying power with a market order that will be routed to ARCA
SetHoldings("SPY", 0.50m, orderProperties: new AtreyuOrderProperties { Exchange = Exchange.ARCA });
Debug("Purchased SPY!");
}
@@ -78,53 +73,45 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 3901;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "93.443%"},
{"Drawdown", "1.100%"},
{"Compounding Annual Return", "39.143%"},
{"Drawdown", "0.500%"},
{"Expectancy", "0"},
{"Net Profit", "0.847%"},
{"Sharpe Ratio", "6.515"},
{"Probabilistic Sharpe Ratio", "67.535%"},
{"Net Profit", "0.423%"},
{"Sharpe Ratio", "5.634"},
{"Probabilistic Sharpe Ratio", "67.498%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0.11"},
{"Annual Variance", "0.012"},
{"Information Ratio", "6.515"},
{"Tracking Error", "0.11"},
{"Annual Standard Deviation", "0.055"},
{"Annual Variance", "0.003"},
{"Information Ratio", "5.634"},
{"Tracking Error", "0.055"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.52"},
{"Estimated Strategy Capacity", "$8600000.00"},
{"Total Fees", "$0.60"},
{"Estimated Strategy Capacity", "$150000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.124"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "78.376"},
{"Portfolio Turnover", "0.124"},
{"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", "cb542eaaeab5eac3bcae5d915ded30da"}
{"Portfolio Turnover", "4.98%"},
{"OrderListHash", "d549c64ee7f5e3866712b3c7dbd64caa"}
};
}
}

View File

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

View File

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

View File

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

View File

@@ -198,6 +198,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 12965;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 240;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -225,25 +235,7 @@ namespace QuantConnect.Algorithm.CSharp
{"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"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-43.943"},
{"Portfolio Turnover", "1.028"},
{"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%"},
{"Portfolio Turnover", "118.08%"},
{"OrderListHash", "1bf1a6d9dd921982b72a6178f9e50e68"}
};
}

View File

@@ -0,0 +1,274 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Brokerages;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Data.Market;
using System.Collections.Generic;
using QuantConnect.Securities.CryptoFuture;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Minute resolution regression algorithm trading Coin and USDT binance futures long and short asserting the behavior
/// </summary>
public class BasicTemplateCryptoFutureAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Dictionary<Symbol, int> _interestPerSymbol = new();
private CryptoFuture _btcUsd;
private CryptoFuture _adaUsdt;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2022, 12, 13); // Set Start Date
SetEndDate(2022, 12, 13); // Set End Date
SetTimeZone(NodaTime.DateTimeZone.Utc);
try
{
SetBrokerageModel(BrokerageName.BinanceFutures, AccountType.Cash);
}
catch (InvalidOperationException)
{
// expected, we don't allow cash account type
}
SetBrokerageModel(BrokerageName.BinanceFutures, AccountType.Margin);
_btcUsd = AddCryptoFuture("BTCUSD");
_adaUsdt = AddCryptoFuture("ADAUSDT");
_fast = EMA(_btcUsd.Symbol, 30, Resolution.Minute);
_slow = EMA(_btcUsd.Symbol, 60, Resolution.Minute);
_interestPerSymbol[_btcUsd.Symbol] = 0;
_interestPerSymbol[_adaUsdt.Symbol] = 0;
// Default USD cash, set 1M but it wont be used
SetCash(1000000);
// the amount of BTC we need to hold to trade 'BTCUSD'
_btcUsd.BaseCurrency.SetAmount(0.005m);
// the amount of USDT we need to hold to trade 'ADAUSDT'
_adaUsdt.QuoteCurrency.SetAmount(200);
}
/// <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)
{
var interestRates = data.Get<MarginInterestRate>();
foreach (var interestRate in interestRates)
{
_interestPerSymbol[interestRate.Key]++;
var cachedInterestRate = Securities[interestRate.Key].Cache.GetData<MarginInterestRate>();
if (cachedInterestRate != interestRate.Value)
{
throw new Exception($"Unexpected cached margin interest rate for {interestRate.Key}!");
}
}
if (_fast > _slow)
{
if (!Portfolio.Invested && Transactions.OrdersCount == 0)
{
var ticket = Buy(_btcUsd.Symbol, 50);
if (ticket.Status != OrderStatus.Invalid)
{
throw new Exception($"Unexpected valid order {ticket}, should fail due to margin not sufficient");
}
Buy(_btcUsd.Symbol, 1);
var marginUsed = Portfolio.TotalMarginUsed;
var btcUsdHoldings = _btcUsd.Holdings;
// Coin futures value is 100 USD
var holdingsValueBtcUsd = 100;
if (Math.Abs(btcUsdHoldings.TotalSaleVolume - holdingsValueBtcUsd) > 1)
{
throw new Exception($"Unexpected TotalSaleVolume {btcUsdHoldings.TotalSaleVolume}");
}
if (Math.Abs(btcUsdHoldings.AbsoluteHoldingsCost - holdingsValueBtcUsd) > 1)
{
throw new Exception($"Unexpected holdings cost {btcUsdHoldings.HoldingsCost}");
}
// margin used is based on the maintenance rate
if (Math.Abs(btcUsdHoldings.AbsoluteHoldingsCost * 0.05m - marginUsed) > 1
|| _btcUsd.BuyingPowerModel.GetMaintenanceMargin(_btcUsd) != marginUsed)
{
throw new Exception($"Unexpected margin used {marginUsed}");
}
Buy(_adaUsdt.Symbol, 1000);
marginUsed = Portfolio.TotalMarginUsed - marginUsed;
var adaUsdtHoldings = _adaUsdt.Holdings;
// USDT/BUSD futures value is based on it's price
var holdingsValueUsdt = _adaUsdt.Price * _adaUsdt.SymbolProperties.ContractMultiplier * 1000;
if (Math.Abs(adaUsdtHoldings.TotalSaleVolume - holdingsValueUsdt) > 1)
{
throw new Exception($"Unexpected TotalSaleVolume {adaUsdtHoldings.TotalSaleVolume}");
}
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost - holdingsValueUsdt) > 1)
{
throw new Exception($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
}
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost * 0.05m - marginUsed) > 1
|| _adaUsdt.BuyingPowerModel.GetMaintenanceMargin(_adaUsdt) != marginUsed)
{
throw new Exception($"Unexpected margin used {marginUsed}");
}
// position just opened should be just spread here
var profit = Portfolio.TotalUnrealizedProfit;
if ((5 - Math.Abs(profit)) < 0)
{
throw new Exception($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
}
if (Portfolio.TotalProfit != 0)
{
throw new Exception($"Unexpected TotalProfit {Portfolio.TotalProfit}");
}
}
}
else
{
// let's revert our position and double
if (Time.Hour > 10 && Transactions.OrdersCount == 3)
{
Sell(_btcUsd.Symbol, 3);
var btcUsdHoldings = _btcUsd.Holdings;
if (Math.Abs(btcUsdHoldings.AbsoluteHoldingsCost - 100 * 2) > 1)
{
throw new Exception($"Unexpected holdings cost {btcUsdHoldings.HoldingsCost}");
}
Sell(_adaUsdt.Symbol, 3000);
var adaUsdtHoldings = _adaUsdt.Holdings;
// USDT/BUSD futures value is based on it's price
var holdingsValueUsdt = _adaUsdt.Price * _adaUsdt.SymbolProperties.ContractMultiplier * 2000;
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost - holdingsValueUsdt) > 1)
{
throw new Exception($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
}
// position just opened should be just spread here
var profit = Portfolio.TotalUnrealizedProfit;
if ((5 - Math.Abs(profit)) < 0)
{
throw new Exception($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
}
// we barely did any difference on the previous trade
if ((5 - Math.Abs(Portfolio.TotalProfit)) < 0)
{
throw new Exception($"Unexpected TotalProfit {Portfolio.TotalProfit}");
}
}
}
}
public override void OnEndOfAlgorithm()
{
if (_interestPerSymbol[_adaUsdt.Symbol] != 1)
{
throw new Exception($"Unexpected interest rate count {_interestPerSymbol[_adaUsdt.Symbol]}");
}
if (_interestPerSymbol[_btcUsd.Symbol] != 3)
{
throw new Exception($"Unexpected interest rate count {_interestPerSymbol[_btcUsd.Symbol]}");
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
Debug(Time + " " + 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 { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 7205;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "4"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.65"},
{"Estimated Strategy Capacity", "$500000000.00"},
{"Lowest Capacity Asset", "ADAUSDT 18R"},
{"Portfolio Turnover", "0.16%"},
{"OrderListHash", "254f39d98378b1e7aa397b1f1e49c6cc"}
};
}
}

View File

@@ -0,0 +1,237 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Brokerages;
using QuantConnect.Data.Market;
using System.Collections.Generic;
using QuantConnect.Securities.CryptoFuture;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Hourly regression algorithm trading ADAUSDT binance futures long and short asserting the behavior
/// </summary>
public class BasicTemplateCryptoFutureHourlyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Dictionary<Symbol, int> _interestPerSymbol = new();
private CryptoFuture _adaUsdt;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2022, 12, 13);
SetEndDate(2022, 12, 13);
SetTimeZone(NodaTime.DateTimeZone.Utc);
try
{
SetBrokerageModel(BrokerageName.BinanceCoinFutures, AccountType.Cash);
}
catch (InvalidOperationException)
{
// expected, we don't allow cash account type
}
SetBrokerageModel(BrokerageName.BinanceCoinFutures, AccountType.Margin);
_adaUsdt = AddCryptoFuture("ADAUSDT", Resolution.Hour);
_fast = EMA(_adaUsdt.Symbol, 3, Resolution.Hour);
_slow = EMA(_adaUsdt.Symbol, 6, Resolution.Hour);
_interestPerSymbol[_adaUsdt.Symbol] = 0;
// Default USD cash, set 1M but it wont be used
SetCash(1000000);
// the amount of USDT we need to hold to trade 'ADAUSDT'
_adaUsdt.QuoteCurrency.SetAmount(200);
}
/// <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)
{
var interestRates = data.Get<MarginInterestRate>();
foreach (var interestRate in interestRates)
{
_interestPerSymbol[interestRate.Key]++;
var cachedInterestRate = Securities[interestRate.Key].Cache.GetData<MarginInterestRate>();
if (cachedInterestRate != interestRate.Value)
{
throw new Exception($"Unexpected cached margin interest rate for {interestRate.Key}!");
}
}
if (_fast > _slow)
{
if (!Portfolio.Invested && Transactions.OrdersCount == 0)
{
var ticket = Buy(_adaUsdt.Symbol, 100000);
if(ticket.Status != OrderStatus.Invalid)
{
throw new Exception($"Unexpected valid order {ticket}, should fail due to margin not sufficient");
}
Buy(_adaUsdt.Symbol, 1000);
var marginUsed = Portfolio.TotalMarginUsed;
var adaUsdtHoldings = _adaUsdt.Holdings;
// USDT/BUSD futures value is based on it's price
var holdingsValueUsdt = _adaUsdt.Price * _adaUsdt.SymbolProperties.ContractMultiplier * 1000;
if (Math.Abs(adaUsdtHoldings.TotalSaleVolume - holdingsValueUsdt) > 1)
{
throw new Exception($"Unexpected TotalSaleVolume {adaUsdtHoldings.TotalSaleVolume}");
}
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost - holdingsValueUsdt) > 1)
{
throw new Exception($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
}
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost * 0.05m - marginUsed) > 1
|| _adaUsdt.BuyingPowerModel.GetMaintenanceMargin(_adaUsdt) != marginUsed)
{
throw new Exception($"Unexpected margin used {marginUsed}");
}
// position just opened should be just spread here
var profit = Portfolio.TotalUnrealizedProfit;
if ((5 - Math.Abs(profit)) < 0)
{
throw new Exception($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
}
if (Portfolio.TotalProfit != 0)
{
throw new Exception($"Unexpected TotalProfit {Portfolio.TotalProfit}");
}
}
}
else
{
// let's revert our position and double
if (Time.Hour > 10 && Transactions.OrdersCount == 2)
{
Sell(_adaUsdt.Symbol, 3000);
var adaUsdtHoldings = _adaUsdt.Holdings;
// USDT/BUSD futures value is based on it's price
var holdingsValueUsdt = _adaUsdt.Price * _adaUsdt.SymbolProperties.ContractMultiplier * 2000;
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost - holdingsValueUsdt) > 1)
{
throw new Exception($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
}
// position just opened should be just spread here
var profit = Portfolio.TotalUnrealizedProfit;
if ((5 - Math.Abs(profit)) < 0)
{
throw new Exception($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
}
// we barely did any difference on the previous trade
if ((5 - Math.Abs(Portfolio.TotalProfit)) < 0)
{
throw new Exception($"Unexpected TotalProfit {Portfolio.TotalProfit}");
}
}
if (Time.Hour >= 22 && Transactions.OrdersCount == 3)
{
Liquidate();
}
}
}
public override void OnEndOfAlgorithm()
{
if (_interestPerSymbol[_adaUsdt.Symbol] != 1)
{
throw new Exception($"Unexpected interest rate count {_interestPerSymbol[_adaUsdt.Symbol]}");
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
Debug(Time + " " + 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 { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 50;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.61"},
{"Estimated Strategy Capacity", "$370000000.00"},
{"Lowest Capacity Asset", "ADAUSDT 18R"},
{"Portfolio Turnover", "0.12%"},
{"OrderListHash", "d2c6198197a4d18fa0a81f5933d935a6"}
};
}
}

View File

@@ -63,6 +63,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 73;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -75,40 +85,22 @@ namespace QuantConnect.Algorithm.CSharp
{"Drawdown", "1.200%"},
{"Expectancy", "0"},
{"Net Profit", "3.464%"},
{"Sharpe Ratio", "9.933"},
{"Probabilistic Sharpe Ratio", "82.470%"},
{"Sharpe Ratio", "19.148"},
{"Probabilistic Sharpe Ratio", "97.754%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"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"},
{"Alpha", "-0.005"},
{"Beta", "0.998"},
{"Annual Standard Deviation", "0.138"},
{"Annual Variance", "0.019"},
{"Information Ratio", "-34.028"},
{"Tracking Error", "0"},
{"Treynor Ratio", "2.651"},
{"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", "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"},
{"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%"},
{"Portfolio Turnover", "10.09%"},
{"OrderListHash", "33d01821923c397f999cfb2e5b5928ad"}
};
}

View File

@@ -84,6 +84,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 3943;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -111,25 +121,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Fees", "$10.32"},
{"Estimated Strategy Capacity", "$27000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.747"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "85.095"},
{"Portfolio Turnover", "0.747"},
{"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", "$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%"},
{"Portfolio Turnover", "59.86%"},
{"OrderListHash", "ad2216297c759d8e5aef48ff065f8919"}
};
}

View File

@@ -0,0 +1,95 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Algorithm demonstrating FutureOption asset types and requesting history.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="history" />
/// <meta name="tag" content="future option" />
public class BasicTemplateFutureOptionAlgorithm : QCAlgorithm
{
private Symbol _symbol;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2022, 1, 1);
SetEndDate(2022, 2, 1);
SetCash(100000);
var gold_futures = AddFuture(Futures.Metals.Gold, Resolution.Minute);
gold_futures.SetFilter(0, 180);
_symbol = gold_futures.Symbol;
AddFutureOption(_symbol, universe => universe.Strikes(-5, +5)
.CallsOnly()
.BackMonth()
.OnlyApplyFilterAtMarketOpen());
// Historical Data
var history = History(_symbol, 60, Resolution.Daily);
Log($"Received {history.Count()} bars from {_symbol} FutureOption historical data call.");
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice slice)
{
// Access Data
foreach(var kvp in slice.OptionChains)
{
var underlyingFutureContract = kvp.Key.Underlying;
var chain = kvp.Value;
if (chain.Count() == 0) continue;
foreach(var contract in chain)
{
Log($@"Canonical Symbol: {kvp.Key};
Contract: {contract};
Right: {contract.Right};
Expiry: {contract.Expiry};
Bid price: {contract.BidPrice};
Ask price: {contract.AskPrice};
Implied Volatility: {contract.ImpliedVolatility}");
}
if (!Portfolio.Invested)
{
var atmStrike = chain.OrderBy(x => Math.Abs(chain.Underlying.Price - x.Strike)).First().Strike;
var selectedContract = chain.Where(x => x.Strike == atmStrike).OrderByDescending(x => x.Expiry).First();
MarketOrder(selectedContract.Symbol, 1);
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
Debug($"{Time} {orderEvent.ToString()}");
}
}
}

View File

@@ -0,0 +1,217 @@
/*
* 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;
using QuantConnect.Indicators;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Example algorithm for trading continuous future
/// </summary>
public class BasicTemplateFutureRolloverAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Dictionary<Symbol, SymbolData> _symbolDataBySymbol = new();
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 8);
SetEndDate(2013, 12, 10);
SetCash(1000000);
var futures = new List<string> {
Futures.Indices.SP500EMini
};
foreach (var future in futures)
{
// Requesting data
var continuousContract = AddFuture(future,
resolution: Resolution.Daily,
extendedMarketHours: true,
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
dataMappingMode: DataMappingMode.OpenInterest,
contractDepthOffset: 0
);
var symbolData = new SymbolData(this, continuousContract);
_symbolDataBySymbol.Add(continuousContract.Symbol, symbolData);
}
}
/// <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)
{
foreach (var kvp in _symbolDataBySymbol)
{
var symbol = kvp.Key;
var symbolData = kvp.Value;
// Call SymbolData.Update() method to handle new data slice received
symbolData.Update(slice);
// Check if information in SymbolData class and new slice data are ready for trading
if (!symbolData.IsReady || !slice.Bars.ContainsKey(symbol))
{
return;
}
var emaCurrentValue = symbolData.EMA.Current.Value;
if (emaCurrentValue < symbolData.Price && !symbolData.IsLong)
{
MarketOrder(symbolData.Mapped, 1);
}
else if (emaCurrentValue > symbolData.Price && !symbolData.IsShort)
{
MarketOrder(symbolData.Mapped, -1);
}
}
}
/// <summary>
/// Abstracted class object to hold information (state, indicators, methods, etc.) from a Symbol/Security in a multi-security algorithm
/// </summary>
public class SymbolData
{
private QCAlgorithm _algorithm;
private Future _future;
public ExponentialMovingAverage EMA;
public decimal Price;
public bool IsLong;
public bool IsShort;
public Symbol Symbol => _future.Symbol;
public Symbol Mapped => _future.Mapped;
/// <summary>
/// Check if symbolData class object are ready for trading
/// </summary>
public bool IsReady => Mapped != null && EMA.IsReady;
/// <summary>
/// Constructor to instantiate the information needed to be hold
/// </summary>
public SymbolData(QCAlgorithm algorithm, Future future)
{
_algorithm = algorithm;
_future = future;
EMA = algorithm.EMA(future.Symbol, 20, Resolution.Daily);
Reset();
}
/// <summary>
/// Handler of new slice of data received
/// </summary>
public void Update(Slice slice)
{
if (slice.SymbolChangedEvents.TryGetValue(Symbol, out var changedEvent))
{
var oldSymbol = changedEvent.OldSymbol;
var newSymbol = changedEvent.NewSymbol;
var tag = $"Rollover - Symbol changed at {_algorithm.Time}: {oldSymbol} -> {newSymbol}";
var quantity = _algorithm.Portfolio[oldSymbol].Quantity;
// Rolling over: to liquidate any position of the old mapped contract and switch to the newly mapped contract
_algorithm.Liquidate(oldSymbol, tag: tag);
_algorithm.MarketOrder(newSymbol, quantity, tag: tag);
Reset();
}
Price = slice.Bars.ContainsKey(Symbol) ? slice.Bars[Symbol].Price : Price;
IsLong = _algorithm.Portfolio[Mapped].IsLong;
IsShort = _algorithm.Portfolio[Mapped].IsShort;
}
/// <summary>
/// Reset RollingWindow/indicator to adapt to newly mapped contract, then warm up the RollingWindow/indicator
/// </summary>
private void Reset()
{
EMA.Reset();
_algorithm.WarmUpIndicator(Symbol, EMA, Resolution.Daily);
}
/// <summary>
/// Disposal method to remove consolidator/update method handler, and reset RollingWindow/indicator to free up memory and speed
/// </summary>
public void Dispose()
{
EMA.Reset();
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1345;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 4;
/// <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.53%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "3.011%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0"},
{"Net Profit", "0.528%"},
{"Sharpe Ratio", "1.999"},
{"Probabilistic Sharpe Ratio", "83.704%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.023"},
{"Beta", "-0.004"},
{"Annual Standard Deviation", "0.011"},
{"Annual Variance", "0"},
{"Information Ratio", "-4.774"},
{"Tracking Error", "0.084"},
{"Treynor Ratio", "-4.853"},
{"Total Fees", "$4.30"},
{"Estimated Strategy Capacity", "$5900000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Portfolio Turnover", "0.27%"},
{"OrderListHash", "40e4b91ec89383f6501d9ba324e50eb9"}
};
}
}

View File

@@ -18,6 +18,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
@@ -58,12 +59,15 @@ namespace QuantConnect.Algorithm.CSharp
// set our expiry filter for this futures chain
// SetFilter method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
// The following statements yield the same filtering criteria
futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
futureGold.SetFilter(0, 182);
var benchmark = AddEquity("SPY");
SetBenchmark(benchmark.Symbol);
var seeder = new FuncSecuritySeeder(GetLastKnownPrices);
SetSecurityInitializer(security => seeder.SeedSecurity(security));
}
/// <summary>
@@ -72,6 +76,15 @@ namespace QuantConnect.Algorithm.CSharp
/// <param name="slice">The current slice of data keyed by symbol string</param>
public override void OnData(Slice slice)
{
foreach (var changedEvent in slice.SymbolChangedEvents.Values)
{
Debug($"{Time} - SymbolChanged event: {changedEvent}");
if (Time.TimeOfDay != TimeSpan.Zero)
{
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
if (!Portfolio.Invested)
{
foreach(var chain in slice.FutureChains)
@@ -112,6 +125,19 @@ namespace QuantConnect.Algorithm.CSharp
var maintenanceIntraday = futureMarginModel.MaintenanceIntradayMarginRequirement;
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var addedSecurity in changes.AddedSecurities)
{
if (addedSecurity.Symbol.SecurityType == SecurityType.Future
&& !addedSecurity.Symbol.IsCanonical()
&& !addedSecurity.HasData)
{
throw new Exception($"Future contracts did not work up as expected: {addedSecurity.Symbol}");
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
@@ -122,53 +148,45 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 68645;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 340;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "8220"},
{"Total Trades", "2700"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "13.500%"},
{"Expectancy", "-0.818"},
{"Net Profit", "-13.517%"},
{"Sharpe Ratio", "-2.678"},
{"Compounding Annual Return", "-99.777%"},
{"Drawdown", "4.400%"},
{"Expectancy", "-0.724"},
{"Net Profit", "-4.430%"},
{"Sharpe Ratio", "-31.389"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "89%"},
{"Win Rate", "11%"},
{"Profit-Loss Ratio", "0.69"},
{"Alpha", "4.469"},
{"Beta", "-0.961"},
{"Annual Standard Deviation", "0.373"},
{"Annual Variance", "0.139"},
{"Information Ratio", "-13.191"},
{"Tracking Error", "0.507"},
{"Treynor Ratio", "1.04"},
{"Total Fees", "$15207.00"},
{"Estimated Strategy Capacity", "$8000.00"},
{"Loss Rate", "83%"},
{"Win Rate", "17%"},
{"Profit-Loss Ratio", "0.65"},
{"Alpha", "-3.059"},
{"Beta", "0.128"},
{"Annual Standard Deviation", "0.031"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-81.232"},
{"Tracking Error", "0.212"},
{"Treynor Ratio", "-7.618"},
{"Total Fees", "$6237.00"},
{"Estimated Strategy Capacity", "$14000.00"},
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
{"Fitness Score", "0.033"},
{"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"}
{"Portfolio Turnover", "9912.69%"},
{"OrderListHash", "8f92e1528c6477a156449fd1e86527e7"}
};
}
}

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 System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to add futures with daily resolution.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="benchmarks" />
/// <meta name="tag" content="futures" />
public class BasicTemplateFuturesDailyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected virtual Resolution Resolution => Resolution.Daily;
protected virtual bool ExtendedMarketHours => false;
// S&P 500 EMini futures
private const string RootSP500 = Futures.Indices.SP500EMini;
// Gold futures
private const string RootGold = Futures.Metals.Gold;
private Future _futureSP500;
private Future _futureGold;
/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 08);
SetEndDate(2014, 10, 10);
SetCash(1000000);
_futureSP500 = AddFuture(RootSP500, Resolution, extendedMarketHours: ExtendedMarketHours);
_futureGold = AddFuture(RootGold, Resolution, extendedMarketHours: ExtendedMarketHours);
// set our expiry filter for this futures chain
// SetFilter method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
_futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
_futureGold.SetFilter(0, 182);
}
/// <summary>
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
/// </summary>
/// <param name="slice">The current slice of data keyed by symbol string</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
foreach(var chain in slice.FutureChains)
{
// find the front contract expiring no earlier than in 90 days
var contract = (
from futuresContract in chain.Value.OrderBy(x => x.Expiry)
where futuresContract.Expiry > Time.Date.AddDays(90)
select futuresContract
).FirstOrDefault();
// if found, trade it.
// Also check if exchange is open for regular or extended hours. Since daily data comes at 8PM, this allows us prevent the
// algorithm from trading on friday when there is not after-market.
if (contract != null && Securities[contract.Symbol].Exchange.Hours.IsOpen(Time, true))
{
MarketOrder(contract.Symbol, 1);
}
}
}
// Same as above, check for cases like trading on a friday night.
else if (Securities.Values.Where(x => x.Invested).All(x => x.Exchange.Hours.IsOpen(Time, true)))
{
Liquidate();
}
foreach (var changedEvent in slice.SymbolChangedEvents.Values)
{
if (Time.TimeOfDay != TimeSpan.Zero)
{
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
}
/// <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 virtual bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 15217;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "118"},
{"Average Win", "0.09%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-0.479%"},
{"Drawdown", "0.500%"},
{"Expectancy", "-0.835"},
{"Net Profit", "-0.483%"},
{"Sharpe Ratio", "-1.938"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "98%"},
{"Win Rate", "2%"},
{"Profit-Loss Ratio", "8.76"},
{"Alpha", "-0.003"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.397"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "5.665"},
{"Total Fees", "$263.30"},
{"Estimated Strategy Capacity", "$1000.00"},
{"Lowest Capacity Asset", "ES VRJST036ZY0X"},
{"Portfolio Turnover", "3.15%"},
{"OrderListHash", "b75b224669c374dcbacc33f946a1cc7c"}
};
}
}

View File

@@ -31,9 +31,12 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public class BasicTemplateFuturesFrameworkAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected virtual bool ExtendedMarketHours => false;
public override void Initialize()
{
UniverseSettings.Resolution = Resolution.Minute;
UniverseSettings.ExtendedMarketHours = ExtendedMarketHours;
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);
@@ -123,60 +126,52 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
public virtual bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 43786;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-92.656%"},
{"Drawdown", "5.000%"},
{"Compounding Annual Return", "-81.734%"},
{"Drawdown", "4.100%"},
{"Expectancy", "0"},
{"Net Profit", "-3.312%"},
{"Sharpe Ratio", "-7.795"},
{"Probabilistic Sharpe Ratio", "0.164%"},
{"Net Profit", "-2.169%"},
{"Sharpe Ratio", "-10.195"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-1.362"},
{"Beta", "0.257"},
{"Annual Standard Deviation", "0.109"},
{"Annual Variance", "0.012"},
{"Information Ratio", "-14.947"},
{"Tracking Error", "0.19"},
{"Treynor Ratio", "-3.309"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$52000000.00"},
{"Alpha", "-1.206"},
{"Beta", "0.238"},
{"Annual Standard Deviation", "0.072"},
{"Annual Variance", "0.005"},
{"Information Ratio", "-15.404"},
{"Tracking Error", "0.176"},
{"Treynor Ratio", "-3.077"},
{"Total Fees", "$4.62"},
{"Estimated Strategy Capacity", "$17000000.00"},
{"Lowest Capacity Asset", "GC VL5E74HP3EE5"},
{"Fitness Score", "0.009"},
{"Kelly Criterion Estimate", "-112.972"},
{"Kelly Criterion Probability Value", "0.671"},
{"Sortino Ratio", "-8.425"},
{"Return Over Maximum Drawdown", "-35.219"},
{"Portfolio Turnover", "0.548"},
{"Total Insights Generated", "6"},
{"Total Insights Closed", "5"},
{"Total Insights Analysis Completed", "5"},
{"Long Insight Count", "6"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$-96.12923"},
{"Total Accumulated Estimated Alpha Value", "$-15.621"},
{"Mean Population Estimated Insight Value", "$-3.1242"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "18ffd3a774c68da83d867e3b09e3e05d"}
{"Portfolio Turnover", "43.23%"},
{"OrderListHash", "323b899ae80aa839e320806411665ce7"}
};
}
}

View File

@@ -0,0 +1,77 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Basic template futures framework algorithm uses framework components to define an algorithm
/// that trades futures.
/// </summary>
public class BasicTemplateFuturesFrameworkWithExtendedMarketAlgorithm : BasicTemplateFuturesFrameworkAlgorithm
{
protected override bool ExtendedMarketHours => true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 123753;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-92.667%"},
{"Drawdown", "5.000%"},
{"Expectancy", "0"},
{"Net Profit", "-3.314%"},
{"Sharpe Ratio", "-6.303"},
{"Probabilistic Sharpe Ratio", "9.333%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-1.465"},
{"Beta", "0.312"},
{"Annual Standard Deviation", "0.134"},
{"Annual Variance", "0.018"},
{"Information Ratio", "-14.77"},
{"Tracking Error", "0.192"},
{"Treynor Ratio", "-2.718"},
{"Total Fees", "$4.62"},
{"Estimated Strategy Capacity", "$52000000.00"},
{"Lowest Capacity Asset", "GC VL5E74HP3EE5"},
{"Portfolio Turnover", "43.77%"},
{"OrderListHash", "18ffd3a774c68da83d867e3b09e3e05d"}
};
}
}

View File

@@ -36,6 +36,9 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="futures" />
public class BasicTemplateFuturesHistoryAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected virtual bool ExtendedMarketHours => false;
protected virtual int ExpectedHistoryCallCount => 42;
// S&P 500 EMini futures
private string [] roots = new []
{
@@ -44,7 +47,6 @@ namespace QuantConnect.Algorithm.CSharp
};
private int _successCount = 0;
public override void Initialize()
{
SetStartDate(2013, 10, 8);
@@ -54,7 +56,7 @@ namespace QuantConnect.Algorithm.CSharp
foreach (var root in roots)
{
// set our expiry filter for this futures chain
AddFuture(root, Resolution.Minute).SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
AddFuture(root, Resolution.Minute, extendedMarketHours: ExtendedMarketHours).SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
}
SetBenchmark(d => 1000000);
@@ -74,7 +76,7 @@ namespace QuantConnect.Algorithm.CSharp
public override void OnEndOfAlgorithm()
{
if (_successCount < 49)
if (_successCount < ExpectedHistoryCallCount)
{
throw new Exception($"Scheduled Event did not assert history call as many times as expected: {_successCount}/49");
}
@@ -118,7 +120,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Order fill event handler. On an order fill update the resulting information is passed to this method.
/// </summary>
/// <param name="orderEvent">Order event details containing details of the evemts</param>
/// <param name="orderEvent">Order event details containing details of the events</param>
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
public override void OnOrderEvent(OrderEvent orderEvent)
{
@@ -128,17 +130,27 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
public virtual bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 44184;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 4818;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},
@@ -162,25 +174,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"Portfolio Turnover", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}

View File

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

View File

@@ -0,0 +1,77 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regressions tests the BasicTemplateFuturesDailyAlgorithm with hour data
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="benchmarks" />
/// <meta name="tag" content="futures" />
public class BasicTemplateFuturesHourlyAlgorithm : BasicTemplateFuturesDailyAlgorithm
{
protected override Resolution Resolution => Resolution.Hour;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 96027;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "638"},
{"Average Win", "0.02%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-1.610%"},
{"Drawdown", "1.600%"},
{"Expectancy", "-0.841"},
{"Net Profit", "-1.622%"},
{"Sharpe Ratio", "-5.105"},
{"Probabilistic Sharpe Ratio", "0.000%"},
{"Loss Rate", "96%"},
{"Win Rate", "4%"},
{"Profit-Loss Ratio", "3.21"},
{"Alpha", "-0.01"},
{"Beta", "-0.003"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.473"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "3.179"},
{"Total Fees", "$1456.18"},
{"Estimated Strategy Capacity", "$6000.00"},
{"Lowest Capacity Asset", "ES VP274HSU1AF5"},
{"Portfolio Turnover", "17.91%"},
{"OrderListHash", "8842e0b890f721371ebf3c25328dee5b"}
};
}
}

View File

@@ -0,0 +1,192 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to add futures for a given underlying asset.
/// It also shows how you can prefilter contracts easily based on expirations, and how you
/// can inspect the futures chain to pick a specific contract to trade.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="benchmarks" />
/// <meta name="tag" content="futures" />
public class BasicTemplateFuturesWithExtendedMarketAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _contractSymbol;
// S&P 500 EMini futures
private const string RootSP500 = Futures.Indices.SP500EMini;
public Symbol SP500 = QuantConnect.Symbol.Create(RootSP500, SecurityType.Future, Market.CME);
// Gold futures
private const string RootGold = Futures.Metals.Gold;
public Symbol Gold = QuantConnect.Symbol.Create(RootGold, SecurityType.Future, Market.COMEX);
/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 10);
SetCash(1000000);
var futureSP500 = AddFuture(RootSP500, extendedMarketHours: true);
var futureGold = AddFuture(RootGold, extendedMarketHours: true);
// set our expiry filter for this futures chain
// SetFilter method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
futureGold.SetFilter(0, 182);
var benchmark = AddEquity("SPY");
SetBenchmark(benchmark.Symbol);
var seeder = new FuncSecuritySeeder(GetLastKnownPrices);
SetSecurityInitializer(security => seeder.SeedSecurity(security));
}
/// <summary>
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
/// </summary>
/// <param name="slice">The current slice of data keyed by symbol string</param>
public override void OnData(Slice slice)
{
foreach (var changedEvent in slice.SymbolChangedEvents.Values)
{
Debug($"{Time} - SymbolChanged event: {changedEvent}");
if (Time.TimeOfDay != TimeSpan.Zero)
{
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
if (!Portfolio.Invested)
{
foreach(var chain in slice.FutureChains)
{
// find the front contract expiring no earlier than in 90 days
var contract = (
from futuresContract in chain.Value.OrderBy(x => x.Expiry)
where futuresContract.Expiry > Time.Date.AddDays(90)
select futuresContract
).FirstOrDefault();
// if found, trade it
if (contract != null)
{
_contractSymbol = contract.Symbol;
MarketOrder(_contractSymbol, 1);
}
}
}
else
{
Liquidate();
}
}
public override void OnEndOfAlgorithm()
{
// Get the margin requirements
var buyingPowerModel = Securities[_contractSymbol].BuyingPowerModel;
var futureMarginModel = buyingPowerModel as FutureMarginModel;
if (buyingPowerModel == null)
{
throw new Exception($"Invalid buying power model. Found: {buyingPowerModel.GetType().Name}. Expected: {nameof(FutureMarginModel)}");
}
var initialOvernight = futureMarginModel.InitialOvernightMarginRequirement;
var maintenanceOvernight = futureMarginModel.MaintenanceOvernightMarginRequirement;
var initialIntraday = futureMarginModel.InitialIntradayMarginRequirement;
var maintenanceIntraday = futureMarginModel.MaintenanceIntradayMarginRequirement;
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var addedSecurity in changes.AddedSecurities)
{
if (addedSecurity.Symbol.SecurityType == SecurityType.Future
&& !addedSecurity.Symbol.IsCanonical()
&& !addedSecurity.HasData)
{
throw new Exception($"Future contracts did not work up as expected: {addedSecurity.Symbol}");
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 204087;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 340;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "8282"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "13.900%"},
{"Expectancy", "-0.824"},
{"Net Profit", "-13.874%"},
{"Sharpe Ratio", "-19.202"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "89%"},
{"Win Rate", "11%"},
{"Profit-Loss Ratio", "0.64"},
{"Alpha", "2.477"},
{"Beta", "-0.215"},
{"Annual Standard Deviation", "0.052"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-58.37"},
{"Tracking Error", "0.295"},
{"Treynor Ratio", "4.66"},
{"Total Fees", "$19131.42"},
{"Estimated Strategy Capacity", "$130000.00"},
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
{"Portfolio Turnover", "32523.20%"},
{"OrderListHash", "85cdd035d7c7a3da178d1c2dff31f1bd"}
};
}
}

View File

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

View File

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

View File

@@ -0,0 +1,116 @@
/*
* 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>
/// Basic template algorithm simply initializes the date range and cash. This is a skeleton
/// framework you can use for designing an algorithm.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="using quantconnect" />
/// <meta name="tag" content="trading and orders" />
public class BasicTemplateHourlyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 07); //Set Start Date
SetEndDate(2013, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
// Find more symbols here: http://quantconnect.com/data
// Forex, CFD, Equities Resolutions: Tick, Second, Minute, Hour, Daily.
// Futures Resolution: Tick, Second, Minute
// Options Resolution: Minute Only.
AddEquity("SPY", Resolution.Hour);
// There are other assets with similar methods. See "Selecting Options" etc for more details.
// AddFuture, AddForex, AddCfd, AddOption
}
/// <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(_spy, 1);
Debug("Purchased Stock");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 78;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "227.693%"},
{"Drawdown", "2.000%"},
{"Expectancy", "0"},
{"Net Profit", "1.529%"},
{"Sharpe Ratio", "8.889"},
{"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.222"},
{"Annual Variance", "0.049"},
{"Information Ratio", "-14.564"},
{"Tracking Error", "0.001"},
{"Treynor Ratio", "1.978"},
{"Total Fees", "$3.44"},
{"Estimated Strategy Capacity", "$110000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "19.96%"},
{"OrderListHash", "f409be3a7c63d9c1394c2e6c005a15ee"}
};
}
}

View File

@@ -30,36 +30,39 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="indexes" />
public class BasicTemplateIndexAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spx;
private Symbol _spxOption;
protected Symbol Spx;
protected Symbol SpxOption;
private ExponentialMovingAverage _emaSlow;
private ExponentialMovingAverage _emaFast;
protected virtual Resolution Resolution => Resolution.Minute;
protected virtual int StartDay => 4;
/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
public override void Initialize()
{
SetStartDate(2021, 1, 4);
SetEndDate(2021, 1, 15);
SetStartDate(2021, 1, StartDay);
SetEndDate(2021, 1, 18);
SetCash(1000000);
// Use indicator for signal; but it cannot be traded
_spx = AddIndex("SPX", Resolution.Minute).Symbol;
Spx = AddIndex("SPX", Resolution).Symbol;
// Trade on SPX ITM calls
_spxOption = QuantConnect.Symbol.CreateOption(
_spx,
SpxOption = QuantConnect.Symbol.CreateOption(
Spx,
Market.USA,
OptionStyle.European,
OptionRight.Call,
3200m,
new DateTime(2021, 1, 15));
AddIndexOptionContract(_spxOption, Resolution.Minute);
AddIndexOptionContract(SpxOption, Resolution);
_emaSlow = EMA(_spx, 80);
_emaFast = EMA(_spx, 200);
_emaSlow = EMA(Spx, 80);
_emaFast = EMA(Spx, 200);
}
/// <summary>
@@ -67,7 +70,7 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public override void OnData(Slice slice)
{
if (!slice.Bars.ContainsKey(_spx) || !slice.Bars.ContainsKey(_spxOption))
if (!slice.Bars.ContainsKey(Spx) || !slice.Bars.ContainsKey(SpxOption))
{
return;
}
@@ -80,7 +83,7 @@ namespace QuantConnect.Algorithm.CSharp
if (_emaFast > _emaSlow)
{
SetHoldings(_spxOption, 1);
SetHoldings(SpxOption, 1);
}
else
{
@@ -90,7 +93,7 @@ namespace QuantConnect.Algorithm.CSharp
public override void OnEndOfAlgorithm()
{
if (Portfolio[_spx].TotalSaleVolume > 0)
if (Portfolio[Spx].TotalSaleVolume > 0)
{
throw new Exception("Index is not tradable.");
}
@@ -99,60 +102,52 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
public virtual bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 16049;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
public virtual 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%"},
{"Total Trades", "3"},
{"Average Win", "6.15%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "435.569%"},
{"Drawdown", "3.400%"},
{"Expectancy", "0"},
{"Net Profit", "5.516%"},
{"Sharpe Ratio", "-6.262"},
{"Probabilistic Sharpe Ratio", "0.011%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"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"},
{"Alpha", "-0.223"},
{"Beta", "0.02"},
{"Annual Standard Deviation", "0.034"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-7.032"},
{"Tracking Error", "0.107"},
{"Treynor Ratio", "-10.779"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$14000000.00"},
{"Estimated Strategy Capacity", "$2000.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"}
{"Portfolio Turnover", "24.07%"},
{"OrderListHash", "5dbee236086bb2c39e2fbeac068280fd"}
};
}
}

View File

@@ -0,0 +1,93 @@
/*
* 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;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression for running an Index algorithm with Daily data
/// </summary>
public class BasicTemplateIndexDailyAlgorithm : BasicTemplateIndexAlgorithm
{
protected override Resolution Resolution => Resolution.Daily;
protected override int StartDay => 1;
// two complete weeks starting from the 5th. The 18th bar is not included since it is a holiday
protected virtual int ExpectedBarCount => 2 * 5;
protected int BarCounter = 0;
/// <summary>
/// Purchase a contract when we are not invested, liquidate otherwise
/// </summary>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
// SPX Index is not tradable, but we can trade an option
MarketOrder(SpxOption, 1);
}
else
{
Liquidate();
}
// Count how many slices we receive with SPX data in it to assert later
if (slice.ContainsKey(Spx))
{
BarCounter++;
}
}
public override void OnEndOfAlgorithm()
{
if (BarCounter != ExpectedBarCount)
{
throw new ArgumentException($"Bar Count {BarCounter} is not expected count of {ExpectedBarCount}");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public override bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 0;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -0,0 +1,64 @@
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression for running an Index algorithm with Hourly data
/// </summary>
public class BasicTemplateIndexHourlyAlgorithm : BasicTemplateIndexDailyAlgorithm
{
protected override Resolution Resolution => Resolution.Hour;
protected override int ExpectedBarCount => base.ExpectedBarCount * 7;
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public override bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 391;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "71"},
{"Average Win", "1.28%"},
{"Average Loss", "-0.06%"},
{"Compounding Annual Return", "-20.546%"},
{"Drawdown", "1.800%"},
{"Expectancy", "-0.402"},
{"Net Profit", "-0.922%"},
{"Sharpe Ratio", "-2.856"},
{"Probabilistic Sharpe Ratio", "22.230%"},
{"Loss Rate", "97%"},
{"Win Rate", "3%"},
{"Profit-Loss Ratio", "19.95"},
{"Alpha", "-0.155"},
{"Beta", "0.025"},
{"Annual Standard Deviation", "0.053"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-2.07"},
{"Tracking Error", "0.121"},
{"Treynor Ratio", "-6.089"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$200000.00"},
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
{"Portfolio Turnover", "24.63%"},
{"OrderListHash", "9e974939d13fd3255c6291a65d2c1eb9"}
};
}
}

View File

@@ -30,20 +30,22 @@ namespace QuantConnect.Algorithm.CSharp
private Symbol _spx;
private ExponentialMovingAverage _emaSlow;
private ExponentialMovingAverage _emaFast;
protected virtual Resolution Resolution => Resolution.Minute;
protected virtual int StartDay => 4;
/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
public override void Initialize()
{
SetStartDate(2021, 1, 4);
SetStartDate(2021, 1, StartDay);
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);
_spx = AddIndex("SPX", Resolution).Symbol;
var spxOptions = AddIndexOption(_spx, Resolution);
spxOptions.SetFilter(filterFunc => filterFunc.CallsOnly());
_emaSlow = EMA(_spx, 80);
@@ -122,17 +124,27 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
public virtual 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 };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 0;
/// </summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "8220"},
{"Average Win", "0.00%"},

View File

@@ -0,0 +1,85 @@
/*
* 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 System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression for running an IndexOptions algorithm with Daily data
/// </summary>
public class BasicTemplateIndexOptionsDailyAlgorithm : BasicTemplateIndexOptionsAlgorithm
{
protected override Resolution Resolution => Resolution.Daily;
protected override int StartDay => 1;
/// <summary>
/// Index EMA Cross trading index options of the index.
/// </summary>
public override void OnData(Slice slice)
{
foreach (var chain in slice.OptionChains.Values)
{
// Select the contract with the lowest AskPrice
var contract = chain.Contracts.OrderBy(x => x.Value.AskPrice).FirstOrDefault().Value;
if (contract == null)
{
return;
}
if (Portfolio.Invested)
{
Liquidate();
}
else
{
MarketOrder(contract.Symbol, 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 override bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 0;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -0,0 +1,79 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression for running an IndexOptions algorithm with Hourly data
/// </summary>
public class BasicTemplateIndexOptionsHourlyAlgorithm : BasicTemplateIndexOptionsDailyAlgorithm
{
protected override Resolution Resolution => Resolution.Hour;
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public override bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public override Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 2143;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "72"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-0.006%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-0.486"},
{"Net Profit", "0.000%"},
{"Sharpe Ratio", "-1.628"},
{"Probabilistic Sharpe Ratio", "17.439%"},
{"Loss Rate", "97%"},
{"Win Rate", "3%"},
{"Profit-Loss Ratio", "17.50"},
{"Alpha", "-0"},
{"Beta", "-0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.449"},
{"Tracking Error", "0.138"},
{"Treynor Ratio", "1.87"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "SPX XL80P59H5E6M|SPX 31"},
{"Portfolio Turnover", "0.00%"},
{"OrderListHash", "0df3713aeb32e9c0738200f2a109e2f9"}
};
}
}

View File

@@ -14,8 +14,9 @@
*/
using QuantConnect.Data;
using QuantConnect.Orders;
using System.Collections.Generic;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
namespace QuantConnect.Algorithm.CSharp
{
@@ -26,29 +27,29 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="using quantconnect" />
/// <meta name="tag" content="trading and orders" />
public class BasicTemplateIndiaAlgorithm : QCAlgorithm
public class BasicTemplateIndiaAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2003, 10, 07); //Set Start Date
SetEndDate(2003, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
SetAccountCurrency("INR"); //Set Account Currency
SetStartDate(2019, 1, 23); //Set Start Date
SetEndDate(2019, 10, 31); //Set End Date
SetCash(100000); //Set Strategy Cash
// Find more symbols here: http://quantconnect.com/data
// Equities Resolutions: Tick, Second, Minute, Hour, Daily.
AddEquity("UNIONBANK", Resolution.Second, Market.India);
//Set Order Prperties as per the requirements for order placement
DefaultOrderProperties = new ZerodhaOrderProperties(exchange: Exchange.NSE);
AddEquity("YESBANK", Resolution.Minute, Market.India);
//Set Order Properties as per the requirements for order placement
DefaultOrderProperties = new IndiaOrderProperties(exchange: Exchange.NSE);
//override default productType value set in config.json if needed - order specific productType value
//DefaultOrderProperties = new ZerodhaOrderProperties(exchange: "nse",ZerodhaOrderProperties.KiteProductType.CNC);
//DefaultOrderProperties = new IndiaOrderProperties(exchange: Exchange.NSE, IndiaOrderProperties.IndiaProductType.CNC);
// General Debug statement for acknowledgement
Debug("Intialization Done");
Debug("Initialization Done");
}
/// <summary>
@@ -59,11 +60,10 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!Portfolio.Invested)
{
var marketTicket = MarketOrder("UNIONBANK", 1);
var marketTicket = MarketOrder("YESBANK", 1);
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Status.IsFill())
@@ -75,60 +75,52 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
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 };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 29524;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "-1.01%"},
{"Compounding Annual Return", "261.134%"},
{"Drawdown", "2.200%"},
{"Expectancy", "-1"},
{"Net Profit", "1.655%"},
{"Sharpe Ratio", "8.505"},
{"Probabilistic Sharpe Ratio", "66.840%"},
{"Loss Rate", "100%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-0.010%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0"},
{"Net Profit", "-0.008%"},
{"Sharpe Ratio", "-1.183"},
{"Probabilistic Sharpe Ratio", "0.001%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.091"},
{"Beta", "1.006"},
{"Annual Standard Deviation", "0.224"},
{"Annual Variance", "0.05"},
{"Information Ratio", "-33.445"},
{"Tracking Error", "0.002"},
{"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.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "85.095"},
{"Portfolio Turnover", "0.747"},
{"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", "$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"}
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.183"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "₹6.00"},
{"Estimated Strategy Capacity", "₹61000000000.00"},
{"Lowest Capacity Asset", "YESBANK UL"},
{"Portfolio Turnover", "0.00%"},
{"OrderListHash", "6cc69218edd7bd461678b9ee0c575db5"}
};
}
}

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 System.Collections.Generic;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
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 BasicTemplateIndiaIndexAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected Symbol Nifty;
protected Symbol NiftyETF;
private ExponentialMovingAverage _emaSlow;
private ExponentialMovingAverage _emaFast;
/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
public override void Initialize()
{
SetAccountCurrency("INR"); //Set Account Currency
SetStartDate(2019, 1, 1); //Set End Date
SetEndDate(2019, 1, 5); //Set End Date
SetCash(1000000); //Set Strategy Cash
// Use indicator for signal; but it cannot be traded
Nifty = AddIndex("NIFTY50", Resolution.Minute, Market.India).Symbol;
//Trade Index based ETF
NiftyETF = AddEquity("JUNIORBEES", Resolution.Minute, Market.India).Symbol;
//Set Order Properties as per the requirements for order placement
DefaultOrderProperties = new IndiaOrderProperties(exchange: Exchange.NSE);
_emaSlow = EMA(Nifty, 80);
_emaFast = EMA(Nifty, 200);
}
/// <summary>
/// Index EMA Cross trading underlying.
/// </summary>
public override void OnData(Slice slice)
{
if (!slice.Bars.ContainsKey(Nifty) || !slice.Bars.ContainsKey(NiftyETF))
{
return;
}
// Warm up indicators
if (!_emaSlow.IsReady)
{
return;
}
if (_emaFast > _emaSlow)
{
if (!Portfolio.Invested)
{
var marketTicket = MarketOrder(NiftyETF, 1);
}
}
else
{
Liquidate();
}
}
public override void OnEndOfAlgorithm()
{
if (Portfolio[Nifty].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 virtual bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 2882;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "6"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-0.386%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.004%"},
{"Sharpe Ratio", "-23.595"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-23.595"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "₹36.00"},
{"Estimated Strategy Capacity", "₹84000.00"},
{"Lowest Capacity Asset", "JUNIORBEES UL"},
{"Portfolio Turnover", "0.04%"},
{"OrderListHash", "57558324bc9b67b36ae33c3e1c191740"}
};
}
}

View File

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

View File

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

View File

@@ -82,7 +82,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Order fill event handler. On an order fill update the resulting information is passed to this method.
/// </summary>
/// <param name="orderEvent">Order event details containing details of the evemts</param>
/// <param name="orderEvent">Order event details containing details of the events</param>
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
public override void OnOrderEvent(OrderEvent orderEvent)
{
@@ -99,6 +99,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 475788;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -123,29 +133,11 @@ namespace QuantConnect.Algorithm.CSharp
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$10.00"},
{"Total Fees", "$75.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"}
{"Portfolio Turnover", "61.34%"},
{"OrderListHash", "cee5cc2b0f80c308b496cac0b8668163"}
};
}
}

View File

@@ -92,7 +92,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Order fill event handler. On an order fill update the resulting information is passed to this method.
/// </summary>
/// <param name="orderEvent">Order event details containing details of the evemts</param>
/// <param name="orderEvent">Order event details containing details of the events</param>
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
public override void OnOrderEvent(OrderEvent orderEvent)
{
@@ -109,12 +109,22 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 476196;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "778"},
{"Total Trades", "418"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
@@ -133,29 +143,11 @@ namespace QuantConnect.Algorithm.CSharp
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$778.00"},
{"Estimated Strategy Capacity", "$1000.00"},
{"Total Fees", "$418.00"},
{"Estimated Strategy Capacity", "$3000.00"},
{"Lowest Capacity Asset", "GOOCV W78ZFMEBBB2E|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", "6a88f302b7f29a2c59e4b1e978161da1"}
{"Portfolio Turnover", "338.56%"},
{"OrderListHash", "e0289a2989c91934656ff7e578f5e810"}
};
}
}

View File

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

View File

@@ -89,7 +89,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Order fill event handler. On an order fill update the resulting information is passed to this method.
/// </summary>
/// <param name="orderEvent">Order event details containing details of the evemts</param>
/// <param name="orderEvent">Order event details containing details of the events</param>
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
public override void OnOrderEvent(OrderEvent orderEvent)
{
@@ -106,6 +106,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 475777;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -133,26 +143,8 @@ namespace QuantConnect.Algorithm.CSharp
{"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"},
{"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", "9d9f9248ee8fe30d87ff0a6f6fea5112"}
{"Portfolio Turnover", "10.71%"},
{"OrderListHash", "838e313ba57850227ec810ed8fb85a23"}
};
}
}

View File

@@ -0,0 +1,163 @@
/*
* 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.Orders;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to add options for a given underlying equity security.
/// It also shows how you can prefilter contracts easily based on strikes and expirations, and how you
/// can inspect the option chain to pick a specific option contract to trade.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="options" />
/// <meta name="tag" content="filter selection" />
public class BasicTemplateOptionsDailyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "GOOG";
public Symbol OptionSymbol;
private bool _optionExpired;
public override void Initialize()
{
SetStartDate(2015, 12, 23);
SetEndDate(2016, 1, 20);
SetCash(100000);
var equity = AddEquity(UnderlyingTicker, Resolution.Daily);
var option = AddOption(UnderlyingTicker, Resolution.Daily);
OptionSymbol = option.Symbol;
option.SetFilter(x => x.CallsOnly().Strikes(0, 1).Expiration(0, 30));
// use the underlying equity as the benchmark
SetBenchmark(equity.Symbol);
}
/// <summary>
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
/// </summary>
/// <param name="slice">The current slice of data keyed by symbol string</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
OptionChain chain;
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
{
// Grab us the contract nearest expiry that is not today
var contractsByExpiration = chain.Where(x => x.Expiry != Time.Date).OrderBy(x => x.Expiry);
var contract = contractsByExpiration.FirstOrDefault();
if (contract != null && IsMarketOpen(contract.Symbol))
{
// if found, trade it
MarketOrder(contract.Symbol, 1);
}
}
}
}
/// <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 events</param>
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
public override void OnOrderEvent(OrderEvent orderEvent)
{
Log(orderEvent.ToString());
// Check for our expected OTM option expiry
if (orderEvent.Message.Contains("OTM", StringComparison.InvariantCulture))
{
// Assert it is at midnight (5AM UTC)
if (orderEvent.UtcTime != new DateTime(2016, 1, 16, 5, 0, 0))
{
throw new ArgumentException($"Expiry event was not at the correct time, {orderEvent.UtcTime}");
}
_optionExpired = true;
}
}
public override void OnEndOfAlgorithm()
{
// Assert we had our option expire and fill a liquidation order
if (_optionExpired != true)
{
throw new ArgumentException("Algorithm did not process the option expiration like expected");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 39654;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-1.31%"},
{"Compounding Annual Return", "-15.304%"},
{"Drawdown", "1.300%"},
{"Expectancy", "-1"},
{"Net Profit", "-1.311%"},
{"Sharpe Ratio", "-3.31"},
{"Probabilistic Sharpe Ratio", "0.035%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0.034"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-3.31"},
{"Tracking Error", "0.034"},
{"Treynor Ratio", "0"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$18000.00"},
{"Lowest Capacity Asset", "GOOCV W78ZFMML01JA|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "0.05%"},
{"OrderListHash", "0b52bbe98ade8e3aab943e64fcf4abfe"}
};
}
}

View File

@@ -41,7 +41,7 @@ namespace QuantConnect.Algorithm.CSharp
public override void Initialize()
{
SetStartDate(2015, 12, 24);
SetEndDate(2015, 12, 24);
SetEndDate(2015, 12, 28);
SetCash(100000);
var equity = AddEquity(UnderlyingTicker);
@@ -97,6 +97,16 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1322413;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
@@ -104,14 +114,14 @@ namespace QuantConnect.Algorithm.CSharp
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Average Loss", "-0.40%"},
{"Compounding Annual Return", "-21.622%"},
{"Drawdown", "0.300%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.311%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
@@ -124,26 +134,8 @@ namespace QuantConnect.Algorithm.CSharp
{"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"},
{"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", "92d8a50efe230524512404dab66b19dd"}
{"Portfolio Turnover", "15.08%"},
{"OrderListHash", "0f8537495f5744c02191656d6b3f9205"}
};
}
}

View File

@@ -36,7 +36,7 @@ namespace QuantConnect.Algorithm.CSharp
UniverseSettings.Resolution = Resolution.Minute;
SetStartDate(2014, 06, 05);
SetEndDate(2014, 06, 06);
SetEndDate(2014, 06, 09);
SetCash(100000);
// set framework models
@@ -136,53 +136,45 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 990979;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "4"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Average Win", "0.14%"},
{"Average Loss", "-0.28%"},
{"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"},
{"Drawdown", "385.400%"},
{"Expectancy", "-0.249"},
{"Net Profit", "-386.489%"},
{"Sharpe Ratio", "-0.033"},
{"Probabilistic Sharpe Ratio", "1.235%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.50"},
{"Alpha", "-95.983"},
{"Beta", "263.726"},
{"Annual Standard Deviation", "30.617"},
{"Annual Variance", "937.371"},
{"Information Ratio", "-0.044"},
{"Tracking Error", "30.604"},
{"Treynor Ratio", "-0.004"},
{"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"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "26"},
{"Total Insights Closed", "24"},
{"Total Insights Analysis Completed", "24"},
{"Long Insight Count", "26"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$31.01809"},
{"Total Accumulated Estimated Alpha Value", "$1.89555"},
{"Mean Population Estimated Insight Value", "$0.07898125"},
{"Mean Population Direction", "50%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "50.0482%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "ce06ddfa4b2ffeb666a8910ac8836992"}
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "13.46%"},
{"OrderListHash", "83c9fb13ee32284702779eff8d11c608"}
};
}
}

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 System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to add options for a given underlying equity security.
/// It also shows how you can prefilter contracts easily based on strikes and expirations, and how you
/// can inspect the option chain to pick a specific option contract to trade.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="options" />
/// <meta name="tag" content="filter selection" />
public class BasicTemplateOptionsHourlyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "AAPL";
public Symbol OptionSymbol;
public override void Initialize()
{
SetStartDate(2014, 6, 6);
SetEndDate(2014, 6, 9);
SetCash(100000);
var equity = AddEquity(UnderlyingTicker, Resolution.Hour);
var option = AddOption(UnderlyingTicker, Resolution.Hour);
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));
// .Expiration(TimeSpan.Zero, TimeSpan.FromDays(180)));
// use the underlying equity as the benchmark
SetBenchmark(equity.Symbol);
}
/// <summary>
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
/// </summary>
/// <param name="slice">The current slice of data keyed by symbol string</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested && IsMarketOpen(OptionSymbol))
{
OptionChain chain;
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
{
// we find at the money (ATM) put contract with farthest expiration
var atmContract = chain
.OrderByDescending(x => x.Expiry)
.ThenBy(x => Math.Abs(chain.Underlying.Price - x.Strike))
.ThenByDescending(x => x.Right)
.FirstOrDefault();
if (atmContract != null && IsMarketOpen(atmContract.Symbol))
{
// if found, trade it
MarketOrder(atmContract.Symbol, 1);
MarketOnCloseOrder(atmContract.Symbol, -1);
}
}
}
}
/// <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 events</param>
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
public override void OnOrderEvent(OrderEvent orderEvent)
{
Log(orderEvent.ToString());
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 32492;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "4"},
{"Average Win", "0%"},
{"Average Loss", "-0.07%"},
{"Compounding Annual Return", "-12.496%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.134%"},
{"Sharpe Ratio", "-8.839"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.083"},
{"Beta", "-0.054"},
{"Annual Standard Deviation", "0.008"},
{"Annual Variance", "0"},
{"Information Ratio", "-18.699"},
{"Tracking Error", "0.155"},
{"Treynor Ratio", "1.296"},
{"Total Fees", "$4.00"},
{"Estimated Strategy Capacity", "$1000.00"},
{"Lowest Capacity Asset", "AAPL 2ZTXYMUAHCIAU|AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "2.28%"},
{"OrderListHash", "81e8a822d43de2165c1d3f52964ec312"}
};
}
}

View File

@@ -0,0 +1,146 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Data.Market;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to add and trade SPX index weekly options
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="options" />
/// <meta name="tag" content="indexes" />
public class BasicTemplateSPXWeeklyIndexOptionsAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spxOption;
/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
public override void Initialize()
{
SetStartDate(2021, 1, 4);
SetEndDate(2021, 1, 10);
SetCash(1000000);
var spx = AddIndex("SPX").Symbol;
// regular option SPX contracts
var spxOptions = AddIndexOption(spx);
spxOptions.SetFilter(u => u.Strikes(0, 1).Expiration(0, 30));
// weekly option SPX contracts
var spxw = AddIndexOption(spx, "SPXW");
spxw.SetFilter(u => u.Strikes(0, 1)
// single week ahead since there are many SPXW contracts and we want to preserve performance
.Expiration(0, 7)
.IncludeWeeklys());
_spxOption = spxw.Symbol;
}
/// <summary>
/// Index EMA Cross trading underlying.
/// </summary>
public override void OnData(Slice slice)
{
if (Portfolio.Invested)
{
return;
}
OptionChain chain;
if (slice.OptionChains.TryGetValue(_spxOption, out chain))
{
// we find at the money (ATM) put contract with closest expiration
var atmContract = chain
.OrderBy(x => x.Expiry)
.ThenBy(x => Math.Abs(chain.Underlying.Price - x.Strike))
.ThenByDescending(x => x.Right)
.FirstOrDefault();
if (atmContract != null)
{
// if found, buy until it expires
MarketOrder(atmContract.Symbol, 1);
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
Debug(orderEvent.ToString());
}
/// <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 virtual bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 65536;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "5"},
{"Average Win", "0%"},
{"Average Loss", "-0.69%"},
{"Compounding Annual Return", "58.005%"},
{"Drawdown", "0.400%"},
{"Expectancy", "-1"},
{"Net Profit", "0.588%"},
{"Sharpe Ratio", "1.448"},
{"Probabilistic Sharpe Ratio", "51.980%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.288"},
{"Beta", "-0.04"},
{"Annual Standard Deviation", "0.004"},
{"Annual Variance", "0"},
{"Information Ratio", "-98.963"},
{"Tracking Error", "0.072"},
{"Treynor Ratio", "-0.149"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$8400000.00"},
{"Lowest Capacity Asset", "SPXW 31K54PVWHUJHQ|SPX 31"},
{"Portfolio Turnover", "0.48%"},
{"OrderListHash", "174bd0a99916d58ca3f12139306940db"}
};
}
}

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.Linq;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Data.Market;
using System.Collections.Generic;
using QuantConnect.Securities.Option;
using System;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to add and trade SPX index weekly option strategy
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="options" />
/// <meta name="tag" content="indexes" />
public class BasicTemplateSPXWeeklyIndexOptionsStrategyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spxOption;
/// <summary>
/// Initialize your algorithm and add desired assets.
/// </summary>
public override void Initialize()
{
SetStartDate(2021, 1, 4);
SetEndDate(2021, 1, 10);
SetCash(1000000);
var spx = AddIndex("SPX").Symbol;
// weekly option SPX contracts
var spxw = AddIndexOption(spx, "SPXW");
spxw.SetFilter(u => u.Strikes(0, 1)
// single week ahead since there are many SPXW contracts and we want to preserve performance
.Expiration(0, 7)
.IncludeWeeklys());
_spxOption = spxw.Symbol;
}
public override void OnData(Slice slice)
{
if (Portfolio.Invested)
{
return;
}
OptionChain chain;
if (slice.OptionChains.TryGetValue(_spxOption, out chain))
{
// we find the first expiration group of call options and order them in ascending strike
var contracts = chain
.Where(x => x.Right == OptionRight.Call)
.OrderBy(x => x.Expiry)
.GroupBy(x => x.Expiry)
.First()
.OrderBy(x => x.Strike)
.ToList();
if (contracts.Count > 1)
{
var smallerStrike = contracts[0];
var higherStrike = contracts[1];
// if found, buy until it expires
var optionStrategy = OptionStrategies.BearCallSpread(_spxOption, smallerStrike.Strike, higherStrike.Strike, smallerStrike.Expiry);
Buy(optionStrategy, 1);
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
Debug(orderEvent.ToString());
if (orderEvent.Symbol.ID.Symbol != "SPXW")
{
throw new Exception("Unexpected order event symbol!");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public virtual bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public virtual Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 35451;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "4"},
{"Average Win", "0.12%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "8.975%"},
{"Drawdown", "0.100%"},
{"Expectancy", "62.078"},
{"Net Profit", "0.110%"},
{"Sharpe Ratio", "-7.925"},
{"Probabilistic Sharpe Ratio", "1.216%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "125.16"},
{"Alpha", "-0.012"},
{"Beta", "0.001"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-103.223"},
{"Tracking Error", "0.069"},
{"Treynor Ratio", "-2.449"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$1800000.00"},
{"Lowest Capacity Asset", "SPXW XKX6S2GM9PGU|SPX 31"},
{"Portfolio Turnover", "0.03%"},
{"OrderListHash", "38db27781e4df93687d0895df9796c7d"}
};
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -32,7 +32,7 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
public override void Initialize()
{
SetStartDate(2010, 01, 01);
SetEndDate(2018, 01, 01);
SetEndDate(2022, 01, 01);
AddSecurity(SecurityType.Equity, "SPY", Resolution.Minute);
@@ -51,7 +51,7 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
// define an indicator that takes the output of the sma and pipes it into our delay indicator
var delayedSma = delay.Of(sma);
// register our new 'delayedSma' for automaic updates on a daily resolution
// register our new 'delayedSma' for automatic updates on a daily resolution
RegisterIndicator(_spy, delayedSma, Resolution.Daily, data => data.Value);
return delayedSma;
@@ -68,4 +68,4 @@ namespace QuantConnect.Algorithm.CSharp.Benchmarks
}
}
}
}
}

View File

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

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