Compare commits

...

864 Commits

Author SHA1 Message Date
Martin-Molinero
31e247689f Allow specifying PositionSize wolverine order properties (#9257) 2026-01-30 16:56:17 -03:00
Roman Yavnikov
297207badb feat: add MappedSynchronizingHistoryProvider base class (#9256)
* feat: add MappedSynchronizingHistoryProvider base class

Introduces an abstract class for history providers that handle symbol mapping and time-aligned data slices. Uses IMapFileProvider to resolve ticker changes, provides an abstract method for mapped history retrieval, and overrides GetHistory to synchronize results. Enables nullable reference types and adds documentation.

* Minor tweaks

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2026-01-30 16:55:10 -03:00
Jhonathan Abreu
ecb8e8da41 Fix trades drawdown calculation (#9249)
* Fix trade drawdown calculation

* Cleanup

* Disable MAE. MFE and Drawdown calculation for FlatToFlat and FlatToReduced trade grouping methods

* Minor test fixes
2026-01-30 15:46:41 -04:00
Martin-Molinero
c6c4c1edec Fix fundamental security direct access timestamp (#9255)
- Fix the date used by fundamental data accessed directly through security.
  Updating regression algorithm asserting behavior
2026-01-30 11:41:24 -03:00
Martin-Molinero
c02a8faedb Improve Wolverine brokerage model limitations (#9252) 2026-01-29 14:36:12 -03:00
JosueNina
e620d3fd7b Replace ':' with '-' in backtest names for API CI (#9251) 2026-01-29 14:03:58 -03:00
Martin-Molinero
4b6643312e Allow emtpy BNFCR cash through (#9247) 2026-01-28 10:53:19 -03:00
Martin-Molinero
4b2f203322 Fix USDC binance crypto future and stable pairs (#9246)
- Minor fix for stable pairs handling without a pair, adding unit tests
- Fix for USDC it's a USD-M crypto future not coin
2026-01-28 09:49:28 -03:00
JosueNina
7eefdebae5 Update signal when rangeBand is zero (#9245) 2026-01-28 09:47:53 -03:00
Jhonathan Abreu
7f17838ad0 Fix crypto future margin model to reflect margin used (#9235)
* Fix crypto future margin model to reflect margin used

* Minor tests fixes

* Cleanup

* Cleanup
2026-01-27 13:40:36 -04:00
Martin-Molinero
5a1ebcbaad Fix LeanDataWriter Compression method so it supports unicode filenames (#9244) 2026-01-27 14:31:46 -03:00
Martin-Molinero
552511ef58 Fix dydx holdings value (#9243)
- dYdX crypto futures holdings value behaves like normal positions qtty
  * price
2026-01-26 16:29:19 -03:00
Jared
8f2fd3d64a Redact local lean error message (#9232)
Redact message in local user's CLI's
2026-01-26 12:56:19 -03:00
JosueNina
609deb2b03 Logging only once price rounding warnings (#9238) 2026-01-26 12:54:33 -03:00
Jhonathan Abreu
7fb246511a Add total performance statistics to live result files (#9224)
* Add total performance statistics to live result files

* Truncate closed trades in live results

* Avoid adding totalPerformance to live minute result file

* Deprecated Trade.Symbol in favor of new Trade.Symbols

* Fixes for Trade serialization

* Add trades json serialization tests

* Cleanup
2026-01-16 15:41:35 -04:00
Martin-Molinero
745292c15a Add Async for submit request to string (#9228) 2026-01-16 13:44:16 -03:00
JosueNina
22e0e5ddf5 Prevent SessionBar EndTime overflow when Time is DateTime.MaxValue (#9215)
* Fix SessionBar EndTime overflow

* Fix broken tests

* Update python regression tests

* Solve review comments

* Revert changes

* Prevent overflow from Time + Period
2026-01-16 12:07:41 -03:00
Adalyat Nazirov
ef94b5affc Add dYdX IoC Time In Force (#9226)
* Add `IoC` and update `PostOnly` in `dYdXOrderProperties` with validation logic; add corresponding unit tests.

* change case to use IOC

* more IOC
2026-01-15 17:20:11 -03:00
Martin-Molinero
61e8c63acd Fix dydx camel case (#9223) 2026-01-14 11:55:29 -03:00
Adalyat Nazirov
1ca7320f2f Add dYdXFutureMarginInterestRateModel (#9221)
* Add `dYdXFutureMarginInterestRateModel` and update `GetMarginInterestRateModel` to support CryptoFuture funding rates

* missing import
2026-01-13 18:00:26 -03:00
JosueNina
5b8e54f272 Reduce excessive debug logging in live trading (#9220)
* Reduce excessive logs

* Revert unnecesary log changes
2026-01-13 14:19:40 -03:00
Jhonathan Abreu
26584c2fd0 Stop and delete unused threads in tests (#9219) 2026-01-13 13:13:37 -03:00
Roman Yavnikov
48fd4eccff Feat: override ToString() in several Event Args (#9217)
* feat: override ToString() in several Event Args

* fix: typo
2026-01-13 10:00:48 -03:00
JosueNina
75d5cbcf2a Fix: RandomDataGenerator crashes when algorithm is null (#9211)
* Fix NullReferenceException in SecurityService

* Simplify the unit test

* Add unit test for RandomDataGenerator

* Improve unit test name

* Solve review comments
2026-01-12 14:50:01 -04:00
Jhonathan Abreu
d702587ad8 Fix SecurityIdentifier properties lazy initialization (#9214) 2026-01-09 18:07:26 -03:00
Jhonathan Abreu
c99a9dab32 Update CNH future quote currency (#9213) 2026-01-09 15:44:29 -03:00
JosueNina
8196d0b557 HistoryRequest parameters now defaults to the security configuration (#9209)
* Fix HistoryRequest DataMappingMode default to use security configuration

* Solve review comments

* Make HistoryRequest inherit existing subscription configuration values generically

* Exclude any class that inherits from BaseChainUniverseData

* Reuse existing filter for user configuration

* Solve review comments

* Normalize DataMappingMode

* Minor fix
2026-01-09 15:43:46 -03:00
Ricardo Andrés Marino Rojas
3ee941f329 Remove wrong holidays in MHDB (#9205)
Remove wrong holidays in CME group Dairy, Livestock and Lumber products.
There was also a wrong holidays in Future-cbot-KE
2026-01-07 16:13:28 -03:00
Ricardo Andrés Marino Rojas
286353b763 Remove duplicated dates (#9207) 2026-01-07 16:13:19 -03:00
Ricardo Andrés Marino Rojas
d5f298c235 Add missing Oanda, SGX and Cfd-InteractiveBrokers 2026 holidays to MHDB (#9204)
* Add 2026 Oanda holidays

* Add 2026 new year holiday SGX

* Add Cfd-interactivebrokers 2026 holidays

* Remove wrong holidays in Forex-oanda-[*]

* Nit change
2026-01-07 13:08:40 -03:00
Ricardo Andrés Marino Rojas
f2c5551b1e Remove dates present in generic entry Index-usa and others (#9202) 2026-01-06 17:19:07 -03:00
Ricardo Andrés Marino Rojas
f86a51ac3f Remove dates in generic Interactive Brokers entry part 10 (#9201)
* Remove dates present in IB generic entry part 9

* Remove dates in IB generic entry part 10
2026-01-06 16:14:25 -03:00
Ricardo Andrés Marino Rojas
1253cc73bd Remove dates present in IB generic entry part 9 (#9200) 2026-01-06 16:12:19 -03:00
Ricardo Andrés Marino Rojas
6506ff53a3 Remove dates in generic Interactive Brokers entry part 8 (#9199)
* Remove dates present in IB generic entry part 7

* Remove dates present in IB generic entry part 8
2026-01-06 14:32:01 -03:00
Ricardo Andrés Marino Rojas
713785157e Remove dates present in IB generic entry part 7 (#9198) 2026-01-06 14:30:07 -03:00
Ricardo Andrés Marino Rojas
fd7048d2d1 Remove dates present in IB generic entry part 6 (#9197) 2026-01-06 13:27:45 -03:00
Ricardo Andrés Marino Rojas
1b66aeede1 Remove dates present in IB generic entry part 5 (#9196) 2026-01-06 13:10:04 -03:00
Ricardo Andrés Marino Rojas
2f80a2a6b9 Remove dates in generic Interactive Brokers entry part 4 (#9193)
* Remove dates present in generic entries

* Remove dates present in IB generic entry
2026-01-06 12:45:59 -03:00
Ricardo Andrés Marino Rojas
68d4da8e76 Remove dates present in generic entries (#9192) 2026-01-06 12:22:20 -03:00
Ricardo Andrés Marino Rojas
538405d152 Remove dates present in generic interactivebrokers (#9191) 2026-01-06 11:59:37 -03:00
Ricardo Andrés Marino Rojas
1f3fd6edbb Reduce (part of) dates already present in generic entries from MHDB (#9190)
* Remove dates present in cme generic entry

* Remove dates present in cbot generic entry

* Remove dates present in nymex generic entry

* Remove dates present in comex generic entry

* Remove dates present in oanda generic entry

* Remove dates present in SGX and HKFE generic entries
2026-01-06 11:52:15 -03:00
Adalyat Nazirov
e3783ed477 Override GetBuyingPowerModel to support USDC collaterla in dYdX brokerage (#9187) 2026-01-05 09:55:46 -03:00
Ricardo Andrés Marino Rojas
1171e4fe52 Add 2026 Future EUREX, CFE and ICE Holidays (#9183)
* rebase Add 2026 EUREX, CFE and ICE Holidays

* Remove entries present in generic entry

For some ICE Future entries, there were holidays that were already
present in their generic entry (Future-ice-[*]), so those dates were
removed from the entry
2026-01-02 16:05:36 -03:00
Martin-Molinero
a66f279852 Fix some incorrect future expirations (#9184)
- Some future expiry functions were missing to account for holidays,
  adding unit test reproducing issue
2026-01-02 12:58:29 -03:00
Martin-Molinero
6575b57146 Fix future expiration year calculation (#9182) 2026-01-02 10:21:02 -03:00
yyxxddjj
3fa700e450 New Feature: Implement Covariance Indicator #6982 (#9144)
* Implements Covariance as Lean Indicator

* Add COV helper method and fix AcceptsVolumeRenkoBarsAsInput test

* Fix AcceptsRenkoBarsAsInput test to use smaller period for faster execution

* Fix slow Renko tests by limiting data processed to 50 rows
2025-12-31 16:02:03 -03:00
Adalyat Nazirov
7735917c83 Prioritize CryptoFuture data feeds for dYdX (#9178)
* Prioritize CryptoFuture data feeds for dYdX

* revert changes for existing crypto subscriptions

* use Concat instead of adding into list
2025-12-31 13:19:58 -03:00
Jhonathan Abreu
67489eef57 Add GetInt64 StreamReader extension method (#9177)
* Add GetInt64 StreamReader extension method

* Minor change

* Cleanup

* Add unit tests
2025-12-31 11:58:51 -04:00
JosueNina
241306275a Replace external dataset with mock data in sweetviz test (#9176) 2025-12-31 12:18:22 -03:00
Ricardo Andrés Marino Rojas
773bd53525 Add 2026 CME Future & HKFE Holidays, early closes, late opens and bank holidays (#9174)
* Add 2026 HKFE Future holidays & early closes

* rebase Add 2026 Future-cme-equity Holidays, Early closes, late opens

* Add (again) HKFE 2026 Holidays and early closes

* Add Future-cme-interest 2026 holidays

* Add 2026 CME Fx 2026 holidays"

- Add 2026 CME Fx holidays, early closes, late opens, bank holidays
- Exclude CNH, MNH and MIR as they expire rules don't consider US
  Holidays
- Fix wrong early close on 12/24/2025 from 12:15 to 12:45

* Add CME Future crypto 2026 Holidays, EC, LO & BH

* Add CME Future Energy 2026 holidays, EC, LO, BH

* Add CME Futures metals holidays, ec, lo, bh

* Add CME Futures grains 2026 holidays, ec, lo, bh

* Add CME Futures Dairy 2026 holidays, ec, lo, bh

* Add CME Futures livestock holidays, ec, lo, bh

* Add CME Future Lumber holidays, ec, lo, bh

* Add CME Futures Softs holidays, ec, lo, bh

* Add CME Futures Oilseeds holidays, ec, lo, bh

* Add CME Futures AW, GD Holidays, EC, LO and BH

* Move repeated bank holidays to generic entries

* Nit change

* Solve bug

Since 11/26/2026 is a bank holiday for CME energy futures, the expiry
date is moved to 11/25/2026 as the expiry date for HH is the third last
business day of the month prior to the contract month
2025-12-31 11:33:59 -03:00
JosueNina
0854ab82da Default option filter now includes weeklies to prevent empty chains (#9162)
* Return weekly contracts if no standard contracts exist

* Fix unit and regression tests

* Centralize default expiration type flags

* Add ExcludeWeeklys() method

* Mark IncludeWeeklys() as obsolete since weeklies are now default
2025-12-31 10:11:46 -03:00
JosueNina
2c0390fde3 Change Config.Get logging from Trace to Debug level (#9171)
* Change Config.Get logs from Trace to Debug level to reduce noise

* Wrap Config.Get logs with DebuggingEnabled check
2025-12-31 10:09:37 -03:00
JosueNina
32fcd94abc Exclude Period property from WindowIndicator (#9172) 2025-12-31 10:08:37 -03:00
Martin-Molinero
090ffebd03 Minor ApiConnection improvement (#9173) 2025-12-30 18:48:27 -03:00
JosueNina
914d0810af Make Collaborator.Uid nullable to fix JSON deserialization error (#9170) 2025-12-30 15:40:22 -03:00
Martin-Molinero
10902f95dd net10 fix: Update clr-loader (#9166) 2025-12-29 19:07:35 -03:00
Martin-Molinero
2e67b9ad4f Feature net10 update (#9161)
* Feature update to net10

* Update to net10

* Update pythonnet to 2.0.51

* Remove dotnet config

* Remove net9

* Minor cleanup
2025-12-29 09:53:37 -03:00
Ricardo Andrés Marino Rojas
7adf27aa61 Add 2026 CME Future Holidays, EC, LP, BH (#9163)
- Add 2026 CME Future Holidays, Early closes, Late opens and bank holidays
- Exclude MIR, CNH, MNH as they expire rules don't follow US holidays
2025-12-27 10:52:23 -03:00
Martin-Molinero
7ea0f60905 Add SGX futures holidays (#9160) 2025-12-26 15:24:55 -03:00
Martin-Molinero
d9c71e3d34 Adding Forex-Oanda & Cfd-IB 2026 new years holiday. Removing duplication (#9159) 2025-12-26 12:10:19 -03:00
Martin-Molinero
b040518d52 Minor foundation update reverts (#9156) 2025-12-24 17:02:49 -03:00
Roman Yavnikov
725737610a fix: several Futures Currencies: 6B, 6M, 6J, 6E, 6C (#9155) 2025-12-24 17:39:50 +02:00
Martin-Molinero
37ccee4937 Update foundation image (#9154) 2025-12-24 11:17:50 -03:00
Jhonathan Abreu
0ab0abd1ca Clean up after removing RestSharp (#9153) 2025-12-23 13:45:31 -03:00
Jhonathan Abreu
c565f4cfd0 Refactor optimization statistics serialization (#8984)
* Refactor optimization result stats serialization

* Handle custom optimization statistics serialization

* Support custom statistics

* Support newest Lean statistics

Address peer review

* Add more tests

* Make indices reserved statistic names

* Minor fixes and cleanup
2025-12-22 17:08:24 -04:00
Ricardo Andrés Marino Rojas
f804b8f0ca Add 2026 Index holidays to MHDB (#9152)
* Add index-usa-[*] holidays and early closes

* Add Index-spx 2026-2027 holidays & early closes

* Add 2026 Index-ndx holidays & early closes

* Add 2026 Index-VIX holidays and early closes

* Add EUREX Index holidays 2026-2030

* Add index HKFE 2026 holidays and early closes

* Add 2026 Index-OSE holidays and early closes

* Add missing 2026 Index-India NSE holidays

* Address suggested changes
2025-12-22 16:42:25 -03:00
Jhonathan Abreu
ef1cf8e4df Replace RestShap with HttpClient (#9143)
* Replace RestShap with HttpClient

* Address peer review

* Minor fixes
2025-12-22 09:50:25 -04:00
Ricardo Andrés Marino Rojas
661356e33e Add missing USA equity holidays and early closes (#9148)
* Add 2025-2027 USA equity holidays

* Address reviews
2025-12-19 17:18:42 -03:00
Martin-Molinero
5842f50b03 Trigger initial selection for a yearly schedule (#9149)
- Trigger initial selection for a yearly scheduled universe. Adding
  regression algorithm.
2025-12-19 16:45:37 -03:00
Martin-Molinero
0f80591f51 Fix null reference un future contract. Adding tests (#9147) 2025-12-19 13:51:45 -03:00
JosueNina
0622f43a0f Fix issues with the IchimokuKinkoHyo indicator (#9135)
* Fix issues with IchimokuKinkoHyo indicator

* Use indicator extension methods for automatic updates
2025-12-19 12:48:49 -03:00
JosueNina
8f0224feb6 Fix StopLimit validation bug (#9142) 2025-12-19 12:35:19 -03:00
Jhonathan Abreu
781897984e Detect serialized json payload in CreateJsonPostRequest (#9145) 2025-12-19 11:24:03 -04:00
Roman Yavnikov
340b40c6ce Fix: AUD(6A) FOP expiration (#9139)
* fix: AUD(6A) FOP expiration

* feat: add 6A to FOP expiry delta
refactor: rename variable to project pattern naming

* remove: AUD fop expiry delta
test:fix: use flexible reference data in  FutureAndOptionMapping

* test:fix: AUD in GetUnderlyingSymbolFromFutureOption
2025-12-19 15:52:06 +02:00
Jhonathan Abreu
58ce899b5d Add Api helper methods for POST requests (#9134)
* Add Api helper methods for POST requests

* Support json serializer setting for json requests

* Minor changes and cleanup

* Make ApiConnection disposable
2025-12-16 18:08:28 -04:00
Martin Nemček
ead8335c84 #8356 Implemention of NHNL indicators (#9109)
* #8356 Implemented NHNL indicators

* #8356 Formatting cleanup

* #8356 Review changes

* #8356 use of var

* #8356 Refactoring of tests classes

---------

Co-authored-by: Martin Nemček <nemcek@metaapp.sk>
2025-12-16 14:24:00 -03:00
Aibek Minbaev
84ee81b35b Feat 8909 add python env support in report generation (#9128)
* Added python-venv to ReportArgumentParser, getting python-venv in Program class

* Added venv activation and python initialization to Report class

* Resolve review comments. Move python init and env addition to Report/Program.cs
2025-12-16 13:42:23 -03:00
JosueNina
03be232f31 Fix issues with IgnoresInsightsWithInvalidMagnitudeValue tests (#9131) 2025-12-15 18:24:11 -03:00
Martin-Molinero
e568162bff Minor slice.AllData api change (#9130) 2025-12-15 10:25:00 -03:00
Derek Melchin
e395892b8e Fix camelCase constructor args (#9127) 2025-12-11 15:15:17 -03:00
Jared
3483fee766 Remove debug message for daily precise end time (#9126)
Removed debug message regarding daily precise end times.
2025-12-11 15:14:22 -03:00
Jhonathan Abreu
6cba915950 Fix minor bug with restsharp auth header (#9125)
* Fix minor bug with restsharp auth header

* Minor fix
2025-12-11 15:13:37 -03:00
Martin-Molinero
046df38be8 Fix log timestamp & minor cleanup (#9124) 2025-12-11 13:44:30 -03:00
Jhonathan Abreu
c7e96b837d Minor fix for json to stream serialization extension (#9123) 2025-12-10 18:29:57 -04:00
Martin-Molinero
2f23c89307 Avoid FF enumerator error warning (#9122) 2025-12-10 18:18:08 -03:00
Jhonathan Abreu
67d19d88d7 Add ApiConnection constructor for backwards compatibility (#9121) 2025-12-10 16:16:38 -04:00
Jhonathan Abreu
b4401db512 Refactor ApiClient to use HttpClient (#9114)
* Refactor ApiClient to use HttpClient

* Minor fix

* Refactor and cleanup in ApiConnection

* Add normalized extension methods for string and stream json serialization

* Minor fixes

* Address peer review

* Minor fixes

* Minor fixes and peer review

* Race condition fix

* Minor changes

* Cleanup

* Minor fixes

* Minor fix
2025-12-10 15:40:46 -04:00
Jhonathan Abreu
bc646c974a Use proper extended dictionary types for public properties (#9119) 2025-12-09 13:01:29 -03:00
Adalyat Nazirov
857a950e23 dYdX Brokerage Essentials (#9116)
* add dYdX market constant

* Add dYdX market constant and update symbol properties database

* get Gaz limit from order properties or default value

* wip

* add symbol properties

* add more dydx order props

* update symbol properties

* Add dYdX brokerage and fee model

* Update dYdX configuration fields

* undone meta files

* minor tweaks

* fix file ending

* Add dYdX brokerage support to BrokerageName and IBrokerageModel

* Refine dYdX fee model integration and update configuration defaults

* Replace custom order size validation in dYdXBrokerageModel with DefaultBrokerageModel implementation

* undone changes

* Add market hours for dYdX CryptoFuture
2025-12-09 09:58:06 -03:00
JosueNina
888752fa0a Avoid unnecessary Python wrapper creation for pure C# models (#9106)
* Centralize Python/C# model detection logic

* Improve helper method

* Remove unnecessary conditionals

* Fix unit tests

* Refactor QCAlgorithm.python.cs to use the new helper method for models

* Solve review comments

* Clean up Python wrapper exception

* Update XML comments to better describe T and TWrapper in CreateModelOrWrapper

* Join unit tests in TestCases

* Solve review comments

* Replace manual TryConvert checks with CreateInstanceOrWrapper helper
2025-12-08 18:01:31 -03:00
Martin-Molinero
14427129c7 Minor fix to handle all tick security updates (#9117) 2025-12-08 17:41:28 -03:00
Jhonathan Abreu
683bfe007a Avoid emitting overlapping fill forwarded data (#9107)
* Avoid emitting overlapping fill forward data

* Cleanup
2025-12-05 10:05:40 -04:00
Jhonathan Abreu
263a9099ed Add TryDownloadData extension method (#9111) 2025-12-05 10:03:27 -04:00
JosueNina
a78004a1e6 Add default values to ConstantAlphaModel (#9104)
* Initial solution

* Add unit tests

* Fix constructor parameter mismatch in ConstantAlphaModel

* Delete unused constructor
2025-12-01 13:49:17 -03:00
Jhonathan Abreu
9acd30c355 Make DataDictionary ordered by key (symbol) (#9105)
* Make DataDictionary ordered by key (symbol)

* Cache DataDictionary sorted items

* Minor tests fixes

* Minor changes

* Minor changes
2025-12-01 12:44:22 -04:00
JosueNina
441ba1a7b5 Add ExtendedDictionary implementations (#9096)
* Add ExtendedDictionary implementations

- Add DefaultExtendedDictionary<TKey, TValue> class
- Add ReadOnlyExtendedDictionary<TKey, TValue> class
- Refactor exposed dictionaries

* Make DataDictionary inherits from DefaultExtendedDictionary

* Refactor UniverseManager

* Return ReadOnlyExtendedDictionary in GetParameters()

* Solve review comments

* Remove unnecesary property, no longer required

* Reduce code duplication

* Solve new review comments

* Remove unnecesary constraints

* Replace BaseExtendedDictionary with DataDictionary in GetLastKnownPrices method

* Remove unused extensions
2025-11-28 16:03:02 -04:00
JosueNina
52b788d9de Fix inclusive loop upper bound (#9102) 2025-11-28 12:39:09 -04:00
Jhonathan Abreu
16fdf61903 Track securities addition and removal notifications (#9097)
* Track security addition and removal sent notifications

* Minor regression algorithm fixes

* Fix regression algorithms data points count

* Add description to new regression algorithms

* Simplify tracking removal notifications

* Cleanup
2025-11-28 10:37:31 -04:00
Roman Yavnikov
59990573c2 Fix: Use decimal option strike precision (#9099)
* fix: use decimal instead long in Scale's LeanData
test:feat: validate naming with large precision

* feat: use normalization in Scale's LeanData
test:fix: strike precisions

* fix: use str normalization in Scale's LeanData
2025-11-25 20:32:06 +02:00
yyxxddjj
acb787e8f6 Docs(Algorithm): Add XML code references (#9077)
* Docs(Algorithm): Add XML code references

Adds XML documentation tags (<see/>, <paramref/>) to code
references within the Algorithm folder. This improves code
navigation, IntelliSense, and helps the stubs generator tool
to correctly map C# elements.

Resolves #9016

* Fix missing newline at end of QCAlgorithm.cs

* Update print statement from 'Hello' to 'Goodbye'

* Fix documentation for market parameter in crypto methods
2025-11-24 17:51:42 -04:00
JosueNina
6260b2f7e0 Replace /// with <summary> (#9095) 2025-11-24 17:09:39 -04:00
Martin-Molinero
95739b8a58 Increase option strike digits precision to 6 (#9086)
* Increase option strike digits precision to 6

- Increase option strike digits precision to 6. Adding unit test

* test:fix: couple of build tests

* fix:test: Asset CUSIP and OrderListHash in Regression Algorithms

* test:fix: several regression algos

* test:fix: old Symbol CUSIPs to new ones

---------

Co-authored-by: Romazes <romazes20@gmail.com>
2025-11-18 16:23:29 -03:00
Jhonathan Abreu
c81f5d7d1a Seed securities by default (#9045)
* Add SeedInitialPrices algorithm setting

This is true by default and indicates that the engine will seed initial prices right after the security is added or selected

* Update regression algorithms

* Update regression algorithms

* Update regression algorithms

* Refactor default securities seeding

* Minor fix

* Minro fixes

* Cleanup

* Updated and add regression algorithms

* Address peer review

* Centralize logic to get last known data for multiple securities

* Some cleanup

* Minor build fix

* Minor fixes

* More logic centralization

* Some more cleanup

* Cleanup

* Update regression algorithms and minor fixes

* Update regression algorithms

* Minor fix

* More minor fixes

* Update regression algorithms

* Cleanup

* Minor test fix

* Address peer review

* Minor fix and performance improvement

* Fix to seed open interest data

* Minor test fixes

* Address peer review

* Minor change

* Minor revert

* Minor fixes and improvements

* Disable initial seeding by default

* Minor fixes

* Cleanup

* Cleanup

* Minor fix
2025-11-18 13:05:56 -04:00
Martin-Molinero
4961844f82 Refactor user define universe handling (#9088)
* Refactor user define universe handling

- Normalize user define universe additions and removals to behave like
  other subscriptions without requiting special handling

* Minor fixes
2025-11-18 12:29:05 -03:00
Martin-Molinero
afca923cd9 Fix history provider equity skip (#9090) 2025-11-18 12:28:17 -03:00
Roman Yavnikov
a31436bc6d Test:Feat: parse different future option file name csv (#9084)
* test:feat: parse different future option file name csv

* test:refactor: ReadSymbolFromZipEntry
2025-11-14 15:45:46 +02:00
JosueNina
ebaa355bf1 Fix Python inheritance issue with SelectionModels (#9069)
* Initial solution

* Solve review comments

* Add PythonSelectionModelHandler to reduce code duplication

* Refactor universe selection models

* Add python instance to Selection Models with virtual/override methods

* Add python instance to Alpha Models

* Add python instance to Execution models

* Solve review comments

* Solve new review comments

* Fix calling SetPythonInstance only when method exists and is callable

* Use unit test instead of regression algorithms

* Solve review comments

* Set python instance to the models

* Initialize Python containers only when instance is set

* Replace try-catch with explicit method existence check

* Initialize containers in BasePythonWrapper only when needed

* Add null instance check before method invocation

* Refactor TryExecuteMethod

* Refactor Python wrappers which inherit from BasePythonWrapper<>

* Solve review comments

* Remove ununsed methods

* Solve review comments
2025-11-13 17:21:55 -03:00
Derek Melchin
46639fc4ec Update deprecation message in Top method (#9081) 2025-11-12 15:29:22 -03:00
Alexandre Catarino
2052a86351 Renames File Stochastics.cs -> Stochastic.cs (#9079)
Match the class name: `Stochastic`.
Fixes summaries.
2025-11-12 09:30:12 -03:00
JosueNina
7a5ff8054b Prevent adding zero quantity currencies to CashBook (#9076)
* Prevent adding zero quantity currencies to CashBook

* Solve review comments

* Solve new review comments

* Add unit test
2025-11-10 09:33:38 -03:00
Roman Yavnikov
a3d6e24741 Test:Feat: Updating process in TrailingStopOrderTestParameters (#9072)
* feat: implement ModifyOrderToFill in TrailingStopOrderTestParameters

* feat: prevent update TrailingOrder not equal SecurityType.Equity

* Revert "feat: prevent update TrailingOrder not equal SecurityType.Equity"

This reverts commit 35548dcfb7.

* rename: variable in TrailingStopOrderTestParameters
2025-11-04 18:25:08 +02:00
Martin-Molinero
6c5b577b46 Update HistoryProviderManagerTests.cs
Remove no longer valid unit test
2025-11-03 09:36:59 -03:00
Jhonathan Abreu
f4bab98b00 Update Pythonnet version to 2.0.50 (#9070) 2025-10-31 16:38:26 -04:00
Martin-Molinero
733be65148 Simplify history request handling for equities (#9068)
- For equity history requests, we will only ask the first provider which
  returns a valid reply, improvements thought for live trading QC+IB
2025-10-30 18:29:41 -03:00
Alexandre Catarino
2c26e9fc26 Adds Missing Indicator Constructor Overloads Without name Parameter (#9062)
* Adds Missing Indicator Constructor Overloads with name Parameter

* Fix Typoes
2025-10-30 18:08:34 -03:00
Martin-Molinero
2faf921731 FixComposer Assembly Resolution (#9066) 2025-10-28 09:26:12 -03:00
Martin-Molinero
89f3968eef Fix performance degradation on expirying assets (#9065)
* Fix performance degradation on expirying assets

- Options would expire and get removed, when the universe removed the
  security it would never be reseted on universe selection, causing
  leaks
- Minor improvement for composer assembly loading
- Minor improvement for loading exception interepreters, so it uses
  composer

* Minor regression test fix

* Add new benchmark algorithm
2025-10-27 18:17:53 -03:00
JosueNina
9c7d633b41 Throw exceptions when ObjectStore limits are exceeded in Research mode (#9060)
* Throw exception in Research mode when storage limits are exceeded

* Solve review comments
2025-10-27 10:16:25 -05:00
Martin-Molinero
cfba82e17a Minor composer improvements (#9064)
- Avoid loading unrequired assemblies and correctly handle assembly
  loading errors
2025-10-27 12:11:59 -03:00
Martin-Molinero
6811b93d6a Add performance tracking tool (#9063)
- Add optional performance tracking tool
2025-10-27 11:31:14 -03:00
Martin-Molinero
6916636e8e Remove Future expiry date from data & use Bank Holidays For Expirations (#8580)
* Use Futures Bank Holidays For Expirations

* Minor improvements

- Futures will be stored by their contract month, not expiry

* Delete dairy future products

* Minor test fixes
2025-10-24 17:18:20 -03:00
JosueNina
0a4c19527b Support index options (#9061) 2025-10-24 13:29:48 -05:00
JosueNina
f807d62b18 Improve cash assignment event message (#9051)
* Improve cash assignment event message

* Fix broken tests

* Solve review comments

* Solve new review comments

* Add P&L message to option exercise order events in portfolio model

* Solve review comments
2025-10-23 11:54:00 -05:00
JosueNina
f5c5c5a3b0 Add configurable initialization timeout via config.json (#9056)
* Add configurable initialization timeout via config.json

* Solve review comments
2025-10-22 12:49:39 -03:00
Ryan Crowley
553bd3993a Add optional strict parameter to PivotPointsHighLow indicator (#9033)
* Add optional strict parameter to PivotPointsHighLow indicator for relaxed comparison

- Added bool strict parameter (default true) to PivotPointsHighLow constructors
- When strict=true: Uses strict inequalities (> and <) - existing behavior
- When strict=false: Uses relaxed inequalities (>= and <=) - allows equal values
- Updated comparison logic in FindNextLowPivotPoint and FindNextHighPivotPoint
- Added new PPHL overload in QCAlgorithm.Indicators.cs with strict parameter
- Added 5 comprehensive unit tests using TestCase attributes
- All tests pass (19/19 relevant tests)
- Backwards compatible: default behavior unchanged

Addresses #8881

* Fix PPHL method signature to resolve overload ambiguity and maintain API consistency

- Remove wrapper overload to eliminate compilation ambiguity
- Reorder parameters: strict parameter now before resolution
- Keep selector as last parameter (consistent with other indicator helpers)
- Add unit tests verifying no overload ambiguity and correct strict parameter behavior

Addresses PR review feedback on #9033

* Implement backward-compatible PPHL overloads to support strict parameter

Added a second overload to maintain backward compatibility while introducing
the strict parameter. This prevents breaking changes for existing code that
uses positional arguments with the PPHL helper method.

Changes:
- Added backward-compatible overload that accepts (symbol, lengthHigh, lengthLow,
  lastStoredValues, resolution, selector) and delegates to the new implementation
  with strict: true
- Kept the new overload with strict parameter as the primary implementation
- Added comprehensive test (QCAlgorithmHelperOverloadResolution) documenting all
  9 valid call patterns to prevent future regressions

This approach ensures:
- Existing calls like PPHL(symbol, 3, 3, 100, Resolution.Minute) continue to work
- New calls like PPHL(symbol, 3, 3, strict: false) are supported
- No ambiguity in overload resolution
- All 23 PPHL tests pass successfully

* Clean up some test duplication

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2025-10-22 09:26:24 -03:00
JosueNina
e74bfeb7f9 Update SPDB - Binance Exchanges (#9054)
* Update SPDB with Binance

* Update SPDB with BinanceUS

* Update SPDB - BinanceUS to solve issues with the unit tests
2025-10-22 09:26:00 -03:00
Martin-Molinero
9ab9fe5f2b Python performance improvement (#9052)
* Minor tweak to cache liquidation fees

* Result handler cleanup

* Update pythonnet version to 2.0.49
2025-10-21 12:34:52 -03:00
Jhonathan Abreu
93e7e3edb4 Fix setting brokerage model after adding security initializer (#9048)
* Fix settting brokerage model after adding security initializer

* Minor fix

* Minor change

* Minor change

* Send warning for calling SetBrokerageModel before setting or adding security initializer

* Send warning for calling SetBrokerageModel before setting or adding security initializer

* Minor change

* Minor change

* Cleanup
2025-10-20 16:32:59 -04:00
JosueNina
49fe020b84 Add ObjectStore limit properties (#9043)
* Initial solution

* Add Unit tests

* Solve review comments

* Fix broken tests

* Solve review comments

* Updated property names
2025-10-20 17:21:31 -03:00
Martin-Molinero
6c95372d27 Disable OHLC session tracking by default (#9046)
* Disable OHLC session tracking by default

* Minor test fix
2025-10-17 15:59:50 -03:00
Jhonathan Abreu
cfd46cf63f Add QCAlgorithm.AddSecurityInitializer method (#9042)
* Add new QCAlgorithm.AddSecurityInitializer method

This allows to add multiple security initializers without manually creating an instance of a CompositeSecurityInitializer

* Add Python support

* Cleanup
2025-10-16 09:51:18 -04:00
JosueNina
ff1638f653 Support CustomData in SecurityCache.GetData(PyObject type) method (#9036)
* Initial Solution

* Add regression algorithms

* Solve review comments

* Update CustomDataSecurityCacheGetDataRegressionAlgorithm.py

---------

Co-authored-by: Martin-Molinero <martin.molinero1@gmail.com>
2025-10-16 10:37:00 -03:00
Lorenzo Vagliano
0dff60442e Fix: Add obsolete flag to AddUniverse coarse+fine (#9031)
* Fix: Add obsolete flag to AddUniverse coarse+fine

Added obsolete flag to AddUniverse(Func<IEnumerable<CoarseFundamental>, IEnumerable<Symbol>> coarseSelector, Func<IEnumerable<FineFundamental>, IEnumerable<Symbol>> fineSelector), added one time logging and altered docs accordingly.

* Update QCAlgorithm.Universe.cs

---------

Co-authored-by: Martin-Molinero <martin.molinero1@gmail.com>
2025-10-16 10:24:22 -03:00
Martin-Molinero
d8d6deb675 Add support for Brokerage ActionRequired message type (#9040)
* Add support for Brokerage ActionRequired message type

* Minor syntax check typo fix
2025-10-15 13:05:14 -03:00
Martin-Molinero
81b2d45440 Add Consolidator Optional Start time (#9034)
- Add consolidators optional start time. Adding tests
2025-10-14 11:04:21 -03:00
JosueNina
fda4859b5a Support Future Options for Continuous Futures (#9022)
* Support Future Options for continuous futures

* Solve review comments

* Resolve review comments

* Improve regression algorithms

* Use canonical symbols in OptionChains lookups

* Solve review comments
2025-10-13 18:20:12 -03:00
Martin-Molinero
9fa2630dc8 Add implicit security to symbol (#9032)
- Add implicit conversion from security to symbol. Adding regression
  algorithms
2025-10-13 17:58:57 -03:00
Ryan Crowley
b27e9e67dd ProcessSplitSymbols crashes during live/paper trading warmup with InvalidOperationException #9029 (#9030)
* Fix ProcessSplitSymbols crash during live mode warmup

Fixes InvalidOperationException when CancelOpenOrders is called during warmup in live/paper trading mode.

When historical splits are replayed during live mode warmup, ProcessSplitSymbols attempts to cancel open orders for option contracts, but CancelOpenOrders throws an exception during warmup.

The fix adds an early return when algorithm.LiveMode && algorithm.IsWarmingUp. This is safe because in live/paper trading, current positions already reflect historical splits.

Includes unit tests validating the fix.

* Some improvements and more tests

- Ignore splits during warmup for backtesting and live trading. Adding a
  regression algorithm reproducing issue

* Minor fix

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2025-10-13 13:21:09 -03:00
Martin-Molinero
afa7cce46a Add ShortMarginInterestRateModel (#9028)
* Add ShortMarginInterestRateModel

- Add new ShortMarginInterestRateModel, and regression algorithms
  asserting the behavior

* Minor syntax check fix
2025-10-13 12:35:03 -03:00
Martin-Molinero
e9c15b2806 Minor refactor to use lazy timer schedling (#9027)
- RateGate, TimeMonitor and ObjectStore won't schedule timer unless
  required
2025-10-13 09:21:27 -03:00
Martin-Molinero
8ee7a190c6 Minor fix for negative rolling window index (#9026)
* Minor fix for negative rolling window index

- Minor fix for negative rolling window index when partially full,
  adding unit test

* Reduce RefreshesSymbolProperties test runtime
2025-10-10 17:47:58 -03:00
Martin-Molinero
ec3b7a8e6a Remove CFD IB MOC and MOO restriction (#9025) 2025-10-10 15:20:27 -03:00
Martin-Molinero
58b422976a Skip langchain from syntax check (#9023) 2025-10-10 11:46:09 -03:00
Martin-Molinero
ee0cf7b3d3 Update virtual-environments.yml 2025-10-10 11:34:26 -03:00
Martin-Molinero
ebda5dba93 Minor api CI fix (#9024) 2025-10-10 10:54:24 -03:00
Martin-Molinero
89110aa9f6 Update PythonVirtualEnvironmentTests.cs 2025-10-09 16:29:06 -03:00
Martin-Molinero
6f94d765fc Update readme.md 2025-10-09 13:14:08 -03:00
Martin-Molinero
fd940463b5 Foundation update oct 2025 (#9020)
* Freeze autoray version to 0.7.2 in foundation image

Required for compatibility with pennylane package

* Update foundation image

- Updating foundation image libraries and new libraries and tests

* Some more foundation tweaks

---------

Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
2025-10-09 12:54:03 -03:00
Roman Yavnikov
3f8fd6ac3d Feature: support ComboLimit Order type in TastyTrade and refactor BrokerageTests (#9003)
* feat: support new OrderType in TastytradeBrokerageModel

* feat: extension GetGroupQuantity

* refactor: WaitOneAssertFail to return bool

* refactor: GetOpenOrders in BrokerageTests

* feat: display holdings when begin/end test run

* refactor: brokerageTest class to support handle combo order
feat: comboOrderTestParameters
feat: tastytrade option strategy algo

* refactor: Tastytrade Algo BullCallSpread

* feat: Bull/Bear-CallSpread test cases in BrokerageTests
feat: ComboLimitOrderTestParameters

* fix: remove static in ComboLimitOrderTestParameters of ExpectedStatus

* feat: restrict submit combo limit cross zero orders in Tastytrade
test:feat: submit combo limit cross zero test cases in tastytrade

* test:fix: missed test helper to c9907b23

* refactor: GetGroupQuantityByEachLegQuantity
feat: overload GreatestCommonDivisor
test:feat: GetGroupQuantityByEachLegQuantity

* test:feat: extra test cases to GetGroupQuantity to 925c214a

* test:refactor: take out Cancel Status update in HandleEvents()

* feat: prop Direction in Leg

* Revert "feat: prop Direction in Leg"

This reverts commit 4f92f97b63.

* refactor: ComboLimitOrderTestParameters

* test:refactor: CancelOrders

* test:feat: add missed xml description

* test:feat: support ModifyUntilFilled Combo orders

* test:feat: Long/Short-Combo unit tests

* test:fix: compare all status if it is combo order type

* test:refactor: applyOrderUpdate in gracefully way in LimitOrderTestParameters

* remover: Tastytrade algo

* test:feat: create new BaseOrderTestParameters with helper methods
test:rename: method in ComboOrderTestParameters
test:remove: duplication
2025-10-06 23:42:30 +03:00
Martin-Molinero
758c1704b5 Minor fix for backtesting stremaing portfolio margin (#9012) 2025-10-03 19:26:10 -03:00
Martin-Molinero
0e5b6ce91e Improve portfolio margin chart (#9011)
- Add StackedBar Series type
- Minor improvements for portfolio margin chart
2025-10-03 17:56:27 -03:00
Jhonathan Abreu
ccf32d3b4f Remove unnecessary constructors from Python models (#9008) 2025-10-02 12:40:29 -04:00
Martin-Molinero
0026cca422 Fix 6N, LBS also ES,EMD,YM,NQ (older) FOP expirations (#9006) 2025-10-01 12:33:46 -03:00
Jhonathan Abreu
633833e3c7 Fix data normalization mode requirement for adding FOP contracts (#9002)
* Fix data normalization mode requirement for adding fop contracts

* Minor change

* Minor fix

* Minor fix
2025-09-30 14:54:04 -04:00
Jhonathan Abreu
be64cdffa0 Minor fix for period history api (#9001)
* Fix extended hours only days period history

Don't include extended hours only days in date range calculated fro period history request

* Add comments

* Cleanup

* Revert some changes

* Cleanup
2025-09-30 09:51:40 -04:00
Martin-Molinero
9670a6684f Fix more FOP expirations (#8998) 2025-09-29 11:42:14 -03:00
Jhonathan Abreu
8447137a3f Add algorithm as parameter to IExecutionModel.OnOrderEvent (#8996) 2025-09-26 17:01:00 -04:00
Martin-Molinero
e75bbf9615 Fix soybean meal & oil FOP expiration (#8995)
* Fix soybean meanl FOP expiration

* Fix Soybean oil FOPs
2025-09-26 17:58:36 -03:00
Jhonathan Abreu
68af7ec15d Expose order ids related to statistics closed trades (#8989)
* Expose related order IDs in closed trades

TradeBuilder.ClosedTrades[*].OrderIds now have the order ids related to each trade

* Minor fix
2025-09-26 11:52:37 -04:00
Jhonathan Abreu
f08ac5bcce Add OnOrderEvent method to IExecutionModel (#8987)
* Add OnOrderEvent to IExecutionModel

Feed order events to execution models

* Minor Python fix
2025-09-26 11:52:28 -04:00
Martin-Molinero
ff2d749d61 Minor performance improvement for session tracking (#8990) 2025-09-25 18:58:41 -03:00
vb-vlb
4cc1dec80b Add VBaseSignalExport (#8954)
* Add VBaseSignalExport

* Add a VBaseSignalExport feature that allows signals to be stamped with the help of the ValidityBase REST API.

* Addressing review comments

* Create DefaultApiBaseUrl  const in VBaseSignalExport

* Add vbase signal export demonstration algorithm

* Set initial parameters for VBaseSignalExportDemonstrationAlgorithm

* Refactor VBaseSignalExport and demonstration algorithm: update symbol list, extend end date, and improve API base URL handling

* Initialize allowed security types in VBaseSignalExport and fix symbol reference in CSV generation

* Adjust rate limiter for vBase signal export to allow 6 requests per hour for better performance

* Minor tweaks

---------

Co-authored-by: Volodymyr Bobko <volodymyr.bobko@un.org>
Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2025-09-24 12:47:32 -03:00
Roman Yavnikov
75993cd021 Feat: Validation for Market On Open Submission Time (#8969) 2025-09-22 20:40:33 +03:00
JosueNina
f7ce35ae82 Track OHLCV for Current Trading Day (#8922)
* Implement Session class

* Use MarketHourAwareConsolidator inside Session

* Delete SecurityCacheSessionConfig

* Refactor session class

* Solve review comments

* Fix regression algorithms

* Add null check to AvailableDataTypes

* Update session class

* Solve new review comments

* Add new test for futures and update regression test to PEP8

* Add new regression algorithm for Session with futures

* Resolve review comments

* Add local time keeper to SecurityCache

* Scan on consolidator updates and time updates

* Add new regression algorithms and unit tests

* Add unit tests and improve comments

* Fix syntax test

* Solve review comments

* Add regression algorithms

* Resolve review comments

* Make SessionConsolidator implement IDataConsolidator

* Add caching to avoid recreating SessionBar instances on every access

* Solve review comments

* Make SessionConsolidator inherit from MarketHourAwareConsolidator

* Add unit test to verify Session preserves previous day values

* Update regression algorithms

* Solve review comments

* Resolve review comments

* Solve new review comments

* Add unit test for Session class

* Refactor SessionBar properties and Update method

* Use WorkingDataInstance reference instead of _workingData.Clone()

* Use a delegate to get the workingBar instance

* Fix bug in MarketHourAwareConsolidator

* Solve review comments

* Handle OI values

* Add regression algorithms for future contracts and options

* Solve review comments

* Refactor SessionConsolidator to inherit PeriodCountConsolidatorBase

* Prevent overlapping higher resolution data

* Update tests

* Solve review comments

* Minor tweaks
2025-09-19 12:25:24 -05:00
Jhonathan Abreu
36404a6187 Adjust async orders handling in backtesting (#8979)
Submit (and fill in case of market orders) in the same time step even if orders are asynchronous in backtesting since it's data driven instead of real time driven.
2025-09-18 11:53:28 -04:00
Jhonathan Abreu
496f210116 Fix start time calculation for daily requests (#8975)
* Fix start time calculation for daily request

* Minor regression algorithm fix
2025-09-15 18:35:25 -03:00
Jhonathan Abreu
b25d53ed6d Minor config fix (#8974) 2025-09-15 12:48:35 -03:00
Jhonathan Abreu
ee7be1a233 Enable concurrency for live paper brokerage (#8972)
* Enable concurrency for paper brokerage.

Implement PaperBrokerageTransactionHandler to handle concurrency for live paper trading transaction handler

* Remove PaperTradingBrokerageTransaction handler

Favor existing BacktestingTransactionHandler

* Minor fixes and cleanup

* Minor unit tests fix
2025-09-15 09:25:49 -04:00
Jhonathan Abreu
5644520545 Refactor some unit and regression tests for speed improvements (#8970)
* Reduce history unit tests duration

* Unit and regression tests speed improvements

* Minor change

* Fix unit test race condition
2025-09-12 10:15:09 -04:00
Roman Yavnikov
5b465216f9 feat: support StopLimit in CharlesSchwabBrokerageModel (#8968) 2025-09-10 20:15:02 +03:00
Jhonathan Abreu
d82d70dacf Support asynchronous non-market orders (#8946)
* Add 'asynchronous' parameter to trading api

* Add regression algorithms

* More fixes for asynchronous orders

* Fix failing unit tests

* Fix failing unit tests

* Add multiple orders requests in transaction handler

Make each transaction thread handle requests corresponding to the same order

* Refactor order state machine in BrokerageTransactionHandler

Now using a single dictionary to hold orders and their state, either pending for submission, open or closed.

* Revert: remove complete orders from new state machine in BTH

* Add order ticket to new BTH open orders state machine

* Run syn in Backtesting transaction handler for new orders submission

* Remove OpenOrderState.SubmissionPending property

* Add Security to OpenOrderState

* Minor fix

* Cleanup

* Some cleanup in BTH

* Cleanup

* Minor fix

* Minor unit test fix

* Minor fix

* Make Brokerage.ConcurrencyEnable property virtual

* Minor change

* Cleanup

* Add 'asynchronous' parameter to SetHoldings api

* Improve regression algorithms
2025-09-10 08:29:50 -04:00
Roman Yavnikov
23afff13fc Feature: new property AccountType (#8967)
* feat: new prop AccountType

* refactor: change data type use string instead of int for AccountType

* feat: add init of AccountType in ctor
2025-09-09 11:11:16 -03:00
Jhonathan Abreu
d7b4fb002f Make Brokerage.ConcurrencyEnabled virtual (#8966) 2025-09-09 09:39:37 -04:00
Roman Yavnikov
85fe39e31b Fix: prevent use CrossZeroOrder with MOO and MOC (#8959)
* feat: not use CrossZeroOrder for MOO and MOC

* Revert "feat: not use CrossZeroOrder for MOO and MOC"

This reverts commit 1a71c5fe90.

* feat: Not support crossZeroOrderTypes
test:feat: cross zero orders

* Revert "feat: Not support crossZeroOrderTypes"

This reverts commit 16785b5d2f.

* feat: not support CrossZeroOrder in TradeStation

* feat: not allow to place MOO and MOC with CrossZeroOrder

* test:feat: MOO and MOC CrossZeroOrder reject
2025-09-08 22:44:13 +03:00
Martin-Molinero
690eb7fc9f Fix python packages CI tests (#8962)
* Fix python packages CI tests

* Remove failing onnx related tests
2025-09-08 11:57:32 -03:00
Martin-Molinero
e44f8cd498 Minor fix for lean data writer merge policy (#8952)
* Minor fix for lean data writer merge policy

- Fix typo in lean data writer merge policy. Enhancing existing unit
  tests

* Minor unit test fix
2025-09-03 12:25:18 -03:00
Roman Yavnikov
ceb52c1b9b feat: make virtual Subscribe() in DataQueueHandlerSubscriptionManager 2025-08-29 18:36:11 +03:00
Jhonathan Abreu
dea1d2eac3 Update Python syntax check rate script accepted success rate (#8944)
* Update Python syntax check script

* Update python syntax check script accepted success rate
2025-08-27 17:28:46 -04:00
Martin-Molinero
f448ab7372 Update run_syntax_check.py 2025-08-27 10:28:49 -03:00
Martin-Molinero
fd9c29c87c Add US futures market halt (#8943) 2025-08-27 10:27:17 -03:00
Jhonathan Abreu
0b62fefb10 Add CFE futures 2026 holidays to MHDB (#8942)
* Add CFE futures 2026 holidays to MHDB

* Fix typo
2025-08-26 12:51:39 -04:00
Jhonathan Abreu
e13214135a Add support for some CME currencies FOPs (#8939)
* Add support for some CME currencies FOPs

Support ADU (6A), GBU (6B), CAU (6C), EUU (6E), JPU (6J), CHU (6S)

* Cleanup

* Consider holidays in FOPs expiry function
2025-08-25 18:02:07 -04:00
Roman Yavnikov
c2fdfb235a feat: global OrderProperties property in abstract Brokerage class to liquidate positions with specific properties (#8938)
fix: missed OrderStatus in ...OrderTestParameters classes
feat: override ToString() in ...OrderTestParameters classes
2025-08-21 19:13:15 -03:00
Jhonathan Abreu
50f8633e90 More Python syntax checks and improvements (#8937)
* More python syntax checks

* More changes

* More changes

* Make PythonConsolidator derive from IDataConsolidator

* More changes

* More changes

* Update python syntax check accepted rate

* Update Update python syntax check accepted rate

* Cleanup

* Cleanup
2025-08-21 12:47:38 -04:00
Martin-Molinero
a3ad12e7e0 Fix tick resolution continuous contract history request (#8936)
- Fix tick resolution continuous contract history requests. Adding unit
  tests
- Some improvements for OpenInterest explicit request. Adding unit tests
2025-08-19 14:21:49 -03:00
Martin-Molinero
db25a3402e Normalize OutOfSampleMaxEndDate datetime format (#8935)
- Normalize OutOfSampleMaxEndDate datetime format. Adding unit test
2025-08-18 18:44:25 -03:00
Martin-Molinero
06f0da69c3 Improve schedule rules symbol handling (#8930)
- Improve schedule rules non existing symbol handling. Adding regression
  tests
2025-08-15 14:59:11 -03:00
Jhonathan Abreu
838232e696 Update Pythonnet version to 2.0.48 (#8929) 2025-08-15 13:04:02 -04:00
JosueNina
e13f8c10a7 Add tag to RemoveSecurity method (#8928)
* Add tag parameter, update CancelOpenOrders and Liquidate calls

* Resolved commen on the related PR: following the pattern of Liquidate() using Liquidated as default, I think the tag should be Removed

* Add tag parameter to RemoveSecurity and update regression algorithms

* Minor tweaks

---------

Co-authored-by: meysam <poormonfared.azimi@gmail.com>
Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2025-08-15 10:40:35 -03:00
Jhonathan Abreu
4c3e79b441 Bump Pythonnet version to 2.0.47 (#8927) 2025-08-14 12:09:07 -04:00
Martin-Molinero
cffd20236c Object store dispose hang (#8925) 2025-08-13 18:18:48 -03:00
Martin-Molinero
3f04b6c90a Update readme.md 2025-08-13 15:04:36 -03:00
Martin-Molinero
852c9cd856 Update IB gateway v10.39.1f (#8923) 2025-08-13 14:51:48 -03:00
Martin-Molinero
37237206dd Use ISO for DateTime JsonConverter (#8919)
- Use ISO for DateTime JsonConverter, keeping backwards compatible.
  Adding unit test
2025-08-13 10:27:30 -03:00
Jared
58979872c1 Delete Api/QuantConnect-Platform-2.0.0.yaml (#8924)
YAML is now hosted in the documentation 
https://github.com/QuantConnect/Documentation/blob/master/QuantConnect-Platform-2.0.0.yaml
2025-08-13 09:43:46 -03:00
Jhonathan Abreu
4c4a34007d Python syntax algorithms fixes (#8916)
* Python syntax algorithms fixes

* More fixes

* More fixes

* Minor fix

* Update python syntax check accepted percentage
2025-08-11 10:55:00 -04:00
JosueNina
a7265c8a41 Place orders only when the algorithm is running (#8917)
* Place orders only when the algorithm is running

* Solve review comments

* Split unit test into separate cases

* Move the algorithm assignment
2025-08-11 11:48:17 -03:00
Martin-Molinero
db96e9e8e4 Minor fix for DAX index market (#8918) 2025-08-07 17:12:05 -03:00
Jhonathan Abreu
cc79cab3dc Support new Pythonnet delegates auto conversion (#8913)
* Use new Pythonnet support for automatic delegates conversion

* Update Pythonnet version to 2.0.46

* Cleanup

* Minor fix

* Add unit tests
2025-08-07 09:40:06 -04:00
JosueNina
69dfdcefc5 Fix EndTime for consolidated bars in count-based consolidator (#8911)
* Set consolidated bar EndTime to last input's EndTime in count-based consolidator

* Solve review comments

* Move EndTime assignment to base class

* Update unit tests
2025-08-06 17:17:57 -03:00
JosueNina
f29bcbc9ae Clean up ListLiveAlgorithms method parameters (#8912)
* Remove startTime and endTime parameters from ListLiveAlgorithms method

* Solve review comments
2025-08-05 19:12:48 -03:00
JosueNina
5ba7f611dd Refactor SubscriptionDataConfigTypeFilter method (#8903)
* Refactor SubscriptionDataConfigTypeFilter method

* Solve review comments

* Resolve review comments

* Clarify why Tick type doesn't rely on matchingSubscriptions

* Use subscription attributes to generate Tick history requests

* Solve review comments
2025-08-04 19:16:39 -03:00
Giri
101d382594 Feature 6620 implement td sequential candlestick indicator (#8877)
* initial draft changes

* Saving draft changes for TD Sequential Implementation

* Fixed failing tests

* Refactoring changes

* Additional refactoring to TDSequential

* Added tests

* Incorporated review comments

* reverted changes to older file

* Updated for review comment

* Updated Buy and Sell Setup Perfect functions based on review comment to remove equality operator

* Added SupportPrice and ResistancePrice as read-only public properties to expose the internal _resistance and _support prices

* Changed return value of ComputeNextValue to TomDemarkSequentialPhase instead of the encoded value of Phase.StepCount as per review comment

* Updated initialization to include bullish and bearish flip checks

* Refactored and cleaned up based on review comments
2025-08-01 12:54:58 -03:00
Jhonathan Abreu
3ef41ee2c9 Fix for Python GetEnumString backwards compatibility (#8907) 2025-08-01 09:56:23 -04:00
Martin-Molinero
4e71203b4c Brokerage downloader daily/hour skips extended market hours (#8906)
- Adjust brokerage data downloader daily and hour resolution requests to
  skip requesting extended market hours
- Add missing dispose of brokerage
2025-07-31 20:08:26 -03:00
Jhonathan Abreu
84b991b577 Some fixes for new C# enums handling in Pythonnet (#8898)
* Some fixes for new C# enums handling in Pythonnet

* Minor changes and cleanup

* Update Pythonnet version to 2.0.45

* Minor changes

* Minor fix

* Minor fix

* Minor change

* Minor change

* Minor unit test fix
2025-07-31 16:53:24 -04:00
Martin-Molinero
9f378a1a6d Minor helper method and tests (#8905) 2025-07-31 16:27:00 -03:00
Roman Yavnikov
8df6c77ca8 feat: update bitfinex spd (#8902) 2025-07-31 11:45:07 -03:00
Aibek Minbaev
eac9fa0d69 Log the Number of Active Subscriptions Before and After Warm Up #8779 (#8880)
* Log the Number of Active Subscriptions Before and After Warm Up #8779

* Refactor: Log subscriptions count once before first timeslice

* Resolve review comments

* Minor cleanup

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2025-07-29 10:47:23 -03:00
Roman Yavnikov
435a82b4db feat: update kraken spd (#8899) 2025-07-29 10:03:08 -03:00
JosueNina
2b7b26d512 Add Consolidate method overload with size parameter (#8882)
* Initial Solution

* Add comments and asserts to the regression algorithm

* Solve review comments

* Update regression algorithm

* Solve review comments

* Resolve review comments

* Add python support

* Add consolidators that use maxCount in the constructor

* Solve review comments
2025-07-28 16:16:56 -03:00
Roman Yavnikov
a64f70888d Refactor: shorten execution time for auth tests (#8892)
* refactor: shorten execution time for auth tests

* remove: jsonBody info from exception
fix: validation attempt to retry
2025-07-25 10:34:03 -03:00
Roman Yavnikov
ad1f1c629c Refactor: minor cleanup (#8886)
* feat: Get AccessToken from Lean API

* feat: create TokenCredentials DTO instead of Tuple

* remove: extra unrequired null reference exceptions on argument check

* remove: SendAsync override in TokenHandler

* feat: override SendAsync in TokenHandler to prevent future bugs

* test:feat: SyncAsync in TokenHandler

* refactor: name property of AccessTokenExpires to Expiration in AccessTokenMetaDataResponse

* feat: add retry logic to getAccessToken in TokenHandler
test:feat: TokenHandler with retry logic

* feat: make retry timeout configurable in ctor
2025-07-24 19:25:54 -03:00
Jhonathan Abreu
0d6d2f7c46 Fix custom data history on any symbol (#8890) 2025-07-24 18:18:54 -04:00
Jhonathan Abreu
0282954b57 Fix launcher exit on null job (#8889) 2025-07-24 18:04:31 -04:00
Jhonathan Abreu
2372153eec Exit properly from launcher program (#8888)
Don't leave unhandled exceptions and exit properly from program
2025-07-24 15:37:05 -04:00
Jhonathan Abreu
480790e3f3 Add messaging handler initialize parameter to job queue (#8887) 2025-07-24 09:27:19 -04:00
Jhonathan Abreu
014389a880 Refactor order ticket (#8884)
* Refactor and clean up OrderTicket class

* Reduce locks quantity in OrderTicket

* Cleanup

* Address peer review
2025-07-23 10:14:13 -04:00
Martin-Molinero
d703cc6660 Update readme.md 2025-07-23 09:47:26 -03:00
Martin-Molinero
12be29fcfb Add live tick sale condition (#8883) 2025-07-22 16:17:16 -03:00
Jhonathan Abreu
546afd2a61 Async orders in execution models (#8872)
* Changed default async to true and passed target.Tag

* Make execution models place orders asynchronously if specified

* Add unit tests

* Execution model default to asynchronous orders.

Also, minor fixes for tickets remaining fill quantity potential race conditions

* Add SecurityHolding.UnrealizedQuantity property

It gets the holding quantity the security will have once all open orders are filled.
Added for thread safety reasons when execution models place asynchronous orders and need to calculate the actual quantity needed to reach the target of there are open orders

* Some cleanup

* Adjust projected holdings quantity on splits

* Minor fix

* More changes and cleanup

* Minor fix

* Improvements for thread safety

* Add IOrderProvider.GetProjectedHoldings to get projected holdings atomically

* Minor unit tests fix

* Add ProjectedHoldings DTO class

* Address peer review

---------

Co-authored-by: arthiondaena <arthiondaena@gmail.com>
2025-07-21 13:11:03 -04:00
JosueNina
9f5f93c5a6 Refactor TargetDownsideDeviation Calculation (#8875)
* Update implementation of TargetDownsideDeviation

* Use ROC's rolling window instead of creating a new one
2025-07-18 17:11:51 -03:00
Martin-Molinero
9df9f32827 Update readme.md 2025-07-17 19:21:03 -03:00
JosueNina
7008d17714 Add MaxDrawdownRecovery metric (#8865)
* Implement  a prototype of the maximum recovery time function.

* Add unit test skeletons.

* Add failing test

* Issue #4581: Implement MaxDrawdownRecoveryTime.

* Issue 4581: Add DTO for Drawdown Percentage, Drawdown Enddate, and High Value

* Issue 4581: Fix bgu for when lDrawdowns list is empty.

* Issue 4581: Change names of tests. Change name of file.

* Issue 4581: Make adjustements to flow of adding drawdowns to lDrawdowns.

* Issue 4581: Add multiple unit tests.

* Issue #4581: Change name of unit test

* Issue #4581: Add to PerformanceMetrics

* Issue #4581: Add Maximum Drawdown Recovery to PortolioStatistics class.

* Issue #4581: Add to portolfio statistics class.

* Issue #4581: Add to statistics builder.

* Issue #4581: Add report key.

* Case #4581: Convert to decimal.

* Issue #4581: Correct comment.

* Issue #4581: Correct performance metrics view model string.

* Case #4581: Correct statistics builder view model string..again.

* Issue #4581: Placed DradownDradownDateHighValueDTO at the end of the file for simpler diff.

* Issue #4581: Add 2 new tests.

* Issue #4581: Change algorithm so that when multiple maximum drawdowns occur, the longest of all recoveries is reported.

* Issue #4581: Add unit test.

* Issue #4581: Remove reportkey. Change dto name.

* Issue #4581: Change summary.

* Issue #4581: Change comment.

* Add max drawdown recovery calculation with unit tests

* Update regression algorithms with the new metric

* Solve review comments

* Update regression algorithms

* Add TryGet to safely get the key: MaximumDrawdownRecovery

* Ignore MaximumDrawdownRecovery metric in OptimizationBacktest Json

* Revert changes in Messaging

* Update regression algorithms

* Add test case: TakesLongestRecoveryAmongMultipleDrawdowns

* Use integer days for MaximumDrawdownRecovery

* Add MaximumDrawdownRecoveryReportElement

* Use more explicit names

* Rename files and variables for consistency

* Update regression algorithms

---------

Co-authored-by: Alain Schaerer <aschaerer@pcatg.com>
2025-07-17 16:32:23 -03:00
Jhonathan Abreu
734a99392e Make python syntax check pass if success rate is over accepted threshold (#8873) 2025-07-16 11:22:20 -03:00
JosueNina
3d763cf98d Rename to Momersion and add legacy wrapper for compatibility (#8876) 2025-07-16 11:22:06 -03:00
Martin-Molinero
d639c13d08 Remove unrequired notification rate limiter (#8870) 2025-07-14 11:40:23 -03:00
Jhonathan Abreu
e63217a953 New options/futures universe files format (#8848)
* Use correct sids when reading options/futures universe files

* Introduce new format for options and futures universe files

* Minor change

* Minor data fix

* Minor change

* Fix failing unit tests

* Add options and futures symbols cache

* [HACK] Force use test universe files

* Minor fix for universe symbols cache

* Performance improvements

* Miror change

* Cleanup

* Sort universe files

* Minor regression algorithm fix

AddAndRemoveOptionContractRegressionAlgorithm to not depend on universe file entries ordering
2025-07-11 16:38:14 -04:00
Martin-Molinero
910b50b787 Fix backtest create organization id type (#8868) 2025-07-11 10:09:17 -03:00
JosueNina
f0781413e0 Fill MarketOnClose orders at or after market close (#8858)
* Add time tolerance when checking if asset is within current bar

* Update IsExchangeOpen and add unit tests

* Solve review comments

* Add unit test in ImmediateFillModelTests

* Delete conditional IsExchangeOpen()

* Fill MOC orders when LocalTime is at or after market close
2025-07-10 18:24:38 -04:00
Martin-Molinero
233a357d9d IB fix does not support Combo FOPs (#8867) 2025-07-10 13:17:46 -03:00
Roman Yavnikov
96fcc032b9 feat: new IB config of FAGroup Filter (#8866) 2025-07-10 18:23:05 +03:00
Martin-Molinero
1f23813cf5 Update readme.md 2025-07-09 12:20:24 -03:00
Martin-Molinero
c2e9c16569 Add interactive fix order properties (#8864) 2025-07-09 12:15:11 -03:00
Jhonathan Abreu
2e9cc39c89 Rename Controls.StoragePermission -> Controls.StorageAccess (#8862)
* Refactor Controls.StoragePermissions format for the API

* Minor changes

* Rename Controls.StoragePermission -> Controls.StorageAccess

* Minor fix
2025-07-09 11:11:27 -04:00
JosueNina
ed551458f5 Use EndTime instead of Time for indicator updates (#8860) 2025-07-08 17:47:00 -04:00
JosueNina
4bfd93770c Add intercept parameter in ARIMA method (#8861)
* Add intercep parameter in ARIMA method

* Solve review comments
2025-07-08 17:46:48 -04:00
Jhonathan Abreu
09f0239101 Support concurrent transaction handlers (#8857)
* Allow multiple concurrent transaction handlers

Also support multiple producers in BrokerageConcurrentMessageHandler

* Minor change

* Minor change

* Add new maximum-transaction-threads config to json file

* Minor naming changes

* Address peer review and add unit tests

* Minor fix

* Minor fix and unit tests

* Address peer review
2025-07-07 18:38:09 -04:00
JosueNina
7c62e410b9 Improve IndicatorHistory<T> filtering of indicator properties (#8853)
* Support sub-indicator discovery using IIndicator and exclude PandasIgnore attribute

* WIP: PandasInclude

* Add PandasInclude annotation

* Resolve review comments

* Add a list of ignored properties

* Clean up [PandasIgnore] in IndicatorBase
2025-07-02 09:31:18 -03:00
Martin-Molinero
c69275a5fe Minor brokerage tests fix (#8855) 2025-07-01 17:03:17 -03:00
JosueNina
bc4458d293 Add progress logs to RandomDataGenerator (#8851)
* Add logs to GenerateTicks method

* Solve review comments

* Add unit test

* Resolve review comments
2025-06-26 17:03:44 -03:00
JosueNina
75ccf0199b Filter out default datetime values from the DataFrame (#8845)
* Initial solution: Filter out default datetime values from the DataFrame

* Solve review comments

* Resolve review comments

* Update AlgorithmIndicatorsTests.cs

---------

Co-authored-by: Martin-Molinero <martin.molinero1@gmail.com>
2025-06-25 11:21:03 -03:00
Martin-Molinero
1c82eb6313 Add interactive brokers fix model (#8849)
* Improve brokerage order update tests

* Add interactive brokeras fix model
2025-06-24 18:01:05 -03:00
Roman Yavnikov
45cc12a5c0 Feat: Level One Service (#8838)
* feat: new Level One service
feat: new ctor in Tick
fix: missed SetValue in Tick ctor

* refactor: LevelOneService
feat: Tick Event Args

* feat: use aggregator in LevelOneService explicitly
remove: extra TickEventArgs

* feat: ThreadSafeDataAggregatorWrapper
refactor: use ThreadSafeDataAggregatorWrapper in LevelOneService

* feat: generic LevelOne Market Data Manager
refactor: LevelOneMarketData
remove: ThreadSafeDataAggregatorWrapper

* feat: support OpenInterest in LevelOneMarketData
feat: add EventBasedDataQueueHandlerSubscriptionManager in LevelOneServiceManager
feat: handle OpenInterest

* feat: add missed license in BaseDataEventArgs

* feat: create un-subscribe wrapper in LevelOneServiceManager
refactor: TryGetLevelOneMarketData
feat: validate the same Quote data in LevelOneMarketData

* feat: handle nullable value in levelOneMarketData

* feat: handle nullable value in LevelOneServiceManager

* refactor: change location of LevelOneMarketData Service
test:feat: test of LevelOneMarketData

* feat: add SetIgnoreZeroSizeUpdates

* refactor: use ignoreZeroSizeUpdates internally in TryResolvePriceSize

* refactor: position add symbols in collection in  LevelOneServiceManager

* fix: validation of IgnoreZeroSizeUpdates setting in LevelOneMarketData

* test:feat: validate UpdateLastTrade with IgnoreZeroSizeUpdates setting
test:refactor: use global DateTime in testCases

* fix:test: missed calculation value in QuoteBar
2025-06-24 00:38:11 +03:00
Martin-Molinero
7bca81c4a8 Add TrailingStopOrderTestParameters (#8847) 2025-06-23 10:41:44 -03:00
Sai Revanth
2ca4c0573e Feature : Implements Parabolic SAR Extended (SAREXT) (#8818)
* sarext

* changes
2025-06-23 10:40:05 -03:00
Martin-Molinero
c1e3b79010 Minor brokerage test improvements (#8844) 2025-06-19 15:49:10 -03:00
Martin-Molinero
d1e927cfce Remove Juneteenth future generic holiday (#8841) 2025-06-19 08:26:25 -03:00
Martin-Molinero
3826b1d86a Update readme.md 2025-06-18 18:32:13 -03:00
JosueNina
b991dc8ada Add PyObject overload constructor to FilteredIdentity (#8840)
* Add PyObject overload constructor to FilteredIdentity for Python filter support

* Solve review comments
2025-06-18 18:31:22 -03:00
JosueNina
5729be4661 Make RollingWindow compatible with any data type (#8836)
* Make RollingWindow compatible with any data type

* Add generic RW<T> method

* Add RollingWindow wrapper class for PyObject

* Solve review comments

* Resolve review comments
2025-06-18 18:29:00 -03:00
Jhonathan Abreu
4dcd41b690 Wire and handle brokerage errors when used as DQH only (#8832)
* Wire and handle brokerage errors when used as DQH only

* Minor fix

* Minor fixes
2025-06-17 12:11:54 -04:00
Jhonathan Abreu
4602a9d222 Fill-forward last warmup data point to normal data feed (#8831)
* Fill-forward last warmup data point to normal data feed

* Minor clean up

* Minor changes and unit tests

* Address peer review

* Minor changes

* Improve unit tests
2025-06-17 12:07:58 -04:00
Martin-Molinero
e2de840aed Avoid empty public constructor from being removed (#8837) 2025-06-17 13:04:30 -03:00
Martin-Molinero
93d58d5cdf Minor fixes for quantbook (#8835) 2025-06-16 18:59:58 -03:00
Martin-Molinero
d611105413 Split conflicting python library tests run (#8830) 2025-06-13 17:14:55 -03:00
Roman Yavnikov
3f53f6ec77 refactor: change access modifier of GetFutureContractMonthNoRulesApplied (#8829) 2025-06-13 14:51:24 -03:00
Martin-Molinero
dbcb464268 Update PythonPackagesTests.cs 2025-06-13 13:39:57 -03:00
Martin-Molinero
26a00a2adb Update readme.md 2025-06-13 13:36:52 -03:00
Martin-Molinero
a75e132bed Foundation update (#8827) 2025-06-13 12:35:45 -03:00
Martin-Molinero
890fcd114e Fix Symbol EOD internal SecurityChanges handling (#8824)
- Fix Symbol EOD internal SecurityChanges handling. Adding unit test and
  regression test
2025-06-12 19:18:15 -03:00
arthion
f3d734c4fe Implements new indicator - KST - Know Sure Thing (#8819)
* feat: Implements Know Sure Thing

* Removed extra space

* Removed identity variables and returned value directly
2025-06-12 19:17:47 -03:00
JosueNina
dbdf014a4c Add BNFCR as stable coin without pair (#8821)
* Add BNFCR as stable coin without pair

* Add unit test

* Skip conversion in PerformCashSync when ConversionRate is zero

* Solve review comments
2025-06-12 19:17:32 -03:00
Martin-Molinero
0d70244d7b Update readme.md 2025-06-10 19:34:01 -03:00
Martin-Molinero
e72362b14d Update readme.md 2025-06-10 19:21:21 -03:00
Martin-Molinero
52365ed766 Update readme.md 2025-06-10 19:00:52 -03:00
Martin-Molinero
592118b323 Fix live warmup price scaling (#8822)
- Fix missing live warmup price scaling. Adding unit test
2025-06-10 13:30:43 -03:00
Martin-Molinero
cd01b769a6 Fix api ObjectStorageUsed size (#8823) 2025-06-10 13:14:14 -03:00
Jhonathan Abreu
9e349259b2 Conditional timeout for live fill forward (#8817)
* Wait for data before emitting fill forwarded bars only on market open/close in live trading

* Minor fixes and more unit tests
2025-06-10 10:58:56 -04:00
Matt Fair
b1ce8f0045 feature: Klinger Volume Oscillator (#8811)
* implements Klinger Volume Oscillator

* preserve newest data file

* improve class summary

* address PR comments, add signal line, use RollingWindow to persist data, refactor code to make easier to follow

* add helper method KVO in in QCAlgorithm.Indicators.cs, add Signal test, fix IsReady and WarmUpPeriod

* default signal period for KVO, refactor and improve ComputeNextValue, simplified code

* update comment

* update comment
2025-06-06 11:03:57 -03:00
Jhonathan Abreu
9e31261116 Add open interest data to future chains contracts (#8805)
* Add open interest data to future chains contracts

Even though futures chains and contracts are not created from internal subscriptions data (like OI subscriptions or continuous futures contracts subscriptions), we still want to add OI data to already created contracts given that OI subscriptions are always internal but trade an quote ones are not.

* Minor changes
2025-06-06 10:35:45 -03:00
Jhonathan Abreu
e70d783c93 Support stop limit orders for crypto futures in Binance (#8792)
Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2025-06-05 09:24:06 -03:00
Jhonathan Abreu
11ddf6abc2 Add support for stop limit orders in Bitfinex (#8810)
* Add support for stop limit orders in Bitfinex

* Add place order exception message to invalid order tag

* Minor change

* Minor change
2025-06-05 09:22:32 -03:00
Alexandre Catarino
515606dc35 Review Collective2 Implemention (#8773)
* Review Collective2 Implemention

According to `SetDesiredPositions` [API](https://api-docs.collective2.com/apis/general/swagger/strategies/c2_api_strategies/setdesiredpositions_post#strategies/c2_api_strategies/setdesiredpositions_post/t=request&path=positions), the quantity must be non-zero. To close a position, send stop sending a position.

The current for all assets, except FOREX, is the quote currency.

FOREX:
- Observe the [C2 minilot](https://support.collective2.com/hc/en-us/articles/360038042774-Forex-minilots)
- Currency is always USD

Unit tests:
- Increase the initial cash to accomodate FOREX minilot
- Additional message for minilot warning
- Fix currencies

* Addresses Peer Review
2025-06-05 09:21:57 -03:00
Jhonathan Abreu
61376cd5cc Support Equity Limit orders outside regular hours in Tradier (#8807)
* Support Equity Limit orders outside regular hours in Tradier

* Address peer review

* Minor change

* Minor change
2025-06-04 13:14:56 -04:00
Jhonathan Abreu
1fc0c37388 Support limit orders outside regular hours in Alpaca (#8800)
* Add support for Limit orders outside regular hours in Alpaca

* Minor change
2025-06-04 09:11:22 -04:00
Jhonathan Abreu
bfa0e26605 Add PostOnly TradeStation order property (#8787)
* Add PostOnly TradeStation order property

* Minor fix
2025-06-04 09:10:32 -04:00
Jhonathan Abreu
85bcb9ef43 Add support for trailing stop orders in TradeStation (#8780) 2025-06-04 09:10:28 -04:00
Jhonathan Abreu
abaa73ebce Add new IgnoreUnknownAssetHoldings algorithm setting (#8764)
* Add new IgnoreUnknownAssetTypes algorithm setting

* Wire brokerage message handler before algorithm initialization

* Ignore unknown assets by default

* Trigger Build

* Rename IgnoreUnknownAssetTypes to IgnoreUnknownAssetHoldings

* Minor change

* Minor change
2025-06-04 09:07:57 -04:00
Roman Yavnikov
d9bdbab810 Feature: Implementation Tastytrade Brokerage (#8809)
* feat: Tastytrade brokerage helper classes and configs

* refactor: TastytradeFeeModel
test:feat: TastytradeFeeModel
refactor: curl brackets in namespaces to keep project style
2025-06-04 10:03:46 -03:00
JosueNina
ba931a26c3 Restrict supported order types in Bitfinex brokerage (#8776)
* Limit supported order types to Market, Limit, and StopMarket in Bitfinex brokerage

* Update brokerage models

* Fix broken unit test

* Solve review comments

* Convert regression algorithm into a unit test

* Resolve review comments
2025-06-03 17:17:31 -03:00
Alexandre Catarino
1d6a5472b0 Updates Python Example get_value to get (#8806)
`get` is the Pythonist way to access a dictionary.
Also, `not x` replaces `is None`, since the former translates into is None or empty.
2025-06-03 17:03:12 -03:00
Derek Melchin
c9c892510a Fix comment (#8788) 2025-06-03 17:00:03 -03:00
JosueNina
666f810dd9 Refactor AverageTrueRange to use TrueRange implementation (#8785)
* Refactor AverageTrueRange

* Solve review comments
2025-06-03 15:57:26 -04:00
JosueNina
4363801ec9 Add alias for AccumulationDistributionOscillator(ChaikinOscillator) (#8781)
* Add alias to AccumulationDistributionOscillator(ChaikinOscillator)

* Add unit tests for ChaikinOscillator
2025-06-03 15:49:29 -04:00
JosueNina
29ab1d6acd Initial solution (#8772) 2025-06-03 14:35:59 -04:00
JosueNina
5d732a877a Add support for negative indexing in RollingWindow (#8770)
* Add support for negative indexing in RollingWindow

* Solve review comments

* Resolve comments review
2025-06-03 14:33:08 -04:00
JosueNina
2edac83d4f Ensure Indicator.Current retains the Symbol from the latest input data (#8767) 2025-06-03 15:26:42 -03:00
JosueNina
791a40596a Update SPDB with CoinBase, ByBit, Bitfinex, Kraken, Binance and BinanceUS (#8765)
* Update SPDB with Bybit

* Update SPDB with CoinBase

* Update SPDB with Bitfinex

* Update SPDB with Kraken

* Update SPDB with Binance

* Update SPDB with BinanceUS

* Update regression algorithms

* Update SPDB - Binanceus to solve issues with the unit tests
2025-06-03 15:21:59 -03:00
Jhonathan Abreu
54e58c6302 Add 2025 equity and equity options holidays (#8799)
* Add 2025 equity and equity options holidays

* Minor fix
2025-05-27 13:22:28 -04:00
JosueNina
eb8043e7c6 Fix problem with IsSubscriptionValidForConsolidator() method (#8754)
* Fix problem with IsSubscriptionValidForConsolidator() method

* Add regression algorithms using TickQuoteBarConsolidator

* Fix the method IsSubscriptionValidForConsolidator()

* Refactor IsSubscriptionValidForConsolidator method

* Resolve review comments

* Add new regression algo and update unit tests

* Update TickTradeBarConsolidatorWithQuoteTickTypeRegressionAlgorithm.cs

---------

Co-authored-by: Martin-Molinero <martin.molinero1@gmail.com>
2025-05-09 16:42:25 -03:00
Jhonathan Abreu
7dad4deb5a Support DAX EUREX indices (#8761) 2025-05-09 15:11:10 -03:00
Martin-Molinero
88947a96b9 Create SPDB and MHDB on engine constructor (#8760) 2025-05-09 10:54:51 -03:00
JosueNina
9f322e150b Update FutureSymbolGenerator to Use FuturesExpiryFunctions for Accurate Expiry Dates (#8749)
* Initial solution

* Solve review comments

* Fix unit tests

* Resolve comments reviews

* Return a default symbol instead of throwing an exception

* Add unit test
2025-05-09 09:20:55 -03:00
Jhonathan Abreu
201ea1ce74 More Python syntax check improvements (#8758)
* Ignore more mypy errors and fix more python algos syntax

* Minor change
2025-05-08 18:06:18 -04:00
Louis Szeto
d2d1ca5c9e Make Local Backtest Config Customizable (#8746)
* customizable lloocal backtest config

* bug fix

* address review
2025-05-08 11:34:18 -03:00
Jhonathan Abreu
5f27689c53 Improve python syntax check (#8744)
* Ignore some errors in python syntax check.

Fix some algorithms syntax as well.

* Revert some changes

* Minor change

* Minor change

* Minor syntax check fixes

* Ignore more mypy errors

* Minor changes

* Ignore more mypy messages

* Ignore more mypy messages
2025-05-07 19:45:17 -03:00
Martin-Molinero
dec831f361 Minor packet type additions (#8752) 2025-05-06 17:18:13 -03:00
Ricardo Andrés Marino Rojas
7942f7d6dc Fix failing API test (#8747) 2025-05-05 13:34:22 -03:00
JosueNina
359c7a7c8e Improve SecurityExchangeHours exception messages (#8741)
* Improve SecurityExchangeHours exception messages

* Solve comments review
2025-05-02 14:02:05 -03:00
Jhonathan Abreu
053c9a20c4 ExtendedDictionary improvements (#8723)
* Make ExtendedDictionary extend IDictionary

* Revert "Make ExtendedDictionary extend IDictionary"

This reverts commit bbbe9c769be682767cb9e487b904480376b53596.

* Make ExtendedDictionary key a type parameter

* Make SecurityPositionGroupModel an ExtendedDictionary

* Add unit tests

* Minor change

* Add more unit tests and other minor changes

* Add Count and ContainsKey to BaseChain

* Update pythonnet version to 2.0.43

* Update some python regression algorithms

* Minor regression algorithms fix

* Make CashBook and ExtendedDictionary

* Minor changes

* Minor changes

* Update pythonnet version to 2.0.44
2025-05-02 11:02:06 -04:00
Roman Yavnikov
4e13189787 Feature: support MOO in CharlesSchwabBrokerageModel (#8737)
* feat: support MOO in CharlesSchwabBrokerageModel

* feat: validate IsMarketOpen with MOO order type in PreOrderChecks

* test:feat: Validate MOO in various Market hours time

* fix: Algo with new MOO time validation

* test:fix: set DateTime of Algo explicitly in OrderQuantityConversionTest
2025-05-02 16:15:17 +03:00
Ricardo Andrés Marino Rojas
25c4a879f6 Add failure API backtest unit tests (#8703)
* First attempt

* Improve unit test

* Add suggestions

* Nit changes

* Address requested changes

* Fix failing unit tests

* First attempt to fix API tests

* Fix command

* Address suggestions

* Address minor suggestions
2025-05-01 15:48:46 -03:00
JosueNina
db3f567ebf Implement the missing python constructors for selection models (#8738)
* Initial solution

* Solve comments reviews

* Resolve comments reviews
2025-05-01 15:23:11 -03:00
Roman Yavnikov
abf0e70a20 Feature: support OutsideRegularTradingHours by TradeStation (#8734)
* wip: show work

* refactor: TradeStationBrokerageModel of using OutsideRegularTradingHours
test:feat: OutsideRegularTradingHours

* remove: comboLimit OrderType in IsLimitOrder(...)

* fix: regression algo which test unsupported OrderType in extend market hours

* fix: condition with supportsOutsideTradingHours in CanSubmitOrder

* refactor: regression test with OutsideRegularMarketHours TradeStation

* refactor: TradeStationBrokerageTradeWithOutsideRegularMarketHoursParameter

---------

Co-authored-by: Henry Ennis-Thomas <henry@henryetdev.com>
2025-04-29 18:52:41 -03:00
Jhonathan Abreu
33d850ae34 Add support for DAX EUREX futures (#8732)
* Add support for DAX EUREX futures

* Add margin files

* Minor change

* Minor changes
2025-04-29 16:06:50 -04:00
JosueNina
07f6cd494d Create DollarVolumeRenkoConsolidator (#8729)
* Initial solution

* Add unit test

* Solve review comments
2025-04-29 16:04:02 -04:00
Martin-Molinero
77a240ff25 Minor tweak (#8731) 2025-04-29 11:04:55 -03:00
JosueNina
e5a81ef285 Implement python version of OptionAssignmentRegressionAlgorithm (#8728)
* Implement python version of OptionAssignmentRegressionAlgorithm

* Solve comments review
2025-04-28 16:00:09 -03:00
Roman Yavnikov
818108b944 Fix: UnsettledCash Handling in Lean and Refactor PerformCashSync from Brokerage (#8726)
* test:feat: Assert Lean UnsettledCash and Brokerage.PerformCashSync
test:feat: new PaperBrokerage with manual cash balance

* test:refactor: calculation of Margin

* feat: change DefaultSettlementTime

* test:fix: use right brokerage settlement cash to balance

* test:refactor: use specific time when SettlementModel.Scan happens
2025-04-28 13:35:47 -03:00
JosueNina
cc38a6410f Add python SecurityCache.GetData method (#8724)
* Initial solution

* Fix regression algorithms
2025-04-28 11:46:31 -03:00
JosueNina
55b21cd714 Fix bug in ClassicRenkoConsolidator (#8713)
* Initial solution: Add an extra conditional in SubscriptionManager and add regression algorithms

* Solve comments review

* Add unit test

* Refactor unit tests in SubscriptionManagerTests

* Resolve comments review
2025-04-24 12:55:23 -04:00
Roman Yavnikov
25618ae5bc feat: generic BrokerageOrderIdChangedEvent in BrokerageTests (#8719) 2025-04-23 16:44:59 -03:00
Martin-Molinero
515408b167 Fix sytanx check on algorithms importing algorithms (#8720) 2025-04-23 16:39:23 -03:00
Jhonathan Abreu
0df082cc68 Add StubsAvoidImplicitsAttribute to avoid generating implicit types in stubs (#8718)
This allows the stubs generator to know when to not generate Union types for parameters that can accept multiple types, like Symbol | str | BaseContract
2025-04-23 14:22:14 -03:00
Jhonathan Abreu
cf8c5b854a Python algorithms typing cleanup [part 1] (#8716)
* Cleanup algorithms python typing

* Minor tweaks

* Improve indicator extensions

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2025-04-23 14:20:38 -03:00
Martin-Molinero
e4ff27a738 Minor improvements for syntax check test script (#8714) 2025-04-22 18:14:48 -03:00
Martin-Molinero
a087d7e766 Update run_syntax_check.py
Sort algorithms before syntax check
2025-04-22 16:57:28 -03:00
Martin-Molinero
065dbf3959 Normalize algorithm trading option strategy return type (#8712) 2025-04-22 12:01:08 -03:00
Martin-Molinero
1be7c9e141 Minor python syntax fixes (#8711) 2025-04-22 10:54:44 -03:00
Jhonathan Abreu
1ad4afa54e Add StubsIgnore attribute to missing methods (#8710) 2025-04-22 09:51:44 -04:00
Jhonathan Abreu
5845f3cd81 Use StubsIgnore attribute in some methods (#8708)
IBaseData.Reader
IBaseData.GetSource
IndicatorBase.Update
IAlgorithm.OnEndOfDay
2025-04-21 16:27:37 -04:00
Martin-Molinero
d60b3323c3 Minor python syntax fixes (#8709) 2025-04-21 17:23:36 -03:00
Martin-Molinero
4584feb7da Merge PythonSlice into Slice (#8707)
- To simplify stub generation, merge PythonSlice into Slice, following
  existing pattern too, see QCAlgorithm.Python.cs
- Minor sintax fixes in example python algorithms
2025-04-21 13:37:33 -03:00
Martin-Molinero
b81bcf086e Minor syntax fixes for python algorithms (#8705) 2025-04-21 10:06:47 -03:00
Martin-Molinero
e34a7e0bfa Update readme.md 2025-04-17 16:08:32 -03:00
JosueNina
e8cdb23cc0 Fix MarginCalls outside of regular market hours (#8696)
* Initial Solution

* Add regression algorithm

* Solve review comments

* Resolve review comments

* Add HasTimeProvider property and prevent overwriting existing time provider

* Resolve review comments

* Filter marginCall orders

* Update EquityMarginCall Algorithm

* Add header to the regression algorithm
2025-04-17 16:00:47 -03:00
Martin-Molinero
ea7d73d95d Add Missing Good Friday (#8702) 2025-04-17 10:42:45 -03:00
Henry Ennis-Thomas
7daa0929fa Update devcontainer.json for improved developer experience (#8697)
Co-authored-by: Henry Ennis-Thomas <henry@henryetdev.com>
2025-04-16 10:04:12 -03:00
Martin-Molinero
a55c387512 Update Packet.cs 2025-04-15 19:49:35 -03:00
Martin-Molinero
c130bb2de4 Dispose of python algorithm instance (#8695) 2025-04-15 11:33:33 -03:00
Roman Yavnikov
a1302d2bcd fix: missed orderProps when create MerketOnOpen (#8693) 2025-04-14 09:44:27 -03:00
Louis Szeto
020cf013df Fix bug/syntax in python examples (#8658)
* CustomDataRegressionAlgorithm

* DescendingCustomDataObjectStoreRegressionAlgorithm

* CustomDataPropertiesRegressionAlgorithm

* DateTime -> should be datetime

* KerasNeuralNetworkAlgorithm

* OptionIndicatorsMirrorContractsRegressionAlgorithm

* BybitCustomDataCryptoRegressionAlgorithm

* DropboxBaseDataUniverseSelectionAlgorithm

* UserDefinedUniverseAlgorithm

* CompleteOrderTagUpdateAlgorithm

* BasicTemplateOptionEquityStrategyAlgorithm hint

* ETFConstituentUniverseFrameworkRegressionAlgorithm

* FutureStopMarketOrderOnExtendedHoursRegressionAlgorithm

* SecurityDynamicPropertyPythonClassAlgorithm

* hint

* hinting

* CallbackCommandRegressionAlgorithm

* CustomWarmUpPeriodIndicatorAlgorithm

* CrunchDAOSignalExportDemonstrationAlgorithm

* ExpiryHelperAlphaModelFrameworkAlgorithm

* ClassicRenkoConsolidatorAlgorithm

* SmaCrossUniverseSelectionAlgorithm

* PEP8 Fix: Assigning to a Method

* SliceGetByTypeRegressionAlgorithm

* MarketOnCloseOrderBufferExtendedMarketHoursRegressionAlgorithm

* MarketOnCloseOrderBufferRegressionAlgorithm

* CustomIndicatorAlgorithm

* ScheduledQueuingAlgorithm

* ComboOrdersFillModelAlgorithm

* CustomIndicatorWithExtensionAlgorithm

* IndicatorWithRenkoBarsRegressionAlgorithm

* CoarseFineOptionUniverseChainRegressionAlgorithm

* NumeraiSignalExportDemonstrationAlgorithm

* DropboxUniverseSelectionAlgorithm

* WeeklyUniverseSelectionRegressionAlgorithm

* AutoRegressiveIntegratedMovingAverageRegressionAlgorithm

* DropboxBaseDataUniverseSelectionAlgorithm

* IronCondorStrategyAlgorithm

* LongAndShortButterflyPutStrategiesAlgorithm

* FutureStopMarketOrderOnExtendedHoursRegressionAlgorithm

* LongAndShortCallCalendarSpreadStrategiesAlgorithm

* KerasNeuralNetworkAlgorithm

* LongAndShortPutCalendarSpreadStrategiesAlgorithm

* OptionPriceModelForOptionStylesBaseRegressionAlgorithm

* TensorFlowNeuralNetworkAlgorithm

* MarketOnCloseOrderBufferRegressionAlgorithm

* MarketOnCloseOrderBufferExtendedMarketHoursRegressionAlgorithm

* typing

* ComboOrderTicketDemoAlgorithm

* PytorchNeuralNetworkAlgorithm

* MultipleSymbolConsolidationAlgorithm

* fixes

* revert getattr mypy syntax

* address peer review

* Addresses Peer-Review

---------

Co-authored-by: Alexandre Catarino <AlexCatarino@users.noreply.github.com>
2025-04-14 09:43:03 -03:00
Jhonathan Abreu
fe46e5ec3b Fill-forward previous universe files for manual chains fetching when current missing (#8691)
* Fill forward prev date universe file in manual chains fetch

If there is no universe file available for the current date, use the previous one and fill forward to avoid having empty chains on a day when we haven't generated the universe files

* Try a maximum of 3 days behind for manual chains fetching

* Minor change

* Minor fix

* Add comments

* Minor fix

* Minor fix for expired contracts
2025-04-11 13:57:29 -03:00
JosueNina
4c7bda8e34 Fix futures history request error (#8678)
* Initial solution

* Create testCases for earlyClose and lateOpen

* Refactor GetExchangeHours and add unit tests

* Update market-hours-database and create a unit test

* Resolve review comments

* Update market-hours-database

* Parallelize the foreach loop to improve test performance
2025-04-11 13:37:14 -03:00
Roman Yavnikov
13ace56eea Refactor: Eze brokerage (#8689)
* refactor: model and OrderProperties of Eze

* feat: additional configs for Eze brokerage
2025-04-11 13:35:14 -03:00
Martin-Molinero
ff185d0311 Minor Api testing improvements (#8687)
* Add missing backtests/read null check

* Improve SPDB error message
2025-04-10 17:30:55 -03:00
Jhonathan Abreu
e90309678e Security initialization on re-addition (#8681)
* Initialize security after addition and re-addition

* Improve regression algorithms

* Add universe selection regression algorithm

* Add minor comment
2025-04-09 16:26:05 -04:00
Alexandre Catarino
ea41fedb30 Handles Empty Signal Export List (#8686) 2025-04-09 16:44:47 -03:00
Alexandre Catarino
1cb0405517 Adds Custom Signal Export Example (#8674)
* Adds example of custom signal exports.

- SignalExportManager send signals automatically after 5 seconds.
- Missing example and Python support.

* Updates Examples to Disable Automatic Export

* Addresses Peer-Review
2025-04-09 10:14:21 -03:00
Jhonathan Abreu
1e4ef83132 Fix failing history unit test (#8682)
* Fix failing unit test

Add algorithm start date so period history request is consistent

* Minor change
2025-04-08 12:00:32 -03:00
Martin-Molinero
e416a54873 Update readme.md 2025-04-07 19:24:29 -03:00
Jhonathan Abreu
a9927fe111 Adjust times to exchange and QB time zones in Option/Future history calls (#8680) 2025-04-07 19:10:41 -03:00
Martin-Molinero
cd7663ef97 Minor tweaks for testing (#8679)
* Minor tweaks for backtest tests

* More tweaks
2025-04-07 18:41:44 -03:00
Roman Yavnikov
e1cd63643f feat: OptionCodeLookup publicly (#8676) 2025-04-07 12:22:18 -03:00
Roman Yavnikov
87487ec4c0 feat: missed order status in OrderTestParameters for different orders (#8677) 2025-04-07 12:22:09 -03:00
Jhonathan Abreu
1974884c13 Security re-addition tidy up (#8656)
* Initialize securities on re-addition

* Minor unit tests fixes

* Reset Index.ManualSetIsTradable when security is removed

* More changes to clean up and simplify

* Address security re-utilization only

* Cleanup regression algorithms
2025-04-04 16:28:15 -04:00
Martin-Molinero
f963e43346 Minor improvements for testing and api (#8672)
* Minor improvements for LLMs

- Minor tweaks in regression tests
- Minor API sugars

* Ignore union-attr error
2025-04-03 17:49:41 -03:00
Ricardo Andrés Marino Rojas
980cdeaa75 Remove fill warnings from order tags (#8668)
* Remove warnings from tags and tests

* Fix bugs

* fix bugs

* Revert wrong updates in some stats

* Fix bugs
2025-04-03 17:49:21 -03:00
Jhonathan Abreu
26ef02399f Fix QuantBook Option/Future history api date range (#8671)
* Fix QuantBook Option/Future history api date range

Properly calculate date range when passed range is not a whole date but a time of day

* Extended unit tests
2025-04-03 16:45:35 -04:00
Jhonathan Abreu
68ec0b72b2 Disable extended market hours for universe history requests (#8670)
* Disable extended market hours for universe history requests

* Exclude extended market hours for all chain universe history requests

* Disable extended market hours for chain universes

* Minor change

* Minor fix

* Minor change
2025-04-02 14:11:38 -03:00
JosueNina
a8d36497d4 Prevent fill-forwarding outside OpenInterest trading hours (#8662)
* Prevent fill-forwarding outside OpenInterest trading hours

* Solve review comments

* Fix unit test

* Resolve review comments

* Revert changes in FillForwardEnumerator

* Revert unrelated changes
2025-04-02 09:22:58 -03:00
Jhonathan Abreu
73684e8e70 Keep time of day on open interest consolidator (#8667)
* Avoid time round down for open interest hour and daily consolidation

* Consolidate OI data on date and hour change

* Cleanup

* Add more test cases
2025-03-31 17:57:12 -04:00
laur89
1e84ee59ce fix CandlestickSeries constructor (#8664)
- likely a copy-pasta error from Series, where index=0 is passed to
  BaseSeries constructor, only now it was passed as SeriesType, which
  is subsequently set in CandlestickSeries constructor
2025-03-31 16:44:22 -03:00
Martin-Molinero
2cafba85f7 Ignore missing types in syntax check (#8660) 2025-03-28 13:19:40 -03:00
Martin-Molinero
513ced31d7 Add python syntax check (#8651)
* Add python syntax check

* Fix some python regression algorithms

* Fixing more bugs
2025-03-28 10:36:26 -03:00
Roman Yavnikov
581e87809b Fix: SettlementDays (#8657)
* feat: make static and get; set; of DefaultSettlementDays in Equity,Option

* refactor: reset _lastUnsettledCash depend on settlementDays in UnsettledCashWhenQuoteCurrencyIsNotAccountCurrencyAlgorithm
2025-03-28 10:36:05 -03:00
JosueNina
80498d5a1f Fix dataType assignment logic in GetMatchingSubscriptions (#8653)
* Fix dataType assignment logic in GetMatchingSubscriptions

* Updated unit test

* Change parameter from string to bool
2025-03-27 16:19:28 -03:00
Ricardo Andrés Marino Rojas
f5dd7236fc Avoid innecessary stub generation (#8654)
* FINAL TEST

* Change version

* test commit

* echo commits

* echo last commits before generating stubs

* Fix bugs

* fix more bugs

* fix yaml error

* try with a different version

* Check we can get last commits

* add variables in options

* Echo commits

* tweaks

* More tweaks

* Add an exception

* FINAL TEST
2025-03-27 13:30:34 -03:00
Jhonathan Abreu
69d2f5ae82 Futures and Future Options file-based universes (#8480)
* Make FOPs selection universe file-based for backtesting

* Make FOPs option chains universe file based

* Make Future universe selection file-based like option universe

* Make Future universe selection file-based like option universe

* Abstraction cleanup

* Add FuturesChains API to QC algorithm

Also refactor future chain provider to use the new FutureUniverse instead of zip file names

* Update regression algorithms stats

* Refactor QuantBook option and future history to use new universes

* Fix failing tests

* Fix failing tests

* Fix failing tests

* Minor future chains unit test improvement

* Add futures chains DataFrame property

Also, remove IDerivativeSecurity interface from Future

* Add DataFrame property to FuturesChains class

* Add regression algorithms

* Add regression algorithms

* Replace QCAlgorithm.FutureChainProvider usages with new FuturesChain api

* Minor fixes

* Reduce number of universe files in repo

* Minor data fixes

* Regression algorithms updates

* Add implicit conversion from FuturesContract to Symbol

Modified algorithms to use futures contract objects directly instead of accessing their Symbol property.
Removed unnecessary import statements and redundant lines in various files.

* Improve resolution handling for history requests

* Changed _auxiliaryData field to lazily-initialized AuxiliaryData property

* Refactor data handling in BaseChain and TimeSliceFactory

- Added `AddData` method to `BaseChain` for adding market data
- Refactored `TimeSliceFactory` to use `BaseChain.AddData` method

* Remove specific constructors and indexers from Chain classes

Removed public indexers in `BaseChains` for getting or setting `BaseChain` instances by `ticker` or `Symbol`, which were used for Pythonnet compatibility.

* Remove chain cache logic from FuturesChainUniverse

* Refactor class and interface names for clarity

Renamed `FileBasedUniverse` to `BaseChainUniverseData` and
`IFileBasedUniverse` to `IChainUniverseData`.

* Add base class for options and futures contracts

- Introduced `BaseContract` as an abstract base class for contracts, consolidating common properties and methods.
- Removed ISymbolInterface

* Add minor fix for future options tickers parsing

Added tests

* Trigger Build

* Trigger Build

* Trigger Build

* Trigger Build

* Clean chain provider classes up

* Remove ZipEntryName other classes and unused code

Removed ZipEntryName class and references across various files.
Removed DataQueueFuturesChainUniverseDataCollectionEnumerator and DataQueueOptionChainUniverseDataCollectionEnumerator classes.
Removed OptionChainUniverseSubscriptionEnumeratorFactory class.
Removed unused code for handling OptionChainUniverse and FuturesChainUniverse in FileSystemDataFeed.cs and LiveTradingDataFeed.cs.
Removed several test files related to enumerator factories and universe data collection.

* Minor changes and cleanup

* Trigger Build

* Trigger Build

* Refactor FuturesContract data handling

Forward price data from bars and ticks stored in private fields for improved memory usage

* Fix: use universe data for market data in FuturesContract

* Update regression algorithms stats after rebase

Added HSI futures universe files

* Sort configs by internal flag

Internals go first

* Throw from option universe data filters for future options

Future options IV, Open interest and greeks are not supported for future options

* Minor changes

* Improve some regression algorithms

* Minor fix for failing unit tests

* Update FOPs universe file header

Removed greeks and IV columns.
Updated FOPs universe files: removed outdated columns.

* Minor unit test fix

* Trigger Build

* Trigger Build

* Trigger Build

* Trigger Build

* Trigger Build

* Trigger Build

* Trigger Build

* Trigger Build

* Trigger Build

* Trigger Build

* Trigger Build

* Trigger Build

* Trigger Build

* Minor fix

* Add history provider as constructor argument for chain providers

* Update new regression algorithms data points count

* Minor fix for FakeDataQueue

* Add initialize method to chain providers classes

* Minor changes

* Trigger Build

* Trigger Build

* Trigger Build

* Minor fix

* Minor fix

* Trigger Build

* Trigger Build

* Trigger Build

* Trigger Build

* Add logs to ProcessedDataProvider

* Removed test logs

* Minor fix

* Support downloading options and futures universe files from api data provider
2025-03-25 16:22:38 -04:00
JosueNina
2d7e3297a6 Add regression algo for indicator updates: Resolution.Daily vs TimeSpan.FromDays(1) (#8646)
* Create regression algorithm

* Add new regression algo

* Update regression algorithms

* Add regression algorithms for other resolutions
2025-03-25 15:57:02 -03:00
Martin-Molinero
57adac59ee Update IB to latest 1034 (#8636) 2025-03-24 13:23:32 -03:00
Martin-Molinero
d57f75ade2 Fix for division by zero in option assigment check (#8644)
- Fix for division by zero in option assigment check. Adding regression
  test reproducing issue. Will now rely on normalized path in universe
  selection to clear the cache
2025-03-21 18:18:48 -03:00
Martin-Molinero
bbb72b771c Minor fix for host culture on regression tests (#8645) 2025-03-21 17:59:13 -03:00
JosueNina
1b4613bc75 Support conversion of IndicatorBase<BaseData> (#8635)
* Support registering indicators of type IndicatorBase<BaseData>

* Add IndicatorBase<BaseData> scenario for all the usages of ConvertPythonIndicator

* Add all scenarios in the test case
2025-03-20 15:31:12 -03:00
JosueNina
e994562d60 Add unit test to CommonIndicatorTest (#8628)
* Initial solution

* Update unit test

* Explicit conversion if T is IndicatorDataPoint

* Solve review comments

* Add override tests for Beta and Alpha

* Refactor and update unit test suite

* Create unit test for OptionIndicators

* Resolve review comments

* Resolve new review comments

* Add a new default selector
2025-03-20 10:16:00 -03:00
Roman Yavnikov
057f0b4d9e Feature: implement MarketOnCloseOrderTestParameters (#8625)
* feat: new MarketOnCloseOrderTestParameters

* feat: support new OrderType in CharlesSchwabBrokerageModel
2025-03-14 17:46:50 -03:00
Martin-Molinero
e6f2776fcf Update readme.md 2025-03-13 12:09:57 -03:00
Roman Yavnikov
87a65451ea Feature: Universe Data Downloader (#8612)
* feat: parsing of universe file path for different security types

* fix: market position in parsing of universe file
refactor: add example of universes file path in xml description method

* test:feat: parsing of universe path

* rename: return variable in ParseUniversePath

* feat: extension to create history request internally

* feat: entity  DataUniverseDownloaderGetParameters

* config: downloaderDataProvider project

* feat: create DataUniverseDownloadConfig in download project

* feat: run universe downloader in DownloaderProvider

* test:fix: missing using
test:remove: parameter ctor of DataDownloadConfig

* refactor: run Universe downloader in Main

* feat: GetUniverseFileName by processingDate

* refactor: CreateDataUniverseDownloaderGetParameters with using Start and EndDate
refactor: exception message in DataUniverseDownloadConfig

* feat: new out argument in TryParsePath's LeanData

* feat: RunUniverseDownloader in DownloadDataProvider

* feat: DerivativeUniverseData to write csv file
feat: extension to download universe data with different parameters

* remove: log warn which path when get universe file path

* refactor: DataUniverseDownloaderGetParameters
feat: run Download Universes file in DownloaderDataProvider internally

* refactor: overload TryParsePath only with 4 parameters

* remove: editconfig file in DownloaderDataProvider

* remove: validation on null parameters

* rename: typo DateType to DataType

* refactor: use endDate in ctor DataUniverseDownloaderGetParameters
refactor: use UnderlyingSymbol from base class Symbol property
remove: CreateDataUniverseDownloaderGetParameters()
refactor: put LoadSymbol in base class
clean/remove: DataUniverseDownloadConfig

* refactor: use Time.EachTradeableDay in CreateDataDownloaderGetParameters
remove: CheckMarketOpenStatus

* fix: RunUniverseDownloader with EndUtc in DownloaderDataProvider

* refactor: GetUniverseFullFilePath

* remove:  validate historyData like Any

* fix: use date from parsing path in DownloaderDataProvider

* feat: download QuoteBar for Universe file
feat: handle QuoteBar in DerivativeUniverseData
refactor: filter option in final dictionary

* revert: CreateHistoryRequest() in DownloaderExtensions

* feat: use optional parameter SecurityExchangeHours in DataUniverseDownloaderGetParameters
refactor: DataUniverseDownloaderGetParameters
refactor: use Log.Debug instead Log.Trace to prevent spamming

* fix: ordering of download universe data
revert: parameter ctor in DataDownloadConfig
revert:test: use parameter ctor instead of Config.Set

* clean: extra `usings`

* fix: Get DataType in DataDownloadConfig
feat: new ctor in BaseDataDownloadConfig
2025-03-12 19:38:18 -03:00
JosueNina
d00ef1c181 Use a fixed number of periods instead of WarmUpPeriod for the second indicator (#8624) 2025-03-12 17:41:08 -03:00
JosueNina
2e1f28d20d Fix IndicatorHistory for options indicators in Python (#8621)
* Fix IndicatorHistory api for options indicators

Fix for indicators based on OptionIndicatorBase to be able to use IndicatorHistory api. They require proper conversion of indicators from PyObjects

* Fix WarmupIndicator to support multi symbol indicators in Python

* Minor fix for WarmUpIndicator api

* Refactored switch statements for indicator conversion

* Solve comments review

* Refactored WarmUpIndicator to remove duplicated code

* Resolve review comments

---------

Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
2025-03-12 16:10:25 -03:00
Alexandre Catarino
d68a41ba73 Allow Receiving Broadcast from Source Project (#8622)
* Allow Receiving Broadcast from Source Project

* empty
2025-03-11 16:58:17 -03:00
JosueNina
09ca345ae8 Custom data type universe - python support (#8618)
* Cache registered custom python security and universe data types

Use this cache to get the correct config for history requests since pythonnet will always pass PythonData and we lose reference to the actual Python type

* Use local repo data for unit tests

* Move unit tests to algorithm history tests

* Use UniverseManager instead of CacheCustomPythonDataType

* Add regression algorithms

* Update regression algorithms to solve issues

* Update regression test and History

* Updated source path to avoid issues with linux

---------

Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
2025-03-10 17:33:17 -03:00
Alexandre Catarino
49265bd773 Adds BroadcastCommand Method (#8617)
* Adds BroadcastCommand Method

Send a command to all live algorithms.

* Addresses Peer-Review

* Minor tweaks

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2025-03-07 17:48:10 -03:00
Martin-Molinero
07003af6d5 Minor Update IB Order Properties (#8619)
- FA EqualQuantity was renamed to Equal, update docs
- Add remarks warning on exclusiveness of FaProfile, FaGroup and Account
2025-03-07 17:36:03 -03:00
JosueNina
5f8d76f6dd Update Stochastic period (#8613)
* Update Stochastic period

* Update regression algorithms

* Resolve review comments

* Fix Regression algorithms
2025-03-07 12:09:33 -03:00
Martin-Molinero
bcc53eff3b Add minor extension methods for value tasks (#8614) 2025-03-06 17:29:25 -03:00
Ricardo Andrés Marino Rojas
bca9ada795 Replace C2 symbol for C2 Exchange symbol (#8604)
* Initial draft of the solution

* Remove old format

* Address requested changes

* Add Index option test case

* nit changes

* Address Martin reviews, improve unit tests and solve 8577

* Add unit tests

* Nit change

* Address requested changes

* Address Martin reviews

* Nit changes and more unit tests

* Nit change

* Address requested changes

* Address requested changes
2025-03-06 13:21:31 -03:00
Martin-Molinero
5cba110b64 Add missing IB dependencies (#8615) 2025-03-05 12:32:33 -03:00
JosueNina
88b32b8352 Python Support for CompositeIndicator (#8598)
* Initial solution

* Add python support for CompositeIndicator

* Add unit tests and update CompositeIndicator

* Add new test case

* Update TryConvertToIndicator logic

* Solve review comments

* Resolve review comments

* Remove unnessary case

* Use GetIndicatorAsManagedObject instead of ConvertToIndicator

* Add regression tests
2025-03-04 15:25:15 -03:00
Martin-Molinero
fef5c8e9c8 Update readme.md 2025-03-04 11:50:13 -03:00
Jhonathan Abreu
867b7e8eb6 Upgrade IB gateway version to 30.10 (#8586)
* Upgrade IB gateway version to 3010

* Update ib gateway version in config file

* Remove ib-version config

Let the brokerage detect or set the correct ib gateway version
2025-03-03 13:17:23 -03:00
Zekun Wang
f9d84a6893 Remove outdated comments (#8601)
* remove oudated comments

* remove outdated comments

---------

Co-authored-by: Zekun Wang <zekun.wang@uwaterloo.ca>
2025-02-21 10:55:54 -03:00
Ricardo Andrés Marino Rojas
bd144e021d Add 2025 & 2024 holidays to MHDB Index entries (#8599) 2025-02-21 10:53:18 -03:00
JosueNina
1a852d2d45 Add new indexes, including market hours - part 4 (#8578)
* Add new indexes, including market hours - part 4

* Resolve review comments

* Add an entry to SPDB for ASX

* Add new indexes and update the old ones

* Add entries to SPDB
2025-02-19 18:50:38 -03:00
Ricardo Andrés Marino Rojas
99dc63a08d Remove trailing commas from MHDB (#8597) 2025-02-19 17:52:38 -03:00
Martin-Molinero
f59fedc042 Add backtest summary (#8593) 2025-02-19 11:32:18 -03:00
JosueNina
5596295774 Set DeploymentTarget to LocalPlatform (#8588) 2025-02-14 17:27:19 -03:00
Martin-Molinero
fabf1191b7 Improve live trading streaming packets (#8584)
* Improve live trading streaming packets

* Further improvements

* Add test for default empty holding

- Improve deserialization
2025-02-13 18:40:55 -03:00
Ricardo Andrés Marino Rojas
9be02d7fa5 Add bank holidays for CME Futures MHDB (#8539)
* Add bank holidays

* Add missing holidays to MHDB

* Add 2025 new year's eve bank holiday

* Add Columbus day and veterans day to bank holidays

* Add missing bank holidays entry

* Modify FuturesExpiryFunctions

* Add missing change

* Remove empty bankHolidays lists from MHDB

* Address review

* Add tests

* Address review

* Add bank holidays from 2009-2024

* Fix unit and regression tests

* Review bank holidays

* Fix tests

* MHDB tweaks

* Remove Bank holidays from CNH, MNH and MIR

* Add setting for bank holidays disabled by default

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2025-02-06 17:50:10 -03:00
JosueNina
55c995e13f Add new indexes, including market hours - part 3 (#8576)
* Add new indexes, including market hours - part 3

* Fix market hours
2025-02-06 13:02:05 -03:00
JosueNina
1d169a19ce Add new indexes, including market hours (#8573) 2025-02-06 11:08:53 -03:00
JosueNina
956ffdfa9c Add new indexes, including market hours (#8571) 2025-02-05 12:32:13 -03:00
Jhonathan Abreu
0b6255c1fc Update GitHub issue template to match new formats (#8572)
* Update GH issue template to match new formats

* Disable github blank issue template selector
2025-02-04 18:09:25 -03:00
JosueNina
6415de83cf Update exchange for new indexes (#8569)
* Update markets and market hours for new indexes

* Update market hours and IndexSymbols
2025-02-04 16:47:32 -04:00
Martin-Molinero
e38f3f3aaf Update RecyclableMemoryStream (#8574) 2025-02-04 17:11:46 -03:00
Jhonathan Abreu
40e887a106 Unseal greeks ComputeIndicator method (#8570) 2025-02-03 11:16:34 -03:00
Jhonathan Abreu
8149c291fc Dynamic market hours for time and date rules (#8541)
* Add unit test reproducing the bug

* Improve unit test

* Apply market hours database updates to instance

Make sure entries are updated instead of overridden so that consumers holding the mhdb can pick up the changes

* Improved unit tests

* Update data folder MHDB entries instead of overriding instance

* Optionally reset custom mhdb entries on reset

* Simplify mhdb reset in live trading

Cleanup and minor fixes

* Ensure symbol properties database updates are picked up by consumers

Update SPDB entries instead of overriding them, just like for the MHDB so that consumers pick up updates after refresh

* Fix for symbol properties update thread safety

* Minor improvements and cleanup

* Mhdb and spdb update logic simplification

* Move "force exchange always open" logic to mhdb

* Simplify symbol properties holder and updates

* Refactor security databases to use a common base class

Introduce BaseSecurityDatabase<T, TEntry> to encapsulate common functionality for MarketHoursDatabase and SymbolPropertiesDatabase.

* Cleanup
2025-01-31 15:00:14 -04:00
Jhonathan Abreu
de9f9bf309 Fix options indicators data synchronization (#8564)
* Add DualSymbolIndicator unit tests

* Introduce MultiSymbolIndicator for indicators working on multiple symbols

Use the new class as base for DualSymbolIndicator and OptionIndicatorBase.
The OptionIndicatorBase can now detect when ready even if underlying and options market close is different when resolution is daily.

* Accept any BaseData for options indicators

* Improve indicator conversion from python on registration

Also minor fixes

* Cleanup and simplification

* Fix ImpliedVolatility IsReady flag

* Update regression algorithm history count

AutomaticIndicatorWarmupOptionIndicatorsMirrorContractsRegressionAlgorithm history count decreased because options indicators period is now 1 instead of 2

* Address peer review
2025-01-31 14:22:06 -04:00
JosueNina
077b6e41d8 Updating Orders should fail if it causes insufficient margin (#8553)
* Initial solution

* Update regression test

* Update assertions

* Resolve PR comments

* Add more order types to regression test

* Update regression algorithm name

* Update old regression algorithm

* Refactor validation to check buying power only for non-ComboLeg update orders

* Update ValidateSufficientBuyingPowerForOrders

* Update regression algorithm

* Resolve review comments

* Use try out pattern
2025-01-31 11:29:30 -03:00
Martin-Molinero
37d0c42149 Minor improvements to compression (#8555) 2025-01-31 11:29:11 -03:00
Roman Yavnikov
ac1365cd7c feat: support new order types in CharlesSchwabBrokerageModel (#8561) 2025-01-29 15:40:26 +02:00
JosueNina
c3530a6a7f Update SPDB - Bybit (#8563) 2025-01-29 10:15:30 -03:00
Ricardo Andrés Marino Rojas
7318c6fc7c Add ICE and NYSE 2025, 2026 and 2027 holidays (#8557)
* Add ICE and NYSE 2025, 2026 and 2027 holidays

* Reduce common holidays
2025-01-28 16:21:32 -03:00
Ashutosh
2e0c3a03a5 Add index data part 1 (#8549)
* Update MHDB for new indexes - part 1

* Central Time correction

* Adding DJX
2025-01-28 15:12:13 -03:00
Ricardo Andrés Marino Rojas
824a754f81 Add CFE, SGX and INDIA 2025 Holidays to MHDB (#8558) 2025-01-28 15:10:47 -03:00
Alexandre Catarino
1000669975 Adds Collective2 Payload To Logs With Debugging Enabled (#8559) 2025-01-28 15:10:39 -03:00
Jhonathan Abreu
24a1fbba60 Clone configuration on re-subscription (#8560)
When re-subscribing a request after a fill forward resolution change, clone Config to avoid memory access race conditions when emitting new tradable date events
2025-01-28 15:09:40 -03:00
Jhonathan Abreu
25d53fe6ff Update default CFE mhdb entry (#8562)
Update segments to reflect regular and extended hours
2025-01-28 15:09:21 -03:00
JosueNina
cad5f20a3d Refactor SetHoldings to return a List<OrderTicket> (#8550)
* Refactor SetHoldings to return a List<OrderTicket>

* Add expectedQuantities to the testCases

* Update regression tests

* Update name of regressionAlgorithm

* Address review comments

* Update unit test
2025-01-23 18:44:29 -04:00
Jhonathan Abreu
c5c56bf98e Fix symbol changed events emission time (#8552)
* Fix symbol changed events emission time

Ensure the symbol changed events are emitted after the securities are processes by the main loop in the AlgorithmManager. This way the algorithm has access to the new symbol security since it would be added by the securities processing logic.

Also, allow all securities to be properly updated, including prices and cash, before emitting the event, so that the any logic (like placing orders) done by the algorithm on the handler has the correct data.

* Minor fix

* Minor change

* Minor change
2025-01-23 18:29:28 -04:00
JosueNina
9b35411f45 Refactor liquidation logic (#8544)
* Create regression tests and refactor liquidation logic

- Implemented regression tests for order creation and liquidation
  scenarios
- Removed LiquidateExistingHoldings method
- Replaced LiquidateExistingHoldings with the general Liquidate method

* Addressed review comments

* Addressed new comments review

* Update default value for 'tag'

* Update ExpectedStatistics

* Identify and liquidate portfolio symbols not included in targets

* Create a new regression test

* Fix minor comments

* Move regression tests to the correct folder
2025-01-22 12:53:48 -03:00
Martin-Molinero
2fe7f5b457 RUT index options support (#8542) 2025-01-22 11:56:42 -03:00
Martin-Molinero
64f848a7b1 Setup net9 C# research (#8548) 2025-01-22 11:56:02 -03:00
Roman Yavnikov
0937d08aa8 fix: missed assign order status in PlaceOrderWaitForStatus (#8546) 2025-01-21 15:59:52 -03:00
Roman Yavnikov
8330dd939e Test:Feat: LongFromZeroUpdateAndCancel (#8545) 2025-01-21 17:18:03 +02:00
JosueNina
1ef66a1083 Fix Retrieval of Historical Data for Equities with Different Resolutions (#8538)
* Refactor GetMatchingSubscriptions:

- Fixed retrieval of minute-resolution quote data for hour-resolution
  equity
- Ensured correct retrieval of data regardless of equity resolution
- Created a unit test to verify functionality

* Update unit test and create test cases

* Add new unit test

* Addressed review comments
2025-01-17 10:18:15 -03:00
Jhonathan Abreu
0fccf6017d Expand index market map (#8540)
* Expand index market map

* Cleanup
2025-01-16 10:49:30 -03:00
Jhonathan Abreu
41f9d1bd3a Support Collective2 white-label API (#8536)
* Support Collective2 white-labe api usage

* Make Collective2SignalExport Destination public and assignable

* Minor comment change
2025-01-15 16:49:55 -04:00
Martin-Molinero
c35d6ee194 Fix HSI future expiration function (#8534)
* Fix HSI future expiration function

- Fix HSI futures expiration function. Adding unit tests reproducing
  issue

* Minor update to sample test data
2025-01-15 15:04:15 -03:00
Ashutosh
1cb8fcf2d9 Update mhdb to add holidays for osaka exchange (#8533)
* Update mhdb to add holidays for osaka exchange

* Minor MHDB cleanup

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2025-01-15 11:29:37 -03:00
Jhonathan Abreu
58b7a9d22a Add FTSE Russell Exchange support (#8531)
* Add FTSE Russell Exchange support

* Cleanup
2025-01-15 10:36:20 -03:00
Jhonathan Abreu
2d4ca75670 Add Russell 2000 (RUT) market hours and symbol properties entries (#8530) 2025-01-14 17:23:08 -04:00
Martin-Molinero
cda769df74 Add Nikkei 225 index support (#8529)
- Add Osaka exchange for nikkei index. Adding regression test
- Improve default market resolution
2025-01-14 17:08:36 -03:00
JosueNina
5accfd6be3 Update secondsTimeStep value (#8528) 2025-01-14 15:17:55 -03:00
Martin-Molinero
265fd8b3b9 Update readme.md 2025-01-14 10:36:11 -03:00
JosueNina
d633fed3ff Handle zero price and target quantity case - Collective2 (#8525)
* Skip zero price and target quantity case

* Addressed PR comments

* Addressed new PR comments
2025-01-13 20:48:20 -03:00
JosueNina
f689826051 Added constructor to initialize USResident flag (#8526) 2025-01-13 20:47:37 -03:00
JosueNina
af7a2cfc85 Update installation instructions (#8524)
* Update readme.md to mention .NET 9 instead of .NET 6

* Update readme.md with new versions of python, pandas and wrapt

* Update readme.md for vscode and vs
2025-01-13 15:43:45 -03:00
Martin-Molinero
6982f6713b Fix index option cash profit (#8520)
- Fix so that option cash settlement impacts profit records. Updating
  existing and adding new tests
2025-01-13 12:52:12 -03:00
Ricardo Andrés Marino Rojas
50f887ca64 Fix delisting time handling in SubscriptionDataReader (#8470)
The delisting time is handled by the DateChangeTimeKeeper now, so there is no need for the SubscriptionDataReader to do any special logic for it.
This was preventing the new tradable date events to be emitted after the delisting date in some cases, like when the day after delisting is not tradable

Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
2025-01-13 10:22:14 -04:00
JosueNina
f08eda3bac Update SPDB with Bitfinex, Kraken, Binance, BinaceUS (#8516)
* Update SPDB with Bitfinex, Kraken, Binance, BinaceUS

* Update unit test

* Added TestCase for CNHT and USD

* Fixed bug in pair comparison logic, corrected concatenation approach

* Add unit test for currency pair match

* Added test cases for currency pair comparison

* Addressed review comments
2025-01-10 18:57:37 -03:00
Martin-Molinero
8ad1016710 Remove index resolution limitations (#8519)
- Remove index resolution limitations being imposed
2025-01-10 14:59:19 -03:00
Jhonathan Abreu
8937995ee4 Add Martin Luther King's day 2025 holiday to CME futures entries (#8515)
* Add Martin Luther King'day holiday to CME futures entries

Add unit test for MCL futures expiry function, first contract of 2025 expires on Jan17 but was returning the 20th

* Add holiday to equity and index

And by extension to options and index options

* Add holiday to other entries
2025-01-09 17:36:06 -04:00
JosueNina
ca7f7710e7 Update SPDB with Bybit and CoinBase (#8512)
* Update SPDB with Bybit

* Update SPDB with Coinbase

* Merge completed successfully without deletion

* Removed expiring crypto futures
2025-01-09 13:04:16 -03:00
Martin-Molinero
0b1b72e921 Fix for multiple market closes in date (#8509)
- Fixes related to support assets with multiple daily market closes.
  Adding unit and regression tests
2025-01-09 12:56:37 -03:00
JosueNina
c44819617f Update IdentityDataConsolidator to track last processed time (#8510) 2025-01-09 09:52:52 -03:00
JosueNina
3569a1f8d0 Collective2 - No index option (#8494)
* Inicial solution

* Use InitialMargin instead of MaintenanceMargin

* Addressed review comments

* Update unit test

* Refactor GenerateOptionTicker method to handle IndexOption

* Addressed PR comments

* Update unit test
2025-01-08 16:58:31 -03:00
oussamanahdi
d71dd86ff5 Updates LEAN readme with LEAN Architecture diagram (#8507)
* Update readme.md

* Update readme.md

* Update readme.md

* Update readme.md
2025-01-07 23:54:08 -03:00
JosueNina
96410b57a0 Add 1/9/2025 holiday to market-hours (#8508)
* Add 1/9/2025 holiday to market-hours

* Patched holidays in MarketHours

* Minor fix

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2025-01-07 23:52:25 -03:00
Martin-Molinero
f17726b890 Fix HSI future expirations (#8505) 2025-01-06 17:20:43 -03:00
Jhonathan Abreu
7ee297ab77 Add BTIC on cryptocurrencies futures back (#8503)
* Add BTIC on cryptocurrencies futures back

Add MIB (BTIC on micro bitcoin futures) and BRM (BTIC on micro ether futures) back

* Minor unit tests fix
2025-01-06 15:01:30 -04:00
Martin-Molinero
94fd3c8f64 Update HSI future margin (#8504) 2025-01-06 12:49:43 -03:00
Ashutosh
50a8de5f67 Update mhdb file for HKFE entries (#8501) 2025-01-06 11:07:59 -03:00
Martin-Molinero
af2043d7d3 Add hang seng future and index support (#8499) 2025-01-03 20:51:37 -03:00
Jhonathan Abreu
57ce6958dd Skip subscription to selected securities when no tradable dates (#8495)
* Skip "no tradable dates" log for options added on non-tradable dates

* Skip subscription to selected securities when no tradable dates

Skip selected securities subscriptions when there are no tradable dates available from selection time till end date

* Minor comment

* Remove "no tradable days" error log
2025-01-03 20:47:52 -03:00
Martin-Molinero
75d8e710d1 Add security Set (#8491) 2025-01-02 17:31:23 -03:00
Ricardo Andrés Marino Rojas
f75ea380e7 Add missing entries and clean MHDB (#8489)
* Move good friday to market entries and fix soft futures

* Keep holidays list order

* Nit change
2025-01-02 10:46:13 -03:00
JosueNina
f3ea223f2a Refactor Correlation and beta indicators (#8485)
* WIP: Refactor Correlation Indicator

* Simplified comparison logic and improved abstraction

* Refactor Correlation and Beta indicators

- Created a base class to handle indicators with dual-symbol
  functionality.
- Refactored the Beta and Correlation indicators to inherit from the new
  base class.
- Updated unit tests.
- Added a new regression test to validate the latest computed value.

* Addressed review comments

* Update regression test

* Add new unit test to CommonIndicatorTests

* Addressed new review comments
2025-01-02 10:42:01 -03:00
Ricardo Andrés Marino Rojas
fb49f5da70 Update CME Future entries MHDB (#8488)
* First potential update

* Add 2025 holidays, early closes and late opens

* Review and improve changes

* add missing entries

* Nit change

* Nit change
2024-12-30 20:28:04 -03:00
Martin-Molinero
0cda5c7f0d Improve brokerage WS default rate limits (#8486)
- Improve brokerage WS default reconnection rate limits
- Minor cleanup in WebSocketClientWrapper
2024-12-27 12:55:21 -03:00
Roman Yavnikov
9175b862d0 Feature: Validate FillPrice and FillQuantity in class BrokerageTest (#8483)
* test:feat: validate FillPrice and FillQuantity in Base Brokerage Test

* test:refactor: use Exception instead of Log
2024-12-26 18:44:24 -03:00
Roman Yavnikov
eca4f5b7f2 feat: init Config in BrokerageDataDownloader (#8482) 2024-12-26 12:57:27 -03:00
Martin-Molinero
2bdddc94b4 Update QuantConnect.csproj 2024-12-23 19:47:13 -03:00
Ricardo Andrés Marino Rojas
12930c444b Fix bug in Index security (#8472)
* Add unit test

* First potential solution

* Add regression tests

* Nit change

* Address requested changes

* Nit change

* Nit change

* Improve implementation

* Fix bugs

* Address requested changes
2024-12-23 16:32:25 -03:00
Derek Melchin
2ec979940c Update Beta.cs (#8478)
Update the docs to explain how the indicator handles missing data.
2024-12-23 16:10:11 -03:00
JosueNina
edd1aea8b0 Implement ZigZag (ZZ) indicator (#8454)
* Implement ZigZag Indicator

* Create Unit Test for ZigZag Indicator

* Update QCAlgorithm with ZigZag Indicator

* Resolved review comments

* Refactor ZigZag Indicator

- Refactored logic to streamline pivot updates and condition checks.
- Exposed PivotType enum to track pivot direction (High/Low).
- Updated CSV processing to reflect pivot type (High/Low).

* Refactor UpdatePivot logic
2024-12-23 13:19:39 -03:00
JosueNina
be4a34c7e4 Implement SqueezeMomentum (SM) indicator (#8462)
* Implement Squeeze Momentum Indicator

* Create unit test for SqueezeMomentum Indicator

* Update QCAlgorithm with SqueezeMomentum indicator

* Resolved review comments

* Switched to using Keltner indicator instead of manual calculation

* Refactor Squeeze Momentum indicator

- Make the Bollinger Bands and Keltner Channels indicators public.
- In IndicatorBase -> Update, if T is IndicatorDataPoint, then create a new
  IndicatorDataPoint.

* Fix issue with regression tests

* Fix unit test
2024-12-20 18:22:32 -03:00
JosueNina
3b559a5f3f Fix bug in beta value computation (#8466)
* Fix bug in beta calculation

- Beta is fill-forwarded
- A correct pair considered when they have different symbols and the
  same date
- Processing occurs when there are at least period+1 correct pairs

* Address review comments

* Add time zone handling and resolution-based truncation

* Fix regression test for Beta indicator

* Handle resolution for beta indicator

- Remove effectiveResolution and Beta constructor parameter for
  resolution.
- Streamlined resolution handling logic for Beta indicator.
- Fixed issues with regression test for Beta.

* Fix issue with period and WarmUpPeriod

* Update unit tests for Alpha indicator

* Fixing minor issues

* Add a variable to track if the previous symbol is the target

* Add regression test for Beta calculation between BTCUSD and SPY

* Add an extra period if the TZ are different
2024-12-20 18:22:04 -03:00
Martin-Molinero
d4fd936772 Update pythonnet to net9 (#8475) 2024-12-20 18:21:44 -03:00
Martin-Molinero
a0328426d9 Update readme.md 2024-12-19 18:15:57 -03:00
Martin-Molinero
890a19c871 Update readme.md 2024-12-19 16:30:13 -03:00
Martin-Molinero
5359561b9d Dotnet 9 (#8459)
* Dotnet 9

* Remove C# kernel
2024-12-19 14:01:26 -03:00
Jhonathan Abreu
a8592e08b5 Greeks calculation on expiration date (#8465)
* Add helper method to calculate options expiration date time

This allows to compute accurate time till expiry for greek indicators to be able to calculate on the actual expiration date before market close

* Update tolerance in greek indicators tests

* Minor fix

* Modify helper method to calculate settlement time instead of expiration time

* Cache option expiration date time

* Minor changes

* Minor changes
2024-12-13 18:23:31 -04:00
Ricardo Andrés Marino Rojas
fcb4ce637d Reduce unrequired live logs for derivatives chains (#8458)
* First draft of the solution

* Address requests

* Reduce more enrequired logs
2024-12-12 15:49:38 -04:00
Jhonathan Abreu
ec428c5f6c Daily options contracts valid open interest values (#8450)
* Fix for daily options open interest data to be added to contracts

* Cleanup

* Update regression algorithms stats

* Minor fix and cleanup

* Minor fix

* Minor fix

* Update regression algorithms data point count

* Address peer review
2024-12-12 14:50:59 -03:00
Ricardo Andrés Marino Rojas
2a62f16833 Make SignalExportManager skip non-tradeable securities (#8453)
* First approach

* Fix bug

* Address requests

* Address requests
2024-12-11 20:01:38 -03:00
Roman Yavnikov
f1c50e41a5 Feature: support trading IndexOption by TradeStation (#8456)
* feat: support IndexOption in TSBrokerageModel

* feat: add IndexOptionFee in TSFeeModel
2024-12-11 20:00:52 -03:00
Nikolay Baraboshkin
7445f7ec5a Improve performance of ConsolidatorScanPriority comparison (#8452)
* Improve the performance of ConsolidatorScanPriority comparison in SubscriptionManager

* address review comments
2024-12-11 19:59:33 -03:00
Martin-Molinero
8febb9ac45 Revert net version target (#8457) 2024-12-10 18:49:14 -03:00
Martin-Molinero
463044b64a Foundation update (#8455) 2024-12-10 18:07:26 -03:00
Louis Szeto
9865ce9815 Add example on volume share slippage model (#8437)
* add csharp example

* add python example

* regression

* add pythom implementation as example model

* peer review

* dependencies

* fix regression test
2024-12-09 15:37:35 -03:00
Ricardo Andrés Marino Rojas
81d7774c80 Fix bug when consolidating hourly bars into daily ones (#8442)
* First draft of the solution

* Add regression tests

* Improve solution and add unit test

* Address suggestions

* Improve unit tests

* Nit changes

* Fix regression algorithms
2024-12-06 14:42:40 -05:00
Nikolay Baraboshkin
22e04913a5 Improve the performance of RollingWindow.GetEnumerator (#8444)
* improve the performance of RollingWindow.GetEnumerator

Closes #8443

* address review comments
2024-12-05 17:32:02 -03:00
JosueNina
8e5893b708 Implement Hurst Exponent (HE) indicator (#8434)
* Implement Hurst Exponent indicator and unit test

- Implemented Hurst Exponent indicator class
- Created unit tests to validate indicator functionality
- Added helper methods for standard deviation and regression line slope

* Optimize Hurst Exponent calculation

- Removed redundat loops and unnecessary operations.
- Precomputed values fro time lag logarithms to avoid recalculation.
- Simplified logic in ComputeNextValue for better performance.
- Updated and clarified comments for improved readability.

* Refactor HurstExponent indicator

- Made _sumX and _sumX2 fields readonly.
- Updated loop for calculating time lag differences to avoid out of
  bound.
- Renamed lookbackPeriod with period.
- Replaced DateTime.Now with a fixed date.
2024-12-05 10:19:31 -03:00
Martin-Molinero
99558928f0 Improve ObjectStore root config handling (#8445) 2024-12-04 19:17:10 -03:00
Roman Yavnikov
a2efee8be9 feat: Binance future support StopMarket for CryptoFuture (#8441)
test:feat: CanSubmit StopMarket Crypto or CryptoFuture in Binance Model
2024-12-04 14:46:02 -03:00
Jhonathan Abreu
a1d0b6cde2 Live trading consolidation synchronization (#8436)
* Adjust time slice time for live trading

Adjust time slice to be driven by data, so that consolidators are update at the correct times.
Live trading uses DateTime.UtcNow which might be a few milliseconds after the latest data, causing some race conditions in consolidators scan times.

* Refactor: rounding time slice time down for past consolidators scan (live)

* Cleanup
2024-12-04 11:15:00 -04:00
JosueNina
8123e76e3c Validate inputs for safe logarithm calculation (#8439)
- Ensure both previousPoint and previousPoint2 are non-zero.
- Prevent division by zero and undefined errors.
- Add unit test to verity the new validation logic.
2024-12-03 17:30:07 -03:00
Jhonathan Abreu
a28d1f2ffe Universe data frames improvements (#8433)
* Default Data to null for ETFConstituentUniverses.

The data collection will be assigned only if needed. This allows data column to be filtered from dataframes since it will always be null for all constituents.

* Make base data collection aggregator reader fall back to BaseDataCollection

After instatiating the collection type, fall back to the base BaseDataCollection to aggregate data if the type is not a base data collection.

* Minor change

* Minor change

* Update pythonnet to 2.0.41

* Ignore data column for every flattened universe dataframe

* Filter empty collections columns in data frames

* Allow snake case named attributes in PythonSlice

* Remove PythonSlice Data Python class

Pythonnet handles dynamic objects behavior
2024-12-03 16:19:17 -04:00
Ricardo Andrés Marino Rojas
f4314549c3 Fix warming up bug QCAlgorithm.WarmUpIndicator() (#8431)
* First draft of the solution

* Add regression tests

* Nit changes

* Solve root issue

* Improve regression tests

* Reduce duplication

* Nit change

* Improve implementation

* Address suggestions

* Address requested improvements

* Nit change

* Nit changes

* Nit change
2024-11-29 16:35:37 -03:00
Jhonathan Abreu
d416580456 Adjust lower-resolution fill-forwarded strict end-timed daily bars (#8412)
* Adjust lower-resolution fill-forwarded daily bars when strict end times is enabled

This allows to get fill-forwarded bars with unchanged time stamps

* Minor fixes

* Minor test data changes

* Fixes and comments

* Address peer review and add some fixes

* Minor fix and add regression algorithm

* Minor fix
2024-11-29 09:52:01 -04:00
Jhonathan Abreu
93ce62536f Revert "Fix warming up bug in Stochastic indicator (#8422)" (#8430)
This reverts commit 312392d6ae.
2024-11-29 09:50:30 -04:00
Ricardo Andrés Marino Rojas
312392d6ae Fix warming up bug in Stochastic indicator (#8422)
* First draft of the solution

* Add regression tests

* Nit changes

* Solve root issue

* Improve regression tests

* Reduce duplication

* Nit change

* Improve implementation
2024-11-29 09:49:06 -04:00
JosueNina
01734e1f61 Implement Mesa Adaptive Moving Average (MAMA) Indicator (#8428)
* Initial implementation of MAMA indicator and tests

* Implemented Mesa Adaptive Moving Average (MAMA) indicator

- Implemented the MAMA indicator.
- Created methods with overloads to support custom and default
  fastLimit/slowLimit
- Included necessary logic to calculate the mesa adaptive moving average
  based on John's formula.
- Created unit tests to validate MAMA's behaviour.

* Refactor Mesa Adaptive Moving Average(MAMA)

- Separated the logic into smaller functions for better maintainability.
- Improved variable names to reflec their purpose.
- Updated comments to reflect changes and improve readability.
- Consolidated MAMA method overlaod by using default parameters values.

* Refactor variables and update method parameters

- Renamed variables for better clarity.
- Updated method to use 'IBaseDataBar' instead of 'TradeBar'
- Used 'MAMA({fastLimit}, {slowLimit}) instead of just 'MAMA'
2024-11-27 18:54:59 -03:00
Ricardo Andrés Marino Rojas
124063a2a4 Change Log.Trace() to Log.Debug() (#8429) 2024-11-27 18:27:54 -03:00
Ricardo Andrés Marino Rojas
b99da54d5a Implement Reset() method (#8410)
* First draft of the feature

* Add XML docs

* Fix and improve unit test

* Address suggestions

* Improve unit test

* Improve implementation
2024-11-27 16:53:02 -03:00
Jhonathan Abreu
bc5d51806d Universe data frames normalization (#8385)
* Normalize universe data frames

Universe and (generically BaseDataCollection) data frames are not normalize and unpacked into a data frame, instead of just creating data frames with the universe lists within it

* Fix unit tests and algorithms to expecte new universe dataframe format

* Fixes

* Add PandasConverter.DataFrameGenerator class

* Pandas data frame generator class fixes

* Add comments

* Housekeeping

* Add attributes to mark classes and properties for pandas processing

* Improve pandas properties expanding

Allow and handle duplicate names

* Use PandasData generalization for Lean common data types

* Add points time as column when converting base data collections to data frames

* Cleanup and minor changes

* Minor change

* Pandas data to get type members on demand

* Move Pandas helper classes to their own files

* Minor changes

* Add flatten argument to python history api

This allows users to decide whether they want fully expanded dataframes for universe and other collection data types. Else, master behavior is kept

* Adding missing changes to last commit

* Update Pythonnet version to 2.0.40

* Add flattent argument to algorithm's OptionChain api

* Minor changes

* Housekeeping

* Minor changes

* Bug fix skipping data collection data points

* Add comment

* Set correct exchange time to OptionUniverse instances

* Address peer review and cleanup

* Cleanup

* Minor changes
2024-11-26 16:16:34 -04:00
JosueNina
f3ed5b1206 Fix correlation type (#8426)
- Addressed bug causing mismatch between types of correlations.
- Updated C method to include CorrelationType.
- Created regression test to ensure proper validation.
2024-11-26 14:05:49 -03:00
Ricardo Andrés Marino Rojas
eb6c5d20f5 Fix typos (#8349)
* Fix typos

* Fix bugs

* second try to fix bugs

* Fix typos

* Nit change

* Update enums too

* Fix bugs
2024-11-26 11:36:14 -03:00
Ricardo Andrés Marino Rojas
b70b5bd5fe Add extended market hours option in DateRules.WeekStart() (#8400)
* First potential solution

* Add unit tests

* Address requested changes

* Add unit test reproducing user bug

* Missing update

* Address reviews

* Improve unit test

* Improve unit test

* Nit change

* Nit changes

* Nit changes
2024-11-25 18:09:44 -03:00
Ricardo Andrés Marino Rojas
5ac7d00e24 Normalize Date timezone (#8420)
* First draft of the solution

* Add unit test

* Nit change
2024-11-25 17:44:22 -03:00
JosueNina
469d960f50 Implement Connor's Relative Strength Index(CRSI) Indicator (#8419)
* Add Connors Relative Strength Index(CRSI) Indicator

- Implemented CRSI combining RSI, Streak RSI, and ROC
- Added unit tests for CRSI calculation to ensure correctness and
  reliability.
- Inclued the spy_crsi.csv file for testing purposes and validation of
  CRSI logic.

* Refactor CRSI indicator

- Updated the CRSI logic to use Percent Change of Daily Returns instead
  of ROC.
- Modified the ConnorsRelativeStrengthIndex class:
  - Updated ComputeNextValue to calculate daily returns and relative
    magnitude
- Improved documentation and comments

* Refactor CRSI Indicator:

- Refactored the method that updated the trend streak based on price
  changes.
- Created a new method ComputeTrendStreak.
- Added check for null or 0 value in _previousInput.

* Fix comments from code review

- Add _ to priceChangeRatios
- Move _srsi.Update() to the top to avoid duplication
2024-11-25 15:43:42 -03:00
Jhonathan Abreu
7eea365aa1 Let delistings through for internal subscriptions (#8398)
* Let delistings through for internal subscriptions

Without it, previously mapped continuous future contracts for which a position is open never received a delisting event for them to be liquidated and marked as non-tradable

* Update regression algorithm stats

* Revert/remove transaction handler initialization parameters DTO class

* Cleanup
2024-11-25 11:41:02 -03:00
Jhonathan Abreu
760071a2f7 Fix 0DTE index options selection (#8418)
* Revert parts of GH PR 8395 to fix 0DTE index options

* Add regression algorithms

* Cleanup

* Cleanup
2024-11-20 09:18:11 -04:00
Jhonathan Abreu
fa1ef4f763 Index option chain backwards compatibility (#8395)
* Fix option universe

Set right time using exchange time zone when reading.
Remove OptionUniverse market hours hack in GetEntry extension method.

* Minor change
2024-11-15 17:30:44 -04:00
Roman Yavnikov
f7b012aa11 Feature: Implementation Charles Schwab Brokerage (#8406)
* feat: ExtendedRegularTradingHours property in CharlesSchwabOrderProperties

* feat: BrokerageModel, FeeModel of Charles Schwab

* refactor: CharlesSchwab Fee model
remove: SecurityType.Index in CanSubmit CharlesSchwab

* refactor: CharlesSchwabFeeModel (a little bit simpler)

* refactor: CharlesSchwabFeeModel (more simpler)
2024-11-15 18:17:20 -03:00
JosueNina
725ad73240 Implement Average Range (AR) Indicator (#8404)
* Add Average Daily Range indicator and tests

- Implemented AverageDailyRange indicator
- The indicator uses a Simple Moving Average (SMA)
- Created unit tests for the indicator
- Includes example input data and test file (spy_adr.csv)

* Refactor AverageDailyRange Indicator

- Renamed AverageDailyRange to AverageRage for a more generic approach
- Replaced explicit types with 'var'
- Updated method name in test cases
- Placed AR method in the correct alphabetical order

* Solving minor issues with AR indicator

- Replace TradeBar with IBaseDataBar
- Remove unnecessary override methods
2024-11-15 11:19:55 -03:00
JosueNina
7bbf42f79b Implement Premier Stochastic Oscillator (PSO) Indicator (#8394)
* Implement Premier Stochastic Oscillator (PSO)

- Added PremierStochasticOscillator class with two Exponential Moving
  Averages (_ema1 and _ema2) for double smoothing.
- Implemented PSO computation:
  - Normalized Stochastic (nsk) = 0.1 * (Fast%K - 50)
  - Double-smoothed Normalized Stochastic
- Added XML documentation for public methods and key calculations.

This commit introduces a new indicator.

* Add license header and adjust spacing

* Refactor Premier Stochastic Oscillator (PSO)

- Renamed smoothing variables for clarity
- Integrated PSO logic directly in ComputeNextValue
- Used IndicatorExtensions for streamlined EMA chaining
- Updated tests to match refactored logic

* Refactor PSO

- Changed "STO" to "PSO"
- Removed unused imports
- Updated private fields
- Minor code cleanup
2024-11-14 18:22:46 -03:00
Ricardo Andrés Marino Rojas
f2da037d42 Solve divide by zero exception in McGinleyDynamic indicator (#8397)
* Add SafeDivision() method

* Add assertions

* Nit changes

* Nit change
2024-11-14 18:20:18 -03:00
Ricardo Andrés Marino Rojas
5c5c527252 Use SafeDivision() method to avoid overflow exception in CCI (#8396)
* Use SafeDivision() method to avoid overflow exception

* Nit change
2024-11-14 18:20:00 -03:00
Martin-Molinero
71d09a3567 Private cloud minor improvements (#8409)
* Private cloud tweaks

* Minor tweaks for optimization
2024-11-14 17:22:33 -03:00
JosueNina
085476a222 job_queue: fix typos in comments (#8390)
Corrected minor typos in comments within the JobQueue class to improve
readability

- Verify all comments for further errors
2024-11-01 19:13:49 -03:00
Alexandre Catarino
c78774b99a Adds Country Static Class (#8389)
This class contains all countries and mapping them to their ISO 3166-1 alpha-3 codes.
2024-11-01 19:13:07 -03:00
Ricardo Andrés Marino Rojas
d5b2e4d8cc Make Target.MoveAhead() case insensitive (#8382)
* First draft of the solution

* Try a different approach

* Nit change

* Add unit tests

* Add edge cases

* Address requests
2024-10-24 09:29:16 -03:00
Ricardo Andrés Marino Rojas
828d9238b8 Remove duplicated keys in OpenInterestFutureUniverseSelectionModel (#8365)
* First draft of the solution

* Enhance implementation
2024-10-21 09:43:06 -03:00
Jhonathan Abreu
f2100adb46 Fix price shifts around futures rollover date (#8371)
* Test

* Fix price shift on continuous future rollover

* Keep track of both data and exchange time in subscription data reader

* Fix for daily and hourly resolutions.

Add daily and hour algorithms

* Fixes for emitting new exchange dates at the beginning and end when data is not available

* Cleanup

* Minor fix

* Minor fix: detect mapping in data reader after advancing time keeper

* Minor fix

* More fixes

* More fixes

* Fixes for universe files

* More fixes for daily resolution data

* Separate DateChangeTimeKeeper to its own file

* Add DateChangeTimeKeeper unit tests

* Minor fix

* Add more DateChangeTimeKeeper unit tests

* Address peer review

* Address peer review

* Address peer review

* Detect mappings using the config NewSymbol event

* DateChangeTimeKeeper performance improvement for time zone conversions

* Clean up date change time keeper

* Cleanup

* Minor regression algo update

* Cleanup

* Cleanup

* Fix perform universe selection on sundays for continuous futures with extended market hours

* Cleanup

* Address peer review

* More cleanup

* More cleanup
2024-10-21 09:38:00 -03:00
Jhonathan Abreu
159fa5a182 Fix Python Consolidate API to respect strict daily times for Daily resolution (#8373)
* Fix ConsolidateRegressionAlgorithm

- Fix Bitcoin custom data time range. Historical data goes from April 2014
- Fix expected consolidated bar counts
- Fix python Consolidate implementations to respect daily strict times for Daily resolution

* Housekeeping
2024-10-16 17:35:10 -03:00
Ricardo Andrés Marino Rojas
8ef0a4977b Fix bug in QuantBook.UniverseHistory() when using Monthly date rule (#8368)
* Fix bug in Universe history with montly selection

* Reduce duplication

* Fix missing overload method

* Address requests

* Nit change

* Improve implementation

* Improve implementation

* Fix bug and add more unit tests

* Nit change

* Address requested changes

* Address requested changes

* Nit change
2024-10-16 17:34:26 -03:00
Martin-Molinero
ffdb615a4d Add research node packet (#8360) 2024-10-15 13:38:39 -03:00
Martin-Molinero
8f57a8c8ff Update readme.md 2024-10-14 18:56:42 -03:00
Roman Yavnikov
a831adc9c8 Fix: Broken Regression Algorithms (#8366)
* fix: CustomData/RegisterIndicator-RegressionAlgorithm

* fix: CustomDataPropertiesRegressionAlgorithm

* fix: CustomDataRegressionAlgorithm py

* fix: CustomDataPropertiesRegressionAlgorithm py

* fix: RegisterIndicatorRegressionAlgorithm py

* refactror: use nasdaq instead of quandl in proxy url
2024-10-10 11:36:18 -03:00
Roman Yavnikov
6b22254924 Feature: new sorting property in SubscriptionDataSource and SortEnumerator (#8352)
* feat: sort property in SubscriptionDataSource

* refactor: read lines (with sort opportunity) in TextSubscriptionDataSourceReader

* refactor: xml description of Sort property in SubscriptionDataSource

* revet: TextSubscriptionDataSourceReader changes

* feat: develop UnsortedTextSubscriptionDataSourceReader

* remove: UnsortedTextSubscriptionDataSourceReader

* feat: develop SortEnumerator
feat: use SortEnumerator in SubscriptionDataReader

* revert: TextSubscriptionDataSourceReader changes

* feat: use sort Enumerator in LiveCustomDataSubscriptionEnumeratorFactory

* test:feat: Unsorted Live Data Feed with using Object Store

* test:feat: history CustomData request with unsorted data

* refactor: develop TryWrapper on SortEnumerator

* remove: extra spacing

* refactor: Sort in SubscriptionDataSource

* feat: add RegressionAlgorithms when source return data in Descending format

* refactor: xml description of prop Sort in  SubscriptionDataSource

* refactor: SortEnumerator

* test:refactor access modifier in ExampleCustomDataWithSort

* test:refactor: increase performance LiveDataFeedSourcesDataFromObjectStore

* feat: add xml comment of regression algorithm

* test:revert: access modifier to public in internal test class

* test:refactor: use while instead of timer

* Revert "test:refactor: use while instead of timer"

This reverts commit 4fe43da809.
2024-10-07 18:16:33 -03:00
Ricardo Andrés Marino Rojas
0e61415ce2 Fix bug ImmediateExecutionModel when using Crypto (#8355)
* First draft of the solution

* Add missing algorithm

* Improve regression tests

* Nit change

* Address requests

* Nit change

* Address minor requests

* Nit changes

* Nit suggestion
2024-10-07 16:46:37 -03:00
Martin-Molinero
16c893deb6 Fix history manager configuration assertion (#8361) 2024-10-07 10:40:28 -03:00
Ricardo Andrés Marino Rojas
33048149af Add custom ToString() method in API classes (#8357)
* Potential solution

* Improve solution

* Nit change

* Nit change
2024-10-07 10:37:11 -03:00
Martin-Molinero
0a2c05ab1e Improve performance of OptionChain (#8359)
- Improve performance of OptionChain by creating a single pandas df
2024-10-04 20:03:53 -03:00
Martin-Molinero
e16b27f089 Update readme.md 2024-10-04 13:33:59 -03:00
Jhonathan Abreu
0a9dc2c71c QCAlgorithm's OptionChain() api refactor (#8334)
* Fix pandas converter to handle list of data with different symbols

* Properly convert list of data into dataframe

Take into consideration data for multiple symbols in the same list

* Cleanup

* Index dataframes by symbol object instead of SID string

* Add symbol equality operator to compare against object

* Exclude "ID" from option chain dataframe

* Minor fix

* Add greeks columns directly in option chain dataframe.

Also add pass-through properties for greek values in OptionUniverse

* Some cleanup

* Minor fix

* Add new QCAlgorithm.OptionChains() method

- Use OptionChains as output
- Add DataFrame to OptionChain and OptionChains
- Rename Greeks classes
- Add ISymbolProvider for classes that have a symbol (IBaseData, OptionContract)

* Unify QCAlgorithmOptionChain API

Also refactor OptionContract to handle: (1) Actual market data and option price model data, and (2) OptionUniverse data

* Pass symbol properties to OptionUniverse option chain from algorithm

* Format OptionContract for dataframe

* Minor fix

* Add multiple option chains api regression algorithms and other minor changes

* Address peer review

Add NullGreeks class: keep ModeledGreeks as internal as possible

* Minor fix and add PandasConverter unit tests

* Peer review: Non-thread-safe Lazy for Python

* Handle Greeks unwrapping by PandasData

* PandasData cleanup

* Add data and other minor changes

* Unit test fix

* Update Pythonnet to 2.0.39

* Cleanup

* PandasData handling children class members

Address peer review

* Fix: indexing symbol conversion in pandas mapper

* Fix pandas mapper to convert string keys to symbol only when necessary

* Cleanup

* Cleanup

* Add PandasColumn python class to handle proper indexing

This allows propery hash and equality between Symbols, C# strings and Python strings

* Minor fixes

* Symbol cache improvements

* Minor fix for cache miss

* Revert PandasMapper reserved names and improvements

* Minor fix

* Revert reserved names

* Minor fix for Symbol equality operators

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-10-04 12:26:15 -04:00
Martin-Molinero
7c9aa858c2 Improve python command serialization (#8351)
- Fix bug in python command serialization, expanding existing tests
2024-10-02 09:19:04 -03:00
Martin-Molinero
8fb70b20d0 Enhance command support (#8348)
* Enhance command support

- Enhance command support, adding link helper methods. Adding and
  expanding new tests
- Minor improvement for command str representation

* Minor test fix
2024-09-30 16:01:08 -03:00
Louis Szeto
809faa24de Add Backspread Option Strategies (#8312)
* Call and put backspread definitions

* Margin model

* regression tests

* strategy unit test

* refactor

* Use option strategies to order
2024-09-26 16:57:20 -03:00
Jhonathan Abreu
ad5aa263c0 Infer data type from configs in bar count history requests (#8344)
* Infer data type from configs in bar count history requests

* Infer data type from configs in bar count history requests

* Minor changes

* Minor fix

* Cleanup
2024-09-26 16:51:19 -03:00
Roman Yavnikov
a1bb907e03 Feature:Alpaca: support MarketOnOpen and MarketOnClose (#8341)
* feat: missed Alpaca config in Launcher

* feature: support of new OrderTypes for Equtity in AlpacaBrokerage model
2024-09-25 14:30:27 -03:00
Roman Yavnikov
71540f5015 Feature: support MarketOnOpen and MarketOnClose (#8340)
* remove: not used proxy config TradeStation

* feat: missed config of TradeStation in Launcher

* feat: support new OrderTypes in TradeStationBrokerageModel
2024-09-24 15:11:36 -03:00
Kevin Wheeler
a0055a3695 Improve data not found error messages. (#8295)
* Improve data not found error messages.

* Minor tweaks

---------

Co-authored-by: Kevin Wheeler <spreadlove5683@gmail.com>
Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-09-20 16:56:58 -03:00
Martin-Molinero
0b285df496 Minor fix for option contract universe (#8337) 2024-09-20 13:16:20 -03:00
Martin Molinero
4d37096b3f Reduce realtime shutdown timeout 2024-09-20 10:04:58 -03:00
Martin Molinero
7c42ea795f Minor improvement for live trading shutdown 2024-09-19 20:09:21 -03:00
Martin-Molinero
f2f1d06237 Improve shutdown (#8335) 2024-09-19 19:32:29 -03:00
Martin-Molinero
86fd80a31a Generic live command support (#8330)
* Generic command support

- Adding generic algorithm command support. Adding regression algorithms
- Allow PythonWrapper to validate classes too

* Minor improvements
2024-09-19 16:02:42 -03:00
Roman Yavnikov
c556d16775 Feature: new Tick constructor for TickType.OpenInterest (#8323)
* feat: create OpenInterest constrcutor of Tick

* feat: GetSubscribedSymbols by TickType

* test:feat: GetSubscribeSymbolsBySpecificTickType

* refactor: equal channel name with InvariantCultureIgnoreCase
2024-09-17 12:52:24 -03:00
Martin-Molinero
6351773a01 Option universe resolution improvements (#8324)
* Option universe improvements

- Improvement for resolution handling of option universes, affecting
  performance in live mode. Adding regression algorithm

* Minor fix for research test
2024-09-16 10:22:58 -03:00
Jhonathan Abreu
bf4b08e202 Fix: adjust option expiry reference date (#8322)
* Fix: adjust option expiry reference date

* Add universe files

* Update data and other minor changes

* Minor changes

* Add regression algorithm summary
2024-09-13 18:22:26 -04:00
Jhonathan Abreu
fa9ff399cc Euro Stoxx 50 Index and Index Futures support (#8278)
* EUREX data

EUREX data model and sample data

* Add EUREX futures expiry function and sample algorithms

* Add EuroStoxx50 futures map and factor files

* Reduce eurex data for repo

* Map eurex market to primary exchange

* Update Euro Stoxx 50 (FESX) map and factol files

* Update Euro Stoxx 50 (FESX) minute data

* Added EURSD data

* Added 2 basic FESX futures algorithms in CSharp and Python (#2)

* Add regression algorithms

* Update regression algorithms and data

* Minor change

* Cleanup

---------

Co-authored-by: paulius-an <118921953+paulius-an@users.noreply.github.com>
2024-09-12 10:00:16 -04:00
Jhonathan Abreu
16c4259342 Add QCAlgorithm.OptionChain() method to fetch option chains (#8316)
* Add new QCAlgorithm.OptionChain method to get full data option chain

* Add extension method to get canonical symbol

* Support future options in new OptionChain method

* Replace option chain provider with OptionChain method in some regression algorithms

* Add new regression algorithms for OptionChain method

* Replace option chain provider with OptionChain method in some regression algorithms

* Minor

* Cleanup

* Minor changes in regression algorithms

* Minor adjustments
2024-09-11 15:15:51 -04:00
Ricardo Andrés Marino Rojas
724d0b06a5 Add extra argument in QuantBook.UniverseHistory() for using an IDateRule (#8301)
* First draft of the solution

* Handle end date better

* Improve unit tests

* Add extra argument in missing method

* Nit change

* Nit change

* Nit change

* Undo changes to C# generic UniverseHistory()

* Address suggestions

* Improve unit test

* Add null checks

* Minor adjustment

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-09-11 13:41:57 -03:00
Ricardo Andrés Marino Rojas
ba7fe05574 Add BeforeMarketOpen() and AfterMarketClose() date rules (#8311)
* First draft of the solution

* Add unit tests

* Improve unit tests

* Nit changes
2024-09-10 15:56:31 -03:00
Ricardo Andrés Marino Rojas
50437946e2 Add missing end_date in python regression algorithm (#8315) 2024-09-10 14:33:44 -03:00
Ricardo Andrés Marino Rojas
418970bb48 Add TravisExclude category to failing CI unit test (#8313) 2024-09-10 13:25:41 -03:00
Roman Yavnikov
bef045a360 Fix: Get GroupOrders ByBrokerageId (#8310)
* fix: Get GroupOrders ByBrokerageId

* test:feat: return all combo orders with the same brokerageId
2024-09-10 13:25:22 -03:00
Jhonathan Abreu
49bf436aa2 Remove Lean path info from runtime exceptions (#8309)
* Strip lean path info from runtime exceptions

* Minor fix
2024-09-09 17:54:29 -04:00
Jhonathan Abreu
e29bb2c5e0 File-based options universe (#8212)
* Initial options universe with greeks implementation

* Options universe improvements

* Address peer review

* File based options universe fixes and improvements.

- Adjust OptionUniverse start-end times and period.
- Adapt unit tests and some algorithms to pass with new options universe selection.

* Updated options regression algorithms stats for new universe data

* Updated options regression algorithms stats for new universe data

* Updated options regression algorithms stats for new universe data

* Updated options regression algorithms stats for new universe data

* Updated options regression algorithms stats for new universe data

* Option chain provider with new options universe

* Allow canonical option history requests

* Address peer review

* Address peer review

* Fix symbols parsing in OptionUniverse

* Fix universe selection subscriptions start time to not include extended market hours

* Minor changes

* Minor changes

* Peer recommended changes and fixes

* Update regression algorithm stats

* Update regression algorithms stats and minor fixes

* Fix option chain provider history request

* Round option indicators values

* Added option universe csv header property

* Update regression algorithms stats

* Update regression algorithms stats

* Data fixes and regression algos stats update

* Unit test fixes

* Minor changes

* Option chain handling in live trading data feed

* Minor changes

* Added processed data provider

* Fix thread-safety violation in Slice class

* Minor change

* Update options filter universe API to use OptionUniverse data

Add new filter methods for greeks, IV and open interest

* Option filter universe api updates

* Add OptionUniverse history regression algorithms

* Add regression algorithms for new options filter universe api methods

* Added options greeks data and updated regression algorithms

* Address peer review

* Address peer review

* Add more assertions to new options filter api regression algorithms

* Minor performance improvement.

Reduce greeks binomial model steps to 140

* Minor tests updates

* Greeks numerical models performance improvements

* Greeks numerical models performance improvements

* Revert array pool change for option pricing numerical models

* Update default dividend yield provider depending on option type

* [TEST]

* Add helper method con calculate time till expiration

* Use double in price option numerical models

* Implied volatility calculation improvements

- Adjust root finding method accuracy as a factor of the option price
- Use BSM to get a first guess

* Cleanup

* Some regression algorithms and unit tests cleanup

* Regression tests updates after rebasing from master

* Add universe files

* Self review and cleanup

* Minor regression tests updates after rebase

* Fix: set data time zone to same as exchange tz for options universes

* Minor change

* Minor change

* Fix for live trading options universe selection

* Keep underlying when aggregating collections in BaseDataCollectionAggregatorEnumerator

* Update index options regression algorithms stats

* Minor change

* Address peer review

* Memory usage improvements

* Minor build fix

* Minor changes and test fixes

* Cache symbols in OptionUniverse

* Cleanup

* Fix index option creation in OptionUniverse

* Use cached underlying SID when parsing from string

* Abstract symbols cache to BaseDataCollection

* Return actual underlying symbol when mapping decomposing ICO ticker

* Address peer review

* Minor performance improvements reduce garbage

* Limit Symbols and SIDs cache size to help with memory usage

* Minor fix in symbols and sid cache cleanup

* Build fix

* Lazily parse greeks on individual access

* Cleanup and tests

* Address peer review

* Minor greeks fix

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-09-09 12:39:31 -03:00
Dennis Yemelyanov
8fcc9f7d4e fix some comments for option security types (#8304) 2024-09-09 11:37:26 -03:00
Andy Geach
5209332074 Update readme.md to remove references to Visual Studio for Mac, which has been discontinued (#8298) 2024-09-06 11:59:28 -03:00
Roman Yavnikov
adfad475cc Feature:TradeStationBrokerage: support ComboMarket && ComboLimit (#8290)
* refactor: adding OrderId in GroupOrderManger

* feat: new support of OrderTypes in TradeStationBrokerageModel
feat: unSupported OrderTypes in CanUpdateOrder's TradeStationBrokerageModel

* feat: AllOrNone property in TradeStationOrderProperties

* feat: unsupported SubmitCrossZero of Combo Order in TSBrokerageModel

* test:feat: submit / update CrossZero Combo Orders

* feat: new Message Brokerage error message
refactor: use new Message in TradeStationBrokerageModel

* feat: setter of Id in GroupOrderManager

* feat: new constructor of GroupOrderManager

* feat: develop GroupOrderCacheManager service

* fix: groupOrderManger.Id in OrderProvider

* fix: incrementOrderGroupOrderManagerID in BrokerageTransactionHandler
feat: add _groupOrderManagerId in OrderProvider

* remove: extra semicolon

* refactor: prevent increment GroupOrderID

* feat: add new Exchanges

* feat: Try Get Group Combo Orders extension

* refactor: ComboORderType in TSBrokerageModel

* remove: implementing of prop ID in GroupOrderManager

* refactor: UnsupportedCrossZeroByOrderType message

* fix: warning of UnsupportedCrossZeroByOrderType

* fix: several exchanges code based on tradier docs
https://documentation.tradier.com/brokerage-api/reference/exchanges

* feat: add missed Exchange in Global class

* refactor: possible update LimitPrice in TSBrokerageModel
test:feat: validate upddate LimitPrice of ComboLimit Order

* refactor: GroupOrderCacheManager
remove: TryGetGroupCachedOrders from extension

* refactor: exchange SPHR to MIAX_SAPPHIRE

* remove: Exchange BYX cuz It is BATS_Y

* refactor: change position of Exchange C2

* refactor: change constructor's access modifier in class Exchange
2024-09-06 10:31:14 -03:00
Martin-Molinero
21fcadf0f8 Ignore failing live future option unit test (#8300) 2024-09-05 16:42:42 -03:00
Ricardo Andrés Marino Rojas
e893e67e9b Throw exception when base currency not found (#8289)
* First draft of the solution

* The same check for crytpo is done before

* Fix failing unit tests

* Remove non perpetual crypto futures from SPDB

* Address requests

* Fix failing unit tests
2024-09-04 12:14:53 -03:00
Alexandre Catarino
3b588d04fb Adds Overload to AddIndexOption (#8291)
* Adds Overload to AddIndexOption

Simplify usage. We don't need to create/add the underlying explicitly, see AddIndexOption(string, Resolution, string, bool) overload.

* Addresses Peer-Review

- Default market is `null` instead of `Market.USA` allowing for `BrokerageModel` setup.
- `AddIndexOption` and `AddIndexOptionContract` methods now return `indexOption` objects.

* Fixes Logic Bug
2024-09-04 10:30:05 -03:00
Ricardo Andrés Marino Rojas
e81bcbb987 Improve PythonIndicator.IsReady implementation (#8287)
* First draft of the solution

* nit change

* Add improvements

* Fix failing unit tests

* Add improvements
2024-09-04 10:07:13 -03:00
Roman Yavnikov
96e91b446d Fix: #8226, update spdb binance/binanceus (#8293)
* feature: update binance spdb data

* feature: update binanceus spdb data

* test:fix: EURUSDC stable coins conversation
2024-09-04 10:05:07 -03:00
Ricardo Andrés Marino Rojas
403f0348bd Update Bybit SPDB (#8294)
* Update Bybit SPDB

* Remove trailing comma
2024-09-03 17:55:12 -03:00
Ricardo Andrés Marino Rojas
eeeb310438 Update minimum price variation of some entries of CME futures in SPDB (#8288)
* Update some entries of CME futures in SPDB

* Adjust 6B minimum price variation
2024-08-28 19:59:40 -03:00
oussamanahdi
271f0bb08e Update readme.md (#8286) 2024-08-26 19:11:04 -03:00
Ricardo Andrés Marino Rojas
3a09c70851 Fix warm up indicator bugs (#8279)
* Potential solution

* Try a different approach

* Improve unit tests

* Nit change

* Improve implementation

* Fix another bug and improve unit tests
2024-08-26 10:20:40 -03:00
Roman Yavnikov
f31251732e Fix: Coinbase MinimumOrderSize tests based on new SPDB data (#8276)
* test:fix: minimValue based on new SPDB data

* fix: Estimated Strategy Capacity in FractionalQuantityRegressionAlgorithm
2024-08-23 11:47:45 -03:00
Roman Yavnikov
9baacdbdd6 feat: Coinbase SPDB update (#8273) 2024-08-22 17:42:58 -03:00
Martin-Molinero
363d469d6a Minor indicator history fix (#8270)
* Minor indicator history fix

- Take into account warmup period when used, the last bar of the warmup
  period is counted as a data point.
- Fix bug where in some cases the last data point could of been missed
  and the indicator not updated with it

* Minor tweak
2024-08-22 16:48:26 -03:00
Ricardo Andrés Marino Rojas
c186addf94 Add missing price magnifier in SPDB (#8271) 2024-08-22 16:44:26 -03:00
Ricardo Andrés Marino Rojas
17049dcd56 Fix null exception thrown in SubscriptionManager.ScanPastConsolidators (#8267)
* Initial draft of the solution

* Improve implemetation

* Nit change

* Address requests

* Switch from LinkedList ot List

* Fix bug
2024-08-22 09:55:41 -03:00
Jhonathan Abreu
d88387ac67 Extend Python wrappers error messages (#8257)
* Implement runtime checks for python wrappers

* Implement runtime checks for python wrappers

* Add more python wrappers runtime checks

* Add dictionary conversion unit tests

* Add python wrappers runtime checks for properties

* CLeanup base python wrapper messages
2024-08-19 14:27:32 -04:00
Ricardo Andrés Marino Rojas
74c3501ed3 Fix bug for history requests with custom symbols (#8262)
* Potential solution to the bug

* Add test file

* Fix bugs

* Address requested changes
2024-08-19 15:26:42 -03:00
Ricardo Andrés Marino Rojas
a543af71dc Solve bug (#8256) 2024-08-19 11:57:21 -03:00
Jhonathan Abreu
9b332c2149 Dividend yield calculation fix (#8264)
* Fix dividend yield calculation

* Get security price as input for dividend yield provider

* Account for splits in dividend yield provider

* Fix split adjustment for dividend yield calculation

* Use right dividend yield in options indicators
2024-08-19 09:30:05 -04:00
keshavdalmia10
1e620e54fe Feature 8132 implement vortex indicator (#8242)
* Implemented the vortex indicator.

* changed the vortex.cs calculations

* chore: Refactor VortexTests.cs and QCAlgorithm.Indicators.cs

* Refactor VortexTests.cs

* made changes according to the comments

* used indicator exxtension methods

* made changes in the naming convention and added condition for division by zero.

* Using composite indicators to clean up

---------

Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
2024-08-14 15:43:21 -03:00
Martin-Molinero
7879795207 Enable daily precise end time by default (#8254)
* Default daily precise end times

- Enable by default daily precise end times. Updating stats
- Minor fix for algorithm manager consolidator updates, adding new regression test
  asserting behavior and updating others
- Minor fix for SubscriptionData creator avoid round down on warmup if
  not appropiate
- Adjust consolidators to emit on daily strict end times if requested
  daily resolution and setting enabled
- Updating regression algorithms

* Skip daily data on extended market hours

* Some cleanup and self review

* Revert unrequired change
2024-08-14 12:49:56 -03:00
Noah Misch
d2d366e3f9 Fix sign of order quantity in example algorithm OnMarginCall(). (#8251)
Despite the comments about avoiding margin calls and about padding, this
turned a proposed sale of 100 shares into a *buy* of 110 shares.
2024-08-12 17:40:51 -03:00
Ricardo Andrés Marino Rojas
5226b7a468 Add more options to Field class (#8228)
* First draft of the solution

* Reduce duplication and add more properties

* Add regression tests

* Add xml docs

* Add unit tests

* Improve regression and unit tests

* Address requested changes

* Address request and improve unit tests

* Add unit test and fix bug

* Improve unit tests and implementation

* Nit change

* Address reviews

* Improve regression tests

* Address requests

* Fix bug

* Address requests
2024-08-07 19:08:34 -03:00
FemtoTrader
1947a58541 Implements new indicator - CKS - ChandeKrollStop (#8198)
* Implements ChandeKrollStop

* readonly

* Move IsReady/WarmUpPeriod above the constructors

* remove private _period

* minor

* rename Stops to Short/Long

* using Maximum/Minimum

* fix tests

* rename some variables and use movingAverageType for ATR

* movingAverageType
2024-08-07 14:51:39 -03:00
Roman Yavnikov
1bca3f6081 feat: missed reference on DownloaderDataProvider in Lean.Launcher (#8247) 2024-08-07 14:51:05 -03:00
Noah Misch
2b1136e446 Fix algorithms using OnData(TradeBars) w/o using arg or other OnData(). (#8245)
Commit d24f665ee4 removed the
Engine/AlgorithmManager.cs support for OnData(TradeBars), making these
methods dead code.  Hence, some of these algorithms no longer placed
orders.  Fix by changing OnData(TradeBars) to OnData(Slice).  Files that
use the TradeBars argument or use OnData(Dividends) have the same
trouble; leave them for future work.
2024-08-06 10:15:56 -03:00
Roman Yavnikov
86fcc40c3e Feature: Generic brokerage downloader wrapper (#8235)
* feat: new constructor of AlgorithmNodePacket

* refactor: extract JobQueue configuration

* remove: not used `using` in IDataDownloader

* feat: create BrokerageDataDownloader

* Revert "refactor: extract JobQueue configuration"

This reverts commit 5778936b71.

* Revert "feat: new constructor of AlgorithmNodePacket"

This reverts commit d7a565ff76.

* feat: new config `data-download-brokerage` in DataDownloadProvider

* refactor: initialize in BrokerageDataDownloader

* remove: not used `using` in Program's DataDownloadProvider

* remove: not used ref on QuantConnect.Queue proj

* refactor: use default market based on SecurityType

* refactor: MarketName in DataDownloadConfig struct
test:feat: validate MarketName

* feat: support Canonical Symbols in BrokerageDataDownloader

* remove: not used command arguments

* feat: init CacheProvider of IOptionChainProvider in Downloader

* feat: add brokerage message event in BrokerageDataDownloader
2024-07-31 19:02:13 -03:00
Jhonathan Abreu
9eb484625d Default option pricing models for options indicators (#8229)
* Set best recommended model based on option style.

The best option model will be used in options indicators based on option style if not specified

* Reduced Greeks/IV numerical models steps to 100

* Minor fixes

* Minor changes and improvements

* Changed default pricing model for IV

* Minor performance improvements

* Minor performance improvements and fixes

* Minor change

* Minor regression algorithm fix

* Update greek indicators internal IV indicator only when not user provided

* Revert unnecessary changes

* Minor changes

* Cleanup
2024-07-30 10:15:21 -04:00
FemtoTrader
85ca5be258 Implements new indicator - RSV - Rogers-Satchell volatility (#8183)
* implement Rogers-Satchell volatility

* naming RSVolat to avoid confusion between volume and volatility

* fix InitializeIndicator call

* fix AcceptsRenkoBarsAsInput test

* add symbol parameter to InitializeIndicator

* Update RogersSatchellVolatility.cs

* some fixes after review

* Return 0 when Open High Low or Close is 0

* IBaseDataBar
2024-07-29 14:47:16 -03:00
Martin-Molinero
9a84a6bd17 Minor test brokerage security provider improvement (#8231) 2024-07-29 13:41:37 -03:00
Martin-Molinero
a46acef9f8 Minor improvements (#8223)
- Liquidate takes into account invested flag
- Minor tweaks for symbol representation parsing
2024-07-23 12:18:26 -03:00
keshavdalmia10
69fa2fd689 Made changes in the ParseOptionTickerOSI function. Now it can handle … (#8219)
* Made changes in the ParseOptionTickerOSI function. Now it can handle both with and without space

* added new function GenerateOptionTickerOSICompact and added the test cases for it, expanded test cases for ParseOptionTickerOSI

* added assertions for strikePrice and date, corrected the indentation
2024-07-23 11:23:11 -03:00
Martin-Molinero
2df58bbca3 Accept live UniverseProvider returning null (#8222)
- Similar to HistoryProviders and Live DataQueueHandler calls, adjust
  live Universe provider manager to handle null returned values
2024-07-23 10:30:19 -03:00
Martin-Molinero
050030bca8 Minor improvement to Invested holdings flag (#8221) 2024-07-23 10:27:40 -03:00
FemtoTrader
7e40b4f1ab Implements new indicator - SOBV - Smoothed On Balance Volume (#8180)
* fix conflict

* fix all SmoothedOnBalanceVolumeTests tests except AcceptsRenkoBarsAsInput

* fix InitializeIndicator call

* fix AcceptsRenkoBarsAsInput test

* add symbol parameter to InitializeIndicator

* shorter
2024-07-22 18:27:52 -03:00
FemtoTrader
229d636628 implements generate_reference_data_from_talib.py (#8196) 2024-07-22 14:50:24 -03:00
FemtoTrader
034bf3d8ae add script using tulipy (#8194) 2024-07-22 14:43:33 -03:00
Martin-Molinero
31b32442c8 Fix Alpaca option order types (#8220) 2024-07-22 14:24:47 -03:00
Ricardo Andrés Marino Rojas
9a92933397 ARIMA indicator error handling (#8218)
* First draft of the solution

* Add comments

* Address requests

* Nit change

* Fix bug
2024-07-22 14:24:12 -03:00
Ricardo Andrés Marino Rojas
97959d560a Add liquidate method overloads (#8210)
* First draft of the solution

* First draft of the tests

* Nit changes

* Nit change

* Add improvements

* Improve unit tests

* Regression algos

* Nit change

* Nit changes

* Improve unit tests

* Improve unit test

* Nit change

* Address reviews
2024-07-22 12:48:53 -03:00
Martin-Molinero
0352a0b07c Fix Alpaca Order Fees (#8217)
- Fix alpaca order fees. Expanding unit tests
- Improve base brokerage test framework
2024-07-22 12:48:34 -03:00
FemtoTrader
bd87ba6f14 Implements new indicator CHOP - Choppiness Index (#8178)
* WIP

* Implement CHOP

* 0m instead of 0

* readonly

* doc - param

* fix InitializeIndicator call

* return 100 when max_high = min_low

* remove unused imports

* remove unused imports

* add symbol parameter to InitializeIndicator

* Update ChoppinessIndex.cs

* Update ChoppinessIndex.cs

* decimal

* fix testing IsReady

* move WarmUpPeriod
2024-07-22 12:14:53 -03:00
Martin-Molinero
ab601cbb08 Minor fix for cross order id (#8213) 2024-07-19 15:20:31 -03:00
FemtoTrader
72a1bd4c48 Implements new indicator StochRSI - Stochastic Relative Strength Index (#8163)
* tests passing except ResetProperly and WarmsUpProperly

* doc

* minor fixes

* doc - return

* fix InitializeIndicator call

* workaround ResetsProperly

* fix WarmsUpProperly test

* remove WriteLine

* remove WriteLine

* cr

* fix data

* open high low defaults to close when these columns don't exist into data

* simplify using ternary operator

* better fix for ResetsProperly

* fix some code conventions issues

* fix some review issues

* Update StochasticRelativeStrengthIndex.cs
2024-07-19 09:26:39 -03:00
Martin-Molinero
3bdde74096 Minor brokerage testing improvements (#8209) 2024-07-18 14:34:29 -03:00
Roman Yavnikov
ba626f18d2 Feature: Implementation Alpaca Brokerage (#8203)
* feat: Alpace models implementation

* Address reviews

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-07-16 12:26:26 -03:00
FemtoTrader
12f6263d8b Implements new indicator VWMA - Volume Weighted Moving Average (#8161)
* WIP

* private fields are camelCased

* private fields starts with underscore

* remove unused imports

* fix WarmsUpProperly test

* fix InitializeIndicator call

* IndicatorValueIsNotZeroAfterReceiveRenkoBars

* add constructor

* return close price if _sumV=0

* no Renko bars

* some fixes after review
2024-07-16 11:14:39 -03:00
FemtoTrader
14db9caf90 Implements new indicator ForceIndex (#8155)
* WIP

* All tests are passing except AcceptsRenkoBarsAsInput

* Update QuantConnect.Tests.csproj

* comment formating and use input.EndTime

* fix AcceptsRenkoBarsAsInput test

* fix InitializeIndicator call

* add symbol parameter to InitializeIndicator

* FI above FISH
2024-07-16 11:14:14 -03:00
Martin-Molinero
dda950b6e4 Test 2024-07-15 16:05:31 -03:00
Martin-Molinero
9b3400e9d1 Delete google9161359af9633398.html 2024-07-12 16:50:37 -03:00
Martin-Molinero
162d3cbca2 Add files via upload 2024-07-12 16:43:24 -03:00
Martin-Molinero
53c2a214a1 Improve indicator warmup (#8192)
* Improve indicator warmup

- Allow indicator warmup to handle multiple symbols, used for option
  greeks. Adding regression test
- Improve indicator history to handle specific T types. Adding unit test
- Remove period, and historical underlying volatility, from IV so
  simplify warmup behavior

* Address review, fix minor issues
2024-07-11 16:16:49 -03:00
FemtoTrader
8136a73801 Implements new indicator IBS - Internal Bar Strength (#8151)
* Implement new indicator IBS

* remove using System

* typo

* doc fix

* Implement new indicator IBS

* remove using System

* typo

* doc fix

* inherit TradeBarIndicator and return 1m when High=Low

* duplicate spy_with_ibs

* returns 0.5 when High=Low
2024-07-11 16:13:31 -03:00
Ricardo Andrés Marino Rojas
554a82527f Fix minor warnings (#8190)
* Fix CA1847 warnings and some CA1307 warnings

* Fix CA1823 and CS0169

* Fix CA1820 warnings

* Address requested changes
2024-07-10 14:17:27 -03:00
Ricardo Andrés Marino Rojas
8b312efd0c Fix CA1829 warning (#8188)
* Fix CA1829 warning

* Fix failing test
2024-07-10 14:08:28 -03:00
FemtoTrader
fcb33d8ba3 implements McGinleyDynamic (#8189) 2024-07-10 11:41:56 -03:00
Ricardo Andrés Marino Rojas
a7efcfe9d5 Fix CS1570 and CS1572 warnings (#8187)
* Fix CS1570 and CS1572 warnings

* Address requested changes
2024-07-10 11:16:16 -03:00
Ricardo Andrés Marino Rojas
5a7a162d34 Fix warnings CA1574 (#8186) 2024-07-09 17:52:07 -03:00
Martin-Molinero
268285e2b3 Minor fix for Mis-Aligned Timestamps from IndicatorHistory (#8185)
* Minor fix for Mis-Aligned Timestamps from IndicatorHistory

- Minor fir for mis-Aligned Timestamps from IndicatorHistory. Adjusting
  unit test to reproduce issue.

* Add another assert to indicator history tests
2024-07-09 17:09:12 -03:00
FemtoTrader
db1f63bae7 Add ZLEMA to MovingAverageTypeExtensions.cs and MovingAverageType.cs (#8177)
* add ZLEMA to Indicators/MovingAverageTypeExtensions.cs and Indicators/MovingAverageType.cs

* add new MA (ZLEMA) to test suite
2024-07-09 17:07:59 -03:00
Ricardo Andrés Marino Rojas
99a949586c Fix warnings part 12 (#8182)
* First part of the warnings

* Second half of the changes
2024-07-09 11:08:42 -03:00
Jhonathan Abreu
e0c90e8c04 Minor changes in option chain fetching algorithms (#8175) 2024-07-09 10:55:45 -03:00
Martin-Molinero
12644f8b2a Minor fixes for IndicatorHistory and IV (#8174)
* Minor fixes for IndicatorHistory and IV

- Minor fix for IndicatorHistory, use ScaledRaw data normalization mode
  for option indicators. Adding unit test
- Expand the IV expected upper range to 400%, given values can be higher
  than previous value of 200%
- Adjust IV to use smoothing function only when both option calculations
  succeed

* Updating regression algorithm expected greeks, minor change
2024-07-09 10:54:55 -03:00
FemtoTrader
28f9db194e fix naming (#8168) 2024-07-08 12:32:40 -03:00
Martin-Molinero
6c30157fab Remove universe selection on extended market dates (#8160)
- Remove universe selection on dates with extended market hours only
- Updating regression algorithms
- Expand date & time rules API to support specifying whether extended
  market hours only dates are desired or not
2024-07-08 11:58:50 -03:00
FemtoTrader
014ec7f626 Implement new indicator - ZLEMA - Zero Lag Exponential Moving Average (#8148)
* Implement new indicator ZLEMA

* Add script to generate reference data from talipp

* Some review fixes

* description

* use isReady

* use Delay(...)

* simplify ComputeNextValue

* Minor tweaks addressing review

* replace DateTime.UtcNow for specific date time instances

* remove unused imports

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-07-08 11:58:05 -03:00
Roman Yavnikov
2941210d20 fix: lock of place first part of cross zero order (#8157) 2024-07-05 16:52:31 -03:00
Louis Szeto
6185a4c6a4 Option Strategy Filters for Jelly Roll and Ladder (#8150)
* add option filter strategy

* unit test

* regression test
2024-07-05 16:31:38 -03:00
Ricardo Andrés Marino Rojas
16a737ee26 Fix most of CA1725 warnings (#8154)
* Fix CA1725 warning

* Address requested changes
2024-07-05 16:19:56 -03:00
Martin-Molinero
ee35c75e62 Minor indicator test suite improvements (#8153)
* Minor indicator test suite improvements

- Simplify and improve indicator test suite assertions
- Reduce indicator suite run time

* Fix DividendYieldProviderTests dependency
2024-07-05 15:10:12 -03:00
Ricardo Andrés Marino Rojas
0a0c012ae9 Fix second half of the CA1051 warnings (#8140)
* Fix second half of the CA1051 warnings

* Address requested changes
2024-07-05 13:54:03 -03:00
Ricardo Andrés Marino Rojas
574eafd00d Add missing endpoint in C# API Client (#8143)
* Add C# API ReadBacktestInsights()

* Address reviews

* Address requested changes
2024-07-05 13:53:27 -03:00
Martin-Molinero
eff8b6f2fb Improve indicator history data update (#8141)
- Do not lose data symbol on indicator update during IndicatorHistory
  call. Adding unit test reproducing issue
2024-07-03 17:59:41 -03:00
Ricardo Andrés Marino Rojas
5fd021996a Fix half of the CA1051 warnings (#8137)
* Fix half of the CA1051 warnings

This warning is about not declaring visible instance fields. There are
something about 500 warnings in the solution, mostly in the QuantConnect and QuantConnect.Algorithm.CSharp projects. I aim to fix one of them in this PR and the other half of them in a second one. To fix it, I'm changing the visible instancce fields for properties.

* fix bugs

* Addressing minor reviews

* More minor fixes

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-07-03 15:43:17 -03:00
Martin-Molinero
ee1a6ef87b Add missing terminal link brokerage name (#8135) 2024-07-02 14:11:21 -03:00
Martin-Molinero
3d17e0e122 Minor thread safety interest rate provider fix (#8119)
- Fix race condition in interest rate provider, we were updating the
  private static variable instance before it was ready, causing
  explosions
2024-07-02 13:19:04 -03:00
Martin-Molinero
9229ddbef0 Fix micro gold expirations (#8117)
- Minor fix for micro gold expected expirations. Updating unit tests
2024-07-01 14:12:20 -03:00
Louis Szeto
409f93a3aa Option Strategy Filter Universe (#8088)
* add 1-2 contracts universes

* Add unit tests for 1-2 contract strategies

* refactor

* Call/Put Butterfly

* Iron Butterfly/Condor & Box Spread

* Refactor and bug fixes

* Add regression algorithms

* use AllSymbols

* refactor on peer review, update unit tests

* update regression tests

* update assertion

* update

* remaining assertion

* order hash update

* use helper method on assertion

* fix bug

* Address reviews. Some cleanup and refactor

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-07-01 13:58:30 -03:00
Martin-Molinero
25c635d846 Add indicator helper methods for base Algorithm (#8076)
* Add indicator helper methods for base Algorithm

- Add indicator helper methods for base algorithm. Adding new unit tests

* Expand indicators helper methods

- Expand indicators helper methods, adding support for C# and custom
  indicators too. Adding unit tests
- Expand indicators helper methods to support multiple symbols as input.
  Adding unit tests
- Improve conversion of symbol enumerable from python to C# adding unit
  tests

* Address reviews

- Keep old QB.Indicator methods for backwards compatibility
- Rename new API to IndicatorHistory, matching
  FutureHistory/OptionHistory
- Add new regression algorithms
- Minor improvement to DynamicData so it supports snake name access
2024-07-01 13:27:47 -03:00
Roman Yavnikov
1911cda7b1 Refactor: Handle OrderStatus with Cross Zero Order Collection (#8114)
* empty

* refactor: orderType for SecondCrossZeroOrder

* refactor: handle some specfic orderStatus in CrossZeroOrder process

* refactor: Handle specific OrderStatus in SecondPartCrossZeroOrder

* refactor: handle order status
revert: convertOrderType of CrossZeroSecondPart

* fix: use right collection when removing cross zero order class
2024-06-28 12:05:19 -03:00
Ricardo Andrés Marino Rojas
a2b420cb0a Fix warnings part 8 (#8113)
* Fix CA1819 and CA1002 warnings

Changed the type of Languages statistic in regression tests from
Language[] to List<Language>. By doing that, the warning CA1819 was
removed but then the warning CA1002 was raised. However, this warning
was expected to be excluded from QuantConnect.Algorithm.CSharp.

* Improve implementation

* Simplify code

* Fix bugs
2024-06-28 10:10:30 -03:00
Louis Szeto
cd1aad657d OptionStrategies for Iron Butterfly (#8072)
* Define Iron Butterfly and its buying power model

* Add unit tests

* Add regression test

* Address peer review

* Add short iron butterfly and short iron condor

* Add unit tests on short strategies

* add regression algorithms

* Invert direction of iron butterfly
2024-06-28 10:07:39 -03:00
Louis Szeto
aae6d617fb Option Strategy: Jelly Roll & Ladder (#8092)
* Define Jelly Roll

* Margin Model

* Add universe filter

* unit tests

* add regression tests

* add definitions

* universe filter

* margin model

* unit tests

* bug fix

* unit tests

* regression tests

* typo

* peer review

* peer review 2

* bug fix, address peer review

* minor fix

* Fixes `middleStrike` Parameter Description

The "middle strike" instead of "with higher/lower" to match the parameter description with name.

---------

Co-authored-by: Alexandre Catarino <AlexCatarino@users.noreply.github.com>
2024-06-27 15:58:06 -03:00
Ricardo Andrés Marino Rojas
621d1252b9 Fix label bug in QCAlgorihtm.Python.History() when requesting data for BaseCollection Datasets (#8093)
* First draft of the solution

* Fix bugs

* Fix bugs

* Fix another overloaded method

* Add new unit test

* Address requested changes

* Address requested changes

* Minor tweaks

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-06-27 15:57:25 -03:00
Jhonathan Abreu
6392b5eed0 Minor changes in BaseSetupHandler. (#8112)
Making it able to update currency conversions for specific currencies.
2024-06-26 18:06:26 -03:00
Ricardo Andrés Marino Rojas
ba2d519910 Remove warnings from csproj files (#8108)
* Remove warnings from csproj files

* Leave just 2 warnings

* Nit change

* Leave just 2 warnings
2024-06-26 17:07:51 -03:00
Martin-Molinero
c8446ae26e Refactor AutomaticIndicatorWarmUp settings (#8111)
- Move EnableAutomaticIndicatorWarmUp as an algorithm setting named AutomaticIndicatorWarmUp
2024-06-26 17:02:48 -03:00
Roman Yavnikov
8a34d4a7a3 Refactor: Cross Zero Order event (#8110)
* refactor: reuse OrderEvent
test:refactor: CrossZeroOrder proccess Status update

* clean: extra paddings
2024-06-26 15:06:04 -03:00
Ricardo Andrés Marino Rojas
57f89620a1 Fix warnings part 6 (#8107)
* Fix half of the XML docs missing warnings

* Remove warnings from csproj files
2024-06-26 13:21:53 -03:00
Martin Molinero
47acbd66a2 Revert test breaking change 2024-06-26 10:18:35 -03:00
Ricardo Andrés Marino Rojas
56d36b97d5 Fix warnings part 5 (#8105)
* Add algorithm unit tests

* Add Brokerage unit tests

* Add Common unit tests

* Fix unit test bugs

* Add remaining unit tests

* Address requested changes

* Address requested changes

* Fix failing unit test

* Address requested changes
2024-06-26 10:11:36 -03:00
Roman Yavnikov
a8b106ae3e Feat: Brokerage Cross Position Order (#8051)
* feat: TryCrossPositionOrder
feat: helper methods to CrossPosition

* refactor: get rid CrossOrder +UTests

* feat: test simulator of cross zero orders request

* remove: callback from TryCrossPositionOrder
rename: TryCrossPositionOrder -> TryCrossZeroPositionOrder
feat: handle event of CrossZeroOrder
feat: new prop in CrossZeroOrderRequest
test:feat: write working test imitate of CrossZeroOrdering and assert different params

* feat: temp collection to keep CrossZeroOrder with Lean

* refactor: flag which indicate should we place crossZero order with LeanEvent or not

* refactor: change access modifier

* fix: CrossZero tests

* refactor: property collection instead of variable

* feat: lock context of CrossZeroOrder
feat: helper method for CrossZeroCollection

* refactor: test of cross brokerage ordering

* refactor: CrossZero Brokerage

* fix: lock area

* feat: Update CrossZero Ordering
refactor: CrossZeroOrders tests

* feat: additional test case for CrossZeroOrdering

* feat: Invalid OrderStatus when FirstPart of CrossZero ordering try to place
feat: message property in CrossZeroOrderResponse
refactor: CrossBrokerageTest a little bit

* feat: PossibleUpdateCrossZeroOrder

* refactor: UpdateCrossZeroOrder

* refactor: TimeOut for resetEvent

* refactor: crossZeroOrder change DateTime UtcNow on specific time
refactor: change action scenario for Filled FirstPart of CrossZeroOrder

* refactor: change firstPartQuantityproperty to link of FirstPartOfCrossZero order completely
fix: crossZeroOrder test put orderStatus internally

* feat: additional orderType in CrossZeroOrder tests

* test:remove: not use GetOrderCrossesZero()

* refactor: extra paddings

* rename: TryGetUpdateCrossZeroOrderQuantity instead of IsPossibleUpdateCrossZeroOrder

* refactor: CrossZeroOrder process and models

* remove: interface ICrossZeroOrderRequest

* feat: TradeStation NotSupportUpdate of CrossZeroOrder quantity

* feat: add license
remove: extra validation of variable

* refactor: add validation of quantity update in TradeStationBrokerageModel

* test:feat: canUpdate of TradeStationOrder

* refactor: reuse OrderEvent when we handle FirstPartCrossZeroOrder

* remove: assignment of filled quantity of FirstPartCrossZeroOrder
2024-06-26 10:06:25 -03:00
Jhonathan Abreu
8bd046a6b8 Add support for FTP notifications (#8097)
* Add support for FTP notifications

* Add optional parameters for SFTP notifications with private key

* Add optional "secure" parameter for FTP notifications.

Improve FTP notifications constructor and input checks.

* FTP notification improvements.

Add public key property.
Add multiple constructors and methods for FTP and SFTP notifications with either password or SSH keys.
Encode file contents.

* Address peer review

Add support for FTP notification with string contents

* Minor changes

* Minor changes

* Remove public key argument

* Fixes and minor changes
2024-06-26 10:03:35 -03:00
Alexandre Catarino
9e2b697792 Fixes AwesomeOscillator Helper Order Of Parameters (#8099)
The second and third parameter are `fastPeriod` and `slowPeriod`, but we had `slowPeriod` and `fastPeriod`, which is inconsistent with the class contructor and other indicators with `fastPeriod` and `slowPeriod` parameters.
2024-06-25 17:33:19 -03:00
Ricardo Andrés Marino Rojas
5699fa48fd Fix 4/4 of CA2201 warnings (#8103)
* Fix 4/4 of CA2201

* Remove warnings
2024-06-25 11:13:32 -03:00
Ricardo Andrés Marino Rojas
aa5ab68b47 Fix 3/4 of CA2201 warnings (#8102)
* Fix 2/4 of CA2201 Warnings

* Fix 3/4 of CA2201 warnings
2024-06-24 19:31:23 -03:00
Ricardo Andrés Marino Rojas
f8b169aa51 Fix 2/4 of CA2201 Warnings (#8101) 2024-06-24 17:00:38 -03:00
Ricardo Andrés Marino Rojas
b41df5b0f2 1/4 of the changes of RegressionTestException (#8100) 2024-06-24 15:23:33 -03:00
Jhonathan Abreu
5432c7c6d8 Fix dynamic SPDB unit tests taking too long (#8094)
* Fix dynamic SPDB unit tests taking too long

* Minor improvements in unit tests

* Minor improvements in unit tests

* Cleanup
2024-06-24 14:36:04 -03:00
Ricardo Andrés Marino Rojas
8c33536498 Add algorithm status statistic (#8095)
* First draft of the solution

* Fix bugs

* Fix bugs
2024-06-24 14:19:32 -03:00
Jhonathan Abreu
f0d02feb13 Rename AlgorithmSettings.DailyStrictEndTimeEnabled (#8098)
* Rename AlgorithmSettings.DailyStrictEndTimeEnabled  to DailyPreciseEndTime

* Minor fix
2024-06-24 14:10:11 -03:00
Ricardo Andrés Marino Rojas
0e0e6bd142 Add Tests for MaximumDrawdownPercentPortfolio (#8096)
* First draft of the solution

* Add more unit tests
2024-06-24 13:14:21 -03:00
Jhonathan Abreu
8424e85ade Reduce test files size (#8084) 2024-06-24 13:03:43 -03:00
Jhonathan Abreu
a159950117 Fix: refresh symbol properties using right type for security. (#8087)
Fix for live trading SPDB refresh
2024-06-11 13:50:33 -04:00
Ricardo Andrés Marino Rojas
4ca5cbca7e Add Yearly Date Rule (#8075)
* First draft of the solution

* Add improvements

* Nit changes

* Address requested changes
2024-06-07 15:48:53 -03:00
Jhonathan Abreu
6b963c735c Make SPDB dynamic with periodic updates (#8083)
* Dynamic spdb

* Minor changes and unit test

* Get MHDB and SPDB refresh period from config

* Add databases refresh period to algorithm settings

* Address peer review and add unit test
2024-06-07 15:48:27 -03:00
Ricardo Andrés Marino Rojas
62373ede5b Duplicate Futures.Energies (#8082)
* Duplicate Futures.Energies

* Nit change

* Add unit test
2024-06-06 19:39:05 -03:00
Martin-Molinero
7975a44d1c Revert "Duplicate "Energies" Futures Ticker Shortcut to Energy (#8067)" (#8081)
This reverts commit 23057f24c8.
2024-06-06 15:02:03 -03:00
Ricardo Andrés Marino Rojas
2823155311 Partial fix for bug (#8079) 2024-06-06 13:06:39 -03:00
Martin-Molinero
5f58254839 Minor improvement for python custom default brokerage message handlers (#8078) 2024-06-05 13:22:34 -03:00
Martin-Molinero
e78150aced Fix for custom streaming data live trading (#8077)
- Minor fix for custom streaming data in live trading. Adding unit test
  reproducing issue
2024-06-05 11:51:43 -03:00
Martin-Molinero
9ace77fb87 Fix consolidator scan determinism (#8074)
- Make sure we can scan consolidators deterministically. Adding
  regression algorithm reproduce reported issue
2024-06-04 11:59:09 -03:00
Martin-Molinero
1a3fedb36d Foundation library update (#8069)
* Foundation update

* Minor fixes
2024-06-04 11:57:04 -03:00
Ricardo Andrés Marino Rojas
23057f24c8 Duplicate "Energies" Futures Ticker Shortcut to Energy (#8067)
* First draft of the solution

* Add backwards compatibility

* Address requested changes
2024-06-04 11:52:58 -03:00
Martin-Molinero
529b24ed1b Live Collection unfolding data will skip old data (#8070)
- Minor tweak for live collection unfolding data will skip old data.
  Adding unit test
2024-06-04 11:52:33 -03:00
Louis Szeto
39bfbccd44 Add Protective Collar to Option Strategies (#8025)
* Add Protective Collar Option Strategy

* Add buying power model for Protective Collar

* Add unit test for Protective Collar

* Add regression test for Protective Collar

* Add unit test on position group buying power

* allow same strike for later abstraction

* minor bug fix

* Set up conversion option strategy

* add margin requirement

* add unit tests

* Add regression test

* add reverse conversion definition

* add reverse conversion and refactor conversion/collar margin model

* added/modified unit tests for conversion/reverse conversion

* minor bug fix on unit test, add regression test

* Address peer review

* update new set of IB testing data
2024-06-03 12:38:52 -03:00
Martin-Molinero
ab24ac4ac8 By default reject brokerage side created orders (#8066) 2024-05-31 14:36:17 -03:00
Martin-Molinero
250ba842ba Minor tweak for split (#8068) 2024-05-31 14:35:50 -03:00
Louis Szeto
79a8c66b39 Box Spread Option Strategy (#8041)
* Add box spread definition

* Add box spread margin model

* Add unit tests

* Add regression tests

* minor nit peer review
2024-05-30 11:41:20 -03:00
Ricardo Andrés Marino Rojas
d76c2bfc7d Add FuncTimeRule and FuncDateRule constructors for PyObject (#8061)
* Initial draft of the solution

* Add more unit tests
2024-05-28 17:35:02 -03:00
Martin-Molinero
158df4434c Update readme.md 2024-05-28 15:57:25 -03:00
Martin-Molinero
88d7380a53 Use SPY as default dividend yield for Index/Future greeks (#8056)
- Index and FOPs will use SPY as the default dividend providers, adding regression algorithms for them
2024-05-28 15:48:21 -03:00
Ricardo Andrés Marino Rojas
0f785372f6 Add unit test (#8060) 2024-05-28 15:39:35 -03:00
Martin-Molinero
0acfdbb9e5 Update readme.md 2024-05-28 10:10:15 -03:00
Jhonathan Abreu
40cfcfc336 Fix: Insight constructors not setting correct values (#8058) 2024-05-24 19:02:59 -03:00
Martin-Molinero
9c1824cccf Enhance GetFilePath subdirectory handling (#8057)
- GetFilePath will create subdirectories assuming the last piece of the
  requested path is a leaf. Expanding unit tests
2024-05-24 18:27:57 -03:00
Jhonathan Abreu
f0286c936d Fix: allow non-standard header values in Api.Download API (#8055) 2024-05-24 18:07:23 -03:00
Martin-Molinero
c87693d883 Update readme.md 2024-05-24 15:44:37 -03:00
Jhonathan Abreu
b6e35468db Update pythonnet to 2.0.38 (#8052) 2024-05-24 14:38:53 -04:00
Martin-Molinero
bb675bdddb Improve DQH handling of exceptions (#8054)
- Improve DataQueueHandlerManager handling of exceptions in the used
  data queue handlers. Adding unit tests
2024-05-24 15:29:14 -03:00
Martin-Molinero
d3b5bbaa1b Avoid duplicate data on FF resolution change (#8053) 2024-05-24 11:58:27 -03:00
Martin-Molinero
3a99e0b47c Fix fill forward resolution adjustment on removal (#8049)
* Fix fill forward resolution adjustment on removal

- Fix fill forward resolution adjustment on subscription removal. Adding
  regression algorithm reproducing issue

* Minor fix for undeterminism behavior on security removals and FF res change

* Further improvements and determinism

- Improve regression algorithm add, remove and readd future, asserting
  FF resolution changes
- Adjust universe selection to be deterministic and avoid unnecessary
  FF resolution changes
2024-05-24 10:15:26 -03:00
Martin-Molinero
5f3cd203d3 Fix for live FF enumerator (#8047)
- Adjust live FF enumerator to rely on the base FF enumerator logic and
  just filter out results based on the frontier. Adding unit tests
2024-05-22 13:39:52 -03:00
Martin-Molinero
2c6074bfdb Limit 'forward only indicator' error log (#8046) 2024-05-21 19:15:53 -03:00
Ricardo Andrés Marino Rojas
ad663ded2c Fix bug in FrontMonth() option filter (#8044)
* First draft of the solution

* Nit changes

* Fix bugs

* Nit changes

* More nit changes
2024-05-20 20:04:31 -03:00
Roman Yavnikov
fe2110de96 Feature: Implementation Trade Station Brokerage (#8031)
* refactor: make public futuresMonth Collection

* feat: TradeStation brokerage

* feat: PositionSide for Option in TradeStationOrderProperties

* feat: missed market TradeStation name

* feat: missed config TradeStation

* remove: extra TradeStation code

* remove: pragrma warning

* feat: implement TradeStationFeeModel
2024-05-20 17:58:44 -03:00
Martin-Molinero
549979f84b Update readme.md 2024-05-20 17:32:58 -03:00
Martin-Molinero
d4e7f584f6 Daily data time adjustment (#8001)
* Daily data Time & EndTime Improvement

- Adjust daily data Time & EndTime to actually reflect the time of the
  data used, for example US Equity from 9.30 to 4PM. Adding new unit and
  regression tests

* Refactor solution to use enumerator

- Refactor daily strict end times solution to be through enumerator
  usage, so it applies for history providers too

* Minor fixes

* Revert fill forward enumerator change

- Revert FillForward enumerator causing stats changing, enhancing unit
  tests

* Some cleanup

* Improve handling of live trading FF enumerator

- Improve handling of live trading FF enumerator, by adding support for
  bars to arrive with a delay so we can handle auction close/option
  prices or data providers which might have some delay making the data
  available. Adding new unit tests asserting the behavior
2024-05-20 17:28:03 -03:00
Ricardo Andrés Marino Rojas
c30ea9d293 Handle order types with unsupported security types in IB Brokerage Model (#8029)
* HandleUnsupportedOrderTypesForSecuritiesInIB

* Nit changes

* Nit changes
2024-05-15 22:56:05 +01:00
Jhonathan Abreu
56cfc51f10 Round combo order prices (#8024)
* Round combo order prices

* Combo limit order round fix: use smallest security min price variation

* Minor unit test change

* Improvements and unit tests

* Minor change

* Cleanup
2024-05-15 14:57:30 -04:00
Ricardo Andrés Marino Rojas
cc3c97a814 Improve exception message when generating Annual Performance Statistic (#8022)
* Improve exception message

* Nit changes
2024-05-15 11:45:12 -03:00
Jhonathan Abreu
c82573a2bc Update Pythonnet version (#8021)
* Update regression algorithm to reproduce GH issue #8011

* Update pythonnet version to 2.0.37
2024-05-15 09:11:52 -04:00
Ricardo Andrés Marino Rojas
b147c7ccfd Api Clean up, Documentation and Standarization part five (#8016)
* Update endpoints and add tests

* Remove JsonProperty tags

* Enhance unit tests

* Add live/insights/read/response

* Add missing class

* Remove old insights property

* Improve read live insights unit test

* Nit change

* Fix failing unit tests

* Revert "Fix failing unit tests"

This reverts commit a2b7c1d34e.

* Add Insights.Ticker back

* Nit change

* Address requested changes
2024-05-13 18:14:40 -03:00
Alexandre Catarino
ddea4ec380 Fix Summary for CancelPending (#8020) 2024-05-13 18:09:55 -03:00
Martin-Molinero
1c32144963 Some refactor and cleanup (#8014)
* Some refactor and cleanup

- Some refactor and cleanups
- Improve live trading CI tests speed

* Minor tweak for live trading data feed log
2024-05-10 12:27:00 -03:00
Martin-Molinero
061d5a9971 Update SPX MHDB to match Options (#8013)
- Update the SPX index MHDB entry to match the spx index options, for
  daily resolution selection support
2024-05-10 11:46:29 -03:00
Jhonathan Abreu
7e7fd4d791 Skip security initializer for benchmark security (#8012) 2024-05-09 18:09:34 -04:00
Jhonathan Abreu
b079d32522 Bug python type comparison (#8008)
* Reapply "Python consolidator removal directly from Python (#7995)" (#8006)

This reverts commit f5f2da3f96.

* Reapply "Fix: interface property implementation in python models (#7987)" (#8007)

This reverts commit 356b51f150.

* Fix: PyObject.TryConvert compares c# and py type by reference
2024-05-09 13:20:44 -04:00
Jhonathan Abreu
28baf03250 Improve PythonException stack trace parser (#8002)
* Improve PythonException stack trace parser

* Minor fix

* Minor improvements
2024-05-09 13:20:20 -04:00
Martin-Molinero
356b51f150 Revert "Fix: interface property implementation in python models (#7987)" (#8007)
This reverts commit ab40b5c0b6.
2024-05-09 10:06:07 -03:00
Martin-Molinero
f5f2da3f96 Revert "Python consolidator removal directly from Python (#7995)" (#8006)
This reverts commit bac3ec09b6.
2024-05-09 10:05:37 -03:00
Martin-Molinero
53fb9942d2 Minor optimization parameter json fix (#8005) 2024-05-08 20:05:47 -03:00
Martin-Molinero
e96e2d26a7 Update readme.md 2024-05-08 19:03:59 -03:00
Martin-Molinero
c13643f3ac Minor camelcase tweaks (#8004) 2024-05-08 18:08:57 -03:00
Martin-Molinero
6915a65900 Further camel case cleanup (#8003) 2024-05-08 17:28:47 -03:00
Martin-Molinero
d40ec77379 Refactor to use camel case (#7981)
* Camel case results

- Camel case lean results and streamed packets

* Update packets to camel case
2024-05-08 12:58:33 -03:00
Louis Szeto
bb7a7f26a7 Bug fix on Option Indicator calculation (#7999)
* Handle expired options

* unit test

* Move Zero Checks to Single Location

---------

Co-authored-by: Alexandre Catarino <AlexCatarino@users.noreply.github.com>
2024-05-07 14:03:29 -03:00
Jhonathan Abreu
520e6046ac Update vsdbg version to be supported in the base ubuntu (#8000) 2024-05-07 09:31:51 -04:00
Ricardo Andrés Marino Rojas
a1b6277492 Api Clean up, Documentation and Standarization part four (#7989)
* Update C# response classes for optimization endpoints

* fix bugs

* Fix bugs

* Fix bug

* More tests, API response classes and updates

* Partially revert wrong changes

* Missing file

* Improve unit tests and solve bugs

* Improve implementation

* Minor tweak

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-05-06 20:33:31 -03:00
Jhonathan Abreu
bac3ec09b6 Python consolidator removal directly from Python (#7995)
* Fix: python consolidator reference lost when wrapped

* Make BasePythonWrapper equatable depending on the PyObject underlying reference

* Fix: TryConvert PyObject instances for generic C# types

* Minor unit tests fixes

* Address peer review and add unit tests
2024-05-06 14:44:04 -04:00
Derek Melchin
d6ff16f9da Add new crisis events (#7991)
* Add new crisis events

* Add new enum values
2024-05-06 14:44:07 -03:00
Roman Yavnikov
9fad556903 Remove: log ETA calculation (#7994)
* remove: ETA in data download provider

* remove: log of ETA calculation

* remove: test with ETA downloader
2024-05-03 14:25:10 -03:00
Jhonathan Abreu
021e507ef0 Holdings price adjustment after split (#7985)
* Fix: properly adjust prices after a split

* Minor fixes

* Minor: Adjust cached data on split

* Minor change

* Expand regression algorithms assertions
2024-05-01 17:42:43 -04:00
Jhonathan Abreu
ab40b5c0b6 Fix: interface property implementation in python models (#7987) 2024-05-01 13:58:02 -03:00
Roman Yavnikov
ef23d7b6fe Add Group Symbol and Total Time Execution Logging for Downloading Canonical Data (#7984)
* refactor: modifier static to parse enum and ignore warning

* feat: group symbol when download cannonicial data
feat: log total time execution of download provider
test: right keeping of cannonicial data

* feat: parameter ctor in DataDownloadConfig

* test:feat: additional assertion of wrote data in file

* feat: static FilterGroupDownloadDataBySymbol

* refactor: extract downloader folder path

* try: map file false

* feat: get rid of dataCacheProvider in DownloaderDataProvider

* refactor: get rid mapFile flag

* CI test fix

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-05-01 13:39:34 -03:00
Ricardo Andrés Marino Rojas
17ba9f8b5d Api Clean up, Documentation and Standarization part three (#7982)
* Updates to data/prices C# response

* Update data, account and organization API responses

* remove unnecessary changes
2024-04-29 20:35:51 -03:00
Martin-Molinero
b527a3dd86 Minor fixes (#7980)
- Minor test improvement
- Adjust DownloaderDataProvider to follow the pattern
2024-04-26 14:37:47 -03:00
Ricardo Andrés Marino Rojas
cce8945fe8 Api Clean up, Documentation and Standarization part two (#7964)
* Add improvements

* Add improvments and unit tests

* Add XML comments

* Nit changes

* Add unit tests for OrderJsonConverter

* Improve unit tests

* Address requested changes

* Fix bugs

* Fix bugs

* Fix bugs and self-review

* Fix bugs

* Address requested changes

* Fix unit test bug

* Fix bugs

* Improve unit tests

* Solve bugs
2024-04-26 13:17:34 -03:00
Jhonathan Abreu
9755f8c916 Sourcing remote zipped custom data (#7976)
* Fix: source custom data from remote CSV zipped file

* Fix: Custom data sourcing zip entry names from remote locations

* Address peer review

* Add unit tests

* Minor fix

* Address peer review

* Minor fixes

* Return byte array in IApi.DownloadBytes

* Allow sourcing custom data from specific csv entry in a zipped remote file

* Minor change
2024-04-26 12:15:01 -04:00
Martin-Molinero
2ac435b117 Minor Config.Write Improvement (#7978) 2024-04-25 19:54:11 -03:00
Roman Yavnikov
74d95f1611 Implement Download Project in Lean (#7975)
* feat: init Download proj

* feat: update docker file to copy download proj

* feat: parsing in cmd arguments

* feat: DataDownloadConfig model
feat: add config file
refactor: logic of parsing config

* feat: overrid ToString in DataDownloaderGetParameters

* remove: not used argument command

* feat: calculate downloading % (without ETA time)

* fix: dockfile copy path for DownloaderDataProvider proj

* feat: additional Property in .csproj

* remove: DataProviderFullName prop from DataDownloadConfig

* remove: extra package (ref from Configuration proj)

* feat: ETA calculation of downloading data

* Minor tweak

* rename: namespace of downloaderDataProvider to generic style format

* test: ETA from DownloaderDataProvider

* fix: calculate ETA like real downloading process

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-04-25 19:53:58 -03:00
Jhonathan Abreu
55b056588d Fix option assignment not processed because of existing open order (#7974)
* Fix: option assignment not processed because of existing open order

* Minor change

* Fix unit test
2024-04-24 10:42:41 -04:00
Martin-Molinero
6d9609799a Calling CSharp releases the GIL (#7970)
- Make sure calling CSharp methods, fields, properties releases the GIL,
  this was not hapenning for fiels & properties, adding unit test
  reproducing the issue
2024-04-23 12:46:50 -03:00
Martin-Molinero
8d2ced945b Minor fundamental properties typos (#7971) 2024-04-23 11:48:20 -03:00
Jhonathan Abreu
b8e49a94ad Python models conversion to PEP8 (#7969)
* Python models conversion to PEP8

* Python models conversion to PEP8

* Minor fix
2024-04-23 10:45:36 -04:00
Martin-Molinero
efd90f7ed9 Fundamental pep8 typos ValuationRatios (#7967) 2024-04-22 16:49:07 -03:00
Martin-Molinero
bec6faef9a CashFlowFromInvestingGrowth & CashFlowFromFinancingGrowth Typos (#7966) 2024-04-22 14:18:22 -03:00
Jhonathan Abreu
6bfe45dbcf PEP8 algorithms conversion (#7962)
* PEP8 algorithms conversion

* PEP8 unit tests algorithms conversion

* Minor fixes
2024-04-22 13:59:50 -03:00
Martin-Molinero
8fa824b19e Rename DebttoAssets to DebtToAssets (#7961) 2024-04-22 12:14:44 -03:00
Martin-Molinero
3e4ad661e2 Update readme.md 2024-04-19 19:41:29 -03:00
Louis Szeto
fa886eba79 pep8 conversion of python algos #12 (#7954)
* pep8 conversion

* PEP8 updates/fixes

* Update pythonnet version to 2.0.35

---------

Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
2024-04-19 16:55:48 -04:00
Ashutosh
b64ad5f68a pep8 conversion of python algos (#7957) 2024-04-19 17:24:37 -03:00
Louis Szeto
08a3de9e2d pep8 conversion of python algos #13 (#7955)
* t status
pep8 conversion

* Minor tweaks and rebase

* Various minor fixes

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-04-19 16:14:12 -03:00
Louis Szeto
d2669fb0c2 pep8 conversion of python alphas and benchmark algos (#7956)
* pep8 conversion of alphas

* pep8 conversion of benchmarks

* Various fixes and rebase

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-04-19 14:50:59 -03:00
Louis Szeto
279a7ef235 pep8 conversion on python algos #10 (#7951)
* pep8 conversion

* PEP8 updates/fixes

---------

Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
2024-04-19 12:59:02 -03:00
Louis Szeto
979bd9baef pep8 conversion of python algos #11 (#7952)
* pep8 conversion

* Minor tweak

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-04-19 12:54:50 -03:00
Ashutosh
3c30e255fe pep8 conversion of python algos (#7948)
* pep8 conversion of python algos

* adding 10 more pep8 converted algos

* PEP8 updates/fixes

---------

Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
2024-04-19 10:06:48 -04:00
Jhonathan Abreu
77591f90c7 PEP8 python algorithms conversion (#7950)
* PEP8 python algorithms conversion

* Fix: Get python or c# methods in PythonData as python wrapper

* Convert portfolio models to PEP8
2024-04-18 19:43:48 -03:00
Alexandre Catarino
d1796bd77e Copies RiskParityPortfolioOptimizer to Output Directory (#7949) 2024-04-18 19:19:19 -03:00
Louis Szeto
4a1f30bd96 pep8 conversion of python #7 (#7945)
* pep8 conversion

* PEP8 updates/fixes

---------

Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
2024-04-18 16:12:36 -03:00
Louis Szeto
7e5b8d6243 pep8 conversion of python algo #8 (#7946)
* pep8 conversion

* Minor tweaks

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-04-18 16:08:34 -03:00
Louis Szeto
e8362c12a3 pep8 conversion (#7947) 2024-04-18 16:04:22 -03:00
Louis Szeto
c2ad893f32 pep8 conversion of python algos #5 (#7943)
* pep8 conversion

* Fix: detect python object of python classes derived from c# classes

* Minor PEP8 updates/fixes

---------

Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
2024-04-18 15:53:32 -03:00
Louis Szeto
5eb236834f pep8 conversions of python algos, #6 (#7944)
* pep8 conversions

* Address review. Fix PythonIndicator

* Minor CSharp algo fix

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-04-18 15:15:18 -03:00
Ashutosh
1cae47ab25 pep8 conversion of python algos (#7942)
* pep8 conversion of python algos

* adding 10 more pep8 converted algos
2024-04-18 15:14:56 -03:00
Louis Szeto
ed351c8726 pep8 conversion of python algorithms #3 (#7934)
* raw pep8 conversion

* Minor fixes

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-04-17 19:28:04 -03:00
Louis Szeto
6d5f5dce58 pep8 conversion of python algorithms #4 (#7935)
* pep8 conversion

* PEP8 updates/fixes

* Minor update

---------

Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
2024-04-17 19:27:00 -03:00
Ashutosh
c97c7a3317 pep8 conversion of python algos (#7938)
* pep8 conversion of python algos

* Minor tweak

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-04-17 19:23:54 -03:00
Louis Szeto
ed7f3ebbbf pep8 conversion of python algos #1-25 (#7926)
* pep8 conversion of python algos

* address peer-review

* PEP8 updates/fixes

* More fixes

---------

Co-authored-by: Jhonathan Abreu <jdabreu25@gmail.com>
2024-04-17 17:02:32 -04:00
Louis Szeto
784e497691 pep8 conversion on python algorithms #2 (#7933)
* pep8 conversion

* more

* Minor fix

* Fix related regression algorithm

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-04-17 17:36:53 -03:00
Kristiyan Michaylov
c2bea3c173 Feature 1076 implementing an indicator derivative oscillator (#7884)
* Initial boilerplate code

* Fix build failure

* Initial iteration for the code for Derivative Oscillator code

* Add foundation for unit tests

* Add reset method for test

* Add test case

* fixed test cases, all tests pass

* Put placeholder for IsReady change

Not implemented, as test cases fail when change is uncommented

* Update documentation and change class name

* Change names for Derivative Oscillator to more meaningful

* Add DO extension to create the indicator

* Provide variable definitions with var, replace old test file with new

* Use chaining for indicators creation

* Add test based on external data

* Change test file

* Fix WarmUp test + alphabetical order + rename indicator class

* Make all tests run except for external data tests

* Fixed warmup period and fixed the ResetsProperly test case

* Removed unused directives

* Add output directory for Derivative Oscillator test

* Minor tweaks

---------

Co-authored-by: HaentjeGH <l.m.j.haenen@student.tue.nl>
Co-authored-by: ivkozlov <ivkozlov@ozon.ru>
Co-authored-by: DanielVanRijswijk <d.j.v.Rijswijk@student.tue.nl>
Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-04-17 16:34:57 -03:00
Martin-Molinero
b1a2f8f06c Bybit SPDB update (#7940)
- Bybit SPDB update
2024-04-17 16:06:31 -03:00
oussamanahdi
a83809c122 Update readme.md (#7939)
Fixed logo link
2024-04-17 15:21:05 -03:00
Jhonathan Abreu
17ba1088bd Pythonnet PEP8 fixes (#7931)
* Improve python exception message for cases when derived class uses member names already defined in base C# classes

* Update pythonnet version to 2.0.33

* Update error message

* Pythonnet version bump to 2.0.34. Minor unit test fix

* Enhance pythonnet overload tests

---------

Co-authored-by: Jared <jaredbroad@gmail.com>
Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-04-17 14:25:25 -03:00
oussamanahdi
3da1afb2fe Update readme.md (#7937)
dark/light mode algoseek logo / link to https://www.algoseek.com/lean.html
2024-04-17 14:23:06 -03:00
Martin-Molinero
dfbe85ca85 PythonData Pep8 Support (#7936)
- Improve PythonData to support pep8 method names if available. Adding
  unit tests
2024-04-17 13:29:14 -03:00
Martin-Molinero
38c90d5a98 Fix CurrentSlice python wrapper (#7932)
- Fix algorithm current slice, to be a python slice wrapper. Updating
  regression algorithmst status
2024-04-16 18:38:53 -03:00
Jared
318701964c Update readme.md (#7927) 2024-04-16 17:34:49 -03:00
Jhonathan Abreu
93bc7a9dc1 Update pythonnet version to 2.0.32 (#7923) 2024-04-15 19:48:54 -03:00
Martin-Molinero
4e39100fa9 Pep8 Python Base Selection Models Update (#7920)
* Pep8 Python Selection Models Update

- Update python selection models to pep 8, keeping backwards
  compatibility support

* Address reviews, further pep8 renames
2024-04-15 19:22:20 -03:00
Martin-Molinero
0e58c4c694 Adjust GoodTilDate Pep8 (#7921)
- Pep8 adjustment for GoodTilDate, so it behaves like `Expiry` static
  readonly funcs which will be binded to both snake case and upper
  constant format, `good_til_date` & `GOOD_TIL_DATE`
2024-04-15 19:02:59 -03:00
Martin-Molinero
2ff13ea8fc Remove unrequired, unused universe DQH call (#7914)
- Remove unrequired, unused DQH subscription call to universe
  subscription
2024-04-15 13:50:30 -03:00
Martin-Molinero
dc1748f4ae Fix composer deadlock (#7917)
- Fix deadlock in composer creating a type like IBDownloader which gets
  the map file provider instance using the composer
2024-04-15 12:32:53 -03:00
Martin-Molinero
e06931c423 Make MorningStart codes readonly (#7919) 2024-04-15 12:32:41 -03:00
Martin-Molinero
f25029b0fe Update readme.md 2024-04-12 17:30:46 -03:00
Jhonathan Abreu
2ddf40b8e9 PEP8 style algorithm API (#7909)
* feat: support snake-case style Python QCAlgorithm implementations

* feat: add unit tests and minor fixes

* feat: implement new BasePythonWrapper class for python wrappers.

Used to cache methods and contains invoke functionality

* feat: make python wrappers implement the new base class for pep8 style support

* feat: keep overriden methods in Algorithm Python Wrapper

* feat: add unit tests for custom models algorithms with PEP8 style

* Bump pythonnet version to 2.0.30

* fix bugs and address peer review

* Address peer review

* Minor revert

* feat: StubsIgnoreAttribute for ignoring members or classes by the stubs generator

* Minor fixes

* Minor fix

* Minor fix

* Bump pythonnet version to 2.0.31

* Added Greeks.Lambda_ alias of Lambda for python compatibility.

Remove unused method
2024-04-12 17:29:15 -03:00
Martin-Molinero
90f09a1d60 Add TerminalLink Execution Instruction (#7916)
- Add optional TerminalLink execution instruction order properties
2024-04-12 15:10:12 -03:00
Ashutosh
94d33a50c4 Correction: Mapping tickSize to minimum_price_variation (#7910)
* Update symbol-properties-database.csv

* Update symbol-properties-database.csv
2024-04-11 12:37:25 -03:00
Martin-Molinero
bf741a155f Minor tweak for Live Synchronizer (#7912) 2024-04-11 10:43:41 -03:00
Martin-Molinero
c42cc841b2 Adjust API project file to accept a nullable id (#7911) 2024-04-10 15:19:38 -03:00
Martin-Molinero
fa9f10bebf Add support for auxiliary data history request (#7906)
* Add support for auxiliary data history request

- Add support for split/dividends/margin interest history requests.
  Adding regression algorithms

* Expand auxiliary history regression tests
2024-04-10 12:59:32 -03:00
Ricardo Andrés Marino Rojas
dc02ac7c84 API Clean Up, Documentation, Standardization (#7893)
* First draft of the update

* Add improvements

* Nit changes

* Add improvements

* Add improvements

* Remove unnecessary files

* Improve unit tests

* Add missing file

* Add new unit tests to CI

* Fix bug

* Fix unit tests

* Address changes

* Nit changes

* Nit changes

* Add fix for list backtest response

* Nit change

* Add changes in ListBacktest

* Fix failing unit test

* Improve API.GetObjectStore method

* Improve Api.GetObjectStore()

* Add C# models for object/get and object/properties

* Improve API methods and tests for object store

* Nit changes

* Nit change
2024-04-10 10:53:05 -03:00
Martin-Molinero
d238a8132e Python fundamental history request fix (#7905)
- Fix python fundamental pandas history request, where properties
  wouldn't change due to cache. Expanding regression test to assert
  issue
2024-04-09 09:55:20 -03:00
Martin-Molinero
7f7011edc0 Minor TZ fix for Scheduled Universe (#7903)
- By default Time rules yield times in UTC TZ, already correctly handled
  by 'ScheduledUniverseSelectionModel' but this wasn't fixed in ScheduledUniverse
2024-04-08 19:03:55 -03:00
Martin-Molinero
bb5c0eb54e Minor api improvements (#7901)
* Minor api improvements

- Adding Universe.Selected to hold the current set of selected symbols.
  Adding regression tests
- Adjusting TimeRules and DateRules to fallback to the MHDB if the
  security hasn't been added. Updating existing regression tests

* Expand regression test assertion
2024-04-05 17:43:25 -03:00
Jhonathan Abreu
314673534c Options/Index Options hour/daily resolution required data only download (#7898)
* fix: download year file data only for hour and daily resolutions for options and index options

* minor fix: index options regression tests expected status

* Minor change

* minor: update regression algorithms stats
2024-04-04 18:18:33 -03:00
Martin-Molinero
d24f665ee4 Adding new algorithm data handling options (#7897)
* Adding new algorithm data handling options

- Adding new QCAlgorithm data handling method options to override.
  Adding Py/C# regression tests
- Removing old OnData Type specific invoker methods

* Address reviews. Remove old OnData C# only methods
2024-04-04 15:38:50 -03:00
Martin-Molinero
3eec4a0090 Add example of scheduled universe selection with custom data (#7896)
- Add example of scheduled universe selection with custom data.
 See https://github.com/QuantConnect/Lean/pull/7895
2024-04-04 13:21:35 -03:00
Martin-Molinero
3aff0ce958 Add Scheduled Universe Selection (#7895)
* Add Scheduled Universe Selection

- Adding `UniverseSettings.Schedule` that will allow users to
specify a custom selection schedule which is independent of the
underlying data frequency
- Adding unit and regression tests

* Add live trading schedule time shift
2024-04-04 12:21:51 -03:00
Martin-Molinero
b65f253d42 Api read order and events handling (#7877)
- Adjust SerializedOrderEvent json format. Adding unit tests
- Removing unused SerializedOrder and it's converter
2024-04-02 18:56:05 -03:00
Martin-Molinero
529841ea77 Add labels to docker foundation files (#7890) 2024-04-02 16:36:08 -03:00
Jhonathan Abreu
6965dc9842 Option style parameter for parsing OSI option tickers (#7889)
* Get option style in OSI option ticker parsing method

* Keep previous SymbolRepresentation.ParseOptionTickerOSI overload

* Minor fix
2024-04-02 15:04:43 -03:00
Roman Yavnikov
0d430e2718 Revert: destination-dir param in Toolbox (#7885)
* revert: destination-dir param in Toolbox

* feat: test case on destination-dir param
2024-04-01 10:50:35 -03:00
Martin-Molinero
8bcd491fc3 Update readme.md 2024-03-28 16:33:13 -03:00
Ashutosh
f5cd9262b5 Added Forex CFD for IB (#7878) 2024-03-28 10:36:24 -03:00
Alexandre Catarino
f5db8788a0 Fixes Typo In Porfolio.Invested (#7876) 2024-03-27 15:44:53 -03:00
Martin-Molinero
0fa7f53539 Update blacklisted-tickers.txt (#7872) 2024-03-27 11:39:28 -03:00
Martin-Molinero
95000c5c29 Fix TF cuda support (#7874) 2024-03-26 17:51:57 -03:00
Martin Molinero
1120d7f050 Fix research CI expected output 2024-03-26 15:02:45 -03:00
Martin-Molinero
1cb262476d Minor python update related CI test fixes (#7873) 2024-03-26 14:42:07 -03:00
Martin Molinero
abadc543a4 Free space in GH CI 2024-03-26 14:06:37 -03:00
Martin-Molinero
9e04371f0b Update gh-actions.yml 2024-03-26 13:58:52 -03:00
Martin-Molinero
4eb16f3456 Update gh-actions.yml 2024-03-26 13:57:27 -03:00
Martin-Molinero
fe2420b9d4 Update readme.md 2024-03-26 13:09:04 -03:00
Martin-Molinero
78647d3a1d Update libraries and python 3.11 (#7856)
* Update python 3.11

* Update ARM foundation image and minor improvements
2024-03-26 12:57:56 -03:00
Jhonathan Abreu
78b49a1d11 Update InteractiveBrokers market symbols in SPDB (#7870)
* Update InteractiveBrokers market symbols in SPDB

* Update IB cfds in MHDB in SPDB

* Update IB index CFDs lot size
2024-03-26 10:44:16 -04:00
Roman Yavnikov
14f94923e1 Remove: old / not used part in ToolBox (#7871)
* remove: ref #6383

* remove: fxcm, ref #5505

* remove: not used pckg in ToolBox

* remove: fxcm downloader mention, ref #5505
2024-03-26 10:10:47 -03:00
Jhonathan Abreu
01eb907f98 Add CFD support for IB brokerage model (#7861)
* Support CFDs in IB

* Add new currency pair util method

* Minor changes to IB fee model and tests

* Add CFD USA market hours

* Add new Market interactivebrokers for cfds

* Add sample algorithm illustrating manually adding market hours to MHDB

* Update MHDB and SPDB
2024-03-25 16:58:17 -04:00
Roman Yavnikov
22dafee9c6 remove: IVolatilityEquity Converter (#7866) 2024-03-25 17:17:03 -03:00
Ricardo Andrés Marino Rojas
6259ee1d91 Remove BaseLiveAlgorithmSettings (#7862)
* Remove BaseLiveAlgorithmSettings

* Fix IB unit test

* Add Python unit test

* Add more unit tests
2024-03-25 15:54:06 -03:00
Ricardo Andrés Marino Rojas
ead2efe6b9 Add Starting and Ending KPI's (#7811)
* First draft of the solution

* Add missing changes

* Remove the new KPI's from report

* Fix bugs

* nit change

* Add improvements

* Fix regression tests

* Solve bugs in the regression algos

* Fix regression tests bugs

* Expand unit tests and add minor changes
2024-03-25 15:40:38 -03:00
Roman Yavnikov
ca99f329dd remove: Dukascopy Downloader (#7865) 2024-03-25 15:39:46 -03:00
Roman Yavnikov
3338c9a332 remove: CryptoIQ Downloader (#7867) 2024-03-25 11:10:10 -03:00
Roman Yavnikov
229caf485c remove: NseMarketDataConverter (#7863) 2024-03-25 11:08:19 -03:00
Roman Yavnikov
82b327b2b9 remove: Kraken Data Downloader from ToolBox (#7860) 2024-03-19 19:17:17 -03:00
Roman Yavnikov
aca30a896c Remove: Yahoo Data Downloader (#7859)
* remove: missed of QBDL PR:#6110

* remove: Yahoo(YDL) mention in proj
2024-03-19 11:40:46 -03:00
Martin-Molinero
3eedde9b6e Normalize ETF constituents universe (#7858)
- Normalize ETF constituents universe data. Adding new tests and
  assertions
2024-03-19 11:28:17 -03:00
Roman Yavnikov
c0d909c72c TryParsePath ignores DateTime (#7857)
* feat: logic of create Symbol with parsed Date

* fix: additional validation that date has value
2024-03-19 11:27:40 -03:00
Roman Yavnikov
7e568bf4ac Feature: find different Ticker data download parameters (#7845)
* refactor: map files in lean/data folder

* feat: Indexers in MapFile

* feat: extension for mapFile and downloader param

* refactor: getAllTickers from MapFiles

* feat: addition out variable in TryParsePath
fix: tests with new variable

* refactor: DownloadDataProvider with getting all ticker with different DateTime Ranges
feat: test

* revert: "refactor: map files in lean/data folder"

This reverts commit 41fa26eb8627446028d4f2d4c536511ea82a9a48.

* revert: "feat: addition out variable in TryParsePath"
refactor: some actual changing

This reverts commit 9de482bd6490eecd1eeee83e035dfc1ece8d6415.

* revert: "feat: Indexers in MapFile"
fix: actual changes

This reverts commit 393181c6316a354a8cdcbfb093707cb545383a8a.

* remove: high performance Any validation
feat: validation on ticker start with specific sign
fix: option test

* feat: validation on mapping
refactor: when resolution less hour
test: new test cases + validation of SecurityType

* refactor: add additional day when return date range from MapFile
fix: FirstTicker instead of Permtick when generate new Equity
feat: validation of request Date in DownloaderDataProvider
refactor: by style proj DownloaderDataProvider
test:fix: starting Date in TestCases

* remove: duplicate code

* fix: check of income data.Time with requested Start/End-Date

* test:fix: download test cuz we can not get/write future data

* remove:  extra Symbol Create mthd

* test:feat: validate of TryParse returns correct symbol

* remove: excess if condition

* test:remove: extra chaning
connected # 3a62adf54c

* refactor: split big method to small ones (add readability)

* fix: typo in xml description

* refactor: get the correct symbol value

* refactor: use local time instead of Utc in download Param extension
refactor: use struct instead of class

* test:fix: convert time to Utc from local time
2024-03-18 14:43:11 -03:00
Ashutosh
ee52ce4676 Update blacklisted-tickers.txt (#7854) 2024-03-18 11:52:07 -03:00
Martin-Molinero
a8280e1452 Minor fix for universe history (#7852)
- Do not cache universe collection data. Adding unit test
2024-03-14 16:20:28 -03:00
Ricardo Andrés Marino Rojas
934a8e0a61 Handle Windows reserved filenames (#7784)
* Add ToValidPathMethod

* Nit change

* Add more unit tests

* Improve implementation

* Enhance implementation

* Add more unit tests

* Enhance implementation

* Improve unit tests

* Improve implementation

* Nit changes

* Adjust reading/writing methods

* Fix bugs

* Add Windows OS flag

* Fix unit tests

* Fix unit tests

* Fix unit tests

* Change FileStream() to SafeFileStream()

* Fix bugs

* Fix bugs

* Nit changes

* Nit changes

* Add improvements

* Missing file

* Address requested changes

* Address requested changes

* Add missing test
2024-03-13 19:05:57 -03:00
Alexandre Catarino
44c7dbd698 Adds Rebate and Fee Rates to Shortable Provider (#7840)
* Adds Rebate and Fee Rates to Shortable Provider

If the provider does have this information, the rates are zero.

* Adds Helper Methods to QCAlgorithm

- Improve summaries.
- Express values as rates instead of percentages.
- Adds headers to files to emulate real data

* Clarify the Data Format

* Removes Helper Methods from QCAlgorithm

* Removes `Shortable` and `ShortableQuantity` from Example

Algorithms should prefer getting the information from the `Security.ShortableProvider`.
2024-03-13 16:04:33 -03:00
Jhonathan Abreu
b89d7d65b2 Fix live trading MHDB update (#7848)
* Add schedule manager unit tests

* Add schedule manager unit tests

* Fix overriding security exchange hours

* Minor comments changes

* Minor change

* Add SecurityExchangeHours.Update method to set without changing the reference

* Minor change
2024-03-13 12:09:15 -04:00
Ricardo Andrés Marino Rojas
09a3b61df8 Fix bug for NQX index options (#7824)
* First draft of the solution

* Add Improvements

* Update python version of the algo

* Update other classes

* Add regression algo

* Add missing data

* Fix bug

* Fix bug

* Nit change

* Clean implementation

* Nit change

* Nit change

* Improve implementation

* Nit change

* Nit change

* Solve bugs

* Improvements

* Address required changes

* Nit change

* Address changes

* Nit changes

* Nit changes

* Rename regression test
2024-03-13 11:42:55 -03:00
Martin-Molinero
516befe0b5 Backwards compatibility research universe history (#7849)
- Add backwards compatibility for research universe history api, adding
  unit tests
2024-03-13 11:20:02 -03:00
Martin-Molinero
17ca8a743f Refactor universe historical data source (#7837)
* Refactor universe historical data source

- Add new universe history API methods
- Refactor QuantBook UniverseHistory to use the universe selection
  itself instead of a given func
- Refactor and rename fundamental types
- Refactor AddUniverse API to handle universe collection data which
  holds another type internally, like fundamental

* Fix minor bug causing ApiDataProvider not to serve Bitfinex universe data

* Further improvements to add universe API

* Handle no selection function
2024-03-12 13:41:49 -03:00
Roman Yavnikov
a98a50237b Helper: Method for Retrieving Historical Ticker Symbols (#7826)
* feat: helper to return old name of symbols
feat: test
refactor: test a little bit neat

* feat: SplitHistoryRequest() with different mapped symbol
feat: test
refactor: RetrieveSymbolHistoricalDefinitions

* refactor: split historyRequest by historical symbol name
refactor: change location of extension
refactor: change location of test extension

* revert: extra changes

* fix: validation on RequiresMapping in SplitHistoryRequest
feat: add Future Symbol tests

* move: extension method to another file

* fix: wrong extension call param position

* fix: wrong extension call param position in test

* refactor: IEnumerable foreach to more simple form
feat: add TickerDateRange struct instead of Tuple
fix: test

* refactor: map extension alway returns empty result

* refactor: SplitHistory extension returns original HistoryRequest

* feature: new extension for RequiresMapping except Futures

* fix: validation of symbol map file to contains something

* refactor: extension test cases

* feat: assert of right ticker in tests

* fix: split historical request with using Local Time instead of UTC
fix: test description

* feat: test helper IEnumerable of TimeZones

* test: validate right EndDate with different TimeZones

* remove: validation of end of date
test: several new test cases

* feat: additional test with specific dateTime

* remove: extra Extension method validation on future and mapping
2024-03-11 11:53:40 -03:00
Martin-Molinero
51b018c616 Update Kraken Symbol Properties (#7844)
* Update symbol-properties-database.csv

Added additional pair
Corrected the config for the SOLUSD pair

* Update Kraken SPDB

---------

Co-authored-by: t984375 <162788827+t984375@users.noreply.github.com>
2024-03-11 10:43:11 -03:00
Louis Szeto
c049a35121 Add Option Gamma, Vega, Theta, Rho Indicator (#7830)
* Add gamma indicator

* add helper method

* add unit tests

* add in regression tests

* Address peer review

* add vega indicator

* add theta and rho indicators

* Address peer review, refactor
2024-03-11 10:32:36 -03:00
Martin-Molinero
8c66e2e715 Update InsufficientBuyingPowerForAutomaticExerciseRegressionAlgorithm.cs 2024-03-07 12:22:08 -03:00
Martin-Molinero
bb3931d911 Update readme.md 2024-03-06 14:58:50 -03:00
Martin-Molinero
feff802479 Standardize trade count statistic (#7827)
* Standarize trade count statistic

* Rename 'Total Trades' to 'Total Orders'
2024-03-06 14:52:34 -03:00
Martin-Molinero
dcbb2d3cf8 Skip failing yahoo data downloader test (#7833) 2024-03-06 11:37:06 -03:00
Jhonathan Abreu
f298f6e21a Handle insufficient margin for option exercise (#7828)
* Handle insufficient margin for option exercise

* Minor change

* Minor changes
2024-03-05 15:39:30 -04:00
Jhonathan Abreu
ce197afe44 Populate order properties for option exercise orders (#7829)
* Populate order properties for option exercise orders

* Minor change

* Not setting broker id for options exercises

* Minor change
2024-03-05 14:19:06 -04:00
Jhonathan Abreu
637fe75b25 Update pythonnet version to 2.0.28 (#7821)
* Bumped pythonnet version to 2.0.27

* Update pythonnet version to 2.0.28
2024-03-05 11:30:40 -04:00
Louis Szeto
6bf2acd0da Allow smoothing in Implied Volatility and add forward tree model (#7820)
* Allow mirror contract and smoothing IV

* Python wrapper on smoothing IV

* helper method update

* Add forward tree model

* modify and add unit tests and data

* address peer review

* address peer review
2024-03-04 11:00:04 -03:00
Jhonathan Abreu
5e2957cbf0 Refactor config file enviroments to match brokerages namespaces (#7823)
* Refactor config file enviroments to match brokerages namespaces

* Use class name only for brokerages and DQH in config file
2024-02-29 14:36:06 -04:00
Martin-Molinero
78c3f81b96 Research configuration initialization improvement (#7825)
- Minor research configuration handling improvement on initialization,
  making sure we reload configs
2024-02-29 15:13:59 -03:00
Martin-Molinero
e500a6b466 QuantBook Initialization Order (#7822)
- QuantBook should first initialize the system handlers and later the
  algorithm handlers, like done by the engine
2024-02-28 17:07:11 -03:00
Martin-Molinero
b9ec218870 Update readme.md 2024-02-28 11:27:47 -03:00
Louis Szeto
e39cec40f5 Implement dividend yield model (#7758)
* dividend yield plug-in model interface

* dividend yield model python wrapper

* Implement symbol dividend yield models

* unit tests on dividend yield provider

* Update IV indicator

* IV indicator unit tests

* update Delta indicator

* Delta indicator unit tests

* update helper method

* Nit

* Address peer review

* Address 2nd peer review

* readability

* Regression tests

* dividend yield model

* Address review

* Fix unit tests

* Minor fix

* Fix tests

---------

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2024-02-27 12:39:46 -03:00
Ashutosh
ea5e4ac8d0 Update symbol-properties-database.csv (#7795)
* Update symbol-properties-database.csv

Updating Symbol properties database to reflect kraken API information.

#### Description
Updated the market_ticker column of Symbol properties database to reflect information as per Kraken API.

#### Related Issue
Close #7794

#### Motivation and Context
We updated symbol mapping for the Kraken market.

#### Requires Documentation Change
No

#### How Has This Been Tested?
<!--- Please describe in detail how you tested your changes. -->
<!--- Include details of your testing environment, and the tests you ran to -->
<!--- see how your change affects other areas of the code, etc. -->

#### Types of changes
<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] Refactor (non-breaking change which improves implementation)
- [ ] Performance (non-breaking change which improves performance. Please add associated performance test and results)
- [X] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] Non-functional change (xml comments/documentation/etc)

#### Checklist:
<!--- The following is a checklist of items that MUST be completed before a PR is accepted -->
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
- [X] My code follows the code style of this project.
- [X] I have read the **CONTRIBUTING** [document](https://github.com/QuantConnect/Lean/blob/master/CONTRIBUTING.md).
- [X] I have added tests to cover my changes. <!--- If not applicable, please explain why -->
- [X] All new and existing tests passed.
- [X] My branch follows the naming convention `bug-<issue#>-<description>` or `feature-<issue#>-<description>`

<!--- Template inspired by https://www.talater.com/open-source-templates/#/page/99 -->

* Update symbol-properties-database.csv

- Update as per peer review

* Correction
2024-02-27 10:45:34 -04:00
Martin-Molinero
1f975332c3 Update readme.md 2024-02-27 10:59:26 -03:00
Martin-Molinero
aa6b909a93 Update readme.md 2024-02-27 10:29:38 -03:00
Will Tindall
9cfd8b7403 Implement Risk Metrics: Value At Risk (#7757)
* Implement VaR in PortfolioStatistics

* Added ValueAtRisk indicator

* Refactored ValueAtRiskTests

* Added returns column to test data

* Change indicator helper method name

* Addressed comments
2024-02-26 11:02:20 -03:00
Pronoy Chowdhury
fec27a56ce Chande Variable Index Dynamic Average (VIDYA) Indicator (#7797)
* Chande Variable Index Dynamic Average (VIDYA) Indicator

* Improvements

* Improvements

* Final Changes

* Editted, Retested

* Comments

* Minor Corrections

* Updated Datetime Format of test data to US Standards

---------

Co-authored-by: Pronoy Chowdhury <rokstarr.dbz@outlook.com>
2024-02-26 10:55:01 -03:00
Roman Yavnikov
e96c08e208 feat: downloader data provider returning null (#7812) 2024-02-23 15:45:47 -03:00
Jhonathan Abreu
d942d58717 Add null check for history in lean data writer (#7814) 2024-02-23 15:45:35 -03:00
Martin-Molinero
387eae9e73 Update readme.md 2024-02-21 18:16:53 -03:00
Martin-Molinero
7e61483ad7 Adjust API tests to fetch creds from globals (#7806) 2024-02-21 17:53:46 -03:00
Martin-Molinero
8595aff670 Handle history provider returning null (#7804) 2024-02-21 15:44:22 -03:00
Martin-Molinero
e375afbe20 Dynamically setup brokerage history provider wrapper (#7802) 2024-02-21 12:03:31 -03:00
Martin-Molinero
1a1f64e7a6 Update readme.md 2024-02-21 10:09:16 -03:00
Martin-Molinero
2e9c7ade2c Initialize report correctly (#7803)
- Fix report initialization, adding CI tests
2024-02-21 10:02:43 -03:00
Jhonathan Abreu
d3928fba6b Manual option contract addition for delisted underlyings error (#7799)
* Throw when trying to add option contracts for delisted underlyings

* Minor change
2024-02-21 09:02:07 -04:00
Jhonathan Abreu
09db45c91d Universes immediate selection (#7785)
* Make sure continuous futures universe selection is performed right away on the start of the algorithm.

This ensures the Future.Mapped is not null

* Minor changes

* Minor fixes

* Update regression algorithms stats

* Add DC futures map file

* Update DC futures map file

* Update regression algorithms stats

* Include ETFs for immediate universe selection

* Include Coarse Fundamentals for immediate universe selection

* Include Futures Chain Universe for immediate selection

* Add Option Chain Universe test

* Include custom universes for immediate selection

* Minor updates

* Include constituents universes for immediate selection

* Minor update

* Minor changes, docs and stats updates

* Minor changes

* Minor changes and clean up

* Minor regression algorithm stat update
2024-02-21 08:59:58 -04:00
Ricardo Andrés Marino Rojas
64fe4ba13b Update LinearWeightedMovingAverage (#7798)
* Add improvements and unit tests

* Add Improvements
2024-02-20 16:51:06 -03:00
Martin-Molinero
2a82c6f9bb Consolidate Configuration.Get usages (#7796) 2024-02-20 13:37:22 -03:00
Ricardo Andrés Marino Rojas
6f6fbee6ee Handle DivisionByZero exception in indicators (#7788)
* Solve bug and add indicator unit test

* Nit change

* Add more checks

* Improve solution

* Nit change

* Solve bugs

* Improve implementation

* Nit change
2024-02-19 16:02:51 -03:00
Martin-Molinero
67b9ecf391 Minor config tweaks (#7792) 2024-02-19 12:05:00 -03:00
Ricardo Andrés Marino Rojas
0e81589efa Bug add future option ozn (#7791)
* Models OZN: 10-Year US Treasury Future Options

<!--- Provide a general summary of your changes in the Title above -->

#### Description
We added future option for OZN

#### Related Issue
Close #7783
<!--- This project only accepts pull requests related to open issues -->
<!--- If suggesting a new feature or change, please discuss it in an issue first -->
<!--- If fixing a bug, there should be an issue describing it with steps to reproduce -->
<!--- Please link to the issue here: -->

#### Motivation and Context
 We added future option supported by CME
https://www.cmegroup.com/markets/interest-rates/us-treasury/10-year-us-treasury-note.contractSpecs.options.html#optionProductId=317

#### Requires Documentation Change
No

#### How Has This Been Tested?
I tested the change using fake files to check if mapping is correct.

#### Types of changes
<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] Refactor (non-breaking change which improves implementation)
- [ ] Performance (non-breaking change which improves performance. Please add associated performance test and results)
- [X] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] Non-functional change (xml comments/documentation/etc)

#### Checklist:
<!--- The following is a checklist of items that MUST be completed before a PR is accepted -->
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
- [X] My code follows the code style of this project.
- [X] I have read the **CONTRIBUTING** [document](https://github.com/QuantConnect/Lean/blob/master/CONTRIBUTING.md).
- [X] I have added tests to cover my changes. <!--- If not applicable, please explain why -->
- [X] All new and existing tests passed.
- [X] My branch follows the naming convention `bug-<issue#>-<description>` or `feature-<issue#>-<description>`

<!--- Template inspired by https://www.talater.com/open-source-templates/#/page/99 -->

* Add unit tests

---------

Co-authored-by: Ashutosh <ashutoshrana171@gmail.com>
2024-02-16 19:13:04 -03:00
Martin-Molinero
07dbfc42a5 Improve consolidator scan (#7789)
* Improve consolidator scan

- Improve consolidator scan to be triggered even if no data is present.
  Adding new regression test, updating existing

* Adding more tests & minor tweaks
2024-02-16 17:22:49 -03:00
Martin-Molinero
ea15e014e2 Live delisting handled (#7774)
- Adjust live equity delisting to be map files based like splits and
  dividends. Adding unit test
- Expand existing unit tests asserting delistings in live mode, set
  securities to not tradable
2024-02-16 16:56:42 -03:00
Martin-Molinero
d602e260b4 Update readme.md 2024-02-13 12:28:20 -03:00
Martin-Molinero
e31a898269 Update readme.md 2024-02-13 11:16:48 -03:00
Roman Yavnikov
1dd186acb4 CoinApi Extraction: Removing from Lean.ToolBox (#7777)
* feat: remove CoinApi realization from ToolBox

* fix: ComposeDataQueueHandlerInstances
we have removed all IDataQueueHandler from ToolBox
2024-02-13 10:40:30 -03:00
Ricardo Andrés Marino Rojas
330946785f Add improvement (#7778) 2024-02-13 10:40:15 -03:00
Jhonathan Abreu
48ce5ef88d Refactor API projects test to avoid leaving created projects in account (#7773) 2024-02-08 17:24:49 -03:00
Martin-Molinero
76a0bdd769 Fix scatter chart point serialization (#7772)
- Fix scatter chart point sometimes being serialized as an array. Adding
  unit test
2024-02-08 15:36:38 -03:00
Ricardo Andrés Marino Rojas
b7740edd15 Solve bug and add unit tests (#7767) 2024-02-07 17:51:28 -03:00
Ricardo Andrés Marino Rojas
0264d346e6 Add obsolete flag (#7768) 2024-02-07 17:50:03 -03:00
Ricardo Andrés Marino Rojas
f59a6be589 Add Python version of AllShortableSymbolsCoarseSelectionRegressionAlgorithm.cs (#7766)
* Add Python version

* Improve implementation

* Improve implementation
2024-02-07 11:46:48 -03:00
Ricardo Andrés Marino Rojas
a5b309ae23 Add CSharp version of BasicTemplateOptionsConsolidationAlgorithm (#7756)
* Add CSharp version

* Nit change
2024-02-07 11:46:41 -03:00
Martin-Molinero
3d673d6de1 RefreshEnumerator retry on stale file exception (#7764)
- The refresh enumerator will retry on stale file handle exception.
  Adding unit test
2024-02-06 19:26:59 -03:00
Martin-Molinero
fdb8c20a1a Update readme.md 2024-02-06 18:02:51 -03:00
Martin-Molinero
6fe368106a Obsolete VAR for V instead (#7763) 2024-02-06 17:50:20 -03:00
Martin-Molinero
379e2d3405 Add optional PositionSide for TerminalLink (#7762)
* Add optional PositionSide for TerminalLink

* Minor rename
2024-02-06 16:08:24 -03:00
3065 changed files with 317567 additions and 55710 deletions

View File

@@ -1,33 +1,43 @@
{
"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"
"build": {
"dockerfile": "Dockerfile"
},
//See https://containers.dev/implementors/json_reference/ for a comprehensive json schema used to define this file.
"customizations": {
"vscode": {
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"ms-dotnettools.csdevkit",
"ms-python.python",
"eamodio.gitlens",
"yzhang.markdown-all-in-one",
"SonarSource.sonarlint-vscode"
],
// Set *default* vscode 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 the same network configuration as the host machine, ensuring no problems with firewalls, proxies etc.
"runArgs": [
"--network=host"
],
// 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": [
"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"
]

View File

@@ -1,4 +1,11 @@
<!--- This template provides sections for bugs and features. Please delete any irrelevant sections before submitting -->
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
#### Expected Behavior
<!--- Required. Describe the behavior you expect to see for your case. -->
@@ -24,4 +31,4 @@
<!--- Required for Bugs, feature request can delete the line below. -->
- [ ] I have provided detailed steps to reproduce the issue
<!--- Template inspired by https://github.com/stevemao/github-issue-templates -->
<!--- Template inspired by https://github.com/stevemao/github-issue-templates -->

1
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1 @@
blank_issues_enabled: false

View File

@@ -0,0 +1,26 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
#### Expected Behavior
<!--- Required. Describe the behavior you expect to see for your case. -->
#### Actual Behavior
<!--- Required. Describe the actual behavior for your case. -->
#### Potential Solution
<!--- Optional. Describe any potential solutions and/or thoughts as to what may be causing the difference between expected and actual behavior. -->
#### Checklist
<!--- Confirm that you've provided all the required information. -->
<!--- Required fields --->
- [ ] I have completely filled out this template
- [ ] I have confirmed that this issue exists on the current `master` branch
- [ ] I have confirmed that this is not a duplicate issue by searching [issues](https://github.com/QuantConnect/Lean/issues)
<!--- Template inspired by https://github.com/stevemao/github-issue-templates -->

View File

@@ -9,14 +9,19 @@ on:
jobs:
build:
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
# Only run on push events (not on pull_request) for security reasons in order to be able to use secrets
if: ${{ github.event_name == 'push' }}
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Free space
run: df -h && rm -rf /opt/hostedtoolcache* && df -h
- name: Liberate disk space
uses: jlumbroso/free-disk-space@main
with:
tool-cache: true
large-packages: false
docker-images: false
swap-storage: false
- name: Run API Tests
uses: addnab/docker-run-action@v3
with:
@@ -27,4 +32,4 @@ jobs:
# Build
dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
# Run Projects tests
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --blame-hang-timeout 300seconds --blame-crash --filter "FullyQualifiedName=QuantConnect.Tests.API.ProjectTests" -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\)
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --blame-hang-timeout 7minutes --blame-crash --logger "console;verbosity=detailed" --filter "FullyQualifiedName=QuantConnect.Tests.API.ProjectTests|FullyQualifiedName=QuantConnect.Tests.API.ObjectStoreTests" -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\)

View File

@@ -9,12 +9,20 @@ on:
jobs:
build:
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Free space
run: df -h && rm -rf /opt/hostedtoolcache* && df -h
with:
fetch-depth: 0 # Ensures we fetch all history
- name: Liberate disk space
uses: jlumbroso/free-disk-space@main
with:
tool-cache: true
large-packages: false
docker-images: false
swap-storage: false
- uses: addnab/docker-run-action@v3
with:
@@ -22,9 +30,15 @@ jobs:
options: --workdir /__w/Lean/Lean -v /home/runner/work:/__w -e GITHUB_REF=${{ github.ref }} -e PYPI_API_TOKEN=${{ secrets.PYPI_API_TOKEN }} -e ADDITIONAL_STUBS_REPOS=${{ secrets.ADDITIONAL_STUBS_REPOS }} -e QC_GIT_TOKEN=${{ secrets.QC_GIT_TOKEN }}
shell: bash
run: |
# Add exception
git config --global --add safe.directory /__w/Lean/Lean
# Get Last Commit of the Current Tag
TAG_COMMIT=$(git rev-parse HEAD) && echo "CURRENT BRANCH LAST COMMIT $TAG_COMMIT"
# Get Last Commit of the master
MASTER_COMMIT=$(git rev-parse origin/master) && echo "MASTER BRANCH LAST COMMIT $MASTER_COMMIT"
# Build
dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln && \
# Run Tests
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\"\) && \
# Generate & Publish python stubs
echo "GITHUB_REF $GITHUB_REF" && if [[ $GITHUB_REF = refs/tags/* ]]; then (chmod +x ci_build_stubs.sh && ./ci_build_stubs.sh -t -g -p); else echo "Skipping stub generation"; fi
echo "GITHUB_REF $GITHUB_REF" && if [[ $GITHUB_REF = refs/tags/* && "$TAG_COMMIT" = "$MASTER_COMMIT" ]]; then echo "Generating stubs" && (chmod +x ci_build_stubs.sh && ./ci_build_stubs.sh -t -g -p); else echo "Skipping stub generation"; fi

View File

@@ -7,7 +7,7 @@ on:
jobs:
build:
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v2
with:

View File

@@ -9,12 +9,17 @@ on:
jobs:
build:
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Free space
run: df -h && rm -rf /opt/hostedtoolcache* && df -h
- name: Liberate disk space
uses: jlumbroso/free-disk-space@main
with:
tool-cache: true
large-packages: false
docker-images: false
swap-storage: false
- uses: addnab/docker-run-action@v3
with:

35
.github/workflows/report-generator.yml vendored Normal file
View File

@@ -0,0 +1,35 @@
name: Report Generator Tests
on:
push:
branches: ['*']
tags: ['*']
pull_request:
branches: [master]
jobs:
build:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Liberate disk space
uses: jlumbroso/free-disk-space@main
with:
tool-cache: true
large-packages: false
docker-images: false
swap-storage: false
- uses: addnab/docker-run-action@v3
with:
image: quantconnect/lean:foundation
options: --workdir /__w/Lean/Lean -v /home/runner/work:/__w
shell: bash
run: |
# Build
dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
# Run Backtest
cd ./Launcher/bin/Release && dotnet QuantConnect.Lean.Launcher.dll && cd ../../../
# Run Report
cd ./Report/bin/Release && dotnet ./QuantConnect.Report.dll --backtest-data-source-file ../../../Launcher/bin/Release/BasicTemplateFrameworkAlgorithm.json --close-automatically true

View File

@@ -9,12 +9,17 @@ on:
jobs:
build:
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Free space
run: df -h && rm -rf /opt/hostedtoolcache* && df -h
- name: Liberate disk space
uses: jlumbroso/free-disk-space@main
with:
tool-cache: true
large-packages: false
docker-images: false
swap-storage: false
- uses: addnab/docker-run-action@v3
with:
@@ -23,9 +28,9 @@ jobs:
shell: bash
run: |
# install dependencies
pip3 install papermill==2.4.0 clr-loader==0.1.6
pip3 install papermill==2.4.0 clr-loader==0.2.9
# install kernel
dotnet tool install --global Microsoft.dotnet-interactive --version 1.0.340501
dotnet tool install -g --no-cache --version 1.0.661703 --add-source "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json" Microsoft.dotnet-interactive
# Add dotnet tools to Path
export PATH="$HOME/.dotnet/tools:$PATH"
# activate kernel for jupyter

32
.github/workflows/syntax-tests.yml vendored Normal file
View File

@@ -0,0 +1,32 @@
name: Syntax Tests
on:
push:
branches: ['*']
tags: ['*']
pull_request:
branches: [master]
jobs:
build:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Liberate disk space
uses: jlumbroso/free-disk-space@main
with:
tool-cache: true
large-packages: false
docker-images: false
swap-storage: false
- name: Run Syntax Test
uses: addnab/docker-run-action@v3
with:
image: quantconnect/lean:foundation
options: --workdir /__w/Lean/Lean -v /home/runner/work:/__w
shell: bash
run: |
pip install --no-cache-dir quantconnect-stubs types-requests==2.32.* types-pytz==2025.2.0.* mypy==1.15.0 && \
python run_syntax_check.py

View File

@@ -9,12 +9,17 @@ on:
jobs:
build:
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Free space
run: df -h && rm -rf /opt/hostedtoolcache* && df -h
- name: Liberate disk space
uses: jlumbroso/free-disk-space@main
with:
tool-cache: true
large-packages: false
docker-images: false
swap-storage: false
- uses: addnab/docker-run-action@v3
with:
@@ -23,36 +28,39 @@ jobs:
shell: bash
run: |
# Build
dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln && \
# Python Virtual Environment System Packages
python -m venv /lean-testenv --system-site-packages && . /lean-testenv/bin/activate && pip install --no-cache-dir lean==1.0.99 && deactivate
python -m venv /lean-testenv --system-site-packages && . /lean-testenv/bin/activate && pip install --no-cache-dir lean==1.0.221 && deactivate && \
# Run Virtual Environment Test System Packages
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonVirtualEnvironmentTests.AssertVirtualEnvironment"
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonVirtualEnvironmentTests.AssertVirtualEnvironment" && \
# Python Virtual Environment
rm -rf /lean-testenv && python -m venv /lean-testenv && . /lean-testenv/bin/activate && pip install --no-cache-dir lean==1.0.99 && deactivate
rm -rf /lean-testenv && python -m venv /lean-testenv && . /lean-testenv/bin/activate && pip install --no-cache-dir lean==1.0.221 && deactivate && \
# Run Virtual Environment Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonVirtualEnvironmentTests.AssertVirtualEnvironment"
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonVirtualEnvironmentTests.AssertVirtualEnvironment" && \
# Run Python Package Tests
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests" --blame-hang-timeout 120seconds --blame-crash
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests" --blame-hang-timeout 120seconds --blame-crash && \
# Run StableBaselines Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.StableBaselinesTest" --blame-hang-timeout 120seconds --blame-crash
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.StableBaselinesTest" --blame-hang-timeout 120seconds --blame-crash && \
# Run AxPlatform Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.AxPlatformTest" --blame-hang-timeout 120seconds --blame-crash
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.AxPlatformTest" --blame-hang-timeout 120seconds --blame-crash && \
# Run TensorlyTest Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorlyTest" --blame-hang-timeout 120seconds --blame-crash
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorlyTest" --blame-hang-timeout 120seconds --blame-crash && \
# Run NeuralTangents, Ignite Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.NeuralTangentsTest|IgniteTest" --blame-hang-timeout 120seconds --blame-crash
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.IgniteTest" --blame-hang-timeout 120seconds --blame-crash && \
# Run TensorflowTest
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorflowTest" --blame-hang-timeout 120seconds --blame-crash
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorflowTest" --blame-hang-timeout 120seconds --blame-crash && \
# Run TensorflowProbability
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorflowProbabilityTest" --blame-hang-timeout 120seconds --blame-crash
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.TensorflowProbabilityTest" --blame-hang-timeout 120seconds --blame-crash && \
# Run Hvplot Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.HvplotTest" --blame-hang-timeout 120seconds --blame-crash
# Run Stellargraph Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.StellargraphTest" --blame-hang-timeout 120seconds --blame-crash
# Run Keras Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.KerasTest" --blame-hang-timeout 120seconds --blame-crash
# Run Scikeras Python Package Test
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.ScikerasTest" --blame-hang-timeout 120seconds --blame-crash
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.RiskparityportfolioTest" --blame-hang-timeout 120seconds --blame-crash && \
# Run Transformers
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.Transformers|XTransformers" --blame-hang-timeout 120seconds --blame-crash
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.Transformers" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.XTransformers" --blame-hang-timeout 120seconds --blame-crash && \
# Run Shap
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.KerasTest|PyvinecopulibTest" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.StatsForecast|Mlforecast" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.MlxtendTest|Thinc" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.ModuleVersionTestExplicit" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.Neuralforecast" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.Tsfel" --blame-hang-timeout 120seconds --blame-crash && \
dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter "FullyQualifiedName=QuantConnect.Tests.Python.PythonPackagesTests.ScikitOptimizeTest" --blame-hang-timeout 120seconds --blame-crash

3
.gitignore vendored
View File

@@ -279,4 +279,5 @@ QuantConnect.Lean.sln.DotSettings*
Research/Notebooks
#Docker result files
Results/
Results/
QuantConnect.Lean.sln.DotSettings

View File

@@ -12,16 +12,16 @@ This document contains information regarding ways to use Visual Studio to work 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 Locally</h2>
1. Install [.Net 6](https://dotnet.microsoft.com/download) for the project
1. Install [.Net 9](https://dotnet.microsoft.com/en-us/download/dotnet/9.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
2. (Optional) Get [Python 3.11.11](https://www.python.org/downloads/release/python-31111/) for running Python algorithms
- Follow Python instructions [here](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#installing-python-311) for your platform
3. Get [Visual Studio](https://visualstudio.microsoft.com/vs/)
@@ -35,7 +35,7 @@ Your environment is prepared and ready to run lean
<h1>How to use Lean</h1>
This section will cover configuring, launching and debugging lean. This is only applicable to option 2 from above. This does not apply to Lean CLI, please refer to [CLI documentation](https://www.quantconnect.com/docs/v2/lean-cli/getting-started/lean-cli)
This section will cover configuring, launching and debugging lean. This is only applicable to option 2 from above. This does not apply to Lean CLI, please refer to [CLI documentation](https://www.quantconnect.com/docs/v2/lean-cli/key-concepts/getting-started)
<br />

6
.vscode/readme.md vendored
View File

@@ -51,10 +51,10 @@ If you would like to mount any additional local files to your container, checkou
<h2>Option 3: Install Dependencies Locally</h2>
1. Install [.NET 6](https://dotnet.microsoft.com/en-us/download/dotnet/6.0) for the project
1. Install [.NET 9](https://dotnet.microsoft.com/en-us/download/dotnet/9.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
2. (Optional) Get [Python 3.11.11](https://www.python.org/downloads/release/python-31111/) for running Python algorithms
- Follow Python instructions [here](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#installing-python-311) 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

View File

@@ -55,7 +55,7 @@ namespace QuantConnect.Algorithm.CSharp
||
Portfolio.TotalHoldingsValue < Portfolio.TotalPortfolioValue * 0.01m)
{
throw new Exception($"Unexpected Total Holdings Value: {Portfolio.TotalHoldingsValue}");
throw new RegressionTestException($"Unexpected Total Holdings Value: {Portfolio.TotalHoldingsValue}");
}
}
@@ -67,7 +67,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -79,17 +79,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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", "199"},
{"Total Orders", "199"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-12.611%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-0.585"},
{"Start Equity", "100000"},
{"End Equity", "99827.80"},
{"Net Profit", "-0.172%"},
{"Sharpe Ratio", "-11.13"},
{"Sortino Ratio", "-16.704"},
@@ -108,7 +115,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$26000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "119.89%"},
{"OrderListHash", "2b4c6d1cb2fc32e25f9a744e8aa7229a"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "d06c26f557b83d8d42ac808fe2815a1e"}
};
}
}

View File

@@ -66,7 +66,7 @@ namespace QuantConnect.Algorithm.CSharp
|| insightsCollection.Insights.Count(insight => insight.Symbol == _spy) != 1
|| insightsCollection.Insights.Count(insight => insight.Symbol == _ibm) != 1)
{
throw new Exception("Unexpected insights were emitted");
throw new RegressionTestException("Unexpected insights were emitted");
}
}
@@ -103,7 +103,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -115,17 +115,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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", "9"},
{"Total Orders", "9"},
{"Average Win", "0.86%"},
{"Average Loss", "-0.27%"},
{"Compounding Annual Return", "184.364%"},
{"Compounding Annual Return", "206.404%"},
{"Drawdown", "1.700%"},
{"Expectancy", "1.781"},
{"Start Equity", "100000"},
{"End Equity", "101441.92"},
{"Net Profit", "1.442%"},
{"Sharpe Ratio", "4.836"},
{"Sortino Ratio", "10.481"},
@@ -141,10 +148,11 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.532"},
{"Treynor Ratio", "-1.174"},
{"Total Fees", "$14.78"},
{"Estimated Strategy Capacity", "$47000000.00"},
{"Estimated Strategy Capacity", "$120000000.00"},
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
{"Portfolio Turnover", "41.18%"},
{"OrderListHash", "e07dec6ddf0ef6b5d9c791b0593ec4dc"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "713c956deb193bed2290e9f379c0f9f9"}
};
}
}

View File

@@ -40,10 +40,12 @@ namespace QuantConnect.Algorithm.CSharp
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);
_contract = OptionChain(aapl)
.OrderBy(symbol => symbol.ID.OptionRight)
.ThenBy(symbol => symbol.ID.StrikePrice)
.ThenBy(symbol => symbol.ID.Date)
.ThenBy(symbol => symbol.ID)
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call);
AddOptionContract(_contract);
}
@@ -59,7 +61,7 @@ namespace QuantConnect.Algorithm.CSharp
}
else
{
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
throw new RegressionTestException("Expect a single call to OnData where we removed the option and underlying");
}
}
}
@@ -68,7 +70,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!_hasRemoved)
{
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
throw new RegressionTestException("Expect a single call to OnData where we removed the option and underlying");
}
}
@@ -80,29 +82,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 24;
public long DataPoints => 26;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
public int AlgorithmHistoryDataPoints => 1;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -121,6 +130,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}

View File

@@ -39,8 +39,8 @@ namespace QuantConnect.Algorithm.CSharp
var aapl = AddEquity("AAPL").Symbol;
_contract = OptionChainProvider.GetOptionContractList(aapl, Time)
.OrderBy(symbol => symbol.ID.Symbol)
_contract = OptionChain(aapl)
.OrderBy(x => x.ID.Symbol)
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American);
}
@@ -49,7 +49,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (_hasRemoved)
{
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
throw new RegressionTestException("Expect a single call to OnData where we removed the option and underlying");
}
_hasRemoved = true;
@@ -65,7 +65,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!_hasRemoved)
{
throw new Exception("We did not remove the option contract!");
throw new RegressionTestException("We did not remove the option contract!");
}
}
@@ -77,29 +77,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 24;
public long DataPoints => 25;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
public int AlgorithmHistoryDataPoints => 1;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -118,6 +125,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}

View File

@@ -0,0 +1,152 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Brokerages;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression test to explain how Beta indicator works
/// </summary>
public class AddBetaIndicatorNewAssetsRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Beta _beta;
private SimpleMovingAverage _sma;
private decimal _lastSMAValue;
public override void Initialize()
{
SetStartDate(2015, 05, 08);
SetEndDate(2017, 06, 15);
SetCash(10000);
AddCrypto("BTCUSD", Resolution.Daily);
AddEquity("SPY", Resolution.Daily);
EnableAutomaticIndicatorWarmUp = true;
_beta = B("BTCUSD", "SPY", 3, Resolution.Daily);
_sma = SMA("SPY", 3, Resolution.Daily);
_lastSMAValue = 0;
if (!_beta.IsReady)
{
throw new RegressionTestException("Beta indicator was expected to be ready");
}
}
public override void OnData(Slice slice)
{
var price = Securities["BTCUSD"].Price;
if (!Portfolio.Invested)
{
var quantityToBuy = (int)(Portfolio.Cash * 0.05m / price);
Buy("BTCUSD", quantityToBuy);
}
if (Math.Abs(_beta.Current.Value) > 2)
{
Liquidate("BTCUSD");
Log("Liquidated BTCUSD due to high Beta");
}
Log($"Beta between BTCUSD 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());
}
}
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 List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 5798;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 26;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "436"},
{"Average Win", "0.28%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "1.925%"},
{"Drawdown", "1.000%"},
{"Expectancy", "1.649"},
{"Start Equity", "10000.00"},
{"End Equity", "10410.99"},
{"Net Profit", "4.110%"},
{"Sharpe Ratio", "0.332"},
{"Sortino Ratio", "0.313"},
{"Probabilistic Sharpe Ratio", "74.084%"},
{"Loss Rate", "90%"},
{"Win Rate", "10%"},
{"Profit-Loss Ratio", "25.25"},
{"Alpha", "0.003"},
{"Beta", "0.001"},
{"Annual Standard Deviation", "0.01"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.495"},
{"Tracking Error", "0.111"},
{"Treynor Ratio", "2.716"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$87000.00"},
{"Lowest Capacity Asset", "BTCUSD 2XR"},
{"Portfolio Turnover", "2.22%"},
{"Drawdown Recovery", "139"},
{"OrderListHash", "896ecc92440d51ed26644aac5b8706e4"}
};
}
}

View File

@@ -47,23 +47,23 @@ namespace QuantConnect.Algorithm.CSharp
if (!_beta.IsReady)
{
throw new Exception("_beta indicator was expected to be ready");
throw new RegressionTestException("Beta indicator was expected to be ready");
}
}
public override void OnData(Slice data)
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
var price = data["IBM"].Close;
var price = slice["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}");
throw new RegressionTestException($"_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}");
@@ -97,7 +97,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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};
public virtual List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -109,17 +109,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 11;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "3"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "12.939%"},
{"Drawdown", "0.300%"},
{"Expectancy", "0"},
{"Start Equity", "10000"},
{"End Equity", "10028.93"},
{"Net Profit", "0.289%"},
{"Sharpe Ratio", "3.924"},
{"Sortino Ratio", "0"},
@@ -138,7 +145,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$35000000.00"},
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
{"Portfolio Turnover", "1.51%"},
{"OrderListHash", "381bb9310f9dceb8a79a56849789bdab"}
{"Drawdown Recovery", "2"},
{"OrderListHash", "1db1ce949db995bba20ed96ea5e2438a"}
};
}
}

View File

@@ -31,7 +31,6 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public class AddFutureContractWithContinuousRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _currentMappedSymbol;
private Future _continuousContract;
private Future _futureContract;
private bool _ended;
@@ -50,26 +49,26 @@ namespace QuantConnect.Algorithm.CSharp
contractDepthOffset: 0
);
_futureContract = AddFutureContract(FutureChainProvider.GetFutureContractList(_continuousContract.Symbol, Time).First());
_futureContract = AddFutureContract(FuturesChain(_continuousContract.Symbol).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)
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice slice)
{
if (_ended)
{
throw new Exception($"Algorithm should of ended!");
throw new RegressionTestException($"Algorithm should of ended!");
}
if (data.Keys.Count > 2)
if (slice.Keys.Count > 2)
{
throw new Exception($"Getting data for more than 2 symbols! {string.Join(",", data.Keys.Select(symbol => symbol))}");
throw new RegressionTestException($"Getting data for more than 2 symbols! {string.Join(",", slice.Keys.Select(symbol => symbol))}");
}
if (UniverseManager.Count != 3)
{
throw new Exception($"Expecting 3 universes (chain, continuous and user defined) but have {UniverseManager.Count}");
throw new RegressionTestException($"Expecting 3 universes (chain, continuous and user defined) but have {UniverseManager.Count}");
}
if (!Portfolio.Invested)
@@ -99,7 +98,7 @@ namespace QuantConnect.Algorithm.CSharp
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}");
throw new RegressionTestException($"We got an unexpected security changes {changes}");
}
}
@@ -111,48 +110,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 63;
public long DataPoints => 61;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
public int AlgorithmHistoryDataPoints => 1;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "4"},
{"Average Win", "0%"},
{"Average Loss", "-0.03%"},
{"Compounding Annual Return", "-2.594%"},
{"Drawdown", "0.000%"},
{"Average Loss", "-0.10%"},
{"Compounding Annual Return", "-14.232%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.034%"},
{"Sharpe Ratio", "-10.666"},
{"Start Equity", "100000"},
{"End Equity", "99803.9"},
{"Net Profit", "-0.196%"},
{"Sharpe Ratio", "-7.95"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "1.216%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.029"},
{"Beta", "0.004"},
{"Annual Standard Deviation", "0.003"},
{"Alpha", "-0.128"},
{"Beta", "0.026"},
{"Annual Standard Deviation", "0.016"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.768"},
{"Tracking Error", "0.241"},
{"Treynor Ratio", "-6.368"},
{"Information Ratio", "-1.186"},
{"Tracking Error", "0.237"},
{"Treynor Ratio", "-4.747"},
{"Total Fees", "$8.60"},
{"Estimated Strategy Capacity", "$5500000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Portfolio Turnover", "66.80%"},
{"OrderListHash", "0ade3a7a7aaafa3263082c93cf17c4d8"}
{"Estimated Strategy Capacity", "$2000.00"},
{"Lowest Capacity Asset", "ES VU1EHIDJYLMP"},
{"Portfolio Turnover", "66.50%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "4720516462fcabb4db1aead46051cb4a"}
};
}
}

View File

@@ -66,9 +66,9 @@ namespace QuantConnect.Algorithm.CSharp
}
}
public override void OnData(Slice data)
public override void OnData(Slice slice)
{
if (!data.HasData)
if (!slice.HasData)
{
return;
}
@@ -76,7 +76,7 @@ namespace QuantConnect.Algorithm.CSharp
_onDataReached = true;
var hasOptionQuoteBars = false;
foreach (var qb in data.QuoteBars.Values)
foreach (var qb in slice.QuoteBars.Values)
{
if (qb.Symbol.SecurityType != SecurityType.FutureOption)
{
@@ -99,7 +99,7 @@ namespace QuantConnect.Algorithm.CSharp
return;
}
if (data.ContainsKey(_es20h20) && data.ContainsKey(_es19m20))
if (slice.ContainsKey(_es20h20) && slice.ContainsKey(_es19m20))
{
SetHoldings(_es20h20, 0.2);
SetHoldings(_es19m20, 0.2);
@@ -114,7 +114,7 @@ namespace QuantConnect.Algorithm.CSharp
if (!_onDataReached)
{
throw new Exception("OnData() was never called.");
throw new RegressionTestException("OnData() was never called.");
}
if (_symbolsReceived.Count != _expectedSymbolsReceived.Count)
{
@@ -132,7 +132,7 @@ namespace QuantConnect.Algorithm.CSharp
if (missingSymbols.Count > 0)
{
throw new Exception($"Symbols: \"{string.Join(", ", missingSymbols)}\" were not found in OnData");
throw new RegressionTestException($"Symbols: \"{string.Join(", ", missingSymbols)}\" were not found in OnData");
}
foreach (var expectedSymbol in _expectedSymbolsReceived)
@@ -146,7 +146,7 @@ namespace QuantConnect.Algorithm.CSharp
if (nonDupeDataCount < 1000)
{
throw new Exception($"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}");
throw new RegressionTestException($"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}");
}
}
}
@@ -159,29 +159,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 311879;
public long DataPoints => 311881;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
public int AlgorithmHistoryDataPoints => 2;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "5512.811%"},
{"Drawdown", "1.000%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "105332.8"},
{"Net Profit", "5.333%"},
{"Sharpe Ratio", "64.084"},
{"Sortino Ratio", "0"},
@@ -200,7 +207,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$22000000.00"},
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
{"Portfolio Turnover", "122.11%"},
{"OrderListHash", "679692e30a7cf3b54b09af766589df80"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "d744fa8beaa60546c84924ed68d945d9"}
};
}
}

View File

@@ -40,16 +40,16 @@ namespace QuantConnect.Algorithm.CSharp
});
}
public override void OnData(Slice data)
public override void OnData(Slice slice)
{
if (!_addedOptions)
{
_addedOptions = true;
foreach (var futuresContracts in data.FutureChains.Values)
foreach (var futuresContracts in slice.FutureChains.Values)
{
foreach (var contract in futuresContracts)
{
var option_contract_symbols = OptionChainProvider.GetOptionContractList(contract.Symbol, Time).ToList();
var option_contract_symbols = OptionChain(contract.Symbol).ToList();
if(option_contract_symbols.Count == 0)
{
continue;
@@ -70,7 +70,7 @@ namespace QuantConnect.Algorithm.CSharp
return;
}
foreach (var chain in data.OptionChains.Values)
foreach (var chain in slice.OptionChains.Values)
{
foreach (var option in chain.Contracts.Keys)
{
@@ -88,29 +88,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 12164;
public long DataPoints => 9922;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
public int AlgorithmHistoryDataPoints => 2;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "20"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "386219349.202%"},
{"Compounding Annual Return", "88398927.578%"},
{"Drawdown", "5.200%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "111911.55"},
{"Net Profit", "11.912%"},
{"Sharpe Ratio", "1604181.904"},
{"Sortino Ratio", "0"},
@@ -127,9 +134,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "68696.045"},
{"Total Fees", "$35.70"},
{"Estimated Strategy Capacity", "$2600000.00"},
{"Lowest Capacity Asset", "ES 31C3JQS9D84PW|ES XCZJLC9NOB29"},
{"Lowest Capacity Asset", "ES 31C3JQS9DCF1G|ES XCZJLC9NOB29"},
{"Portfolio Turnover", "495.15%"},
{"OrderListHash", "39179b5e977b8bf5411fbd31896a7953"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "af830085995d0b8fa0d33a6e80dd1241"}
};
}
}

View File

@@ -0,0 +1,145 @@
/*
* 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;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Algorithm asserting AddFutureOptionContract does not throw even when the underlying security configurations are internal
/// </summary>
public class AddFutureOptionContractWithInternalMappedUnderlyingRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Future _continuousContract;
private Option _fopContract;
public override void Initialize()
{
SetStartDate(2020, 01, 04);
SetEndDate(2020, 01 , 06);
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
dataMappingMode: DataMappingMode.LastTradingDay,
contractDepthOffset: 0);
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
if (changes.AddedSecurities.Any(security => security.Symbol == _continuousContract.Symbol))
{
if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_continuousContract.Mapped).Count != 0 ||
SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_continuousContract.Mapped, includeInternalConfigs: true).Count == 0)
{
throw new RegressionTestException("Continuous future underlying should only have internal subscription configs");
}
var contract = OptionChain(_continuousContract.Mapped).FirstOrDefault()?.Symbol;
try
{
_fopContract = AddFutureOptionContract(contract);
}
catch (Exception e)
{
throw new RegressionTestException($"Failed to add future option contract {contract}", e);
}
}
else if (_fopContract != null && changes.AddedSecurities.Any(security => security.Symbol == _fopContract.Symbol))
{
var underlyingSubscriptions = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_fopContract.Symbol.Underlying);
if (underlyingSubscriptions.Any(x => x.DataNormalizationMode == DataNormalizationMode.Raw))
{
throw new RegressionTestException("Future option underlying should not have raw data normalization mode");
}
}
}
public override void OnEndOfAlgorithm()
{
if (_fopContract == null)
{
throw new RegressionTestException("Failed to add future 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 List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 3181;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 1;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino 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", "-14.395"},
{"Tracking Error", "0.043"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -55,10 +55,10 @@ namespace QuantConnect.Algorithm.CSharp
{
_optionFilterRan = true;
var expiry = new HashSet<DateTime>(optionContracts.Select(x => x.Underlying.ID.Date)).SingleOrDefault();
// Cast to IEnumerable<Symbol> because OptionFilterContract overrides some LINQ operators like `Select` and `Where`
var expiry = new HashSet<DateTime>(optionContracts.Select(x => x.Symbol.Underlying.ID.Date)).SingleOrDefault();
// Cast to List<Symbol> because OptionFilterContract overrides some LINQ operators like `Select` and `Where`
// and cause it to mutate the underlying Symbol collection when using those operators.
var symbol = new HashSet<Symbol>(((IEnumerable<Symbol>)optionContracts).Select(x => x.Underlying)).SingleOrDefault();
var symbol = new HashSet<Symbol>(((List<Symbol>)optionContracts).Select(x => x.Underlying)).SingleOrDefault();
if (expiry == null || symbol == null)
{
@@ -75,9 +75,9 @@ namespace QuantConnect.Algorithm.CSharp
});
}
public override void OnData(Slice data)
public override void OnData(Slice slice)
{
if (!data.HasData)
if (!slice.HasData)
{
return;
}
@@ -85,7 +85,7 @@ namespace QuantConnect.Algorithm.CSharp
_onDataReached = true;
var hasOptionQuoteBars = false;
foreach (var qb in data.QuoteBars.Values)
foreach (var qb in slice.QuoteBars.Values)
{
if (qb.Symbol.SecurityType != SecurityType.FutureOption)
{
@@ -108,7 +108,7 @@ namespace QuantConnect.Algorithm.CSharp
return;
}
foreach (var chain in data.OptionChains.Values)
foreach (var chain in slice.OptionChains.Values.OrderBy(x => x.Symbol.Underlying.ID.Date))
{
var futureInvested = false;
var optionInvested = false;
@@ -122,7 +122,7 @@ namespace QuantConnect.Algorithm.CSharp
var future = option.Underlying;
if (!optionInvested && data.ContainsKey(option))
if (!optionInvested && slice.ContainsKey(option))
{
var optionContract = Securities[option];
var marginModel = optionContract.BuyingPowerModel as FuturesOptionsMarginModel;
@@ -131,16 +131,16 @@ namespace QuantConnect.Algorithm.CSharp
|| marginModel.MaintenanceIntradayMarginRequirement == 0
|| marginModel.MaintenanceOvernightMarginRequirement == 0)
{
throw new Exception("Unexpected margin requirements");
throw new RegressionTestException("Unexpected margin requirements");
}
if (marginModel.GetInitialMarginRequirement(optionContract, 1) == 0)
{
throw new Exception("Unexpected Initial Margin requirement");
throw new RegressionTestException("Unexpected Initial Margin requirement");
}
if (marginModel.GetMaintenanceMargin(optionContract) != 0)
{
throw new Exception("Unexpected Maintenance Margin requirement");
throw new RegressionTestException("Unexpected Maintenance Margin requirement");
}
MarketOrder(option, 1);
@@ -149,10 +149,10 @@ namespace QuantConnect.Algorithm.CSharp
if (marginModel.GetMaintenanceMargin(optionContract) == 0)
{
throw new Exception("Unexpected Maintenance Margin requirement");
throw new RegressionTestException("Unexpected Maintenance Margin requirement");
}
}
if (!futureInvested && data.ContainsKey(future))
if (!futureInvested && slice.ContainsKey(future))
{
MarketOrder(future, 1);
_invested = true;
@@ -170,7 +170,7 @@ namespace QuantConnect.Algorithm.CSharp
}
if (!_onDataReached)
{
throw new Exception("OnData() was never called.");
throw new RegressionTestException("OnData() was never called.");
}
if (_symbolsReceived.Count != _expectedSymbolsReceived.Count)
{
@@ -188,7 +188,7 @@ namespace QuantConnect.Algorithm.CSharp
if (missingSymbols.Count > 0)
{
throw new Exception($"Symbols: \"{string.Join(", ", missingSymbols)}\" were not found in OnData");
throw new RegressionTestException($"Symbols: \"{string.Join(", ", missingSymbols)}\" were not found in OnData");
}
foreach (var expectedSymbol in _expectedSymbolsReceived)
@@ -202,7 +202,7 @@ namespace QuantConnect.Algorithm.CSharp
if (nonDupeDataCount < 1000)
{
throw new Exception($"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}");
throw new RegressionTestException($"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}");
}
}
}
@@ -215,48 +215,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 608372;
public long DataPoints => 319494;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "347.065%"},
{"Drawdown", "0.900%"},
{"Compounding Annual Return", "430.834%"},
{"Drawdown", "4.200%"},
{"Expectancy", "0"},
{"Net Profit", "1.951%"},
{"Sharpe Ratio", "15.402"},
{"Start Equity", "100000"},
{"End Equity", "102313.03"},
{"Net Profit", "2.313%"},
{"Sharpe Ratio", "17.721"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "95.977%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.886"},
{"Beta", "1.066"},
{"Annual Standard Deviation", "0.155"},
{"Annual Variance", "0.024"},
{"Information Ratio", "13.528"},
{"Tracking Error", "0.142"},
{"Treynor Ratio", "2.237"},
{"Alpha", "2.663"},
{"Beta", "1.264"},
{"Annual Standard Deviation", "0.184"},
{"Annual Variance", "0.034"},
{"Information Ratio", "16.514"},
{"Tracking Error", "0.169"},
{"Treynor Ratio", "2.574"},
{"Total Fees", "$3.57"},
{"Estimated Strategy Capacity", "$760000.00"},
{"Lowest Capacity Asset", "ES XCZJLDQX2SRO|ES XCZJLC9NOB29"},
{"Portfolio Turnover", "32.31%"},
{"OrderListHash", "b508146aff4ac449e9c6f502928e2115"}
{"Estimated Strategy Capacity", "$28000000.00"},
{"Lowest Capacity Asset", "ES XCZJLCA62LNO|ES XCZJLC9NOB29"},
{"Portfolio Turnover", "33.84%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "7c82013ecabca41591e0253a477025dd"}
};
}
}

View File

@@ -0,0 +1,131 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Interfaces;
using System;
using QuantConnect.Securities;
using QuantConnect.Data.UniverseSelection;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to use the FutureUniverseSelectionModel to select futures contracts for a given underlying asset.
/// The model is set to update daily, and the algorithm ensures that the selected contracts meet specific criteria.
/// This also includes a check to ensure that only future contracts are added to the algorithm's universe.
/// </summary>
public class AddFutureUniverseSelectionModelRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 10);
SetUniverseSelection(new FutureUniverseSelectionModel(
TimeSpan.FromDays(1),
time => new List<Symbol> {
QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME)
}
));
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
if (changes.AddedSecurities.Count > 0)
{
foreach (var security in changes.AddedSecurities)
{
if (security.Symbol.SecurityType != SecurityType.Future)
{
throw new RegressionTestException($"Expected future security, but found '{security.Symbol.SecurityType}'");
}
if (security.Symbol.ID.Symbol != "ES")
{
throw new RegressionTestException($"Expected future symbol 'ES', but found '{security.Symbol.ID.Symbol}");
}
}
}
}
public override void OnEndOfAlgorithm()
{
if (ActiveSecurities.Count == 0)
{
throw new RegressionTestException("No active securities found. Expected at least one active security");
}
}
/// <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 List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 26094;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-66.775"},
{"Tracking Error", "0.243"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -42,12 +42,12 @@ namespace QuantConnect.Algorithm.CSharp
AddUniverse("my-daily-universe-name", time => new List<string> { "AAPL" });
}
public override void OnData(Slice data)
public override void OnData(Slice slice)
{
if (_option == null)
{
var option = OptionChainProvider.GetOptionContractList(_twx, Time)
.OrderBy(symbol => symbol.ID.Symbol)
var option = OptionChain(_twx)
.OrderBy(x => x.ID.Symbol)
.FirstOrDefault(optionContract => optionContract.ID.Date == _expiration
&& optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American);
@@ -68,11 +68,11 @@ namespace QuantConnect.Algorithm.CSharp
if (!config.Any())
{
throw new Exception($"Was expecting configurations for {symbol}");
throw new RegressionTestException($"Was expecting configurations for {symbol}");
}
if (config.Any(dataConfig => dataConfig.DataNormalizationMode != DataNormalizationMode.Raw))
{
throw new Exception($"Was expecting DataNormalizationMode.Raw configurations for {symbol}");
throw new RegressionTestException($"Was expecting DataNormalizationMode.Raw configurations for {symbol}");
}
}
}
@@ -81,14 +81,14 @@ namespace QuantConnect.Algorithm.CSharp
{
if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_option).Any())
{
throw new Exception($"Unexpected configurations for {_option} after it has been delisted");
throw new RegressionTestException($"Unexpected configurations for {_option} after it has been delisted");
}
if (Securities[_twx].Invested)
{
if (!SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_twx).Any())
{
throw new Exception($"Was expecting configurations for {_twx}");
throw new RegressionTestException($"Was expecting configurations for {_twx}");
}
// first we liquidate the option exercised position
@@ -99,7 +99,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_twx).Any())
{
throw new Exception($"Unexpected configurations for {_twx} after it has been liquidated");
throw new RegressionTestException($"Unexpected configurations for {_twx} after it has been liquidated");
}
}
}
@@ -112,29 +112,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 37597;
public long DataPoints => 37598;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
public int AlgorithmHistoryDataPoints => 1;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "3"},
{"Average Win", "2.73%"},
{"Average Loss", "-2.98%"},
{"Compounding Annual Return", "-4.619%"},
{"Drawdown", "0.300%"},
{"Expectancy", "-0.042"},
{"Start Equity", "100000"},
{"End Equity", "99668"},
{"Net Profit", "-0.332%"},
{"Sharpe Ratio", "-4.614"},
{"Sortino Ratio", "0"},
@@ -151,9 +158,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "2.01"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$5700000.00"},
{"Lowest Capacity Asset", "AOL VRKS95ENLBYE|AOL R735QTJ8XC9X"},
{"Lowest Capacity Asset", "AOL VRKS95ENPM9Y|AOL R735QTJ8XC9X"},
{"Portfolio Turnover", "0.55%"},
{"OrderListHash", "402c66beb5c96b2f2ae357c49e890dc5"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "d314aef81752b6583fd58f9e49054cd4"}
};
}
}

View File

@@ -13,12 +13,12 @@
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
namespace QuantConnect.Algorithm.CSharp
{
@@ -50,7 +50,7 @@ namespace QuantConnect.Algorithm.CSharp
enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl });
}
public override void OnData(Slice data)
public override void OnData(Slice slice)
{
if (_option != null && Securities[_option].Price != 0 && !_traded)
{
@@ -66,7 +66,7 @@ namespace QuantConnect.Algorithm.CSharp
// assert underlying still there after the universe selection removed it, still used by the manually added option contract
if (!configs.Any())
{
throw new Exception($"Was expecting configurations for {_twx}" +
throw new RegressionTestException($"Was expecting configurations for {_twx}" +
$" even after it has been deselected from coarse universe because we still have the option contract.");
}
}
@@ -83,7 +83,7 @@ namespace QuantConnect.Algorithm.CSharp
var configs = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol);
if (configs.Any())
{
throw new Exception($"Unexpected configuration for {symbol} after it has been deselected from coarse universe and option contract is removed.");
throw new RegressionTestException($"Unexpected configuration for {symbol} after it has been deselected from coarse universe and option contract is removed.");
}
}
}
@@ -94,11 +94,11 @@ namespace QuantConnect.Algorithm.CSharp
{
if (_securityChanges.RemovedSecurities.Intersect(changes.RemovedSecurities).Any())
{
throw new Exception($"SecurityChanges.RemovedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!");
throw new RegressionTestException($"SecurityChanges.RemovedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!");
}
if (_securityChanges.AddedSecurities.Intersect(changes.AddedSecurities).Any())
{
throw new Exception($"SecurityChanges.AddedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!");
throw new RegressionTestException($"SecurityChanges.AddedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!");
}
// keep track of all removed and added securities
_securityChanges += changes;
@@ -110,24 +110,24 @@ namespace QuantConnect.Algorithm.CSharp
foreach (var addedSecurity in changes.AddedSecurities)
{
var option = OptionChainProvider.GetOptionContractList(addedSecurity.Symbol, Time)
.OrderBy(symbol => symbol.ID.Symbol)
var option = OptionChain(addedSecurity.Symbol)
.OrderBy(contractData => contractData.ID.Symbol)
.First(optionContract => optionContract.ID.Date == _expiration
&& optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American);
AddOptionContract(option);
foreach (var symbol in new[] { option, option.Underlying })
foreach (var symbol in new[] { option.Symbol, option.UnderlyingSymbol })
{
var config = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol).ToList();
if (!config.Any())
{
throw new Exception($"Was expecting configurations for {symbol}");
throw new RegressionTestException($"Was expecting configurations for {symbol}");
}
if (config.Any(dataConfig => dataConfig.DataNormalizationMode != DataNormalizationMode.Raw))
{
throw new Exception($"Was expecting DataNormalizationMode.Raw configurations for {symbol}");
throw new RegressionTestException($"Was expecting DataNormalizationMode.Raw configurations for {symbol}");
}
}
@@ -143,16 +143,16 @@ namespace QuantConnect.Algorithm.CSharp
{
if (SubscriptionManager.Subscriptions.Any(dataConfig => dataConfig.Symbol == _twx || dataConfig.Symbol.Underlying == _twx))
{
throw new Exception($"Was NOT expecting any configurations for {_twx} or it's options, since we removed the contract");
throw new RegressionTestException($"Was NOT expecting any configurations for {_twx} or it's options, since we removed the contract");
}
if (SubscriptionManager.Subscriptions.All(dataConfig => dataConfig.Symbol != _aapl))
{
throw new Exception($"Was expecting configurations for {_aapl}");
throw new RegressionTestException($"Was expecting configurations for {_aapl}");
}
if (SubscriptionManager.Subscriptions.All(dataConfig => dataConfig.Symbol.Underlying != _aapl))
{
throw new Exception($"Was expecting options configurations for {_aapl}");
throw new RegressionTestException($"Was expecting options configurations for {_aapl}");
}
}
@@ -164,29 +164,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 5798;
public long DataPoints => 5800;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
public int AlgorithmHistoryDataPoints => 2;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.23%"},
{"Compounding Annual Return", "-15.596%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "99768"},
{"Net Profit", "-0.232%"},
{"Sharpe Ratio", "-8.903"},
{"Sortino Ratio", "0"},
@@ -203,9 +210,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0.335"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$2800000.00"},
{"Lowest Capacity Asset", "AOL VRKS95ENLBYE|AOL R735QTJ8XC9X"},
{"Lowest Capacity Asset", "AOL VRKS95ENPM9Y|AOL R735QTJ8XC9X"},
{"Portfolio Turnover", "1.14%"},
{"OrderListHash", "99fd501dbd9e78656be9b32869fc32e0"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "e33b98d8e94ed92d0441fc6fe0d461fb"}
};
}
}

View File

@@ -39,12 +39,12 @@ namespace QuantConnect.Algorithm.CSharp
UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero;
UniverseSettings.FillForward = false;
AddEquity("SPY", Resolution.Daily);
AddEquity("SPY", Resolution.Hour);
var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
_contract = OptionChainProvider.GetOptionContractList(aapl, Time)
.OrderBy(symbol => symbol.ID.Symbol)
_contract = OptionChain(aapl)
.OrderBy(x => x.ID.StrikePrice)
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American);
AddOptionContract(_contract);
@@ -56,7 +56,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!_reAdded && slice.ContainsKey(_contract) && slice.ContainsKey(_contract.Underlying))
{
throw new Exception("Getting data for removed option and underlying!");
throw new RegressionTestException("Getting data for removed option and underlying!");
}
if (!Portfolio.Invested && _reAdded)
@@ -95,11 +95,11 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!_hasRemoved)
{
throw new Exception("We did not remove the option contract!");
throw new RegressionTestException("We did not remove the option contract!");
}
if (!_reAdded)
{
throw new Exception("We did not re add the option contract!");
throw new RegressionTestException("We did not re add the option contract!");
}
}
@@ -111,30 +111,37 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 4677;
public long DataPoints => 3818;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
public int AlgorithmHistoryDataPoints => 1;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.05%"},
{"Compounding Annual Return", "-4.548%"},
{"Drawdown", "0.100%"},
{"Average Loss", "-0.50%"},
{"Compounding Annual Return", "-39.406%"},
{"Drawdown", "0.700%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.051%"},
{"Start Equity", "100000"},
{"End Equity", "99498"},
{"Net Profit", "-0.502%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
@@ -149,10 +156,11 @@ namespace QuantConnect.Algorithm.CSharp
{"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", "b01a993665c5333c37de9dbef0717e14"}
{"Estimated Strategy Capacity", "$5000000.00"},
{"Lowest Capacity Asset", "AAPL VXBK4R62H7S6|AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "22.70%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "71511e4929377cd55fbf5e7e9555c248"}
};
}
}

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.Collections.Generic;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Interfaces;
using System;
using QuantConnect.Data.UniverseSelection;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to use the OptionUniverseSelectionModel to select options contracts based on specified conditions.
/// The model is updated daily and selects different options based on the current date.
/// The algorithm ensures that only valid option contracts are selected for the universe.
/// </summary>
public class AddOptionUniverseSelectionModelRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private int _optionCount;
public override void Initialize()
{
SetStartDate(2014, 06, 05);
SetEndDate(2014, 06, 06);
UniverseSettings.Resolution = Resolution.Minute;
SetUniverseSelection(new OptionUniverseSelectionModel(
TimeSpan.FromDays(1),
SelectOptionChainSymbols
));
}
private static IEnumerable<Symbol> SelectOptionChainSymbols(DateTime utcTime)
{
var newYorkTime = utcTime.ConvertFromUtc(TimeZones.NewYork);
if (newYorkTime.Date < new DateTime(2014, 06, 06))
{
yield return QuantConnect.Symbol.Create("TWX", SecurityType.Option, Market.USA);
}
if (newYorkTime.Date >= new DateTime(2014, 06, 06))
{
yield return QuantConnect.Symbol.Create("AAPL", SecurityType.Option, Market.USA);
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
if (changes.AddedSecurities.Count > 0)
{
foreach (var security in changes.AddedSecurities)
{
var symbol = security.Symbol.Underlying == null ? security.Symbol : security.Symbol.Underlying;
if (symbol != "AAPL" && symbol != "TWX")
{
throw new RegressionTestException($"Unexpected security {security.Symbol}");
}
_optionCount += (security.Symbol.SecurityType == SecurityType.Option) ? 1 : 0;
}
}
}
public override void OnEndOfAlgorithm()
{
if (ActiveSecurities.Count == 0)
{
throw new RegressionTestException("No active securities found. Expected at least one active security");
}
if (_optionCount == 0)
{
throw new RegressionTestException("The option count should be greater than 0");
}
}
/// <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 List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 2349547;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino 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%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -13,7 +13,6 @@
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data.UniverseSelection;
@@ -59,19 +58,9 @@ namespace QuantConnect.Algorithm.CSharp
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 =>
if (Time != Time.Date)
{
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");
throw new RegressionTestException($"Expected options filter to be run only at midnight. Actual was {Time}");
}
}
@@ -83,29 +72,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all time slices of algorithm
/// </summary>
public long DataPoints => 5952220;
public long DataPoints => 470217;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -124,6 +120,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}

View File

@@ -29,20 +29,21 @@ namespace QuantConnect.Algorithm.CSharp
public class AddRemoveOptionUniverseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "GOOG";
public readonly Symbol Underlying = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Equity, Market.USA);
public readonly Symbol OptionChainSymbol = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Option, Market.USA);
private readonly Symbol Underlying = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Equity, Market.USA);
private readonly Symbol OptionChainSymbol = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Option, Market.USA);
private readonly HashSet<Symbol> _expectedSecurities = new HashSet<Symbol>();
private readonly HashSet<Symbol> _expectedData = new HashSet<Symbol>();
private readonly HashSet<Symbol> _expectedUniverses = new HashSet<Symbol>();
private bool _expectUniverseSubscription;
private DateTime _universeSubscriptionTime;
// order of expected contract additions as price moves
private int _expectedContractIndex;
private readonly List<Symbol> _expectedContracts = new List<Symbol>
{
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00747500"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00750000"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00752500")
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00752500"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00755000")
};
public override void Initialize()
@@ -59,16 +60,16 @@ namespace QuantConnect.Algorithm.CSharp
_expectedUniverses.Add(UserDefinedUniverse.CreateSymbol(SecurityType.Equity, Market.USA));
}
public override void OnData(Slice data)
public override void OnData(Slice slice)
{
// verify expectations
if (SubscriptionManager.Subscriptions.Count(x => x.Symbol == OptionChainSymbol)
!= (_expectUniverseSubscription ? 1 : 0))
{
Log($"SubscriptionManager.Subscriptions: {string.Join(" -- ", SubscriptionManager.Subscriptions)}");
throw new Exception($"Unexpected {OptionChainSymbol} subscription presence");
throw new RegressionTestException($"Unexpected {OptionChainSymbol} subscription presence");
}
if (!data.ContainsKey(Underlying))
if (Time != _universeSubscriptionTime && !slice.ContainsKey(Underlying))
{
// TODO : In fact, we're unable to properly detect whether or not we auto-added or it was manually added
// this is because when we auto-add the underlying we don't mark it as an internal security like we do with other auto adds
@@ -77,42 +78,42 @@ namespace QuantConnect.Algorithm.CSharp
// of the internal flag's purpose, so kicking this issue for now with a big fat note here about it :) to be considerd for any future
// refactorings of how we manage subscription/security data and track various aspects about the security (thinking a flags enum with
// things like manually added, auto added, internal, and any other boolean state we need to track against a single security)
throw new Exception("The underlying equity data should NEVER be removed in this algorithm because it was manually added");
throw new RegressionTestException("The underlying equity data should NEVER be removed in this algorithm because it was manually added");
}
if (_expectedSecurities.AreDifferent(Securities.Total.Select(x => x.Symbol).ToHashSet()))
{
var expected = string.Join(Environment.NewLine, _expectedSecurities.OrderBy(s => s.ToString()));
var actual = string.Join(Environment.NewLine, Securities.Keys.OrderBy(s => s.ToString()));
throw new Exception($"{Time}:: Detected differences in expected and actual securities{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
throw new RegressionTestException($"{Time}:: Detected differences in expected and actual securities{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
}
if (_expectedUniverses.AreDifferent(UniverseManager.Keys.ToHashSet()))
{
var expected = string.Join(Environment.NewLine, _expectedUniverses.OrderBy(s => s.ToString()));
var actual = string.Join(Environment.NewLine, UniverseManager.Keys.OrderBy(s => s.ToString()));
throw new Exception($"{Time}:: Detected differences in expected and actual universes{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
throw new RegressionTestException($"{Time}:: Detected differences in expected and actual universes{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
}
if (_expectedData.AreDifferent(data.Keys.ToHashSet()))
if (Time != _universeSubscriptionTime && _expectedData.AreDifferent(slice.Keys.ToHashSet()))
{
var expected = string.Join(Environment.NewLine, _expectedData.OrderBy(s => s.ToString()));
var actual = string.Join(Environment.NewLine, data.Keys.OrderBy(s => s.ToString()));
throw new Exception($"{Time}:: Detected differences in expected and actual slice data keys{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
var actual = string.Join(Environment.NewLine, slice.Keys.OrderBy(s => s.ToString()));
throw new RegressionTestException($"{Time}:: Detected differences in expected and actual slice data keys{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
}
// 10AM add GOOG option chain
if (Time.TimeOfDay.Hours == 10 && Time.TimeOfDay.Minutes == 0)
if (Time.TimeOfDay.Hours == 10 && Time.TimeOfDay.Minutes == 0 && !_expectUniverseSubscription)
{
if (Securities.ContainsKey(OptionChainSymbol))
{
throw new Exception("The option chain security should not have been added yet");
throw new RegressionTestException("The option chain security should not have been added yet");
}
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)
if (u.LocalTime.Hour < 10)
{
throw new Exception($"Unexpected underlying data point {u.Underlying.EndTime} {u.Underlying}");
throw new RegressionTestException($"Unexpected selection time {u.LocalTime}");
}
// find first put above market price
return u.IncludeWeeklys()
@@ -124,6 +125,7 @@ namespace QuantConnect.Algorithm.CSharp
_expectedSecurities.Add(OptionChainSymbol);
_expectedUniverses.Add(OptionChainSymbol);
_expectUniverseSubscription = true;
_universeSubscriptionTime = Time;
}
// 11:30AM remove GOOG option chain
@@ -151,7 +153,7 @@ namespace QuantConnect.Algorithm.CSharp
var expectedContract = _expectedContracts[_expectedContractIndex];
if (added.Symbol != expectedContract)
{
throw new Exception($"Expected option contract {expectedContract} to be added but received {added.Symbol}");
throw new RegressionTestException($"Expected option contract {expectedContract.Value} to be added but received {added.Symbol}");
}
_expectedContractIndex++;
@@ -172,7 +174,7 @@ namespace QuantConnect.Algorithm.CSharp
// receive removed event next timestep at 11:31AM
if (Time.TimeOfDay.Hours != 11 || Time.TimeOfDay.Minutes != 31)
{
throw new Exception($"Expected option contracts to be removed at 11:31AM, instead removed at: {Time}");
throw new RegressionTestException($"Expected option contracts to be removed at 11:31AM, instead removed at: {Time}");
}
if (changes.RemovedSecurities
@@ -180,13 +182,13 @@ namespace QuantConnect.Algorithm.CSharp
.ToHashSet(s => s.Symbol)
.AreDifferent(_expectedContracts.ToHashSet()))
{
throw new Exception("Expected removed securities to equal expected contracts added");
throw new RegressionTestException("Expected removed securities to equal expected contracts added");
}
}
if (Securities.ContainsKey(Underlying))
{
Console.WriteLine($"{Time:o}:: PRICE:: {Securities[Underlying].Price} CHANGES:: {changes}");
Log($"{Time:o}:: PRICE:: {Securities[Underlying].Price} CHANGES:: {changes}");
}
}
@@ -198,29 +200,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 200807;
public long DataPoints => 3502;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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", "6"},
{"Total Orders", "6"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "98784"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -236,10 +245,11 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$6.00"},
{"Estimated Strategy Capacity", "$3000.00"},
{"Lowest Capacity Asset", "GOOCV 305RBR0BSWIX2|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "1.49%"},
{"OrderListHash", "3adcc7ebf4153baabb073a8152e8cb2b"}
{"Estimated Strategy Capacity", "$4000.00"},
{"Lowest Capacity Asset", "GOOCV 305RBQ2BZGA4M|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "2.58%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "f418de0673fc166487daf80991dfe3a0"}
};
}
}

View File

@@ -41,8 +41,8 @@ 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)
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
@@ -59,9 +59,9 @@ namespace QuantConnect.Algorithm.CSharp
var ticket = MarketOrder("AIG", 1);
if (ticket.Status != OrderStatus.Invalid)
if (ticket.Status != OrderStatus.Invalid || aig.HasData || aig.Price != 0)
{
throw new Exception("Expected order to always be invalid because there is no data yet!");
throw new RegressionTestException("Expected order to always be invalid because there is no data yet!");
}
}
else
@@ -78,29 +78,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 11202;
public long DataPoints => 15042;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "19"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "271.720%"},
{"Drawdown", "2.500%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "101753.84"},
{"Net Profit", "1.754%"},
{"Sharpe Ratio", "11.954"},
{"Sortino Ratio", "29.606"},
@@ -119,7 +126,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$830000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "20.49%"},
{"OrderListHash", "48d8e1195003665a2febf547c075d07f"}
{"Drawdown Recovery", "2"},
{"OrderListHash", "6ebe462373e2ecc22de8eb2fe114d704"}
};
}
}

View File

@@ -18,6 +18,7 @@ using System.Collections.Generic;
using QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Data;
namespace QuantConnect.Algorithm.CSharp
{
@@ -51,7 +52,7 @@ namespace QuantConnect.Algorithm.CSharp
/// 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 void OnData(TradeBars data)
public override void OnData(Slice slice)
{
if (lastAction.Date == Time.Date) return;
@@ -104,29 +105,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 7063;
public long DataPoints => 7065;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "5"},
{"Total Orders", "5"},
{"Average Win", "0.46%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "296.356%"},
{"Drawdown", "1.400%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "101776.32"},
{"Net Profit", "1.776%"},
{"Sharpe Ratio", "12.966"},
{"Sortino Ratio", "0"},
@@ -145,7 +153,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$4700000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Portfolio Turnover", "29.88%"},
{"OrderListHash", "b26f2f30082b754b065c41bb0ace44cc"}
{"Drawdown Recovery", "2"},
{"OrderListHash", "f04b3521256c7d6740966bc3df34e7b1"}
};
}
}

View File

@@ -57,7 +57,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -69,17 +69,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "3"},
{"Average Win", "1.02%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "296.066%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "101775.37"},
{"Net Profit", "1.775%"},
{"Sharpe Ratio", "9.34"},
{"Sortino Ratio", "0"},
@@ -98,7 +105,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$38000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "59.74%"},
{"OrderListHash", "b5a7935f37d94eb20f6bcd88578dbaee"}
{"Drawdown Recovery", "3"},
{"OrderListHash", "5d7657ec9954875eca633bed711085d3"}
};
}
}

View File

@@ -41,8 +41,8 @@ namespace QuantConnect.Algorithm.CSharp
var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
var contracts = OptionChainProvider.GetOptionContractList(aapl, Time)
.OrderBy(symbol => symbol.ID.Symbol)
var contracts = OptionChain(aapl)
.OrderBy(x => x.ID.StrikePrice)
.Where(optionContract => optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American)
.Take(2)
@@ -69,7 +69,7 @@ namespace QuantConnect.Algorithm.CSharp
SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs("AAPL");
if (subscriptions.Count == 0)
{
throw new Exception("No configuration for underlying was found!");
throw new RegressionTestException("No configuration for underlying was found!");
}
if (!Portfolio.Invested)
@@ -84,7 +84,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!_hasRemoved)
{
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
throw new RegressionTestException("Expect a single call to OnData where we removed the option and underlying");
}
}
@@ -96,29 +96,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1578;
public long DataPoints => 1579;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
public int AlgorithmHistoryDataPoints => 1;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "99238"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -134,10 +141,11 @@ namespace QuantConnect.Algorithm.CSharp
{"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", "afec48c499382b1d01af22daafe9f648"}
{"Estimated Strategy Capacity", "$6200000.00"},
{"Lowest Capacity Asset", "AAPL VXBK4QA5IWKM|AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "90.27%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "a332b93ff5e2dfe89258c450a64c7125"}
};
}
}

View File

@@ -57,14 +57,14 @@ namespace QuantConnect.Algorithm.CSharp
{
if (UniverseManager.Count != 3)
{
throw new Exception("Unexpected universe count");
throw new RegressionTestException("Unexpected universe count");
}
if (UniverseManager.ActiveSecurities.Count != 3
|| UniverseManager.ActiveSecurities.Keys.All(symbol => symbol.Value != "SPY")
|| UniverseManager.ActiveSecurities.Keys.All(symbol => symbol.Value != "AAPL")
|| UniverseManager.ActiveSecurities.Keys.All(symbol => symbol.Value != "FB"))
{
throw new Exception("Unexpected active securities");
throw new RegressionTestException("Unexpected active securities");
}
}
@@ -76,48 +76,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 53;
public long DataPoints => 50;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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", "10"},
{"Average Win", "0%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-14.233%"},
{"Drawdown", "3.300%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.168%"},
{"Sharpe Ratio", "62.464"},
{"Total Orders", "6"},
{"Average Win", "0.01%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "1296.838%"},
{"Drawdown", "0.400%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "102684.23"},
{"Net Profit", "2.684%"},
{"Sharpe Ratio", "34.319"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.117"},
{"Beta", "1.19"},
{"Annual Standard Deviation", "0.213"},
{"Annual Variance", "0.046"},
{"Information Ratio", "70.778"},
{"Tracking Error", "0.043"},
{"Treynor Ratio", "11.2"},
{"Total Fees", "$22.21"},
{"Estimated Strategy Capacity", "$340000000.00"},
{"Alpha", "-5.738"},
{"Beta", "1.381"},
{"Annual Standard Deviation", "0.246"},
{"Annual Variance", "0.06"},
{"Information Ratio", "-26.937"},
{"Tracking Error", "0.068"},
{"Treynor Ratio", "6.106"},
{"Total Fees", "$18.61"},
{"Estimated Strategy Capacity", "$980000000.00"},
{"Lowest Capacity Asset", "FB V6OIPNZEM8V9"},
{"Portfolio Turnover", "26.92%"},
{"OrderListHash", "be09b39c5d01b0694f474ea7f7c5ae09"}
{"Portfolio Turnover", "25.56%"},
{"Drawdown Recovery", "1"},
{"OrderListHash", "5ee20c8556d706ab0a63ae41b6579c62"}
};
}
}

View File

@@ -68,14 +68,14 @@ namespace QuantConnect.Algorithm.CSharp
{
if (UniverseManager.Count != 3)
{
throw new Exception("Unexpected universe count");
throw new RegressionTestException("Unexpected universe count");
}
if (UniverseManager.ActiveSecurities.Count != 3
|| UniverseManager.ActiveSecurities.Keys.All(symbol => symbol.Value != "SPY")
|| UniverseManager.ActiveSecurities.Keys.All(symbol => symbol.Value != "AAPL")
|| UniverseManager.ActiveSecurities.Keys.All(symbol => symbol.Value != "FB"))
{
throw new Exception("Unexpected active securities");
throw new RegressionTestException("Unexpected active securities");
}
}
@@ -87,48 +87,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 234018;
public long DataPoints => 234015;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "21"},
{"Average Win", "0.00%"},
{"Total Orders", "21"},
{"Average Win", "0.01%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-75.275%"},
{"Drawdown", "5.800%"},
{"Expectancy", "-0.609"},
{"Net Profit", "-5.581%"},
{"Sharpe Ratio", "-3.288"},
{"Sortino Ratio", "-3.828"},
{"Probabilistic Sharpe Ratio", "5.546%"},
{"Loss Rate", "73%"},
{"Win Rate", "27%"},
{"Profit-Loss Ratio", "0.43"},
{"Alpha", "-0.495"},
{"Beta", "1.484"},
{"Annual Standard Deviation", "0.196"},
{"Annual Variance", "0.039"},
{"Information Ratio", "-3.843"},
{"Tracking Error", "0.141"},
{"Treynor Ratio", "-0.435"},
{"Total Fees", "$31.25"},
{"Estimated Strategy Capacity", "$550000000.00"},
{"Compounding Annual Return", "-77.566%"},
{"Drawdown", "6.000%"},
{"Expectancy", "-0.811"},
{"Start Equity", "100000"},
{"End Equity", "94042.73"},
{"Net Profit", "-5.957%"},
{"Sharpe Ratio", "-3.345"},
{"Sortino Ratio", "-3.766"},
{"Probabilistic Sharpe Ratio", "4.557%"},
{"Loss Rate", "89%"},
{"Win Rate", "11%"},
{"Profit-Loss Ratio", "0.70"},
{"Alpha", "-0.519"},
{"Beta", "1.491"},
{"Annual Standard Deviation", "0.2"},
{"Annual Variance", "0.04"},
{"Information Ratio", "-3.878"},
{"Tracking Error", "0.147"},
{"Treynor Ratio", "-0.449"},
{"Total Fees", "$29.11"},
{"Estimated Strategy Capacity", "$680000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "7.33%"},
{"OrderListHash", "b2ec2148ac94b67038a5bb4a2655f0a6"}
{"Portfolio Turnover", "7.48%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "2c814c55e7d7c56482411c065b861b33"}
};
}
}

View File

@@ -63,21 +63,21 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
SetHoldings(_aapl, 1);
}
if (data.Splits.ContainsKey(_aapl))
if (slice.Splits.ContainsKey(_aapl))
{
Log(data.Splits[_aapl].ToString());
Log(slice.Splits[_aapl].ToString());
}
if (data.Bars.ContainsKey(_aapl))
if (slice.Bars.ContainsKey(_aapl))
{
var aaplData = data.Bars[_aapl];
var aaplData = slice.Bars[_aapl];
// Assert our volume matches what we expect
if (_expectedAdjustedVolume.MoveNext() && _expectedAdjustedVolume.Current != aaplData.Volume)
@@ -99,9 +99,9 @@ namespace QuantConnect.Algorithm.CSharp
}
}
if (data.QuoteBars.ContainsKey(_aapl))
if (slice.QuoteBars.ContainsKey(_aapl))
{
var aaplQuoteData = data.QuoteBars[_aapl];
var aaplQuoteData = slice.QuoteBars[_aapl];
// Assert our askSize matches what we expect
if (_expectedAdjustedAskSize.MoveNext() && _expectedAdjustedAskSize.Current != aaplQuoteData.LastAskSize)
@@ -151,7 +151,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -163,17 +163,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100146.57"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -192,7 +199,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$42000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "99.56%"},
{"OrderListHash", "92cacc8a537ff29960b6d092c3f92cf1"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "60f03c8c589a4f814dc4e8945df23207"}
};
}
}

View File

@@ -34,25 +34,25 @@ namespace QuantConnect.Algorithm.CSharp
if (AlgorithmMode != AlgorithmMode.Backtesting)
{
throw new Exception($"Algorithm mode is not backtesting. Actual: {AlgorithmMode}");
throw new RegressionTestException($"Algorithm mode is not backtesting. Actual: {AlgorithmMode}");
}
if (LiveMode)
{
throw new Exception("Algorithm should not be live");
throw new RegressionTestException("Algorithm should not be live");
}
if (DeploymentTarget != DeploymentTarget.LocalPlatform)
{
throw new Exception($"Algorithm deployment target is not local. Actual{DeploymentTarget}");
throw new RegressionTestException($"Algorithm deployment target is not local. Actual{DeploymentTarget}");
}
// For a live deployment these checks should pass:
//if (AlgorithmMode != AlgorithmMode.Live) throw new Exception("Algorithm mode is not live");
//if (!LiveMode) throw new Exception("Algorithm should be live");
//if (AlgorithmMode != AlgorithmMode.Live) throw new RegressionTestException("Algorithm mode is not live");
//if (!LiveMode) throw new RegressionTestException("Algorithm should be live");
// For a cloud deployment these checks should pass:
//if (DeploymentTarget != DeploymentTarget.CloudPlatform) throw new Exception("Algorithm deployment target is not cloud");
//if (DeploymentTarget != DeploymentTarget.CloudPlatform) throw new RegressionTestException("Algorithm deployment target is not cloud");
Quit();
}
@@ -65,7 +65,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -77,17 +77,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -106,6 +113,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}

View File

@@ -100,27 +100,25 @@ namespace QuantConnect.Algorithm.CSharp
SetBrokerageModel(new AllShortableSymbolsRegressionAlgorithmBrokerageModel());
}
public override void OnData(Slice data)
public override void OnData(Slice slice)
{
if (Time.Date == _lastTradeDate)
{
return;
}
foreach (var symbol in ActiveSecurities.Keys.OrderBy(symbol => symbol))
foreach (var (symbol, security) in ActiveSecurities.Where(kvp => !kvp.Value.Invested).OrderBy(kvp => kvp.Key))
{
if (!Portfolio.ContainsKey(symbol) || !Portfolio[symbol].Invested)
var shortableQuantity = security.ShortableProvider.ShortableQuantity(symbol, Time);
if (shortableQuantity == null)
{
if (!Shortable(symbol))
{
throw new Exception($"Expected {symbol} to be shortable on {Time:yyyy-MM-dd}");
}
// Buy at least once into all Symbols. Since daily data will always use
// MOO orders, it makes the testing of liquidating buying into Symbols difficult.
MarketOrder(symbol, -(decimal)ShortableQuantity(symbol));
_lastTradeDate = Time.Date;
throw new RegressionTestException($"Expected {symbol} to be shortable on {Time:yyyy-MM-dd}");
}
// Buy at least once into all Symbols. Since daily data will always use
// MOO orders, it makes the testing of liquidating buying into Symbols difficult.
MarketOrder(symbol, -(decimal)shortableQuantity);
_lastTradeDate = Time.Date;
}
}
@@ -139,11 +137,11 @@ namespace QuantConnect.Algorithm.CSharp
var gme = QuantConnect.Symbol.Create("GME", SecurityType.Equity, Market.USA);
if (!shortableSymbols.ContainsKey(gme))
{
throw new Exception("Expected unmapped GME in shortable symbols list on 2014-03-27");
throw new RegressionTestException("Expected unmapped GME in shortable symbols list on 2014-03-27");
}
if (!coarse.Select(x => x.Symbol.Value).Contains("GME"))
{
throw new Exception("Expected mapped GME in coarse symbols on 2014-03-27");
throw new RegressionTestException("Expected mapped GME in coarse symbols on 2014-03-27");
}
expectedMissing = 1;
@@ -152,7 +150,7 @@ namespace QuantConnect.Algorithm.CSharp
var missing = _expectedSymbols[Time.Date].Except(selectedSymbols).ToList();
if (missing.Count != expectedMissing)
{
throw new Exception($"Expected Symbols selected on {Time.Date:yyyy-MM-dd} to match expected Symbols, but the following Symbols were missing: {string.Join(", ", missing.Select(s => s.ToString()))}");
throw new RegressionTestException($"Expected Symbols selected on {Time.Date:yyyy-MM-dd} to match expected Symbols, but the following Symbols were missing: {string.Join(", ", missing.Select(s => s.ToString()))}");
}
_coarseSelected[Time.Date] = true;
@@ -235,48 +233,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp};
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 37754;
public long DataPoints => 36573;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "5"},
{"Total Orders", "8"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "19.147%"},
{"Drawdown", "0%"},
{"Compounding Annual Return", "11.027%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0"},
{"Net Profit", "0.192%"},
{"Sharpe Ratio", "221.176"},
{"Start Equity", "10000000"},
{"End Equity", "10011469.88"},
{"Net Profit", "0.115%"},
{"Sharpe Ratio", "11.963"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.156"},
{"Beta", "-0.007"},
{"Annual Standard Deviation", "0.001"},
{"Alpha", "0.07"},
{"Beta", "-0.077"},
{"Annual Standard Deviation", "0.008"},
{"Annual Variance", "0"},
{"Information Ratio", "4.804"},
{"Tracking Error", "0.098"},
{"Treynor Ratio", "-21.505"},
{"Total Fees", "$307.50"},
{"Estimated Strategy Capacity", "$2600000.00"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "10.61%"},
{"OrderListHash", "9c129e856afe96579b52cbfe95237100"}
{"Information Ratio", "3.876"},
{"Tracking Error", "0.105"},
{"Treynor Ratio", "-1.215"},
{"Total Fees", "$282.50"},
{"Estimated Strategy Capacity", "$61000000000.00"},
{"Lowest Capacity Asset", "NB R735QTJ8XC9X"},
{"Portfolio Turnover", "3.62%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "0ea806c53bfa2bdca2504ba7155ef130"}
};
}
}

View File

@@ -80,7 +80,7 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
/// <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 List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -92,12 +92,17 @@ namespace QuantConnect.Algorithm.CSharp.Alphas
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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", "2465"},
{"Total Orders", "2465"},
{"Average Win", "0.26%"},
{"Average Loss", "-0.24%"},
{"Compounding Annual Return", "7.848%"},

View File

@@ -37,7 +37,7 @@ namespace QuantConnect.Algorithm.CSharp
SetStartDate(2013, 1, 07);
SetEndDate(2013, 12, 11);
EnableAutomaticIndicatorWarmUp = true;
Settings.AutomaticIndicatorWarmUp = true;
AddEquity("SPY", Resolution.Daily);
_arima = ARIMA("SPY", 1, 1, 1, 50);
_ar = ARIMA("SPY", 1, 1, 0, 50);
@@ -71,7 +71,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -83,36 +83,44 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 100;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "52"},
{"Total Orders", "53"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "0.096%"},
{"Compounding Annual Return", "0.076%"},
{"Drawdown", "0.100%"},
{"Expectancy", "3.321"},
{"Net Profit", "0.089%"},
{"Sharpe Ratio", "-8.214"},
{"Sortino Ratio", "-9.025"},
{"Probabilistic Sharpe Ratio", "40.893%"},
{"Loss Rate", "24%"},
{"Win Rate", "76%"},
{"Profit-Loss Ratio", "4.67"},
{"Expectancy", "2.933"},
{"Start Equity", "100000"},
{"End Equity", "100070.90"},
{"Net Profit", "0.071%"},
{"Sharpe Ratio", "-9.164"},
{"Sortino Ratio", "-9.852"},
{"Probabilistic Sharpe Ratio", "36.417%"},
{"Loss Rate", "27%"},
{"Win Rate", "73%"},
{"Profit-Loss Ratio", "4.41"},
{"Alpha", "-0.008"},
{"Beta", "0.008"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.961"},
{"Tracking Error", "0.092"},
{"Treynor Ratio", "-0.826"},
{"Total Fees", "$52.00"},
{"Estimated Strategy Capacity", "$32000000000.00"},
{"Treynor Ratio", "-0.911"},
{"Total Fees", "$53.00"},
{"Estimated Strategy Capacity", "$16000000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "0.02%"},
{"OrderListHash", "e6711c76cb05bbb575ca067664348d88"}
{"Drawdown Recovery", "50"},
{"OrderListHash", "685c37df6e4c49b75792c133be189094"}
};
}
}

View File

@@ -33,12 +33,12 @@ namespace QuantConnect.Algorithm.CSharp
public override void Initialize()
{
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
EnableAutomaticIndicatorWarmUp = true;
Settings.AutomaticIndicatorWarmUp = true;
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 10);
var SP500 = QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME);
_symbol = FutureChainProvider.GetFutureContractList(SP500, StartDate).First();
_symbol = FuturesChain(SP500).OrderBy(x => x.Symbol.ID.Date).First();
// Test case: custom IndicatorBase<QuoteBar> indicator using Future unsubscribed symbol
var indicator1 = new CustomIndicator();
@@ -82,7 +82,7 @@ namespace QuantConnect.Algorithm.CSharp
if (!sma11.Current.Equals(sma1.Current))
{
throw new Exception("Expected SMAs warmed up before and after adding the Future to the algorithm to have the same current value. " +
throw new RegressionTestException("Expected SMAs warmed up before and after adding the Future to the algorithm to have the same current value. " +
"The result of 'WarmUpIndicator' shouldn't change if the symbol is or isn't subscribed");
}
@@ -94,7 +94,7 @@ namespace QuantConnect.Algorithm.CSharp
if (!smaSpy.Current.Equals(sma.Current))
{
throw new Exception("Expected SMAs warmed up before and after adding the Equity to the algorithm to have the same current value. " +
throw new RegressionTestException("Expected SMAs warmed up before and after adding the Equity to the algorithm to have the same current value. " +
"The result of 'WarmUpIndicator' shouldn't change if the symbol is or isn't subscribed");
}
}
@@ -103,7 +103,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (indicator.IsReady != isReady)
{
throw new Exception($"Expected indicator state, expected {isReady} but was {indicator.IsReady}");
throw new RegressionTestException($"Expected indicator state, expected {isReady} but was {indicator.IsReady}");
}
}
@@ -111,7 +111,7 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
@@ -141,7 +141,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -151,19 +151,26 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 84;
public int AlgorithmHistoryDataPoints => 85;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "733913.744%"},
{"Drawdown", "15.900%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "106827.7"},
{"Net Profit", "6.828%"},
{"Sharpe Ratio", "203744786353.299"},
{"Sortino Ratio", "0"},
@@ -182,7 +189,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$200000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Portfolio Turnover", "351.80%"},
{"OrderListHash", "23cf084b30ec3d70b1b9f54c9b3b975f"}
{"Drawdown Recovery", "1"},
{"OrderListHash", "dfd9a280d3c6470b305c03e0b72c234e"}
};
}
}

View File

@@ -0,0 +1,127 @@
/*
* 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.Indicators;
using QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting the behavior of the AutomaticIndicatorWarmUp on option greeks
/// </summary>
public class AutomaticIndicatorWarmupOptionIndicatorsMirrorContractsRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2015, 12, 24);
SetEndDate(2015, 12, 24);
Settings.AutomaticIndicatorWarmUp = true;
var underlying = "GOOG";
var resolution = Resolution.Minute;
var expiration = new DateTime(2015, 12, 24);
var strike = 650m;
var equity = AddEquity(underlying, resolution).Symbol;
var option = QuantConnect.Symbol.CreateOption(underlying, Market.USA, OptionStyle.American, OptionRight.Put, strike, expiration);
AddOptionContract(option, resolution);
// add the call counter side of the mirrored pair
var mirrorOption = QuantConnect.Symbol.CreateOption(underlying, Market.USA, OptionStyle.American, OptionRight.Call, strike, expiration);
AddOptionContract(mirrorOption, resolution);
var impliedVolatility = IV(option, mirrorOption);
var delta = D(option, mirrorOption, optionModel: OptionPricingModelType.BinomialCoxRossRubinstein, ivModel: OptionPricingModelType.BlackScholes);
var gamma = G(option, mirrorOption, optionModel: OptionPricingModelType.ForwardTree, ivModel: OptionPricingModelType.BlackScholes);
var vega = V(option, mirrorOption, optionModel: OptionPricingModelType.ForwardTree, ivModel: OptionPricingModelType.BlackScholes);
var theta = T(option, mirrorOption, optionModel: OptionPricingModelType.ForwardTree, ivModel: OptionPricingModelType.BlackScholes);
var rho = R(option, mirrorOption, optionModel: OptionPricingModelType.ForwardTree, ivModel: OptionPricingModelType.BlackScholes);
if (impliedVolatility == 0m || delta == 0m || gamma == 0m || vega == 0m || theta == 0m || rho == 0m)
{
throw new RegressionTestException("Expected IV/greeks calculated");
}
if (!impliedVolatility.IsReady || !delta.IsReady || !gamma.IsReady || !vega.IsReady || !theta.IsReady || !rho.IsReady)
{
throw new RegressionTestException("Expected IV/greeks to be ready");
}
Quit($"Implied Volatility: {impliedVolatility}, Delta: {delta}, Gamma: {gamma}, Vega: {vega}, Theta: {theta}, Rho: {rho}");
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally => true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <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 => 18;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino 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%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -34,14 +34,14 @@ namespace QuantConnect.Algorithm.CSharp
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);
EnableAutomaticIndicatorWarmUp = true;
Settings.AutomaticIndicatorWarmUp = true;
// Test case 1
_spy = AddEquity("SPY").Symbol;
var sma = SMA(_spy, 10);
if (!sma.IsReady)
{
throw new Exception("Expected SMA to be warmed up");
throw new RegressionTestException("Expected SMA to be warmed up");
}
// Test case 2
@@ -50,20 +50,20 @@ namespace QuantConnect.Algorithm.CSharp
if (indicator.IsReady)
{
throw new Exception("Expected CustomIndicator Not to be warmed up");
throw new RegressionTestException("Expected CustomIndicator Not to be warmed up");
}
WarmUpIndicator(_spy, indicator);
if (!indicator.IsReady)
{
throw new Exception("Expected CustomIndicator to be warmed up");
throw new RegressionTestException("Expected CustomIndicator to be warmed up");
}
}
/// <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)
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
@@ -72,7 +72,7 @@ namespace QuantConnect.Algorithm.CSharp
// we expect 1 consolidator per indicator
if (subscription.Consolidators.Count != 2)
{
throw new Exception($"Unexpected consolidator count for subscription: {subscription.Consolidators.Count}");
throw new RegressionTestException($"Unexpected consolidator count for subscription: {subscription.Consolidators.Count}");
}
SetHoldings(_spy, 1);
}
@@ -88,7 +88,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (_previous != null && input.EndTime == _previous.EndTime)
{
throw new Exception($"Unexpected indicator double data point call: {_previous}");
throw new RegressionTestException($"Unexpected indicator double data point call: {_previous}");
}
_previous = input;
return base.ComputeNextValue(window, input);
@@ -103,7 +103,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -115,17 +115,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 40;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "271.453%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "101691.92"},
{"Net Profit", "1.692%"},
{"Sharpe Ratio", "8.854"},
{"Sortino Ratio", "0"},
@@ -144,7 +151,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$56000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "19.93%"},
{"OrderListHash", "0c0f9328786b0c9e8f88d271673d16c3"}
{"Drawdown Recovery", "3"},
{"OrderListHash", "3da9fa60bf95b9ed148b95e02e0cfc9e"}
};
}
}

View File

@@ -0,0 +1,137 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Interfaces;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Data.Market;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting that security are automatically seeded by default
/// </summary>
public abstract class AutomaticSeedBaseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected virtual bool ShouldHaveTradeData { get; }
protected virtual bool ShouldHaveQuoteData { get; }
protected virtual bool ShouldHaveOpenInterestData { get; }
public override void OnSecuritiesChanged(SecurityChanges changes)
{
var gotTrades = false;
var gotQuotes = false;
var gotOpenInterest = false;
foreach (var addedSecurity in changes.AddedSecurities.Where(x => !x.Symbol.IsCanonical() || x.Symbol.SecurityType == SecurityType.Future))
{
if (addedSecurity.Price == 0)
{
throw new RegressionTestException("Security was not seeded");
}
if (!addedSecurity.HasData)
{
throw new RegressionTestException("Security does not have TradeBar or QuoteBar or OpenInterest data");
}
gotTrades |= addedSecurity.Cache.GetData<TradeBar>() != null;
gotQuotes |= addedSecurity.Cache.GetData<QuoteBar>() != null;
gotOpenInterest |= addedSecurity.Cache.GetData<OpenInterest>() != null;
}
if (changes.AddedSecurities.Count > 0)
{
if (ShouldHaveTradeData && !gotTrades)
{
throw new RegressionTestException("No contract had TradeBar data");
}
if (ShouldHaveQuoteData && !gotQuotes)
{
throw new RegressionTestException("No contract had QuoteBar data");
}
if (ShouldHaveOpenInterestData && !gotOpenInterest)
{
throw new RegressionTestException("No contract had OpenInterest data");
}
}
}
/// <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 List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public abstract long DataPoints { get; }
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public abstract int AlgorithmHistoryDataPoints { get; }
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino 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%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -0,0 +1,169 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Interfaces;
using QuantConnect.Data.Market;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Example algorithm using and asserting the behavior of auxiliary Data handlers
/// </summary>
public class AuxiliaryDataHandlersRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private bool _onSplits;
private bool _onDividends;
private bool _onDelistingsCalled;
private bool _onSymbolChangedEvents;
/// <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(2007, 05, 16);
SetEndDate(2015, 1, 1);
UniverseSettings.Resolution = Resolution.Daily;
// will get delisted
AddEquity("AAA.1");
// get's remapped
AddEquity("SPWR");
// has a split & dividends
AddEquity("AAPL");
}
public override void OnDelistings(Delistings delistings)
{
if (!delistings.ContainsKey("AAA.1"))
{
throw new RegressionTestException("Unexpected OnDelistings call");
}
_onDelistingsCalled = true;
}
public override void OnSymbolChangedEvents(SymbolChangedEvents symbolsChanged)
{
if (!symbolsChanged.ContainsKey("SPWR"))
{
throw new RegressionTestException("Unexpected OnSymbolChangedEvents call");
}
_onSymbolChangedEvents = true;
}
public override void OnSplits(Splits splits)
{
if (!splits.ContainsKey("AAPL"))
{
throw new RegressionTestException("Unexpected OnSplits call");
}
_onSplits = true;
}
public override void OnDividends(Dividends dividends)
{
if (!dividends.ContainsKey("AAPL"))
{
throw new RegressionTestException("Unexpected OnDividends call");
}
_onDividends = true;
}
public override void OnEndOfAlgorithm()
{
if (!_onDelistingsCalled)
{
throw new RegressionTestException("OnDelistings was not called!");
}
if (!_onSymbolChangedEvents)
{
throw new RegressionTestException("OnSymbolChangedEvents was not called!");
}
if (!_onSplits)
{
throw new RegressionTestException("OnSplits was not called!");
}
if (!_onDividends)
{
throw new RegressionTestException("OnDividends was not called!");
}
}
/// <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 List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 126222;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino 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.332"},
{"Tracking Error", "0.183"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -0,0 +1,156 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting that in backtesting, orders are submitted in the same time step even when asynchronous
/// </summary>
public class BacktestingAsynchronousOrdersRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _symbol;
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 08);
SetCash(100000);
_symbol = AddEquity("SPY").Symbol;
}
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
var marketOrderTicket = MarketOrder(_symbol, 100, asynchronous: false);
AssertMarketOrderStatus(marketOrderTicket);
var asyncMarketOrderTicket = MarketOrder(_symbol, -100, asynchronous: true);
AssertMarketOrderStatus(asyncMarketOrderTicket);
var limitPrice = Securities[_symbol].Price * 0.95m;
var limitOrderTicket = LimitOrder(_symbol, 100, limitPrice, asynchronous: false);
AssertLimitOrderStatus(limitOrderTicket);
var asyncLimitOrderTicket = LimitOrder(_symbol, -100, limitPrice, asynchronous: true);
AssertLimitOrderStatus(asyncLimitOrderTicket);
}
}
private static void AssertMarketOrderStatus(OrderTicket ticket)
{
// In backtesting the order should be submitted and filled right away.
// Note that OrderSet event will not be fired if there is an error when processing the order submission,
// but this is a happy case
if (!ticket.OrderSet.WaitOne(0))
{
throw new RegressionTestException("Order was not submitted immediately in backtesting mode");
}
if (!ticket.OrderClosed.WaitOne(0))
{
throw new RegressionTestException("Order was not filled immediately in backtesting mode");
}
if (ticket.Status != OrderStatus.Filled)
{
throw new RegressionTestException($"Order status is not filled: {ticket.Status}");
}
}
private static void AssertLimitOrderStatus(OrderTicket ticket)
{
// In backtesting the order should be submitted right away but not filled since price hasn't moved even when asynchronous
// Note that OrderSet event will not be fired if there is an error when processing the order submission,
// but this is a happy case
if (!ticket.OrderSet.WaitOne(0))
{
throw new RegressionTestException("Asynchronous limit order was not submitted immediately in backtesting mode");
}
if (ticket.OrderClosed.WaitOne(0))
{
throw new RegressionTestException("Asynchronous limit order was filled immediately in backtesting mode when it shouldn't");
}
if (ticket.Status != OrderStatus.Submitted)
{
throw new RegressionTestException($"Order status is not submitted: {ticket.Status}");
}
}
/// <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 List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1582;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "4"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100168.20"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino 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", "$3.00"},
{"Estimated Strategy Capacity", "$22000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "21.72%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "65f010e904a929e5383f0920a3c5b797"}
};
}
}

View File

@@ -151,12 +151,12 @@ namespace QuantConnect.Algorithm.CSharp
case OrderStatus.PartiallyFilled:
if (order.LastFillTime == null)
{
throw new Exception("LastFillTime should not be null");
throw new RegressionTestException("LastFillTime should not be null");
}
if (order.Quantity / 2 != orderEvent.FillQuantity)
{
throw new Exception("Order size should be half");
throw new RegressionTestException("Order size should be half");
}
break;
@@ -164,7 +164,7 @@ namespace QuantConnect.Algorithm.CSharp
case OrderStatus.Filled:
if (order.SecurityType == SecurityType.Equity && order.CreatedTime == order.LastFillTime)
{
throw new Exception("Order should not finish during the CreatedTime bar");
throw new RegressionTestException("Order should not finish during the CreatedTime bar");
}
break;
@@ -182,12 +182,12 @@ namespace QuantConnect.Algorithm.CSharp
// If the option price isn't the same as the strike price, its incorrect
if (order.Price != _optionStrikePrice)
{
throw new Exception("OptionExercise order price should be strike price!!");
throw new RegressionTestException("OptionExercise order price should be strike price!!");
}
if (orderEvent.Quantity != -1)
{
throw new Exception("OrderEvent Quantity should be -1");
throw new RegressionTestException("OrderEvent Quantity should be -1");
}
}
@@ -198,14 +198,14 @@ namespace QuantConnect.Algorithm.CSharp
{
if (!Portfolio.ContainsKey(_optionBuy.Symbol) || !Portfolio.ContainsKey(_optionBuy.Symbol.Underlying) || !Portfolio.ContainsKey(_equityBuy.Symbol))
{
throw new Exception("Portfolio does not contain the Symbols we purchased");
throw new RegressionTestException("Portfolio does not contain the Symbols we purchased");
}
//Check option holding, should not be invested since it expired, profit should be -400
var optionHolding = Portfolio[_optionBuy.Symbol];
if (optionHolding.Invested || optionHolding.Profit != -400)
{
throw new Exception("Options holding does not match expected outcome");
throw new RegressionTestException("Options holding does not match expected outcome");
}
//Check the option underlying symbol since we should have bought it at exercise
@@ -213,7 +213,7 @@ namespace QuantConnect.Algorithm.CSharp
var optionExerciseHolding = Portfolio[_optionBuy.Symbol.Underlying];
if (!optionExerciseHolding.Invested || optionExerciseHolding.Quantity != 100 || optionExerciseHolding.AveragePrice != _optionBuy.Symbol.ID.StrikePrice)
{
throw new Exception("Equity holding for exercised option does not match expected outcome");
throw new RegressionTestException("Equity holding for exercised option does not match expected outcome");
}
//Check equity holding, should be invested, profit should be
@@ -221,7 +221,7 @@ namespace QuantConnect.Algorithm.CSharp
var equityHolding = Portfolio[_equityBuy.Symbol];
if (!equityHolding.Invested || equityHolding.Quantity != 52 || equityHolding.AveragePrice != _equityBuy.AverageFillPrice)
{
throw new Exception("Equity holding does not match expected outcome");
throw new RegressionTestException("Equity holding does not match expected outcome");
}
}
@@ -291,29 +291,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1267414;
public long DataPoints => 27071;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "3"},
{"Average Win", "0%"},
{"Average Loss", "-0.40%"},
{"Compounding Annual Return", "-22.717%"},
{"Compounding Annual Return", "-21.378%"},
{"Drawdown", "0.400%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "99671.06"},
{"Net Profit", "-0.329%"},
{"Sharpe Ratio", "-14.095"},
{"Sortino Ratio", "0"},
@@ -332,7 +339,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "17.02%"},
{"OrderListHash", "a172538bd18fa82b11adaeac4f504b2e"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "1be5073f2cf8802ffa163f7dab7d040e"}
};
}
}

View File

@@ -63,7 +63,7 @@ namespace QuantConnect.Algorithm.CSharp
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}");
throw new RegressionTestException($"The number of active insights should be 0. Actual: {insightsCount}");
}
}
@@ -75,7 +75,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -87,6 +87,11 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>

View File

@@ -49,7 +49,7 @@ namespace QuantConnect.Algorithm.CSharp
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// Slice object keyed by symbol containing the stock data
public override void OnData(Slice data)
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
@@ -63,4 +63,4 @@ namespace QuantConnect.Algorithm.CSharp
}
}
}
}
}

View File

@@ -50,7 +50,7 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
@@ -67,7 +67,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -77,19 +77,26 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 120;
public int AlgorithmHistoryDataPoints => 15;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000.00"},
{"End Equity", "92395.59"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -108,7 +115,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "€85000.00"},
{"Lowest Capacity Asset", "BTCEUR 2XR"},
{"Portfolio Turnover", "107.64%"},
{"OrderListHash", "b0544d71cee600ef1f09c6000d6a3229"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "6819dc936b86af6e4b89b6017b7d5284"}
};
}
}

View File

@@ -37,7 +37,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -47,19 +47,26 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 120;
public int AlgorithmHistoryDataPoints => 15;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "200000.00"},
{"End Equity", "184791.19"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -78,7 +85,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "€85000.00"},
{"Lowest Capacity Asset", "BTCEUR 2XR"},
{"Portfolio Turnover", "107.64%"},
{"OrderListHash", "64c44a56824e67b86213539212d08e25"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "3d450fd418a0e845b3eaaac17fcd13fc"}
};
}
}

View File

@@ -53,7 +53,7 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
@@ -70,7 +70,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -82,17 +82,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "271.453%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "101691.92"},
{"Net Profit", "1.692%"},
{"Sharpe Ratio", "8.854"},
{"Sortino Ratio", "0"},
@@ -111,7 +118,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$56000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "19.93%"},
{"OrderListHash", "0c0f9328786b0c9e8f88d271673d16c3"}
{"Drawdown Recovery", "3"},
{"OrderListHash", "3da9fa60bf95b9ed148b95e02e0cfc9e"}
};
}
}

View File

@@ -44,8 +44,8 @@ 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)
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
@@ -64,7 +64,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -76,17 +76,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "39.143%"},
{"Drawdown", "0.500%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100423.24"},
{"Net Profit", "0.423%"},
{"Sharpe Ratio", "5.498"},
{"Sortino Ratio", "0"},
@@ -105,7 +112,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$150000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "4.98%"},
{"OrderListHash", "c198b0d9bf2b4c41d69c7ea4750f09b5"}
{"Drawdown Recovery", "3"},
{"OrderListHash", "8774049eb5141a2b6956d9432426f837"}
};
}
}

View File

@@ -18,7 +18,6 @@ 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;
@@ -59,14 +58,14 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice slice)
{
foreach (var changedEvent in data.SymbolChangedEvents.Values)
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}!");
throw new RegressionTestException($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
@@ -113,48 +112,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 713394;
public long DataPoints => 162575;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "5"},
{"Average Win", "2.90%"},
{"Total Orders", "5"},
{"Average Win", "2.48%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "13.087%"},
{"Drawdown", "1.100%"},
{"Compounding Annual Return", "11.325%"},
{"Drawdown", "1.500%"},
{"Expectancy", "0"},
{"Net Profit", "6.387%"},
{"Sharpe Ratio", "1.532"},
{"Sortino Ratio", "871.704"},
{"Probabilistic Sharpe Ratio", "90.613%"},
{"Start Equity", "100000"},
{"End Equity", "105549.6"},
{"Net Profit", "5.550%"},
{"Sharpe Ratio", "1.332"},
{"Sortino Ratio", "879.904"},
{"Probabilistic Sharpe Ratio", "79.894%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.088"},
{"Beta", "-0.022"},
{"Annual Standard Deviation", "0.054"},
{"Alpha", "0.075"},
{"Beta", "-0.017"},
{"Annual Standard Deviation", "0.053"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-1.35"},
{"Tracking Error", "0.1"},
{"Treynor Ratio", "-3.781"},
{"Information Ratio", "-1.48"},
{"Tracking Error", "0.099"},
{"Treynor Ratio", "-4.187"},
{"Total Fees", "$10.75"},
{"Estimated Strategy Capacity", "$1100000000.00"},
{"Estimated Strategy Capacity", "$7100000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Portfolio Turnover", "2.32%"},
{"OrderListHash", "c42bb4b319557346b155cd2c06ade894"}
{"Portfolio Turnover", "2.33%"},
{"Drawdown Recovery", "37"},
{"OrderListHash", "223735440010fcec5889bb7becacfa82"}
};
}
}

View File

@@ -59,15 +59,15 @@ 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)
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice slice)
{
foreach (var changedEvent in data.SymbolChangedEvents.Values)
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}!");
throw new RegressionTestException($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
@@ -118,48 +118,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 2217324;
public long DataPoints => 504530;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "5"},
{"Average Win", "4.45%"},
{"Average Loss", "-0.26%"},
{"Compounding Annual Return", "8.423%"},
{"Drawdown", "0.800%"},
{"Expectancy", "8.202"},
{"Net Profit", "4.162%"},
{"Sharpe Ratio", "0.951"},
{"Sortino Ratio", "2.8"},
{"Probabilistic Sharpe Ratio", "53.568%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "17.40"},
{"Alpha", "0.053"},
{"Beta", "-0.005"},
{"Annual Standard Deviation", "0.054"},
{"Total Orders", "5"},
{"Average Win", "2.86%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "12.959%"},
{"Drawdown", "1.100%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "106337.1"},
{"Net Profit", "6.337%"},
{"Sharpe Ratio", "1.41"},
{"Sortino Ratio", "1.242"},
{"Probabilistic Sharpe Ratio", "77.992%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.071"},
{"Beta", "0.054"},
{"Annual Standard Deviation", "0.059"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-1.681"},
{"Tracking Error", "0.099"},
{"Treynor Ratio", "-10.255"},
{"Information Ratio", "-1.392"},
{"Tracking Error", "0.097"},
{"Treynor Ratio", "1.518"},
{"Total Fees", "$10.75"},
{"Estimated Strategy Capacity", "$190000000.00"},
{"Estimated Strategy Capacity", "$890000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Portfolio Turnover", "2.34%"},
{"OrderListHash", "8a6ad6061fc3c311934a0801c26744eb"}
{"Portfolio Turnover", "2.32%"},
{"Drawdown Recovery", "34"},
{"OrderListHash", "1504a8892da8d8c0650018732f315753"}
};
}
}

View File

@@ -79,8 +79,8 @@ 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)
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice slice)
{
if (Portfolio.CashBook["EUR"].ConversionRate == 0
|| Portfolio.CashBook["BTC"].ConversionRate == 0
@@ -92,7 +92,7 @@ namespace QuantConnect.Algorithm.CSharp
Log($"LTC conversion rate: {Portfolio.CashBook["LTC"].ConversionRate}");
Log($"ETH conversion rate: {Portfolio.CashBook["ETH"].ConversionRate}");
throw new Exception("Conversion rate is 0");
throw new RegressionTestException("Conversion rate is 0");
}
if (Time.Hour == 1 && Time.Minute == 0)
{
@@ -167,11 +167,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (Portfolio.CashBook["LTC"].Amount > 0)
{
// The following two statements currently behave differently if we have initial holdings:
// https://github.com/QuantConnect/Lean/issues/1860
Liquidate("LTCUSD");
// SetHoldings("LTCUSD", 0);
}
}
}
@@ -196,7 +192,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -206,19 +202,26 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 240;
public int AlgorithmHistoryDataPoints => 35;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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", "10"},
{"Total Orders", "12"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "31592.84"},
{"End Equity", "30866.71"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -237,7 +240,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTCEUR 2XR"},
{"Portfolio Turnover", "118.08%"},
{"OrderListHash", "77458586d24f1cd00623d63da8279be2"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "26b9a07ace86b6a0e0eb2ff8c168cee0"}
};
}
}

View File

@@ -79,9 +79,9 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice slice)
{
var interestRates = data.Get<MarginInterestRate>();
var interestRates = slice.Get<MarginInterestRate>();
foreach (var interestRate in interestRates)
{
_interestPerSymbol[interestRate.Key]++;
@@ -89,7 +89,7 @@ namespace QuantConnect.Algorithm.CSharp
var cachedInterestRate = Securities[interestRate.Key].Cache.GetData<MarginInterestRate>();
if (cachedInterestRate != interestRate.Value)
{
throw new Exception($"Unexpected cached margin interest rate for {interestRate.Key}!");
throw new RegressionTestException($"Unexpected cached margin interest rate for {interestRate.Key}!");
}
}
@@ -100,7 +100,7 @@ namespace QuantConnect.Algorithm.CSharp
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");
throw new RegressionTestException($"Unexpected valid order {ticket}, should fail due to margin not sufficient");
}
Buy(_btcUsd.Symbol, 1);
@@ -113,17 +113,15 @@ namespace QuantConnect.Algorithm.CSharp
if (Math.Abs(btcUsdHoldings.TotalSaleVolume - holdingsValueBtcUsd) > 1)
{
throw new Exception($"Unexpected TotalSaleVolume {btcUsdHoldings.TotalSaleVolume}");
throw new RegressionTestException($"Unexpected TotalSaleVolume {btcUsdHoldings.TotalSaleVolume}");
}
if (Math.Abs(btcUsdHoldings.AbsoluteHoldingsCost - holdingsValueBtcUsd) > 1)
{
throw new Exception($"Unexpected holdings cost {btcUsdHoldings.HoldingsCost}");
throw new RegressionTestException($"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)
if (_btcUsd.BuyingPowerModel.GetMaintenanceMargin(_btcUsd) != marginUsed)
{
throw new Exception($"Unexpected margin used {marginUsed}");
throw new RegressionTestException($"Unexpected margin used {marginUsed}");
}
Buy(_adaUsdt.Symbol, 1000);
@@ -136,28 +134,27 @@ namespace QuantConnect.Algorithm.CSharp
if (Math.Abs(adaUsdtHoldings.TotalSaleVolume - holdingsValueUsdt) > 1)
{
throw new Exception($"Unexpected TotalSaleVolume {adaUsdtHoldings.TotalSaleVolume}");
throw new RegressionTestException($"Unexpected TotalSaleVolume {adaUsdtHoldings.TotalSaleVolume}");
}
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost - holdingsValueUsdt) > 1)
{
throw new Exception($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
throw new RegressionTestException($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
}
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost * 0.05m - marginUsed) > 1
|| _adaUsdt.BuyingPowerModel.GetMaintenanceMargin(_adaUsdt) != marginUsed)
if (_adaUsdt.BuyingPowerModel.GetMaintenanceMargin(_adaUsdt) != marginUsed)
{
throw new Exception($"Unexpected margin used {marginUsed}");
throw new RegressionTestException($"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}");
throw new RegressionTestException($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
}
if (Portfolio.TotalProfit != 0)
{
throw new Exception($"Unexpected TotalProfit {Portfolio.TotalProfit}");
throw new RegressionTestException($"Unexpected TotalProfit {Portfolio.TotalProfit}");
}
}
}
@@ -172,7 +169,7 @@ namespace QuantConnect.Algorithm.CSharp
if (Math.Abs(btcUsdHoldings.AbsoluteHoldingsCost - 100 * 2) > 1)
{
throw new Exception($"Unexpected holdings cost {btcUsdHoldings.HoldingsCost}");
throw new RegressionTestException($"Unexpected holdings cost {btcUsdHoldings.HoldingsCost}");
}
Sell(_adaUsdt.Symbol, 3000);
@@ -184,19 +181,19 @@ namespace QuantConnect.Algorithm.CSharp
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost - holdingsValueUsdt) > 1)
{
throw new Exception($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
throw new RegressionTestException($"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}");
throw new RegressionTestException($"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}");
throw new RegressionTestException($"Unexpected TotalProfit {Portfolio.TotalProfit}");
}
}
}
@@ -206,12 +203,12 @@ namespace QuantConnect.Algorithm.CSharp
{
if (_interestPerSymbol[_adaUsdt.Symbol] != 1)
{
throw new Exception($"Unexpected interest rate count {_interestPerSymbol[_adaUsdt.Symbol]}");
throw new RegressionTestException($"Unexpected interest rate count {_interestPerSymbol[_adaUsdt.Symbol]}");
}
if (_interestPerSymbol[_btcUsd.Symbol] != 3)
{
throw new Exception($"Unexpected interest rate count {_interestPerSymbol[_btcUsd.Symbol]}");
throw new RegressionTestException($"Unexpected interest rate count {_interestPerSymbol[_btcUsd.Symbol]}");
}
}
@@ -228,7 +225,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -240,17 +237,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "5"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000200.00"},
{"End Equity", "1000278.02"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -266,10 +270,11 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.65"},
{"Estimated Strategy Capacity", "$500000000.00"},
{"Estimated Strategy Capacity", "$620000000.00"},
{"Lowest Capacity Asset", "ADAUSDT 18R"},
{"Portfolio Turnover", "0.16%"},
{"OrderListHash", "ed329700a93491ffe30354769767c6aa"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "dcc4f964b5549c753123848c32eaee41"}
};
}
}

View File

@@ -74,9 +74,9 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice slice)
{
var interestRates = data.Get<MarginInterestRate>();
var interestRates = slice.Get<MarginInterestRate>();
foreach (var interestRate in interestRates)
{
_interestPerSymbol[interestRate.Key]++;
@@ -84,7 +84,7 @@ namespace QuantConnect.Algorithm.CSharp
var cachedInterestRate = Securities[interestRate.Key].Cache.GetData<MarginInterestRate>();
if (cachedInterestRate != interestRate.Value)
{
throw new Exception($"Unexpected cached margin interest rate for {interestRate.Key}!");
throw new RegressionTestException($"Unexpected cached margin interest rate for {interestRate.Key}!");
}
}
@@ -93,9 +93,9 @@ namespace QuantConnect.Algorithm.CSharp
if (!Portfolio.Invested && Transactions.OrdersCount == 0)
{
var ticket = Buy(_adaUsdt.Symbol, 100000);
if(ticket.Status != OrderStatus.Invalid)
if (ticket.Status != OrderStatus.Invalid)
{
throw new Exception($"Unexpected valid order {ticket}, should fail due to margin not sufficient");
throw new RegressionTestException($"Unexpected valid order {ticket}, should fail due to margin not sufficient");
}
Buy(_adaUsdt.Symbol, 1000);
@@ -108,28 +108,27 @@ namespace QuantConnect.Algorithm.CSharp
if (Math.Abs(adaUsdtHoldings.TotalSaleVolume - holdingsValueUsdt) > 1)
{
throw new Exception($"Unexpected TotalSaleVolume {adaUsdtHoldings.TotalSaleVolume}");
throw new RegressionTestException($"Unexpected TotalSaleVolume {adaUsdtHoldings.TotalSaleVolume}");
}
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost - holdingsValueUsdt) > 1)
{
throw new Exception($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
throw new RegressionTestException($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
}
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost * 0.05m - marginUsed) > 1
|| _adaUsdt.BuyingPowerModel.GetMaintenanceMargin(_adaUsdt) != marginUsed)
if (_adaUsdt.BuyingPowerModel.GetMaintenanceMargin(_adaUsdt) != marginUsed)
{
throw new Exception($"Unexpected margin used {marginUsed}");
throw new RegressionTestException($"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}");
throw new RegressionTestException($"Unexpected TotalUnrealizedProfit {Portfolio.TotalUnrealizedProfit}");
}
if (Portfolio.TotalProfit != 0)
{
throw new Exception($"Unexpected TotalProfit {Portfolio.TotalProfit}");
throw new RegressionTestException($"Unexpected TotalProfit {Portfolio.TotalProfit}");
}
}
}
@@ -147,19 +146,19 @@ namespace QuantConnect.Algorithm.CSharp
if (Math.Abs(adaUsdtHoldings.AbsoluteHoldingsCost - holdingsValueUsdt) > 1)
{
throw new Exception($"Unexpected holdings cost {adaUsdtHoldings.HoldingsCost}");
throw new RegressionTestException($"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}");
throw new RegressionTestException($"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}");
throw new RegressionTestException($"Unexpected TotalProfit {Portfolio.TotalProfit}");
}
}
@@ -174,7 +173,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (_interestPerSymbol[_adaUsdt.Symbol] != 1)
{
throw new Exception($"Unexpected interest rate count {_interestPerSymbol[_adaUsdt.Symbol]}");
throw new RegressionTestException($"Unexpected interest rate count {_interestPerSymbol[_adaUsdt.Symbol]}");
}
}
@@ -191,7 +190,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -203,17 +202,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "3"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000200"},
{"End Equity", "1000189.47"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -229,10 +235,11 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.61"},
{"Estimated Strategy Capacity", "$370000000.00"},
{"Estimated Strategy Capacity", "$460000000.00"},
{"Lowest Capacity Asset", "ADAUSDT 18R"},
{"Portfolio Turnover", "0.12%"},
{"OrderListHash", "5b1290390c34b0e64ac0b9e834c27b07"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "50a51d06d03a5355248a6bccef1ca521"}
};
}
}

View File

@@ -43,8 +43,8 @@ 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)
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
@@ -61,48 +61,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 73;
public long DataPoints => 72;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "246.546%"},
{"Drawdown", "1.200%"},
{"Compounding Annual Return", "424.375%"},
{"Drawdown", "0.800%"},
{"Expectancy", "0"},
{"Net Profit", "3.464%"},
{"Sharpe Ratio", "19.094"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "97.754%"},
{"Start Equity", "100000"},
{"End Equity", "104486.22"},
{"Net Profit", "4.486%"},
{"Sharpe Ratio", "17.304"},
{"Sortino Ratio", "35.217"},
{"Probabilistic Sharpe Ratio", "96.835%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"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.644"},
{"Total Fees", "$3.45"},
{"Estimated Strategy Capacity", "$970000000.00"},
{"Alpha", "-0.249"},
{"Beta", "1.015"},
{"Annual Standard Deviation", "0.141"},
{"Annual Variance", "0.02"},
{"Information Ratio", "-19"},
{"Tracking Error", "0.011"},
{"Treynor Ratio", "2.403"},
{"Total Fees", "$3.49"},
{"Estimated Strategy Capacity", "$1200000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "10.09%"},
{"OrderListHash", "418c8ec9920ec61bdefa2d02a8557048"}
{"Portfolio Turnover", "10.01%"},
{"Drawdown Recovery", "1"},
{"OrderListHash", "70f21e930175a2ec9d465b21edc1b6d9"}
};
}
}

View File

@@ -0,0 +1,240 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This algorithm tests and demonstrates EUREX futures subscription and trading:
/// - It tests contracts rollover by adding a continuous future and asserting that mapping happens at some point.
/// - It tests basic trading by buying a contract and holding it until expiration.
/// - It tests delisting and asserts the holdings are liquidated after that.
/// </summary>
public class BasicTemplateEurexFuturesAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Future _continuousContract;
private Symbol _mappedSymbol;
private Symbol _contractToTrade;
private int _mappingsCount;
private decimal _boughtQuantity;
private decimal _liquidatedQuantity;
private bool _delisted;
public override void Initialize()
{
SetStartDate(2024, 5, 30);
SetEndDate(2024, 6, 23);
SetAccountCurrency(Currencies.EUR);
SetCash(1000000);
_continuousContract = AddFuture(Futures.Indices.EuroStoxx50, Resolution.Minute,
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
dataMappingMode: DataMappingMode.FirstDayMonth,
contractDepthOffset: 0);
_continuousContract.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(180));
_mappedSymbol = _continuousContract.Mapped;
var benchmark = AddIndex("SX5E");
SetBenchmark(benchmark.Symbol);
var seeder = new FuncSecuritySeeder(GetLastKnownPrices);
SetSecurityInitializer(security => seeder.SeedSecurity(security));
}
public override void OnData(Slice slice)
{
foreach (var changedEvent in slice.SymbolChangedEvents.Values)
{
if (++_mappingsCount > 1)
{
throw new RegressionTestException($"{Time} - Unexpected number of symbol changed events (mappings): {_mappingsCount}. " +
$"Expected only 1.");
}
Debug($"{Time} - SymbolChanged event: {changedEvent}");
if (changedEvent.OldSymbol != _mappedSymbol.ID.ToString())
{
throw new RegressionTestException($"{Time} - Unexpected symbol changed event old symbol: {changedEvent}");
}
if (changedEvent.NewSymbol != _continuousContract.Mapped.ID.ToString())
{
throw new RegressionTestException($"{Time} - Unexpected symbol changed event new symbol: {changedEvent}");
}
// Let's trade the previous mapped contract, so we can hold it until expiration for testing
// (will be sooner than the new mapped contract)
_contractToTrade = _mappedSymbol;
_mappedSymbol = _continuousContract.Mapped;
}
// Let's trade after the mapping is done
if (_contractToTrade != null && _boughtQuantity == 0 && Securities[_contractToTrade].Exchange.ExchangeOpen)
{
Buy(_contractToTrade, 1);
}
if (_contractToTrade != null && slice.Delistings.TryGetValue(_contractToTrade, out var delisting))
{
if (delisting.Type == DelistingType.Delisted)
{
_delisted = true;
if (Portfolio.Invested)
{
throw new RegressionTestException($"{Time} - Portfolio should not be invested after the traded contract is delisted.");
}
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Symbol != _contractToTrade)
{
throw new RegressionTestException($"{Time} - Unexpected order event symbol: {orderEvent.Symbol}. Expected {_contractToTrade}");
}
if (orderEvent.Direction == OrderDirection.Buy)
{
if (orderEvent.Status == OrderStatus.Filled)
{
if (_boughtQuantity != 0 && _liquidatedQuantity != 0)
{
throw new RegressionTestException($"{Time} - Unexpected buy order event status: {orderEvent.Status}");
}
_boughtQuantity = orderEvent.Quantity;
}
}
else if (orderEvent.Direction == OrderDirection.Sell)
{
if (orderEvent.Status == OrderStatus.Filled)
{
if (_boughtQuantity <= 0 && _liquidatedQuantity != 0)
{
throw new RegressionTestException($"{Time} - Unexpected sell order event status: {orderEvent.Status}");
}
_liquidatedQuantity = orderEvent.Quantity;
if (_liquidatedQuantity != -_boughtQuantity)
{
throw new RegressionTestException($"{Time} - Unexpected liquidated quantity: {_liquidatedQuantity}. Expected: {-_boughtQuantity}");
}
}
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var addedSecurity in changes.AddedSecurities)
{
if (addedSecurity.Symbol.SecurityType == SecurityType.Future && addedSecurity.Symbol.IsCanonical())
{
_mappedSymbol = _continuousContract.Mapped;
}
}
}
public override void OnEndOfAlgorithm()
{
if (_mappingsCount == 0)
{
throw new RegressionTestException($"Unexpected number of symbol changed events (mappings): {_mappingsCount}. Expected 1.");
}
if (!_delisted)
{
throw new RegressionTestException("Contract was not delisted");
}
// Make sure we traded and that the position was liquidated on delisting
if (_boughtQuantity <= 0 || _liquidatedQuantity >= 0)
{
throw new RegressionTestException($"Unexpected sold quantity: {_boughtQuantity} and liquidated quantity: {_liquidatedQuantity}");
}
}
/// <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 List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 94326;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.11%"},
{"Compounding Annual Return", "-1.667%"},
{"Drawdown", "0.100%"},
{"Expectancy", "-1"},
{"Start Equity", "1000000"},
{"End Equity", "998849.48"},
{"Net Profit", "-0.115%"},
{"Sharpe Ratio", "-34.455"},
{"Sortino Ratio", "-57.336"},
{"Probabilistic Sharpe Ratio", "0.002%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "-6.176"},
{"Tracking Error", "0.002"},
{"Treynor Ratio", "0"},
{"Total Fees", "€1.02"},
{"Estimated Strategy Capacity", "€2300000000.00"},
{"Lowest Capacity Asset", "FESX YJHOAMPYKRS5"},
{"Portfolio Turnover", "0.40%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "ac9acc478ba1afe53993cdbb92f8ec6e"}
};
}
}

View File

@@ -13,6 +13,7 @@
* limitations under the License.
*/
using QuantConnect.Data;
using QuantConnect.Data.Market;
namespace QuantConnect.Algorithm.CSharp
@@ -41,8 +42,8 @@ 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">TradeBars IDictionary object with your stock data</param>
public void OnData(TradeBars data)
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -59,14 +59,14 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
SetHoldings("EURUSD", .5);
SetHoldings("NZDUSD", .5);
Log(string.Join(", ", data.Values));
Log(string.Join(", ", slice.Values));
}
}
}
}
}

View File

@@ -82,7 +82,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -94,17 +94,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "3"},
{"Average Win", "0%"},
{"Average Loss", "-1.01%"},
{"Compounding Annual Return", "261.134%"},
{"Drawdown", "2.200%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "101655.30"},
{"Net Profit", "1.655%"},
{"Sharpe Ratio", "8.472"},
{"Sortino Ratio", "0"},
@@ -123,7 +130,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$27000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "59.86%"},
{"OrderListHash", "75c4c7221e2e70d0aa5c9844aae9009c"}
{"Drawdown Recovery", "3"},
{"OrderListHash", "f209ed42701b0419858e0100595b40c0"}
};
}
}

View File

@@ -92,4 +92,4 @@ namespace QuantConnect.Algorithm.CSharp
Debug($"{Time} {orderEvent.ToString()}");
}
}
}
}

View File

@@ -98,10 +98,10 @@ namespace QuantConnect.Algorithm.CSharp
{
private QCAlgorithm _algorithm;
private Future _future;
public ExponentialMovingAverage EMA;
public decimal Price;
public bool IsLong;
public bool IsShort;
public ExponentialMovingAverage EMA { get; set; }
public decimal Price { get; set; }
public bool IsLong { get; set; }
public bool IsShort { get; set; }
public Symbol Symbol => _future.Symbol;
public Symbol Mapped => _future.Mapped;
@@ -171,48 +171,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1333;
public long DataPoints => 727;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 4;
public int AlgorithmHistoryDataPoints => 2;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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%"},
{"Total Orders", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "3.011%"},
{"Compounding Annual Return", "-0.010%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0"},
{"Net Profit", "0.528%"},
{"Sharpe Ratio", "1.285"},
{"Start Equity", "1000000"},
{"End Equity", "999983.2"},
{"Net Profit", "-0.002%"},
{"Sharpe Ratio", "-225.214"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "83.704%"},
{"Probabilistic Sharpe Ratio", "0.135%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.015"},
{"Beta", "-0.004"},
{"Annual Standard Deviation", "0.011"},
{"Alpha", "-0.008"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-4.774"},
{"Tracking Error", "0.084"},
{"Treynor Ratio", "-3.121"},
{"Total Fees", "$4.30"},
{"Estimated Strategy Capacity", "$5900000000.00"},
{"Information Ratio", "-5.146"},
{"Tracking Error", "0.083"},
{"Treynor Ratio", "-542.359"},
{"Total Fees", "$2.15"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Portfolio Turnover", "0.27%"},
{"OrderListHash", "9fb6d9433c29815301d818ccd7f3863f"}
{"Portfolio Turnover", "0.13%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "a6ccce3a1a7f549f887d83e84bfa878d"}
};
}
}
}

View File

@@ -39,11 +39,9 @@ namespace QuantConnect.Algorithm.CSharp
// 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.
@@ -81,7 +79,7 @@ namespace QuantConnect.Algorithm.CSharp
Debug($"{Time} - SymbolChanged event: {changedEvent}");
if (Time.TimeOfDay != TimeSpan.Zero)
{
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
throw new RegressionTestException($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
@@ -117,7 +115,7 @@ namespace QuantConnect.Algorithm.CSharp
var futureMarginModel = buyingPowerModel as FutureMarginModel;
if (buyingPowerModel == null)
{
throw new Exception($"Invalid buying power model. Found: {buyingPowerModel.GetType().Name}. Expected: {nameof(FutureMarginModel)}");
throw new RegressionTestException($"Invalid buying power model. Found: {buyingPowerModel.GetType().Name}. Expected: {nameof(FutureMarginModel)}");
}
var initialOvernight = futureMarginModel.InitialOvernightMarginRequirement;
var maintenanceOvernight = futureMarginModel.MaintenanceOvernightMarginRequirement;
@@ -133,7 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
&& !addedSecurity.Symbol.IsCanonical()
&& !addedSecurity.HasData)
{
throw new Exception($"Future contracts did not work up as expected: {addedSecurity.Symbol}");
throw new RegressionTestException($"Future contracts did not work up as expected: {addedSecurity.Symbol}");
}
}
}
@@ -146,29 +144,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 75401;
public long DataPoints => 40308;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 340;
public int AlgorithmHistoryDataPoints => 354;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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", "2700"},
{"Total Orders", "2700"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-99.777%"},
{"Compounding Annual Return", "-99.597%"},
{"Drawdown", "4.400%"},
{"Expectancy", "-0.724"},
{"Start Equity", "1000000"},
{"End Equity", "955700.5"},
{"Net Profit", "-4.430%"},
{"Sharpe Ratio", "-31.63"},
{"Sortino Ratio", "-31.63"},
@@ -187,7 +192,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$14000.00"},
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
{"Portfolio Turnover", "9912.69%"},
{"OrderListHash", "398c0383a9ba3235f15ac472a7fbcb8a"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "6e0f767a46a54365287801295cf7bb75"}
};
}
}

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -33,7 +33,6 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateFuturesConsolidationAlgorithm : QCAlgorithm
{
private const string RootSP500 = Futures.Indices.SP500EMini;
public Symbol SP500 = QuantConnect.Symbol.Create(RootSP500, SecurityType.Future, Market.CME);
private HashSet<Symbol> _futureContracts = new HashSet<Symbol>();
public override void Initialize()
@@ -78,4 +77,4 @@ namespace QuantConnect.Algorithm.CSharp
Log(quoteBar.ToString());
}
}
}
}

View File

@@ -18,8 +18,8 @@ using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
@@ -83,7 +83,7 @@ namespace QuantConnect.Algorithm.CSharp
// 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))
if (contract != null)
{
MarketOrder(contract.Symbol, 1);
}
@@ -99,11 +99,21 @@ namespace QuantConnect.Algorithm.CSharp
{
if (Time.TimeOfDay != TimeSpan.Zero)
{
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
throw new RegressionTestException($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
if (changes.RemovedSecurities.Count > 0 &&
Portfolio.Invested &&
Securities.Values.Where(x => x.Invested).All(x => x.Exchange.Hours.IsOpen(Time, true)))
{
Liquidate();
}
}
/// <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>
@@ -112,48 +122,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 14036;
public virtual long DataPoints => 5867;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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", "128"},
{"Average Win", "0.26%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-0.071%"},
{"Drawdown", "0.400%"},
{"Expectancy", "-0.116"},
{"Net Profit", "-0.071%"},
{"Sharpe Ratio", "-1.999"},
{"Sortino Ratio", "-1.806"},
{"Probabilistic Sharpe Ratio", "10.091%"},
{"Loss Rate", "97%"},
{"Win Rate", "3%"},
{"Profit-Loss Ratio", "27.29"},
{"Alpha", "-0.008"},
{"Beta", "0.001"},
{"Total Orders", "38"},
{"Average Win", "0.33%"},
{"Average Loss", "-0.03%"},
{"Compounding Annual Return", "0.098%"},
{"Drawdown", "0.300%"},
{"Expectancy", "0.165"},
{"Start Equity", "1000000"},
{"End Equity", "1000991.96"},
{"Net Profit", "0.099%"},
{"Sharpe Ratio", "-1.708"},
{"Sortino Ratio", "-0.84"},
{"Probabilistic Sharpe Ratio", "14.542%"},
{"Loss Rate", "89%"},
{"Win Rate", "11%"},
{"Profit-Loss Ratio", "10.07"},
{"Alpha", "-0.007"},
{"Beta", "0.002"},
{"Annual Standard Deviation", "0.004"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.367"},
{"Information Ratio", "-1.354"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "-5.445"},
{"Total Fees", "$285.44"},
{"Estimated Strategy Capacity", "$1000.00"},
{"Treynor Ratio", "-4.054"},
{"Total Fees", "$85.54"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "ES VRJST036ZY0X"},
{"Portfolio Turnover", "3.41%"},
{"OrderListHash", "1666cd6c277c6ea8b1b46d5dfa6bac9f"}
{"Portfolio Turnover", "1.04%"},
{"Drawdown Recovery", "69"},
{"OrderListHash", "eafc33ea4dcb219f7aacdbdd0973d5bc"}
};
}
}

View File

@@ -131,29 +131,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 57752;
public virtual long DataPoints => 24883;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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", "2"},
{"Total Orders", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-81.734%"},
{"Drawdown", "4.100%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "97830.76"},
{"Net Profit", "-2.169%"},
{"Sharpe Ratio", "-10.299"},
{"Sortino Ratio", "-10.299"},
@@ -172,7 +179,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$17000000.00"},
{"Lowest Capacity Asset", "GC VL5E74HP3EE5"},
{"Portfolio Turnover", "43.23%"},
{"OrderListHash", "1daca8b4534258de0f1bf09214205b77"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "c0fc1bcdc3008a8d263521bbc9d7cdbd"}
};
}
}

View File

@@ -36,24 +36,26 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public override List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 163392;
public override long DataPoints => 70262;
/// <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"},
{"Total Orders", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-92.667%"},
{"Drawdown", "5.000%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "96685.76"},
{"Net Profit", "-3.314%"},
{"Sharpe Ratio", "-6.359"},
{"Sortino Ratio", "-11.237"},
@@ -72,7 +74,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$52000000.00"},
{"Lowest Capacity Asset", "GC VL5E74HP3EE5"},
{"Portfolio Turnover", "43.77%"},
{"OrderListHash", "ba6e16f476a2ddeeaab9c9091664f7a1"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "dcdaafcefa47465962ace2759ed99c91"}
};
}
}

View File

@@ -69,7 +69,7 @@ namespace QuantConnect.Algorithm.CSharp
var history = History(10, Resolution.Minute);
if (history.Count() < 10)
{
throw new Exception($"Empty history at {Time}");
throw new RegressionTestException($"Empty history at {Time}");
}
_successCount++;
}
@@ -78,7 +78,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (_successCount < ExpectedHistoryCallCount)
{
throw new Exception($"Scheduled Event did not assert history call as many times as expected: {_successCount}/49");
throw new RegressionTestException($"Scheduled Event did not assert history call as many times as expected: {_successCount}/49");
}
}
@@ -135,29 +135,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 48688;
public virtual long DataPoints => 25316;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 5305;
public virtual int AlgorithmHistoryDataPoints => 6075;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Total Orders", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000000"},
{"End Equity", "1000000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -176,6 +183,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}

View File

@@ -42,29 +42,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public override List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 147769;
public override long DataPoints => 76063;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 6112;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000000"},
{"End Equity", "1000000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -83,6 +90,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}

View File

@@ -14,12 +14,7 @@
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
@@ -36,43 +31,46 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public override List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 87391;
public override long DataPoints => 25339;
/// <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%"},
{"Total Orders", "718"},
{"Average Win", "0.03%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-1.610%"},
{"Drawdown", "1.600%"},
{"Expectancy", "-0.841"},
{"Net Profit", "-1.622%"},
{"Sharpe Ratio", "-8.787"},
{"Sortino Ratio", "-5.428"},
{"Compounding Annual Return", "-1.720%"},
{"Drawdown", "1.700%"},
{"Expectancy", "-0.770"},
{"Start Equity", "1000000"},
{"End Equity", "982676.58"},
{"Net Profit", "-1.732%"},
{"Sharpe Ratio", "-8.877"},
{"Sortino Ratio", "-5.476"},
{"Probabilistic Sharpe Ratio", "0.000%"},
{"Loss Rate", "96%"},
{"Win Rate", "4%"},
{"Profit-Loss Ratio", "3.21"},
{"Profit-Loss Ratio", "4.90"},
{"Alpha", "-0.018"},
{"Beta", "-0.003"},
{"Beta", "-0.002"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.473"},
{"Information Ratio", "-1.484"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "5.593"},
{"Total Fees", "$1456.18"},
{"Estimated Strategy Capacity", "$9000.00"},
{"Treynor Ratio", "9.171"},
{"Total Fees", "$1638.42"},
{"Estimated Strategy Capacity", "$8000.00"},
{"Lowest Capacity Asset", "ES VP274HSU1AF5"},
{"Portfolio Turnover", "17.91%"},
{"OrderListHash", "19d70e24c5d0922d1557de4adbf60ab5"}
{"Portfolio Turnover", "20.14%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "c301a0a086f8905b1a555f0257087272"}
};
}
}

View File

@@ -39,11 +39,9 @@ namespace QuantConnect.Algorithm.CSharp
// 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.
@@ -81,7 +79,7 @@ namespace QuantConnect.Algorithm.CSharp
Debug($"{Time} - SymbolChanged event: {changedEvent}");
if (Time.TimeOfDay != TimeSpan.Zero)
{
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
throw new RegressionTestException($"{Time} unexpected symbol changed event {changedEvent}!");
}
}
@@ -117,7 +115,7 @@ namespace QuantConnect.Algorithm.CSharp
var futureMarginModel = buyingPowerModel as FutureMarginModel;
if (buyingPowerModel == null)
{
throw new Exception($"Invalid buying power model. Found: {buyingPowerModel.GetType().Name}. Expected: {nameof(FutureMarginModel)}");
throw new RegressionTestException($"Invalid buying power model. Found: {buyingPowerModel.GetType().Name}. Expected: {nameof(FutureMarginModel)}");
}
var initialOvernight = futureMarginModel.InitialOvernightMarginRequirement;
var maintenanceOvernight = futureMarginModel.MaintenanceOvernightMarginRequirement;
@@ -133,7 +131,7 @@ namespace QuantConnect.Algorithm.CSharp
&& !addedSecurity.Symbol.IsCanonical()
&& !addedSecurity.HasData)
{
throw new Exception($"Future contracts did not work up as expected: {addedSecurity.Symbol}");
throw new RegressionTestException($"Future contracts did not work up as expected: {addedSecurity.Symbol}");
}
}
}
@@ -146,29 +144,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 224660;
public long DataPoints => 117079;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 340;
public int AlgorithmHistoryDataPoints => 354;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "8282"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "13.900%"},
{"Expectancy", "-0.824"},
{"Start Equity", "1000000"},
{"End Equity", "861260.7"},
{"Net Profit", "-13.874%"},
{"Sharpe Ratio", "-19.346"},
{"Sortino Ratio", "-19.346"},
@@ -187,7 +192,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$130000.00"},
{"Lowest Capacity Asset", "GC VOFJUCDY9XNH"},
{"Portfolio Turnover", "32523.20%"},
{"OrderListHash", "584fbdabd837921edc6a7e99759b9c66"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "0664a72652a19956ea3c4915269cc4b9"}
};
}
}

View File

@@ -14,14 +14,7 @@
*
*/
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
{
@@ -38,43 +31,46 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public override List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 16263;
public override long DataPoints => 5971;
/// <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", "156"},
{"Average Win", "0.31%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-0.024%"},
{"Drawdown", "0.400%"},
{"Expectancy", "-0.035"},
{"Net Profit", "-0.025%"},
{"Sharpe Ratio", "-1.602"},
{"Sortino Ratio", "-1.913"},
{"Probabilistic Sharpe Ratio", "11.172%"},
{"Loss Rate", "97%"},
{"Win Rate", "3%"},
{"Profit-Loss Ratio", "36.65"},
{"Total Orders", "36"},
{"Average Win", "0.33%"},
{"Average Loss", "-0.03%"},
{"Compounding Annual Return", "0.103%"},
{"Drawdown", "0.300%"},
{"Expectancy", "0.172"},
{"Start Equity", "1000000"},
{"End Equity", "1001033.76"},
{"Net Profit", "0.103%"},
{"Sharpe Ratio", "-1.701"},
{"Sortino Ratio", "-0.809"},
{"Probabilistic Sharpe Ratio", "14.685%"},
{"Loss Rate", "89%"},
{"Win Rate", "11%"},
{"Profit-Loss Ratio", "9.55"},
{"Alpha", "-0.007"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.005"},
{"Beta", "0.002"},
{"Annual Standard Deviation", "0.004"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.359"},
{"Information Ratio", "-1.353"},
{"Tracking Error", "0.089"},
{"Treynor Ratio", "8.008"},
{"Total Fees", "$347.56"},
{"Estimated Strategy Capacity", "$1000.00"},
{"Treynor Ratio", "-4.042"},
{"Total Fees", "$81.24"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "ES VRJST036ZY0X"},
{"Portfolio Turnover", "4.16%"},
{"OrderListHash", "ce63f5e611a7ab2f49d49c9fdc777ef5"}
{"Portfolio Turnover", "0.99%"},
{"Drawdown Recovery", "69"},
{"OrderListHash", "67120ad5c9a6116001dda6c8061e5353"}
};
}
}

View File

@@ -36,27 +36,29 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public override List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 228936;
public override long DataPoints => 67998;
/// <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", "1990"},
{"Total Orders", "1992"},
{"Average Win", "0.01%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-4.683%"},
{"Compounding Annual Return", "-4.687%"},
{"Drawdown", "4.700%"},
{"Expectancy", "-0.911"},
{"Net Profit", "-4.717%"},
{"Sharpe Ratio", "-7.178"},
{"Sortino Ratio", "-5.126"},
{"Start Equity", "1000000"},
{"End Equity", "952789.22"},
{"Net Profit", "-4.721%"},
{"Sharpe Ratio", "-7.183"},
{"Sortino Ratio", "-5.14"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "97%"},
{"Win Rate", "3%"},
@@ -67,12 +69,13 @@ namespace QuantConnect.Algorithm.CSharp
{"Annual Variance", "0"},
{"Information Ratio", "-1.702"},
{"Tracking Error", "0.09"},
{"Treynor Ratio", "5.049"},
{"Total Fees", "$4538.98"},
{"Treynor Ratio", "5.054"},
{"Total Fees", "$4543.28"},
{"Estimated Strategy Capacity", "$3000.00"},
{"Lowest Capacity Asset", "ES VP274HSU1AF5"},
{"Portfolio Turnover", "56.68%"},
{"OrderListHash", "4ebc10fed9201f59aa7fcd90fbb49448"}
{"Portfolio Turnover", "56.73%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "6ce7812de5c98744cc35169a86a24325"}
};
}
}

View File

@@ -52,8 +52,8 @@ 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)
/// <param name="slice">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
@@ -70,7 +70,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -82,17 +82,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "227.693%"},
{"Drawdown", "2.000%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "101529.08"},
{"Net Profit", "1.529%"},
{"Sharpe Ratio", "8.855"},
{"Sortino Ratio", "0"},
@@ -111,7 +118,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$110000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "19.96%"},
{"OrderListHash", "0f357e8eeee4108d6b53f2b671e97f29"}
{"Drawdown Recovery", "2"},
{"OrderListHash", "60747dce5c2aed393b7dccc258d2c9b5"}
};
}
}

View File

@@ -30,8 +30,8 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="indexes" />
public class BasicTemplateIndexAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected Symbol Spx;
protected Symbol SpxOption;
protected Symbol Spx { get; set; }
protected Symbol SpxOption { get; set; }
private ExponentialMovingAverage _emaSlow;
private ExponentialMovingAverage _emaFast;
@@ -61,8 +61,10 @@ namespace QuantConnect.Algorithm.CSharp
AddIndexOptionContract(SpxOption, Resolution);
_emaSlow = EMA(Spx, 80);
_emaFast = EMA(Spx, 200);
_emaSlow = EMA(Spx, Resolution > Resolution.Minute ? 6 : 80);
_emaFast = EMA(Spx, Resolution > Resolution.Minute ? 2 : 200);
Settings.DailyPreciseEndTime = true;
}
/// <summary>
@@ -91,12 +93,25 @@ namespace QuantConnect.Algorithm.CSharp
}
}
/// <summary>
/// Asserts indicators are ready
/// </summary>
/// <exception cref="RegressionTestException"></exception>
protected void AssertIndicators()
{
if (!_emaSlow.IsReady || !_emaFast.IsReady)
{
throw new RegressionTestException("Indicators are not ready!");
}
}
public override void OnEndOfAlgorithm()
{
if (Portfolio[Spx].TotalSaleVolume > 0)
{
throw new Exception("Index is not tradable.");
throw new RegressionTestException("Index is not tradable.");
}
AssertIndicators();
}
/// <summary>
@@ -107,48 +122,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 16049;
public virtual long DataPoints => 16199;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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", "3"},
{"Average Win", "6.15%"},
{"Total Orders", "3"},
{"Average Win", "7.08%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "435.569%"},
{"Compounding Annual Return", "603.355%"},
{"Drawdown", "3.400%"},
{"Expectancy", "0"},
{"Net Profit", "5.516%"},
{"Sharpe Ratio", "-6.336"},
{"Sortino Ratio", "-12.182"},
{"Probabilistic Sharpe Ratio", "0.011%"},
{"Start Equity", "1000000"},
{"End Equity", "1064395"},
{"Net Profit", "6.440%"},
{"Sharpe Ratio", "-4.563"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0.781%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.226"},
{"Beta", "0.02"},
{"Annual Standard Deviation", "0.034"},
{"Alpha", "-0.169"},
{"Beta", "0.073"},
{"Annual Standard Deviation", "0.028"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-7.032"},
{"Tracking Error", "0.107"},
{"Treynor Ratio", "-10.906"},
{"Information Ratio", "-6.684"},
{"Tracking Error", "0.099"},
{"Treynor Ratio", "-1.771"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$3000.00"},
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
{"Portfolio Turnover", "24.07%"},
{"OrderListHash", "d1987f604e6d61584838ccc94adf7256"}
{"Lowest Capacity Asset", "SPX XL80P3GHIA9A|SPX 31"},
{"Portfolio Turnover", "23.97%"},
{"Drawdown Recovery", "9"},
{"OrderListHash", "4b560d2a8cfae510c3c8dc92603470fc"}
};
}
}

View File

@@ -15,8 +15,10 @@
*/
using System;
using System.Linq;
using QuantConnect.Data;
using System.Collections.Generic;
using QuantConnect.Data.Market;
namespace QuantConnect.Algorithm.CSharp
{
@@ -30,7 +32,7 @@ namespace QuantConnect.Algorithm.CSharp
// 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;
protected int BarCounter { get; set; }
/// <summary>
/// Purchase a contract when we are not invested, liquidate otherwise
@@ -60,6 +62,35 @@ namespace QuantConnect.Algorithm.CSharp
{
throw new ArgumentException($"Bar Count {BarCounter} is not expected count of {ExpectedBarCount}");
}
AssertIndicators();
if (Resolution != Resolution.Daily)
{
return;
}
var openInterest = Securities[SpxOption].Cache.GetAll<OpenInterest>();
if (openInterest.Single().EndTime != new DateTime(2021, 1, 15, 15, 15, 0))
{
throw new ArgumentException($"Unexpected open interest time: {openInterest.Single().EndTime}");
}
foreach (var symbol in new[] { SpxOption, Spx })
{
var history = History(symbol, 10).ToList();
if (history.Count != 10)
{
throw new RegressionTestException($"Unexpected history count: {history.Count}");
}
if (history.Any(x => x.Time.TimeOfDay != new TimeSpan(8, 30, 0)))
{
throw new RegressionTestException($"Unexpected history data start time");
}
if (history.Any(x => x.EndTime.TimeOfDay != new TimeSpan(15, 15, 0)))
{
throw new RegressionTestException($"Unexpected history data end time");
}
}
}
/// <summary>
@@ -70,24 +101,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public override List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 0;
public override long DataPoints => 122;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 0;
public override int AlgorithmHistoryDataPoints => 30;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"}
{"Total Orders", "11"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "653.545%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000000"},
{"End Equity", "1084600"},
{"Net Profit", "8.460%"},
{"Sharpe Ratio", "9.923"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "93.682%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "3.61"},
{"Beta", "-0.513"},
{"Annual Standard Deviation", "0.359"},
{"Annual Variance", "0.129"},
{"Information Ratio", "8.836"},
{"Tracking Error", "0.392"},
{"Treynor Ratio", "-6.937"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "SPX XL80P3GHIA9A|SPX 31"},
{"Portfolio Turnover", "2.42%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "ce421d0aeb7bde3bc92a6b87c09c510e"}
};
}
}

View File

@@ -8,7 +8,7 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateIndexHourlyAlgorithm : BasicTemplateIndexDailyAlgorithm
{
protected override Resolution Resolution => Resolution.Hour;
protected override int ExpectedBarCount => base.ExpectedBarCount * 7;
protected override int ExpectedBarCount => base.ExpectedBarCount * 8;
/// <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.
@@ -18,29 +18,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public override List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 391;
public override long DataPoints => 401;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "81"},
{"Average Win", "1.28%"},
{"Average Loss", "-0.06%"},
{"Compounding Annual Return", "-20.546%"},
{"Drawdown", "1.800%"},
{"Expectancy", "-0.402"},
{"Start Equity", "1000000"},
{"End Equity", "990775"},
{"Net Profit", "-0.922%"},
{"Sharpe Ratio", "-2.903"},
{"Sortino Ratio", "-6.081"},
@@ -57,9 +64,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "-6.189"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$300000.00"},
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
{"Lowest Capacity Asset", "SPX XL80P3GHIA9A|SPX 31"},
{"Portfolio Turnover", "24.63%"},
{"OrderListHash", "380076bc7854977f46318e8add9f1a25"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "7bc05310e971f09b0663bc380fdfee80"}
};
}
}

View File

@@ -14,7 +14,6 @@
*
*/
using System;
using QuantConnect.Data;
using System.Collections.Generic;
using QuantConnect.Indicators;
@@ -48,8 +47,10 @@ namespace QuantConnect.Algorithm.CSharp
var spxOptions = AddIndexOption(_spx, Resolution);
spxOptions.SetFilter(filterFunc => filterFunc.CallsOnly());
_emaSlow = EMA(_spx, 80);
_emaFast = EMA(_spx, 200);
_emaSlow = EMA(_spx, Resolution > Resolution.Minute ? 6 : 80);
_emaFast = EMA(_spx, Resolution > Resolution.Minute ? 2 : 200);
Settings.DailyPreciseEndTime = true;
}
/// <summary>
@@ -102,12 +103,13 @@ namespace QuantConnect.Algorithm.CSharp
{
if (Portfolio[_spx].TotalSaleVolume > 0)
{
throw new Exception("Index is not tradable.");
throw new RegressionTestException("Index is not tradable.");
}
if (Portfolio.TotalSaleVolume == 0)
{
throw new Exception("Trade volume should be greater than zero by the end of this algorithm");
throw new RegressionTestException("Trade volume should be greater than zero by the end of this algorithm");
}
AssertIndicators();
}
public Symbol InvertOption(Symbol symbol)
@@ -121,6 +123,18 @@ namespace QuantConnect.Algorithm.CSharp
symbol.ID.Date);
}
/// <summary>
/// Asserts indicators are ready
/// </summary>
/// <exception cref="RegressionTestException"></exception>
protected void AssertIndicators()
{
if (!_emaSlow.IsReady || !_emaFast.IsReady)
{
throw new RegressionTestException("Indicators are not ready!");
}
}
/// <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>
@@ -129,7 +143,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -141,12 +155,17 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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", "8220"},
{"Total Orders", "8220"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-100.000%"},

View File

@@ -62,24 +62,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public override List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 0;
public override long DataPoints => 360;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"}
{"Total Orders", "11"},
{"Average Win", "0%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-0.092%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Start Equity", "1000000"},
{"End Equity", "999920"},
{"Net Profit", "-0.008%"},
{"Sharpe Ratio", "-19.865"},
{"Sortino Ratio", "-175397.15"},
{"Probabilistic Sharpe Ratio", "0.013%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.003"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.454"},
{"Tracking Error", "0.138"},
{"Treynor Ratio", "-44.954"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "SPX XL80P59H9OI6|SPX 31"},
{"Portfolio Turnover", "0.00%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "34d295b82e29b1dbe8f104d3300d9255"}
};
}
}

View File

@@ -33,29 +33,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public override List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public override long DataPoints => 2143;
public override long DataPoints => 1269;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public override int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "81"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-0.006%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-0.486"},
{"Start Equity", "1000000"},
{"End Equity", "999995"},
{"Net Profit", "0.000%"},
{"Sharpe Ratio", "-101.77"},
{"Sortino Ratio", "-9053542.758"},
@@ -72,9 +79,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "116.921"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "SPX XL80P59H5E6M|SPX 31"},
{"Lowest Capacity Asset", "SPX XL80P59H9OI6|SPX 31"},
{"Portfolio Turnover", "0.00%"},
{"OrderListHash", "832944f7bfd8801bb37e5683a7510705"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "214026660a13ecaecc7074fa97f86ea1"}
};
}
}

View File

@@ -56,7 +56,7 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
@@ -80,7 +80,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -92,17 +92,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-0.010%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "99992.45"},
{"Net Profit", "-0.008%"},
{"Sharpe Ratio", "-497.389"},
{"Sortino Ratio", "-73.22"},
@@ -121,7 +128,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "₹61000000000.00"},
{"Lowest Capacity Asset", "YESBANK UL"},
{"Portfolio Turnover", "0.00%"},
{"OrderListHash", "0cfbdeedf1ba2a02af1b6b35dfe8aac3"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "06f782c83dd633dac6f228b91273ba26"}
};
}
}

View File

@@ -31,8 +31,8 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="indexes" />
public class BasicTemplateIndiaIndexAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected Symbol Nifty;
protected Symbol NiftyETF;
protected Symbol Nifty { get; set; }
protected Symbol NiftyETF { get; set; }
private ExponentialMovingAverage _emaSlow;
private ExponentialMovingAverage _emaFast;
@@ -92,7 +92,7 @@ namespace QuantConnect.Algorithm.CSharp
{
if (Portfolio[Nifty].TotalSaleVolume > 0)
{
throw new Exception("Index is not tradable.");
throw new RegressionTestException("Index is not tradable.");
}
}
@@ -104,7 +104,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
@@ -116,17 +116,24 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "6"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-0.386%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Start Equity", "1000000"},
{"End Equity", "999961.17"},
{"Net Profit", "-0.004%"},
{"Sharpe Ratio", "-328.371"},
{"Sortino Ratio", "-328.371"},
@@ -145,7 +152,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "₹84000.00"},
{"Lowest Capacity Asset", "JUNIORBEES UL"},
{"Portfolio Turnover", "0.04%"},
{"OrderListHash", "5823d79e97915654a8f68ae5fa600b5a"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "8790bec8175539e6d92e01608ac57733"}
};
}
}

View File

@@ -32,8 +32,8 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateIntrinioEconomicData : QCAlgorithm
{
// Set your Intrinio user and password.
public string _user = "";
public string _password = "";
private string _user = string.Empty;
private string _password = string.Empty;
private Symbol _uso; // United States Oil Fund LP
private Symbol _bno; // United States Brent Oil Fund LP
@@ -81,9 +81,9 @@ namespace QuantConnect.Algorithm.CSharp
/// 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)
public override void OnData(Slice slice)
{
var customData = data.Get<IntrinioEconomicData>();
var customData = slice.Get<IntrinioEconomicData>();
if (customData.Count == 0) return;
foreach (var economicData in customData.Values)
@@ -116,7 +116,7 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "91"},
{"Total Orders", "91"},
{"Average Win", "0.09%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "5.732%"},

View File

@@ -32,7 +32,7 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="trading and orders" />
public class BasicTemplateOptionEquityStrategyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
protected Symbol _optionSymbol;
private Symbol _optionSymbol;
public override void Initialize()
{
@@ -44,7 +44,7 @@ namespace QuantConnect.Algorithm.CSharp
_optionSymbol = option.Symbol;
// set our strike/expiry filter for this option chain
option.SetFilter(u => u.Strikes(-2, +2)
option.SetFilter(u => u.StandardsOnly().Strikes(-2, +2)
// Expiration method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
.Expiration(0, 180));
@@ -73,7 +73,7 @@ namespace QuantConnect.Algorithm.CSharp
var higherStrike = callContracts[2].Strike;
var optionStrategy = OptionStrategies.CallButterfly(_optionSymbol, higherStrike, middleStrike, lowerStrike, expiry);
Order(optionStrategy, 10);
}
}
@@ -97,29 +97,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 471135;
public long DataPoints => 15023;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "3"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "98024"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -135,10 +142,11 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$26.00"},
{"Estimated Strategy Capacity", "$70000.00"},
{"Lowest Capacity Asset", "GOOCV W78ZERHAOVVQ|GOOCV VP83T1ZUHROL"},
{"Estimated Strategy Capacity", "$69000.00"},
{"Lowest Capacity Asset", "GOOCV W78ZERHAT67A|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "61.31%"},
{"OrderListHash", "a36c60c5fb020121d6541683138d8f28"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "ccd6cb1b6244d0c6d30b2760938958f1"}
};
}
}

View File

@@ -50,8 +50,9 @@ namespace QuantConnect.Algorithm.CSharp
// set our strike/expiry filter for this option chain
// SetFilter method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
option.SetFilter(-2, +2, 0, 180);
// option.SetFilter(-2, +2, TimeSpan.Zero, TimeSpan.FromDays(180));
option.SetFilter(u => u.StandardsOnly()
.Strikes(-2, +2)
.Expiration(0, 180));
// Adding this to reproduce GH issue #2314
SetWarmup(TimeSpan.FromMinutes(1));
@@ -83,7 +84,7 @@ namespace QuantConnect.Algorithm.CSharp
Liquidate();
}
foreach(var kpv in slice.Bars)
foreach (var kpv in slice.Bars)
{
Log($"---> OnData: {Time}, {kpv.Key.Value}, {kpv.Value.Close:0.00}");
}
@@ -107,29 +108,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 471124;
public long DataPoints => 15130;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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", "418"},
{"Total Orders", "420"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000000"},
{"End Equity", "952636.6"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -145,10 +153,11 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$543.40"},
{"Estimated Strategy Capacity", "$3000.00"},
{"Lowest Capacity Asset", "GOOCV W78ZFMEBBB2E|GOOCV VP83T1ZUHROL"},
{"Estimated Strategy Capacity", "$4000.00"},
{"Lowest Capacity Asset", "GOOCV W78ZFMEBFLDY|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "338.60%"},
{"OrderListHash", "c9eb598f33939941206efc018eb6ee45"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "8229716b93428dc885cf856b4cc9fc35"}
};
}
}

View File

@@ -35,7 +35,7 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateOptionsAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "GOOG";
public Symbol OptionSymbol;
private Symbol _optionSymbol;
public override void Initialize()
{
@@ -45,14 +45,13 @@ namespace QuantConnect.Algorithm.CSharp
var equity = AddEquity(UnderlyingTicker);
var option = AddOption(UnderlyingTicker);
OptionSymbol = option.Symbol;
_optionSymbol = option.Symbol;
// set our strike/expiry filter for this option chain
option.SetFilter(u => u.Strikes(-2, +2)
option.SetFilter(u => u.StandardsOnly().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)));
.Expiration(0, 180)); // .Expiration(TimeSpan.Zero, TimeSpan.FromDays(180)));
// use the underlying equity as the benchmark
SetBenchmark(equity.Symbol);
@@ -64,10 +63,10 @@ namespace QuantConnect.Algorithm.CSharp
/// <param name="slice">The current slice of data keyed by symbol string</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested && IsMarketOpen(OptionSymbol))
if (!Portfolio.Invested && IsMarketOpen(_optionSymbol))
{
OptionChain chain;
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
if (slice.OptionChains.TryGetValue(_optionSymbol, out chain))
{
// we find at the money (ATM) put contract with farthest expiration
var atmContract = chain
@@ -104,29 +103,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 471124;
public long DataPoints => 15012;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "99718"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -143,9 +149,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$1300000.00"},
{"Lowest Capacity Asset", "GOOCV 30AKMEIPOSS1Y|GOOCV VP83T1ZUHROL"},
{"Lowest Capacity Asset", "GOOCV 30AKMEIPOX2DI|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "10.71%"},
{"OrderListHash", "6b2f02d5cedb870e539a7bfb967c777f"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "19ba1220073493495880581b38df2da9"}
};
}
}

View File

@@ -0,0 +1,152 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using QuantConnect.Data;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using System;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// A demonstration of consolidating options data into larger bars for your algorithm.
/// </summary>
public class BasicTemplateOptionsConsolidationAlgorithm: QCAlgorithm, IRegressionAlgorithmDefinition
{
private Dictionary<Symbol, IDataConsolidator> _consolidators = new();
public override void Initialize()
{
SetStartDate(2013, 10, 7);
SetEndDate(2013, 10, 11);
SetCash(1000000);
var option = AddOption("SPY");
option.SetFilter(-2, 2, 0, 189);
}
public void OnQuoteBarConsolidated(object sender, QuoteBar quoteBar)
{
Log($"OnQuoteBarConsolidated called on {Time}");
Log(quoteBar.ToString());
}
public void OnTradeBarConsolidated(object sender, TradeBar tradeBar)
{
Log($"OnTradeBarConsolidated called on {Time}");
Log(tradeBar.ToString());
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach(var security in changes.AddedSecurities)
{
IDataConsolidator consolidator;
if (security.Type == SecurityType.Equity)
{
consolidator = new TradeBarConsolidator(TimeSpan.FromMinutes(5));
(consolidator as TradeBarConsolidator).DataConsolidated += OnTradeBarConsolidated;
}
else
{
consolidator = new QuoteBarConsolidator(new TimeSpan(0, 5, 0));
(consolidator as QuoteBarConsolidator).DataConsolidated += OnQuoteBarConsolidated;
}
SubscriptionManager.AddConsolidator(security.Symbol, consolidator);
_consolidators[security.Symbol] = consolidator;
}
foreach(var security in changes.RemovedSecurities)
{
_consolidators.Remove(security.Symbol, out var consolidator);
SubscriptionManager.RemoveConsolidator(security.Symbol, consolidator);
if (security.Type == SecurityType.Equity)
{
(consolidator as TradeBarConsolidator).DataConsolidated -= OnTradeBarConsolidated;
}
else
{
(consolidator as QuoteBarConsolidator).DataConsolidated -= OnQuoteBarConsolidated;
}
}
}
/// <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 List<Language> Languages { get; } = new() { 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>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000000"},
{"End Equity", "1000000"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-8.91"},
{"Tracking Error", "0.223"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -34,21 +34,21 @@ namespace QuantConnect.Algorithm.CSharp
/// <meta name="tag" content="filter selection" />
public class BasicTemplateOptionsDailyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "GOOG";
public Symbol OptionSymbol;
private const string UnderlyingTicker = "AAPL";
private Symbol _optionSymbol;
private bool _optionExpired;
public override void Initialize()
{
SetStartDate(2015, 12, 23);
SetEndDate(2016, 1, 20);
SetStartDate(2015, 12, 15);
SetEndDate(2016, 2, 1);
SetCash(100000);
var equity = AddEquity(UnderlyingTicker, Resolution.Daily);
var option = AddOption(UnderlyingTicker, Resolution.Daily);
OptionSymbol = option.Symbol;
_optionSymbol = option.Symbol;
option.SetFilter(x => x.CallsOnly().Strikes(0, 1).Expiration(0, 30));
option.SetFilter(x => x.CallsOnly().Expiration(0, 60));
// use the underlying equity as the benchmark
SetBenchmark(equity.Symbol);
@@ -63,7 +63,7 @@ namespace QuantConnect.Algorithm.CSharp
if (!Portfolio.Invested)
{
OptionChain chain;
if (slice.OptionChains.TryGetValue(OptionSymbol, out 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);
@@ -117,48 +117,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 36834;
public long DataPoints => 308;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "2"},
{"Average Win", "0%"},
{"Average Loss", "-1.31%"},
{"Compounding Annual Return", "-15.304%"},
{"Drawdown", "1.300%"},
{"Average Loss", "-1.16%"},
{"Compounding Annual Return", "-8.351%"},
{"Drawdown", "1.200%"},
{"Expectancy", "-1"},
{"Net Profit", "-1.311%"},
{"Sharpe Ratio", "-3.607"},
{"Sortino Ratio", "-1.188"},
{"Probabilistic Sharpe Ratio", "0.035%"},
{"Start Equity", "100000"},
{"End Equity", "98844"},
{"Net Profit", "-1.156%"},
{"Sharpe Ratio", "-4.04"},
{"Sortino Ratio", "-2.422"},
{"Probabilistic Sharpe Ratio", "0.099%"},
{"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"},
{"Alpha", "-0.058"},
{"Beta", "0.021"},
{"Annual Standard Deviation", "0.017"},
{"Annual Variance", "0"},
{"Information Ratio", "1.49"},
{"Tracking Error", "0.289"},
{"Treynor Ratio", "-3.212"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "GOOCV W78ZFMML01JA|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "0.05%"},
{"OrderListHash", "27226eb0860aa34fd513a8a66a732ad0"}
{"Estimated Strategy Capacity", "$72000.00"},
{"Lowest Capacity Asset", "AAPL W78ZEO29CFS6|AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "0.02%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "5639c19a7d56ec312f61029b943903b8"}
};
}
}

View File

@@ -14,7 +14,6 @@
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
@@ -36,7 +35,7 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateOptionsFilterUniverseAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "GOOG";
public Symbol OptionSymbol;
private Symbol _optionSymbol;
public override void Initialize()
{
@@ -46,7 +45,7 @@ namespace QuantConnect.Algorithm.CSharp
var equity = AddEquity(UnderlyingTicker);
var option = AddOption(UnderlyingTicker);
OptionSymbol = option.Symbol;
_optionSymbol = option.Symbol;
// Set our custom universe filter, Expires today, is a call, and is within 10 dollars of the current price
option.SetFilter(universe => from symbol in universe.WeeklysOnly().Expiration(0, 1)
@@ -64,7 +63,7 @@ namespace QuantConnect.Algorithm.CSharp
if (!Portfolio.Invested)
{
OptionChain chain;
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
if (slice.OptionChains.TryGetValue(_optionSymbol, out chain))
{
// Get the first ITM call expiring today
var contract = (
@@ -95,29 +94,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 1252633;
public long DataPoints => 12290;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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 Orders", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.40%"},
{"Compounding Annual Return", "-21.622%"},
{"Compounding Annual Return", "-20.338%"},
{"Drawdown", "0.300%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "99689"},
{"Net Profit", "-0.311%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
@@ -136,7 +142,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "15.08%"},
{"OrderListHash", "f76ee0af976faeb84643e8fcd6c7b331"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "c53bc9318676161ed3b7797c945e2113"}
};
}
}

View File

@@ -134,48 +134,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 993927;
public long DataPoints => 17487;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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.14%"},
{"Average Loss", "-0.28%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "385.400%"},
{"Expectancy", "0.502"},
{"Net Profit", "-386.489%"},
{"Sharpe Ratio", "-0.033"},
{"Total Orders", "5"},
{"Average Win", "0.13%"},
{"Average Loss", "-0.30%"},
{"Compounding Annual Return", "-46.395%"},
{"Drawdown", "1.600%"},
{"Expectancy", "0.429"},
{"Start Equity", "100000"},
{"End Equity", "99149.50"},
{"Net Profit", "-0.850%"},
{"Sharpe Ratio", "-4.298"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "1.235%"},
{"Probabilistic Sharpe Ratio", "15.319%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0.50"},
{"Alpha", "-94.012"},
{"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"},
{"Profit-Loss Ratio", "0.43"},
{"Alpha", "-0.84"},
{"Beta", "0.986"},
{"Annual Standard Deviation", "0.098"},
{"Annual Variance", "0.01"},
{"Information Ratio", "-9.299"},
{"Tracking Error", "0.091"},
{"Treynor Ratio", "-0.428"},
{"Total Fees", "$4.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "13.46%"},
{"OrderListHash", "135d5cf7bc14eb9eb88260bbf6b3a671"}
{"Portfolio Turnover", "13.50%"},
{"Drawdown Recovery", "2"},
{"OrderListHash", "2ab4ffc0944a2888a3be0568c2570a79"}
};
}
}

View File

@@ -35,7 +35,7 @@ namespace QuantConnect.Algorithm.CSharp
public class BasicTemplateOptionsHourlyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "AAPL";
public Symbol OptionSymbol;
private Symbol _optionSymbol;
public override void Initialize()
{
@@ -45,10 +45,10 @@ namespace QuantConnect.Algorithm.CSharp
var equity = AddEquity(UnderlyingTicker, Resolution.Hour);
var option = AddOption(UnderlyingTicker, Resolution.Hour);
OptionSymbol = option.Symbol;
_optionSymbol = option.Symbol;
// set our strike/expiry filter for this option chain
option.SetFilter(u => u.Strikes(-2, +2)
option.SetFilter(u => u.StandardsOnly().Strikes(-2, +2)
// Expiration method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
.Expiration(0, 180));
@@ -64,10 +64,10 @@ namespace QuantConnect.Algorithm.CSharp
/// <param name="slice">The current slice of data keyed by symbol string</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested && IsMarketOpen(OptionSymbol))
if (!Portfolio.Invested && IsMarketOpen(_optionSymbol))
{
OptionChain chain;
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
if (slice.OptionChains.TryGetValue(_optionSymbol, out chain))
{
// we find at the money (ATM) put contract with farthest expiration
var atmContract = chain
@@ -104,29 +104,36 @@ namespace QuantConnect.Algorithm.CSharp
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 32351;
public long DataPoints => 9504;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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"},
{"Total Orders", "5"},
{"Average Win", "0%"},
{"Average Loss", "-0.07%"},
{"Compounding Annual Return", "-12.496%"},
{"Compounding Annual Return", "-11.517%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "99866"},
{"Net Profit", "-0.134%"},
{"Sharpe Ratio", "-9.78"},
{"Sortino Ratio", "0"},
@@ -143,9 +150,10 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "1.434"},
{"Total Fees", "$4.00"},
{"Estimated Strategy Capacity", "$1000.00"},
{"Lowest Capacity Asset", "AAPL 2ZTXYMUAHCIAU|AAPL R735QTJ8XC9X"},
{"Lowest Capacity Asset", "AAPL 2ZTXYMUAHGSME|AAPL R735QTJ8XC9X"},
{"Portfolio Turnover", "2.28%"},
{"OrderListHash", "3f6cce0fcc7b988ba378a357ede1af93"}
{"Drawdown Recovery", "0"},
{"OrderListHash", "70bbc60c969f18e943e8e00cf0f7a0ea"}
};
}
}

View File

@@ -43,14 +43,12 @@ namespace QuantConnect.Algorithm.CSharp
SetEndDate(2021, 1, 10);
SetCash(1000000);
var spx = AddIndex("SPX").Symbol;
// regular option SPX contracts
var spxOptions = AddIndexOption(spx);
var spxOptions = AddIndexOption("SPX");
spxOptions.SetFilter(u => u.Strikes(0, 1).Expiration(0, 30));
// weekly option SPX contracts
var spxw = AddIndexOption(spx, "SPXW");
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)
@@ -100,48 +98,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 57794;
public virtual long DataPoints => 21467;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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%"},
{"Total Orders", "5"},
{"Average Win", "0.63%"},
{"Average Loss", "-0.03%"},
{"Compounding Annual Return", "54.478%"},
{"Drawdown", "0.400%"},
{"Expectancy", "-0.5"},
{"Net Profit", "0.588%"},
{"Sharpe Ratio", "0.836"},
{"Expectancy", "23.219"},
{"Start Equity", "1000000"},
{"End Equity", "1006025"},
{"Net Profit", "0.602%"},
{"Sharpe Ratio", "2.62"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "51.980%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.286"},
{"Beta", "-0.04"},
{"Probabilistic Sharpe Ratio", "63.221%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "23.22"},
{"Alpha", "0.067"},
{"Beta", "-0.013"},
{"Annual Standard Deviation", "0.004"},
{"Annual Variance", "0"},
{"Information Ratio", "-98.963"},
{"Tracking Error", "0.072"},
{"Treynor Ratio", "-0.086"},
{"Information Ratio", "-50.808"},
{"Tracking Error", "0.086"},
{"Treynor Ratio", "-0.725"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$580000.00"},
{"Lowest Capacity Asset", "SPXW 31K54PVWHUJHQ|SPX 31"},
{"Portfolio Turnover", "0.48%"},
{"OrderListHash", "07469a94a93198bbccadc8bc9cdfe87a"}
{"Lowest Capacity Asset", "SPXW 31K54PVWHYTTA|SPX 31"},
{"Portfolio Turnover", "0.40%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "03148bbb5453fc1056a3285bd31ce158"}
};
}
}

View File

@@ -92,7 +92,7 @@ namespace QuantConnect.Algorithm.CSharp
Debug(orderEvent.ToString());
if (orderEvent.Symbol.ID.Symbol != "SPXW")
{
throw new Exception("Unexpected order event symbol!");
throw new RegressionTestException("Unexpected order event symbol!");
}
}
@@ -104,48 +104,56 @@ namespace QuantConnect.Algorithm.CSharp
/// <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 };
public virtual List<Language> Languages { get; } = new() { Language.CSharp };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public virtual long DataPoints => 40893;
public virtual long DataPoints => 16680;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public virtual int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
/// <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", "10"},
{"Average Win", "0.47%"},
{"Total Orders", "10"},
{"Average Win", "0.46%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "99.729%"},
{"Compounding Annual Return", "101.998%"},
{"Drawdown", "0.100%"},
{"Expectancy", "24.484"},
{"Net Profit", "0.890%"},
{"Sharpe Ratio", "8.078"},
{"Expectancy", "24.137"},
{"Start Equity", "1000000"},
{"End Equity", "1009050"},
{"Net Profit", "0.905%"},
{"Sharpe Ratio", "8.44"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "93.697%"},
{"Probabilistic Sharpe Ratio", "95.546%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "49.97"},
{"Alpha", "-1.975"},
{"Beta", "0.301"},
{"Profit-Loss Ratio", "49.27"},
{"Alpha", "-2.01"},
{"Beta", "0.307"},
{"Annual Standard Deviation", "0.021"},
{"Annual Variance", "0"},
{"Information Ratio", "-143.477"},
{"Tracking Error", "0.049"},
{"Treynor Ratio", "0.566"},
{"Information Ratio", "-144.654"},
{"Tracking Error", "0.048"},
{"Treynor Ratio", "0.589"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$13000000.00"},
{"Lowest Capacity Asset", "SPXW XKX6S2GM9PGU|SPX 31"},
{"Lowest Capacity Asset", "SPXW XKX6S2GMDZSE|SPX 31"},
{"Portfolio Turnover", "0.28%"},
{"OrderListHash", "69b28e4f5b33ff54f173c14ea1e00c50"}
{"Drawdown Recovery", "2"},
{"OrderListHash", "9d03f85003416861df07ccb31a18af9a"}
};
}
}

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