Compare commits

...

277 Commits
11368 ... 12921

Author SHA1 Message Date
Martin-Molinero
0931ae868a Fix multiple coarse selection algorithms (#5927)
- Fix for live trading multiple coarse selections. Adding unit test
  reproducing issue.
2021-09-14 20:27:09 -03:00
Martin-Molinero
e13df5c901 Fix null reference loading existing holdings and cash balance (#5925) 2021-09-14 11:20:03 -03:00
Martin-Molinero
7be1b7db1a Algorithm Language can be case insensitive (#5924) 2021-09-13 10:31:31 -03:00
Gerardo Salazar
024d416ddd Adds support for getting a Lean symbol based on FIGI, CUSIP, ISIN, SEDOL (#5922)
* Adds support for getting a Lean symbol based on FIGI, CUSIP, ISIN, SEDOL

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

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

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

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

* Add null check for SecurityDefinitions

* Fix unit tests

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

* Get types from SM

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

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

* Fix naming in config

* Add license messages

* Add fees for stablecoins

* add kraken databases

* Review fixes, tests added

* Remove redundant field and using

* add CanUpdateOrder & summary

* Remove null

* Change to equal

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

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

* Update TimeProfile.cs to include valueAreaVolumePercentage parameter

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

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

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

* Code styling request changes

* Minor suggestions

* Minor renaming tweaks

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

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

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

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

consider fillQuantity as total filled quantity

cover edge case of fully filled

fix async events received from zerodha

indentation fix

* Fix coding style

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

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

* Fix unit tests

* Add QCAlgorithm.GetLastKnownPrices API

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

* Adding more unit tests for GetLastKnownPrice

* Address reviews

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

* Address review: improve CoinAPI stability by making inputted market lowercase
2021-08-27 13:26:55 -03:00
Martin-Molinero
9acf68ad19 Bump pythonNet to 2.0.6 (#5881) 2021-08-26 18:01:05 -03:00
Martin-Molinero
5ebf451fb3 Fix for python SetHoldings precision loss (#5879)
- After https://github.com/QuantConnect/Lean/pull/5872 trading API
  changes numpy float64 was not converted correctly by pythonNet and
  used an int. Reverting API changes and adding regression test. This
  should be fixed at pythonNet layer
2021-08-25 15:25:39 -03:00
Gerardo Salazar
a4d49c05ca Adds ETF(...) to UniverseDefinitions (#5873)
* Adds ETF(...) to UniverseDefinitions

  * Adds ETF constituents universe framework regression algorithm
    for C#/Python

* Address review: adds test cases for ticker/Symbol ETF universe additions

  * Fixes bug where null Market would result in null dereference exception

* Address review: add missing Index tests

* Address review: don't hardcode market when creating constituent universe

  * Uses Brokerage Model's default markets collection to determine
    the market for the given security type

* Address review: restore QC500 and DollarVolume.Top(...)

  * Restores algorithms related to both helper universe
    definition methods

* Address review: remove copy to output directory for python algos

* Add example algorithms for ETF constituent universes using custom RSI alpha model

* Address review: adjust algorithm to use cache + algo RSI & clean up code

* Address review: make ETF Constituent RSI Alpha Model algo a regression test

* Address review: increase trade count and remove single trade logic
2021-08-25 11:22:31 -03:00
Martin-Molinero
aaba566954 Alpha Streams Improvements. Python Imports (#5874)
* Order handling improvements

- Execution model will only trigger market order if they are above the
  minimum order margin portfolio percetage value
- SecurityCache.Reset is complete

* Python Import fixes

- Add regression test for ImmediateExecutionModel minimum order margin
  check
2021-08-24 11:15:48 -03:00
Martin-Molinero
bf28a1d313 Add basic template Atreyu algorithm (#5872)
* Add basic template Atreyu algorithm

- Add C# and Python basic template atreyu algorithm. Show casing how to
  specify exchange to execute in different ways.
- Adjust trading API to allow specifying order properties to use

* Lean Exchange improvements

- Rename PrimaryExchange to Exchange
- OrderPropeties will use Exchange enum instead of string
- Adding BSE exchange value

* Regression tests fixes
2021-08-23 18:24:44 -03:00
Julio
85a4d3364b Add prefix "oanda-" to access-token (#5870)
Add prefix "oanda-" to account-id
2021-08-23 10:55:31 -03:00
IlshatGaripov
eccca2c029 Fix for Trailing Stop Risk Management Model (#5791)
* To fix the referenced issue

* Fixing up TrailingStopRiskManagementModel

* Fix-ups to address review

* Impl. tests + relevant improvements

* Minor logic improvement at first dictionary update

* Regression test small fix

* Adds explicit 'D' suffix for numbers in test case double arr

* Use integer values in test cases

* Removes failing testcases in MaximumDrawdownPercentPerSecurityTests (!) & renaming

* Revert "Removes failing testcases in MaximumDrawdownPercentPerSecurityTests (!) & renaming"

This reverts commit f9cd279f8c.

* Fix up for failing test cases
2021-08-20 15:14:36 -03:00
Martin-Molinero
b0314e1c7c Fix for alpha license (#5868)
* Fix organization read alpha license field

* Add import statement for python
2021-08-19 15:51:48 -03:00
Martin-Molinero
3410832ccf Alpha holdings state (#5770)
* Alpha holdings state

- Alpha result packet will optionally provide the algorithms portfolio
  state

* Rename

* Convert AlphaStreamsPortfolio to data source

* Improvements on AlphaStreams algorithm

* Fix regression tests

* Add unit tests for EW AS PCM and fixing bugs

* Protobuf AlphaStreamsPortfoliot staState

- Protobuf AlphaStreamsPortfolioState. Adding unit tests
- Add variable TPV tests for EW ASPCM

* Add alpha license to Organization response

* Improvements EW AS PCM respects free portfolio value

* Fixes

- Update tests expected statistics results affected by MHDB custom data timezone fix
- Fix for Extensions.IsCustomDataType

* Fixed and adding more regression tests

- Adding support and regression test with alpha consumer with different account currency
- Adding support and regression test of a universe adding custom data
  types
- Add support and regression test for algorithm alpha consumer with existing holdings

* Add AlphaStreamsOrderEvent data type
2021-08-19 13:56:18 -03:00
Stefano Raggi
d573a0f6c7 BrokerageTransactionHandler - handle OrderStatus.New in order update/cancel (#5867) 2021-08-19 12:01:38 -03:00
IlshatGaripov
7a3d8667c5 More logging for BinanceRestApiClient (#5846)
* More logging for BinanceRestApiClient

* Changing LogLevel to Debug for history providers : Binance, Polygon

* Minor fixes

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-08-18 11:25:51 -03:00
Martin-Molinero
c3543f844a Add paper trading for Binance (#5859)
- Adding paper trading support for binance
2021-08-18 10:57:45 -03:00
Martin-Molinero
1fdb36ee89 Improve object store logs (#5864) 2021-08-18 10:33:34 -03:00
Gerardo Salazar
cd9e451ead Adds Support for ETF Constituent Universes (#5862)
* Adds support for ETF constituent universes

  * Adds filtering for universe data if it doesn't match the
    universe subscription type

  * Update mapping for ALL underlying Symbols if
    `Symbol.UpdateMappedSymbol(...)` is called. Required to support
    constituent ETF universes that might have mapping events

  * Delistings of composite constituent universe Symbol will result in
    removal of universe securities.

  * Added regression algorithms for ETF constituent mappings (C#/Python),
    along with data required to run locally

  * Refactor universe delistings in SubscriptionSynchronizer -
    big thank you to @Martin-Molinero :)

* Address review: update regression algorithms and add explanatory comments

* Address review: add additional checks to delisting regression algorithms

  * Adds new regression algorithm testing the addition of a universe
    without calling AddEquity() and asserts same behavior
2021-08-17 19:54:29 -03:00
Stefano Raggi
b4f6b51ad1 Update IBAutomater to v2.0.52 (#5863) 2021-08-17 17:07:33 -03:00
Stefano Raggi
a5e395d298 Update IBAutomater to v2.0.50 (#5860)
* Update IBAutomater to v2.0.47

* Update IBAutomater to v2.0.48

* Update IBAutomater to v2.0.49

* Update IBAutomater to v2.0.50
2021-08-16 21:08:22 -03:00
Stefano Raggi
a40329c70c Update IBAutomater to v2.0.46 (#5852) 2021-08-12 11:32:14 -03:00
Alexandre Catarino
6546647e08 Get Best Effort Price For Fill Price (#5855)
`EquityFillModel` will use Trade Tick or TradeBar data if there is no L1 data available leading to filling to stale price.
2021-08-12 10:16:20 -03:00
Martin-Molinero
46829f0f01 Dependency clean up (#5834) 2021-08-11 12:39:00 -03:00
Colton Sellers
e722e72aaa Pandas Mapper Recursion Bug Fix (#5848)
* Adjust wrapper

* Adjustments

* Add red -> green unit tests

* Address review
2021-08-10 20:32:09 -03:00
Martin-Molinero
e92230a7fe Fix SubscriptionDataReader auxiliary data out of order (#5843)
* Fix SubscriptionDataReader auxiliary data out of order

- Fix for SubscriptionDataReader emitting auxiliary data out of order
  due to sparse that and enumerator refresh logic. Adding regression
  algorithm
- Minor tweaks for unit tests failing on and off

* Fix for SDR internal subscriptions

- Fix for SubscriptionDataReader enumerator refresh for internal
  subscriptions which were ignored. Adding regression test
- Updating custom data regression algorithms affected by the issue
	- DropboxBaseDataUniverse was emitting a custom data point being end time
	- UnlinkedTraderBarIconicType was emitting a single data point
	  of the underlying SPY minute data when if should of emitted
	  all data points
2021-08-10 18:57:23 -03:00
Ronit Jain
7881aeb3a5 Websocket-refactor for websocket message data as text and binary (#5833)
* websocket-refactor for websocket message  as text and binary

Initial commit

websocket support for text and binary messageData

code style fixes

test fix

* delete un-used file

* zerodha websocket textMessage parse

* messageData class abscration

* Empty

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-08-10 17:40:07 -03:00
Stefano Raggi
32fdb51ab5 Update IBAutomater to v2.0.45 (#5847) 2021-08-10 12:01:29 -03:00
IlshatGaripov
190fe012f1 Perform update (#5841) 2021-08-10 11:18:23 -03:00
IlshatGaripov
893ca2b41d Makes sure to create directory for results-destination-folder (#5842) 2021-08-09 17:39:57 -03:00
Stefano Raggi
c30bd32fb0 Fix IB history requests (#5832)
* Fix IB history requests

- Fix time zone bug causing incomplete results
- Use RegularTradingHours flag only for equities
- Second resolution data is now requested in 30 minute chunks (instead of 1 minute):
https://interactivebrokers.github.io/tws-api/historical_limitations.html

* Filter history result respecting market hours and IncludeExtendedMarketHours flag

* Add history unit tests
2021-08-09 16:57:12 -03:00
Martin-Molinero
e720147e50 Algorithm Manager will break when algorithm is deleted (#5840) 2021-08-09 15:42:13 -03:00
Martin-Molinero
b77f0122b2 Improve python exception parsing (#5831)
* Improve python exception parsing

- Improve python exception parsing adding support for line shift. Adding
  unit tests

* PythonException revert change

* Centralized and normalize algorithm runtime handling

* Adding support for C# line and file exception report
2021-08-06 20:11:54 -03:00
Colton Sellers
646adb9131 Remove Ray from ARM image (#5830) 2021-08-05 19:06:44 -03:00
Colton Sellers
e2ae173d99 Feature Python Library: Ray (#5824)
* Add Ray lib to both foundation images

* Update some version failing tests
2021-08-05 17:55:51 -03:00
Stefano Raggi
1cfc044034 Update Lean Foundation docker files to IBGateway v985.1j (#5828) 2021-08-05 17:55:30 -03:00
Alexandre Catarino
9b7af08b3e Fixes Market On Open Fill of Equity Fill Model (#5679)
* Fixes Market On Open Fill of Equity Fill Model

Only use trade data (Tick with Trade type or TradeBar) to get the open price, since MOO is filled with the opening action price. Ensure that this method doesn't use trade data from before the market opens for high-resolution data case.

Fix unit tests to show that the new implementation only fills with trade data from the current open market.

Change regression tests to reflect the bug fix.
In the `ExtendedMarketHoursHistoryRegressionAlgorithm`, MOO was filled with extended market hours.

* Fix Bug for Tick Resolution Case

For tick susbcription, the tick with the open price information is the the first valid (non-zero) tick of trade type from an open market.
Addresses peer-review by moving the if-condition for data belonging to the open market where the subscriscribed types are checked.

* Fix Bug for Low Resolution Edge Case

For the edge case where the order is placed after the trade bar is open, for example, order places at 1 pm with daily-resolution data. The fill model will not use the open of the bar that will close at midnight, since this value is prior to the order.

Adds unit test.

Change regression tests to reflect the bug fix.
In the `RegressionAlgorithm`, MOO was filled with open prior to the order. The algorithm now has one order less, since the last MOO would need to wait another day to be filled.

* Implements SaleCondition and Exchange Check For Tick

- Adds additional unit tests for MOO

* Fixes Regression Test in DataConsolidatorPythonWrapperTests

* Addresses Peer-Review

- Adds new unit test cases.
2021-08-05 12:53:04 -03:00
Stefano Raggi
1a02fbaae5 Add autorestart for Binance data connections (#5827) 2021-08-05 10:54:50 -03:00
Alexandre Catarino
ed835faf35 Change Binance Benchmark to BTCUSDC (#5823)
`BTCUSD` is not supported by Binance (see Symbol Properties Dabase)
2021-08-04 21:45:03 -03:00
Gerardo Salazar
5ea70e2a89 Adds support for CoinAPI Binance processing (#5819) 2021-08-03 21:17:23 -03:00
Martin-Molinero
2603694263 C# research will pre load all QC dlls (#5820) 2021-08-03 21:14:59 -03:00
Stefano Raggi
4a3a7a44f5 Update Lean Foundation docker files to IBGateway v985 (#5815)
* Update Lean Foundation docker files to IBGateway v985

* Add apt-get update for ARM foundation

* Update default value of IB gateway

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-08-03 19:13:38 -03:00
Martin-Molinero
76c930a035 Update readme.md 2021-08-03 11:47:27 -03:00
Martin-Molinero
12f70aab46 Add DataSource place holder (#5817) 2021-08-03 11:30:12 -03:00
Gerardo Salazar
650ce2e2b5 Removes References To Built-in Custom Data Implementations (#5793)
* WIP removal of custom data references & tests updates

* Regression algos updated and python algorithms moved to DataSource repos

* Fixes failing unit tests

* Add "LiveDataTypes" field to LiveNodePacket

* Adds Initialize() to IDataChannelProvider

  * Adds new extension method to convert
    HistoryRequest -> SubscriptionDataConfig

* Address review: Add protobuf definitions for Iconic data types

* Address review: re-adds DynamicSecurityDataAlgorithm as regression algo

  * Small adjustments to variable naming and documentation

* Move test files to respective DataSource repos
2021-08-02 19:24:45 -03:00
Martin-Molinero
ef4fea7592 Fix engine initialization (#5814) 2021-07-30 17:33:03 -07:00
Martin-Molinero
3cf9cc7d41 Update RestSharp to 106.12.0t (#5810) 2021-07-30 17:45:59 -03:00
Colton Sellers
a9b634b096 Pandas Dataframe indexing w/ list (#5813)
* Wrap df.__getitem__ to map all keys before indexing

* Add reproducing test case
2021-07-30 16:34:03 -03:00
Stefano Raggi
1793add749 Add support for IBGateway v985 (#5812)
* Add support for IBGateway v985

- Effective in TWS version 985 and later, for US stocks the bid, ask, and last size quotes are shown in shares (not in lots).

* Add missing error log in IB symbol mapper

* Trigger build
2021-07-30 13:55:26 -03:00
Martin-Molinero
41636c94c3 Common engine initialization (#5809)
- Create Lean common engine initialization class, which will be called
  by research and Lean launcher
- Fix backtest deserialization bug due to failing to handle decimal
  value
2021-07-29 21:14:17 -03:00
Stefano Raggi
2624b8c6f5 Update IBAutomater to v2.0.43 (#5807)
* Update IBAutomater to v2.0.42

* Update IBAutomater to v2.0.43
2021-07-29 20:53:38 -03:00
Colton Sellers
d8a86f182f Pandas Remapper Refactor (#5808)
* Refactor pandas mapper to support newer versions

* Clean up remapper

* Finalize deprecated tests and adjust those that should apply to new pandas

* Move mapper to its own file

* Add supporting Py tests and setup instructions

* Add license
2021-07-29 20:10:00 -03:00
Martin-Molinero
0da9d626dc Remove security from all universes holdings it (#5798)
- Calling RemoveSecurity() will remove the security from all the
  universes holdings it, there was a race condition here where it would
  just take the first universe and remove it from it.
  Adding regression test adding and removing an option contract and it's underlying
2021-07-28 18:03:09 -03:00
Jovad Uribe
9888081cc0 Relative Daily Volume Indicator (#5747)
* Relative Volume Indicator

* Requested changes and renamed indicator

* Made changes, included Resolution

* Added requested changes

* Update

* Update RelativeDailyVolumeTests.cs

* Update RelativeDailyVolume.cs

* Fixed Test Case File

* Update RelativeDailyVolume.cs

* Fixed IsReady flag
2021-07-28 18:02:34 -03:00
Martin-Molinero
611326b140 WebSocketClient improvements (#5799)
- Take lock to refresh client to avoid null reference
  exception
- Reduce gate rate
- Use extension methods to await tasks
- Avoid copying the data multiple times
2021-07-28 15:17:08 -03:00
Stefano Raggi
907a9f086c Update BinanceBrokerage to handle more than 512 symbols (#5773)
* Update BinanceBrokerage to handle more than 512 symbols

* Address review

- fetch symbol weights only if required
- remove code duplication

* Add rate limiting for new connections

* Update WebSocketMessage to include the websocket instance

* Handle resubscriptions on reconnect

* Address review

* Address review

* Remove unnecessary locking

* WebSocketClientWrapper updates

- remove allocation of receive buffer on each message
- add missing lock in Close method
- log message data when message type is Close
- fix race condition after unexpected websocket close

* Set WebSocketClientWrapper task to LongRunning

* Add missing check in GetHistory

* Fix exceptions with Binance downloader

- closes #5794
2021-07-28 11:10:40 -03:00
Stefano Raggi
0c4e577885 BitfinexBrokerage updates (#5787)
* Update BinanceBrokerage to handle more than 512 symbols

* Address review

- fetch symbol weights only if required
- remove code duplication

* Add rate limiting for new connections

* Update WebSocketMessage to include the websocket instance

* Handle resubscriptions on reconnect

* Address review

* Address review

* Remove unnecessary locking

* WebSocketClientWrapper updates

- remove allocation of receive buffer on each message
- add missing lock in Close method
- log message data when message type is Close
- fix race condition after unexpected websocket close

* Set WebSocketClientWrapper task to LongRunning

* Add missing check in GetHistory

* Fix exceptions with Binance downloader

- closes #5794

* Update Bitfinex symbols in symbol properties database

* Update BitfinexBrokerage to use BrokerageMultiWebSocketSubscriptionManager

* Address review

* Remove unnecessary locking

* Remove old channels on resubscription
2021-07-28 11:10:12 -03:00
Marco Grassi
e823dfdfb7 fix a typo, and remove all unnecessary semicolumns in Python (#5795) 2021-07-27 16:05:13 -03:00
Martin-Molinero
4469d18eb6 Set timezone for DateRules (#5796)
- If algorithm timeZone is changed Update DateRules timezone. Adding
  unit test
2021-07-27 15:34:11 -03:00
Ishant Jain
808ba17bff Indian Market Holidays & Early Open/Late Close Modified (#5792) 2021-07-26 11:14:22 -03:00
Ronit Jain
00f68b951f Zerodha - GetHistory DateTime Parse Correction (#5788)
* logging and kite connection retry

(cherry picked from commit 9845a2d79e86c338093cadcae7f41b29d897c78c)

* changed thread.sleep time for kite connection retries

* websresponse retry on error - coding style change

* datetome parse to convert time in utc

* indentation code-style fix

* zerodhaDownloader support for dataTimeZone

* removed code redundancy for single conversion without hardcoded TZ

* removed hardcode dataTimeZone and code refactor

* returns exchange TZ to lean and data TZ to local disk from downloader

* Kite historical candle timestamp TZ conversion

* added unit test for kite historical candle

* access modifier correection
2021-07-23 18:34:48 -03:00
Stefano Raggi
c07b643273 Filter Bitfinex currencies in Derivatives wallet (#5786) 2021-07-21 14:39:01 -03:00
Gerardo Salazar
95f199eae5 Bug fix: don't throw on unsupported exchanges in CoinApi converter (#5784) 2021-07-20 19:09:29 -03:00
Martin-Molinero
2cb239a330 Fix price left over split cash adjustment (#5780)
- After a split if there are left over shares we model them getting sold
  using the new price. Adding unit and regression test
2021-07-19 13:18:10 -03:00
Martin-Molinero
cb326788b3 Filter out small orders based on Setting (#5776)
* Filter out small orders based on Setting

- BuyingPowerModel will filter out small orders based on algorithm
  setting, a % of PTV, instead of hard coded 1 share value. Addin unit
  and regression tests
- Updating regression algorithms to use new setting, reduce order trades

* Update regression algorithms
2021-07-19 13:17:51 -03:00
Ronit Jain
e2e2b5f102 zerodhaDownloader support for new market convention - Market.India (#5775)
* zerodhaDownloader support for India Market

(cherry picked from commit c36272ef9c4c7eddfff77413d900faab3a2a8654)

* indenation styling fix

* zerodha donwloader

* Market.India support from zerodhaSymbolMapper

* code styling changes
2021-07-19 11:43:17 -03:00
Martin-Molinero
f75e81bd7d Add null check for API data folder (#5774)
- Api.Initialize will not throw for null data folder. Adding unit test
2021-07-16 18:27:42 -03:00
Ronit Jain
522fe14951 Zerodha ProductType customization for Fetching Positions&holdings and also while placing orders (#5766)
* re adding KiteProductType

* check kiteProductType per order and get all Product Type Account Holdings

* use WithLockedStream and remove lock unlock stream

* filter holding if config productType set otherwise fetch all

* improvements in styling and properties

* unionbank has less margin requirements, second always works
2021-07-16 11:43:14 -03:00
Martin-Molinero
9cf4075957 Send invalid orderEvent for non shortable order (#5772)
- TransactionHandler will see invalid OrderEvent for an order which
  tries to short an non shortable asset. Adding unit test, updating
  regression algorithm.
- Fix Api data price path normalization, found while testing with
shortable provider. Adding unit tests
2021-07-15 21:10:46 -03:00
Martin-Molinero
1ed390c5f7 Minor tweaks (#5771)
- Improve readme file, add nuget link, update Lean home page
- Increase 10min look back to 60 for setting currency conversion
- Replace error message for trace when minute resolution history request
  is empty
2021-07-15 13:03:46 -03:00
Jasper van Merle
f5224f8be9 Logging improvements (#5767) 2021-07-14 20:53:09 -03:00
Colton Sellers
8d11bbf0ba Update to PythonNet 2.0.5 (#5764) 2021-07-14 11:01:57 -03:00
Martin-Molinero
1dcdfe79b0 Add data paths to PriceEntry (#5761) 2021-07-13 14:56:20 -03:00
Stefano Raggi
e453635458 Update Binance symbols in symbol properties database (#5759)
* Update Binance symbols in symbol properties database

* Fix failing unit tests
2021-07-12 13:28:28 -03:00
Martin-Molinero
d84ad9ebfc Reduce research image size (#5758)
- Reduce research image size
- Increate BrokerageConcurrentMessageHandler unit test timeout
2021-07-12 09:58:11 -03:00
Martin-Molinero
f9adc6b136 Rename data permissions (#5753) 2021-07-09 22:59:14 -03:00
Jovad Uribe
e5f62fa4dd Feature Augen Price Spike Indicator (#5713)
* Added Augen Price Spike Files

* AugenPriceSpike Update

Adjusted indicator calculations and added test data from Trading View

* Requested Changes

* Minor changes
2021-07-09 20:07:15 -03:00
Colton Sellers
3430b46e6a BuyingPowerModel GetMaximumOrder Adjustments (#5756)
* Add reproducing unit test

* Apply fix to force adjustment if needed

* Adjust fee to correctly replicate original issue

* Adjust solution

* Update unit test to reflect the way this function is used

* nit - rename test

* Cleanup error message to improve reproducibility

* nit - Drop unneeded var

* Add in adjustment test cases as well, fixed
2021-07-09 19:37:48 -03:00
Colton Sellers
00ac4f33af Implement Python overload of Notify.Web for PyObject Headers (#5749)
* Implement Python overload of Notify.Web for PyObject Headers

* Address review + add unit tests
2021-07-08 21:07:19 -03:00
Colton Sellers
0d752abae6 Feature Telegram Notification (#5535)
* Lay telegram notification groundwork

* nit comments

* Implement in JSON converter, and add roundtrip test

* Update comment docs

* Implement configurable token in NotificationTelegram

* Rename to ID, due to @ handles not usable

* Address review + nits

* Nit comment fix
2021-07-07 21:06:45 -03:00
Martin-Molinero
2a77a8d3c0 Update readme.md 2021-07-07 19:50:23 -03:00
Martin-Molinero
49d6cb0021 QuantBook fundamental history request (#5743)
- Allow requiesting the entire FineFundamental object for a QuantBook
  history request. Adding unit test
2021-07-07 12:02:01 -03:00
Stefano Raggi
9a81414a94 IB Brokerage updates (#5744)
* IB Brokerage updates

- Update IBAutomater to v2.0.40
- Add config setting to enable export of IBGateway logs (default=false)
- Downgrade IB log level from Information to Warning

* Update IBAutomater to v2.0.41

* Trigger build
2021-07-07 11:26:09 -03:00
Martin-Molinero
3f85c9ab82 Update readme.md 2021-07-06 23:06:03 -03:00
Martin-Molinero
f062b54450 Update readme.md 2021-07-06 19:59:58 -03:00
Colton Sellers
64b95b2e8e MaximumOrderQuantity Error Log Expansion (#5741)
* Add more details to the log to improve insight into bugs

* Keep string formatting invariant
2021-07-06 19:26:49 -03:00
Martin-Molinero
7bcaaf8f23 Reduce dockerfoundation size (#5740)
- Clean files and conda after each docker build step
- Merge steps to reduce size
- Clear apt lists
2021-07-06 17:42:19 -03:00
bmello4688
8383163aae fixed problems with testcasesource (#5722) 2021-07-06 12:04:04 -03:00
bmello4688
04f3c850ba test fails sometimes from a race to check value (#5720)
* test fails sometimes from a race to check value

* add while limit
2021-07-05 19:03:12 -03:00
Martin-Molinero
5bd0675423 Fix minor race condition in brokerage message handler (#5736)
* Fix minor race condition in brokerage message handler

- Fix race condition where a message could be enqueued and
wait for a new call, not being processed ASAP

* Reduce BrokerageTransactionHandler logs
2021-07-03 19:46:31 -03:00
Jasper van Merle
6eb3822193 Fix coarse universe generator crashing on single processor (#5735)
* Fix coarse universe generator on single processor

* Make sure MaxDegreeOfParallelism value is not less than 1

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2021-07-03 19:08:55 -03:00
Martin-Molinero
12b62f6ec9 Add organization id to packet (#5733) 2021-07-02 20:59:59 -03:00
Martin-Molinero
8d2455b629 Add BrokerageConcurrentMessageHandler (#5731)
* Add BrokerageConcurrentMessageHandler

- Add Brokerage helper `BrokerageConcurrentMessageHandler` class to lock message stream
while executing an action, for example placing an order, adding unit tests.
- Binance will use new message handler

* Fix unit test
2021-07-02 19:11:25 -03:00
Colton Sellers
171f0f19d5 MaximumOrderQuantity Bug Fix (#5727)
* Implement solution with lightest changes possible

* Update regressions v1

* Adjust AlgorithmTradingTests

* Adjust PatternDayTradingMarginBuyingPowerModel tests

* Drop need to loop twice

* Adjust last unit test, with calculations included

* nit - comment fix

* Break out adjustment calculation to static function; add unit test

* Update Py regression

* Upgrade adjustment calculation to be smart enough to get us to target always

* nit - cleanup GetAmountToOrder

* Add license to test

* nit - comment fix

* cleanup GetAmountToOrder further

* Add additional test cases
2021-07-02 18:52:15 -03:00
Martin-Molinero
e5a50109b4 DownloaderDataProvider improvements (#5730)
- Ignore margin files requests. Only provided by ApiDataProvider
- Reduce noise by LeanData.TryParse() call on failure
2021-07-02 14:03:16 -03:00
Ronit Jain
c8d13080a8 Indian Market support for backtesting and live deploys through Zerodha (#5710)
* added symbolData class to store exchange and token values of tickers

* support for India Market

(cherry picked from commit 5f629dcb9e72426dc7b560e782cb1fae72861574)

* removed local vscode workspace file

* support for india market instead of nse and other exchanges

* changed hardcoded india values to Market.India

* changed zerodha getcash fromm available to net

* addded edge case handoing with expections

* support for market info (nse, bse) for india market

* exchange info for EmitQuoteTick

* basic testing with c#

* c# algo

* c# testing

* live orders during market open success

* support orderproperties for exchange value for order placement

* added exceptional handling cases

* fix xml descriptions for the files

* fix zerodha-product-type in DefaultOrderProperties

* add basic template for india market

* fix orderProperites for default values

* fix for local data, python implementation not available

* fix access modifiers of SymbolData

* fix variable name case

* fix single check for exchange, call to base

* fix styling, redundent code and access modifers

* fix non static not callable from static

* fix static
2021-07-02 11:06:47 -03:00
Rohan Sharma
8d352b6318 feat: Improve error message from ObjectStore (#5729) 2021-07-02 10:37:37 -03:00
Martin-Molinero
00cd8947a8 Update bitfinex channel Id (#5728) 2021-07-01 21:42:17 -03:00
Gerardo Salazar
c211d04798 Adjust AlgoSeek Futures price multipliers to quote/process prices in USD (#5725)
* Adjust AlgoSeek Futures price multipliers to quote prices in USD

* Revert changes to AUP scaling

  * After a second review, seems that this contract isn't scaled.
    The contract multiplier differs from the NYMEX Aluminum Index's
    contract multiplier, and so does the minimum price variation.
    The minimum price fluctuation seems consistent with CME's
    quoted prices, which also claims the contract is quoted in USD.

* Fix futures contract multipliers for some scaled contracts
2021-07-01 18:46:36 -03:00
Martin-Molinero
55195867a9 Reduce LTRH error log to debug (#5723) 2021-06-30 16:44:52 -03:00
Gerardo Salazar
c9a3ad35e1 Fix Futures SymbolRepresentation disambiguation of ticker with limited year information (#5715)
* Fixes bug where future converter processing includes invalid values

* Fix issue in SymbolRepresentation

* Fixup

* Empty commit

* Empty commit
2021-06-29 17:37:06 -03:00
Martin-Molinero
0d45bf5101 Add composite DataProvider (#5714)
- Add new CompositeDataProvider that will wrap multiple instance. Allows
  using for example the ApiDataProvider and a DownloaderDataProvider.
- Adjusting ProductJsonConverter after recent Modules addition
2021-06-29 12:40:31 -03:00
Martin-Molinero
66552b49bd Add new DownloaderDataProvider (#5709)
* Add new DownloaderDataProvider

- Moving LeanDataWrite and IDataDownloader to common project
- Add new BaseDataDownloaderDataProvider with concurrency helper method
- Add new DownloaderDataProvider which will use a IDataDownloader or
  IBrokerage implementation as data source

* Add support for downloading symbol chains data
2021-06-28 15:56:10 -03:00
Martin-Molinero
0642f58bda Fix SEC downloader (#5711) 2021-06-28 11:24:23 -03:00
Colton Sellers
c7e6c96933 Encode/Decode Extension Addition (#5708)
* Implement Encode/Decode Base 64

* Add unit test
2021-06-25 17:50:55 -03:00
Colton Sellers
5c10b2cb82 Move Encode to Extension Util (#5707)
* Move to extension util

* Move decode to extensions
2021-06-25 10:26:10 -03:00
Antoine Dray
4dd2ad85a9 Fix KrakenDownloader error on invalid pair format (#5703) (#5704)
The Kraken allow queries from pairs of format XBTUSD and XXBTZUSD but it will only return data with the XXBTZUSD causing errors when XBTUSD ticker is specified.
This commit adds a more meaningful error when KDL is called with XBTUSD format.
2021-06-24 19:42:13 -03:00
Martin-Molinero
10defd4928 Include IB CSharpAPI in brokerage nuget (#5706) 2021-06-24 18:59:14 -03:00
Martin-Molinero
891aeb87d3 Update readme.md 2021-06-23 18:17:25 -03:00
Stefano Raggi
2fa07561b1 Add missing IBGateway dependency library (#5696) 2021-06-23 17:12:50 -03:00
Stefano Raggi
148b9c8d45 IB Brokerage updates (#5695)
* Update IBAutomater to v2.0.39

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

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

* Add unit tests for both cases

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

* nit - rename tests

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

* Testing

* Filter final results

* Explicitly filter alpha charts if not needed

* Use filtered charts for Live results handler

* Refactor solution to manage alpha charts internally by creator

* nit comment fixes

* Implement drawdown as default chart

* Implement Capacity Estimate for backtest default chart

* Add default values to QC.Plotting

* Adjust drawdown calculation

* Only sample "Capacity" once a day

* Implement Volume chart

* Nit fixes

* Volume Chart adjustments and fixes

* Rename to "Assets Sales Volume"

* Implement Exposure Sampling

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

* Add new plots to default charts

* nit change name

* Address reviews

* Reduce duplication and clean up exposure sampling

* Address reviews

* Improve sample exposure

* Address review

* Only enumerate holdings once

* nit - comments

* Post rebase fix

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

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

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

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

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

- Result handlers can receive notifications for brokerage message events

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

* Updates Unit Tests

* Updates Regression Tests

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

* Updates Regression Tests 2

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

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

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

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

* Revert File Update for SPWR and SPWRA

* Fix Regression Tests

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

* Changes Optimization Method in MinimumVariancePortfolioOptimizer [Py]

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

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

* Update VSCode Launch options

* Drop issue these changes fixes

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

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

* Add reproducing unit test

* Only resolve mapping for types that require it

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

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

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

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

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

* Centralize algorithm imports

* Add regression test GH action

* Unit test python import clean up

* Join research and main imports

* More python import clean up

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

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

* Only enforce our case after the BB is ready

* Nit comment fixes

* Add unit test

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

* Update readme

* Notebook adjustments

* Drop launch script support

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

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

* Clean up some details after testing

* Adjustments

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

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

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

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

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

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

* PaperBrokerage config based live state recovery

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

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.py

* Create SpreadExecutionModel.cs

* Create SpreadExecutionModelTests.cs

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModel.cs

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModel.cs

* Update SpreadExecutionModel.cs

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModel.cs

* Update QuantConnect.Algorithm.Framework.csproj

* Create SpreadExecutionModelRegressionAlgorithm.py

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModelTests.cs

* Update SpreadExecutionModel.py

* Update SpreadExecutionModel.cs

* Address review

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

* Address review. Add comment and Abs spread percent

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

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

* this has to be removed

* -- Fixes -- [WIP]

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

* Finishes GetEquityTradeTicks() impl.

* Do not break iteration if result is null

* Uses DisposeSafely and fixes a typo

* To use IEnumerable for return type in GetHistoryAsync

* Fixes GetEquityQuoteTicks()

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

* SubscriptionManager -> revert the changes

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

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

* Fixes GetForexQuoteTicks()

* Introduce ResponseSizeLimitAggregateData

* Fixes up GetCryptoTradeTicks()

* Small fixes for tick processing methods

* Removes launchSettings.json

* Refactor download data logic

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

* Update PolygonDataQueueHandler.cs

Remove commented code

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

* Use data provider for AllShortableSymbols

* Refactor of NeedToDownload logic

* Adjustments

* nit - cleanup

* Expand test cases

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

* Filter brokerage message event for IB warning

- 10197 - No market data during competing live session.

* Update IBAutomater to v2.0.32

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

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

* Add reproducing test

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

* Add regression algorithm for issue

* Minor tweaks

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

* key -> filePath rename and some cleanup

* Refactor

* Add Organizations Endpoints

* Add some organization api wrapper objects

* Address namespace issue

* Reorganize Api Test into seperate files using one ApiTestBase

* Add Organization tests

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

* Add License to test base

* Update /data endpoint functions and response objects

* Update ApiDataProvider Logic

* Handle deserialization of organization products

* Simplify converter

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

* Add missing header

* Make arguement exception

* Api adjustments

* Add Zip factor and map file providers

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

* Refactor FactorFileProvider to use DataProvider to fetch files

* Use resulting MinimumDate in construction of FactorFile

* Nit FactorFile comments and arrangement

* Refactor MapFileProviders to use DataProvider for fetching files

* Refactor ZipFileProvider

* Clean up

* Refactor Backtesting Future/Option chain providers to use dataprovider

* Fixes for data/ endpoints and test adjustments

* Response objects adjustments/cleanups

* ApiDateProvider fixes and testing

* Add LocalZipFactorFileTests

* Update ApiDataProvider download test to verify stream is not null

* Implement posting of agreement summary and signed time

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

* Clarify default token on ApiTestBase

* Adjust summary

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

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

* Fix multiple markets for ZipFactorFile provider

* Use Symbol as cache key

* Api.cs review

* Dispose of factorFileStream after reading

* Use zip.EntryFileNames

* Address a few reviews

* Few more fixes

* Address Api Review

* Add Job Org id to config

* Minor tweaks

* Compare with invariant culture

* Fixes Option Universe selection

* ZipEntryNameSubscriptionDataSourceReader will use IDataProvider

* Fix research

* Fix null reference exception

* Make duplicate log debug

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

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

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

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

* Update IBAutomater to v2.0.28

* Update IBAutomater to v2.0.29

* Update IBAutomater to v2.0.30

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

* Fix broken Python Universe Selection model

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

* Make C# version match

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

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

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

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

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

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

* Adds suspicious tick filtering to ticks

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

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

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

* config

* make method public

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

* Add Sleep before restarting IBAutomater

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

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

# Conflicts:
#	Tests/QuantConnect.Tests.csproj

* Some fixes

* Refactoring + Adds NewPivotPointFormed event

* Fixing tests

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

* To address review + more fixes

* Fixing xml comments typos

* Implements separate rolling windows to calculate highs and low

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

* Overrides Reset()

* Adds a helper method

* Change numerical return to Enum types

* Changes IsReady condition :

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

* Address reviews

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

* Update regression

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

* Update some incorrect marketHours

* Update all Oanda CFD market hours

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

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

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

* Update readme

* Mention building manually is optional

* Add portable pdbs to use C# coreclr debugging

* Update VS and VSCode docs

* Add reference to Lean CLI in main readme

* remove run_docker scripts

* Remove PyCharm files

* Cleanup

* Remove run_docker tasks from VS Code

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

* Style and documentation changes requested

* Throw exception for unexpected response content

* Added rate limiting to AlphaVantageDataDownloader

* Minor tweaks and rebase

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

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

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

* Clean up

* Process review comments

* Add tests

* symbol -> potentialConversionRateSymbol

* Ensure regression tests run/get data

* Fix broken test

* Process review comments

* Process review comments

* Simplify currency conversion logic

* Performance improvement, doc updates and test rename

* Rebase fixes

* Remove obsolete properties

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

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

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

* Add BaseSetupHandlerTests

* Minor tweaks. Adding missing dispose call.

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

* Update test

* Add regression

* Cleanup regression

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

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

* Use UniverseSettings for leverage, fillforward, and extendedmarkethours

* Update unrequested security message

* Use UniverseSettings ExtendedMarketHours for underlying on OptionContracts

* Add unit test to prove setting persistence

* Cleanup unit test

* Adjust crypto unit test assert

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

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

* Address reviews

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

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

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

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

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

* Update unit tests expected result

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

* Refactor solution to centralized function `Scale`

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

* Add regression algorithm

* Update regression statistics

* Address review

* NOP to trigger cloud build

* adjust QuoteBar ask and bid size

* adjust broken regression

* Update tests to include QuoteBar adjustments

* nit cleanup

* Adjust Quote Tick bid and ask sizes

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

* nit

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

* Upgrade IBAutomater to v2.0.1

* Upgrade IBAutomater to v2.0.6

* Upgrade IBAutomater to v2.0.7

* Upgrade IBAutomater to v2.0.9

* Upgrade IBAutomater to v2.0.10

* Upgrade IBAutomater to v2.0.12

* Upgrade IBAutomater to v2.0.13

* Upgrade IBAutomater to v2.0.14

* Upgrade IBAutomater to v2.0.15

* Reset disconnected flag on IBGateway exit/restart

This bug was causing invalid algorithm termination after reconnection

* Fix unhandled exceptions in exit/restart event handlers

* Upgrade IBAutomater to v2.0.16

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

* Add immediate logging for brokerage unit tests

* Tradier brokerage updates

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

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

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

* Add CoarseUniverseGenerator logs

* Fixes 100 nanosecond increment lookahead bias when parsing large numbers

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

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

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

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

  * Removes Market requirement from CoinAPI data converter

* Remove timeout on decompression of raw AlgoSeek futures data

* Updates SEC downloader to use HttpClient where requests were failing

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

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

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

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

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

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

* Refactor Estimize to speed up processing time

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

* Remove debug log statements leftover from previous commit

* Add support for non-tick Index resolutions in LeanDataWriter

* Empty commit

* Empty commit

* Empty commit

* Empty commit

* Empty commit

* Empty commit

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

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

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

* Add null checks

* Remove uninvested and untradable assets from capacty calculations

* Add SymbolCapacity influential period

* Updates Regression Tests

- DelistingEventsAlgorithm
  - Allows additional contributions from delisted AAA.1

- DelistingFutureOptionRegressionAlgorithm
  - Removes DC01H12 contributions one month later

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

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

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

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

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

* Adds Lowest Capacity Asset to Regression Tests

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

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

* Update Regressions

* Update 'Lowest Capacity Asset' to Symbol.ID

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

* Updates Regression Algorithms

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

* Updates Unit Tests

Minor changes in expected values

* Updates Regression Tests

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

* Adjusted Quantity By Lot Size in OrderTargetsByMarginImpact

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

* Reduce dictionary access x3 on OrderTargetsByMarginImpact

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

* Remove C# changes

* Update System.Reflection.Emit to 4.7.0

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

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

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

* Add simple unit test for issue #5491

* Cleanup warmup period math and add comments

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

* Centralize GetConfiguredDataFeeds()

* nit - extra space

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

* Fix breaking test

* Cleanup

* fix return var

* remove unneeded if/else

* Minor changes

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

* Stop SubscriptionUtils from forcing Adjusted mode

* Return behavior to original and add comments

* nit typo

* Add regression

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

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

* Fix ambiguous errors. Add IBAutomator net5

* Remove FXCM

* Upgrade IBAutomater to v1.0.51

ignored, and an empty message aborts the commit.

* Fix rebase

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

* Remove unrequired references

* Fixes

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

* Don't call ReadKey when input is redirected

* Fix ConsoleLeanOptimizer

* Research fixes

* Update comment

* Add vsdbg to Dockerfile

* Fixes

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

* Replace ICSharp with .NET Interactive

* Fixes after rebase

* CSharp research fixes

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

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

* Make test cover issue case

* Filter out times before startTimeUtc

* Refactor solution, fixes missing first date

* Fix case where none is expected

* Cleanup tests, add TriggerTimesNone

* Drop unused imports

* Add missing dipose call

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

* Nit error spacing

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

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

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

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

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

* IBuyingPowerModel: Add margin functions Maintenance/Initial/ForOrder

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

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

* Add ConstantBuyingPowerModel

Provides an implementation of IBuyingPowerModel that returns the same
constant value

* Update BuyingPowerModelPythonWrapper to use reflection for method names

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

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

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

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

* Support computing maintenance margin for arbitrary quantities

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

* Address review

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

* Add SecurityHolding.QuantityChanged event

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

See #4065

* PortfolioManager: Group fields and remove unused field

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

* Remove unused _currencyConverter from Security

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

* Add Parse.Enum functions

* Support disabling regression algorithms by language via config.json

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

* Implement IComparable in SecurityIdentitfier

This can be used to deterministically sort securities and symbols

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

* Fix typo in IBuyingPowerModel.GetBuyingPower xml docs

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

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

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

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

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

* Add decimal.DiscretelyRoundBy extension method

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

* Update FutureMarginBuyingPowerModelTests to respect the security's lot size

* Add core position group classes and abstractions

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

* Add SufficientBuyingPower and GetReservedBuyingPower to position group model

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

* Resolve position groups on each fill

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

* fixup! Add SufficientBuyingPower and GetReservedBuyingPower to position group model

* Add GetMaximumLotsFor{Target|Delta}BuyingPower

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

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

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

* Convert remaining IBuyingPowerModel call sites to position groups

* Rename PositionManasger.CreateDefaultGroup -> GetOrCreateDefaultGroup

Better describes its behavior

* Add Position Groups readme.md

* Add Option Strategy BuyingPowerModel

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

* Address self reviews

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

* Address reviews

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

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

* Fix typo in warning collection used

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

* Only post the message if the set has values

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

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

* Enforce a hard limit and improve message if full

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

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

* Limit max size of the warning queue to 10

* Only allow to emit once per backtest

* Set limit as var, if at limit suggest more

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

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

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

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

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

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

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

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

  * Adjusts logic to determine bar type

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

* Cover more stablecoin cases unique to our crypto brokers

* Add unit test

* Cleanup and expand test cases

* Add USDCEUR and USDCGBP to GDAX Symbols

* Add missing tickers to SPDB

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

* test is progress

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

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

* Updates SPY Market Data

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

* Updates Unit Tests to Reflect Data Update

* Updates Regression Tests to Reflect Data Update I

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

* Updates Regression Tests to Reflect Data Update II

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

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

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

* Addresses Peer-Review

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

* Cleanup futures regression

* Add Options regression

* Add IRegressionAlgorithmDefinition

* Add IRegressionAlgorithmDefinition

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

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

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

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

* Let custom data configurations bypass filter

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

* another small adjustment

* Use ExpectedBarCount in error message

* Add filter test for both cases

* Add some clarifying comments

* Verify we did recieve data in the regressions

* Make _shouldEmitAuxiliaryData private readonly

* Filter out aux data for history requests

* Remove option to not include aux data in subscriptions

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

* Cleanup comments after removed var

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

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

* Add ASI

* Add Swing Index

* Add Accumulative Swing Index

* Fix XML comment

* Add SI and ASI

* Add test data

* Add SI tests

* Add ASI tests

* Convert get only properties to methods

* Fix indicator name

* Replace special characters

* Fix indicator formula

* Replace test data

* Replace test data

* Update QCAlgorithm.Indicators.cs

* Minor format tweaks

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

* Remove logging and speed up test time advancement

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

* Cap symbol count in generator when needed
2021-04-09 10:37:35 -07:00
1617 changed files with 140622 additions and 143446 deletions

13
.editorconfig Normal file
View File

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

View File

@@ -3,29 +3,28 @@ name: Build & Test Lean
on:
push:
branches: ['*']
tags: ['*']
pull_request:
branches: [master]
jobs:
build:
runs-on: ubuntu-16.04
runs-on: ubuntu-20.04
container:
image: quantconnect/lean:foundation
steps:
- uses: actions/checkout@v2
- name: Restore nuget dependencies
run: |
nuget restore QuantConnect.Lean.sln -v quiet
nuget install NUnit.Runners -Version 3.11.1 -OutputDirectory testrunner
- name: Build
run: msbuild /p:Configuration=Release /p:VbcToolExe=vbnc.exe /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
run: dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
- name: Run Tests
run: mono ./testrunner/NUnit.ConsoleRunner.3.11.1/tools/nunit3-console.exe ./Tests/bin/Release/QuantConnect.Tests.dll --where "cat != TravisExclude" --labels=Off --params:log-handler=ConsoleErrorLogHandler
run: dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter TestCategory!=TravisExclude -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\)
- name: Generate & Publish python stubs
if: startsWith(github.ref, 'refs/tags/')
run: |
chmod +x ci_build_stubs.sh
./ci_build_stubs.sh -d -t -g #Ignore Publish as of since credentials are missing on CI
./ci_build_stubs.sh -t -g -p
env:
PYPI_API_TOKEN: ${{ secrets.PYPI_API_TOKEN }}

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

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

144
.idea/readme.md generated
View File

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

37
.idea/workspace.xml generated
View File

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

View File

@@ -1,9 +1,8 @@
sudo: required
language: csharp
mono: none
dotnet: 5.0
mono:
- 5.12.0
solution: QuantConnect.Lean.sln
os: linux
dist: focal
before_install:
- export PATH="$HOME/miniconda3/bin:$PATH"
- export PYTHONNET_PYDLL="$HOME/miniconda3/lib/libpython3.6m.so"
@@ -18,11 +17,7 @@ before_install:
- conda install -y cython=0.29.15
- conda install -y scipy=1.4.1
- conda install -y wrapt=1.12.1
install:
- nuget install NUnit.Runners -Version 3.11.1 -OutputDirectory testrunner
script:
- dotnet nuget add source $TRAVIS_BUILD_DIR/LocalPackages
- dotnet build /p:Configuration=Release /p:VbcToolExe=vbnc.exe /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
- mono ./testrunner/NUnit.ConsoleRunner.3.11.1/tools/nunit3-console.exe ./Tests/bin/Release/QuantConnect.Tests.dll --where "cat != TravisExclude" --labels=Off --params:log-handler=ConsoleErrorLogHandler
- chmod +x ci_build_stubs.sh
- sudo -E ./ci_build_stubs.sh -d -t -g -p
- dotnet build /p:Configuration=Release /v:quiet /p:WarningLevel=1 QuantConnect.Lean.sln
- dotnet test ./Tests/bin/Release/QuantConnect.Tests.dll --filter TestCategory!=TravisExclude -- TestRunParameters.Parameter\(name=\"log-handler\", value=\"ConsoleErrorLogHandler\"\)

View File

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

73
.vscode/launch.json vendored
View File

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

173
.vscode/readme.md vendored
View File

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

102
.vscode/tasks.json vendored
View File

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

View File

@@ -77,44 +77,45 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "199"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-12.472%"},
{"Compounding Annual Return", "-12.611%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-0.586"},
{"Net Profit", "-0.170%"},
{"Sharpe Ratio", "-9.693"},
{"Probabilistic Sharpe Ratio", "12.704%"},
{"Loss Rate", "79%"},
{"Win Rate", "21%"},
{"Profit-Loss Ratio", "0.95"},
{"Expectancy", "-0.585"},
{"Net Profit", "-0.172%"},
{"Sharpe Ratio", "-10.169"},
{"Probabilistic Sharpe Ratio", "12.075%"},
{"Loss Rate", "78%"},
{"Win Rate", "22%"},
{"Profit-Loss Ratio", "0.87"},
{"Alpha", "-0.149"},
{"Beta", "0.037"},
{"Beta", "0.035"},
{"Annual Standard Deviation", "0.008"},
{"Annual Variance", "0"},
{"Information Ratio", "-9.471"},
{"Tracking Error", "0.212"},
{"Treynor Ratio", "-2.13"},
{"Information Ratio", "-9.603"},
{"Tracking Error", "0.215"},
{"Treynor Ratio", "-2.264"},
{"Total Fees", "$199.00"},
{"Estimated Strategy Capacity", "$23000000.00"},
{"Estimated Strategy Capacity", "$26000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "38.64"},
{"Kelly Criterion Probability Value", "0.229"},
{"Sortino Ratio", "-21.545"},
{"Return Over Maximum Drawdown", "-77.972"},
{"Portfolio Turnover", "1.135"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "-22.493"},
{"Return Over Maximum Drawdown", "-77.93"},
{"Portfolio Turnover", "1.211"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
{"Total Insights Analysis Completed", "99"},
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$126657.6305"},
{"Total Accumulated Estimated Alpha Value", "$20405.9516"},
{"Mean Population Estimated Insight Value", "$206.1207"},
{"Mean Population Direction", "54.5455%"},
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"},
{"OrderListHash", "0a28eedf6304023f5002ef672b489b88"}
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "3c4c4085810cc5ecdb927d3647b9bbf3"}
};
}
}

View File

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

View File

@@ -0,0 +1,134 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm reproducing GH issue #5748 where in some cases an option underlying symbol was not being
/// removed from all universes it was hold
/// </summary>
public class AddAndRemoveOptionContractRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _contract;
private bool _hasRemoved;
public override void Initialize()
{
SetStartDate(2014, 06, 06);
SetEndDate(2014, 06, 09);
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero;
var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
_contract = OptionChainProvider.GetOptionContractList(aapl, Time)
.OrderBy(symbol => symbol.ID.Symbol)
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call
&& optionContract.ID.OptionStyle == OptionStyle.American);
AddOptionContract(_contract);
}
public override void OnData(Slice slice)
{
if (slice.HasData)
{
if (!_hasRemoved)
{
RemoveOptionContract(_contract);
RemoveSecurity(_contract.Underlying);
_hasRemoved = true;
}
else
{
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
}
}
}
public override void OnEndOfAlgorithm()
{
if (!_hasRemoved)
{
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -186,6 +186,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "$7.40"},
{"Estimated Strategy Capacity", "$28000000.00"},
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
{"Fitness Score", "1"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

@@ -21,6 +21,7 @@ using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
namespace QuantConnect.Algorithm.CSharp
{
@@ -123,9 +124,33 @@ namespace QuantConnect.Algorithm.CSharp
if (!optionInvested && data.ContainsKey(option))
{
var optionContract = Securities[option];
var marginModel = optionContract.BuyingPowerModel as FuturesOptionsMarginModel;
if (marginModel.InitialIntradayMarginRequirement == 0
|| marginModel.InitialOvernightMarginRequirement == 0
|| marginModel.MaintenanceIntradayMarginRequirement == 0
|| marginModel.MaintenanceOvernightMarginRequirement == 0)
{
throw new Exception("Unexpected margin requirements");
}
if (marginModel.GetInitialMarginRequirement(optionContract, 1) == 0)
{
throw new Exception("Unexpected Initial Margin requirement");
}
if (marginModel.GetMaintenanceMargin(optionContract) != 0)
{
throw new Exception("Unexpected Maintenance Margin requirement");
}
MarketOrder(option, 1);
_invested = true;
optionInvested = true;
if (marginModel.GetMaintenanceMargin(optionContract) == 0)
{
throw new Exception("Unexpected Maintenance Margin requirement");
}
}
if (!futureInvested && data.ContainsKey(future))
{
@@ -219,7 +244,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.044"},
{"Treynor Ratio", "0.479"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$12000.00"},
{"Estimated Strategy Capacity", "$41000.00"},
{"Lowest Capacity Asset", "ES 31C3JQTOYO9T0|ES XCZJLC9NOB29"},
{"Fitness Score", "0.41"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

@@ -132,14 +132,15 @@ namespace QuantConnect.Algorithm.CSharp
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.92"},
{"Alpha", "-0.021"},
{"Beta", "-0.01"},
{"Beta", "-0.011"},
{"Annual Standard Deviation", "0.006"},
{"Annual Variance", "0"},
{"Information Ratio", "-3.374"},
{"Information Ratio", "-3.385"},
{"Tracking Error", "0.058"},
{"Treynor Ratio", "2.133"},
{"Treynor Ratio", "2.117"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$45000000.00"},
{"Lowest Capacity Asset", "AOL R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -159,7 +160,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "486118a60d78f74811fe8d927c2c6b43"}
{"OrderListHash", "b006bb7864c0b2f1a6552fb2aa7f03b8"}
};
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -83,33 +83,34 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "10"},
{"Total Trades", "11"},
{"Average Win", "0%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-14.333%"},
{"Compounding Annual Return", "-14.217%"},
{"Drawdown", "3.300%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.169%"},
{"Sharpe Ratio", "-0.131"},
{"Probabilistic Sharpe Ratio", "45.057%"},
{"Net Profit", "-0.168%"},
{"Sharpe Ratio", "-0.126"},
{"Probabilistic Sharpe Ratio", "45.081%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-3.068"},
{"Beta", "0.595"},
{"Annual Standard Deviation", "0.382"},
{"Annual Variance", "0.146"},
{"Information Ratio", "-13.618"},
{"Tracking Error", "0.376"},
{"Treynor Ratio", "-0.084"},
{"Total Fees", "$13.98"},
{"Estimated Strategy Capacity", "$61000000.00"},
{"Fitness Score", "0.146"},
{"Alpha", "-2.896"},
{"Beta", "0.551"},
{"Annual Standard Deviation", "0.385"},
{"Annual Variance", "0.148"},
{"Information Ratio", "-13.66"},
{"Tracking Error", "0.382"},
{"Treynor Ratio", "-0.088"},
{"Total Fees", "$23.21"},
{"Estimated Strategy Capacity", "$340000000.00"},
{"Lowest Capacity Asset", "FB V6OIPNZEM8V9"},
{"Fitness Score", "0.147"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "1"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-4.398"},
{"Portfolio Turnover", "0.268"},
{"Return Over Maximum Drawdown", "-4.352"},
{"Portfolio Turnover", "0.269"},
{"Total Insights Generated", "15"},
{"Total Insights Closed", "12"},
{"Total Insights Analysis Completed", "12"},
@@ -123,7 +124,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "8971c92ba163cec8526379865d9b9ee4"}
{"OrderListHash", "a7a0983c8413ff241e7d223438f3d508"}
};
}
}

View File

@@ -37,6 +37,10 @@ namespace QuantConnect.Algorithm.CSharp
// Set requested data resolution
UniverseSettings.Resolution = Resolution.Daily;
// Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
// Commented so regression algorithm is more sensitive
//Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;
SetStartDate(2014, 03, 24);
SetEndDate(2014, 04, 07);
SetCash(100000);
@@ -90,33 +94,34 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "23"},
{"Average Win", "0.00%"},
{"Total Trades", "27"},
{"Average Win", "0.01%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-75.307%"},
{"Compounding Annual Return", "-75.320%"},
{"Drawdown", "5.800%"},
{"Expectancy", "-0.859"},
{"Net Profit", "-5.586%"},
{"Sharpe Ratio", "-3.257"},
{"Probabilistic Sharpe Ratio", "5.931%"},
{"Loss Rate", "92%"},
{"Win Rate", "8%"},
{"Profit-Loss Ratio", "0.70"},
{"Alpha", "-0.593"},
{"Beta", "0.692"},
{"Annual Standard Deviation", "0.204"},
{"Annual Variance", "0.042"},
{"Information Ratio", "-2.884"},
{"Tracking Error", "0.194"},
{"Treynor Ratio", "-0.962"},
{"Total Fees", "$25.92"},
{"Estimated Strategy Capacity", "$69000000.00"},
{"Expectancy", "-0.731"},
{"Net Profit", "-5.588%"},
{"Sharpe Ratio", "-3.272"},
{"Probabilistic Sharpe Ratio", "5.825%"},
{"Loss Rate", "86%"},
{"Win Rate", "14%"},
{"Profit-Loss Ratio", "0.89"},
{"Alpha", "-0.594"},
{"Beta", "0.707"},
{"Annual Standard Deviation", "0.203"},
{"Annual Variance", "0.041"},
{"Information Ratio", "-2.929"},
{"Tracking Error", "0.193"},
{"Treynor Ratio", "-0.942"},
{"Total Fees", "$37.25"},
{"Estimated Strategy Capacity", "$520000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.004"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "1"},
{"Sortino Ratio", "-4.462"},
{"Return Over Maximum Drawdown", "-13.032"},
{"Portfolio Turnover", "0.083"},
{"Sortino Ratio", "-4.469"},
{"Return Over Maximum Drawdown", "-13.057"},
{"Portfolio Turnover", "0.084"},
{"Total Insights Generated", "33"},
{"Total Insights Closed", "30"},
{"Total Insights Analysis Completed", "30"},
@@ -130,7 +135,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "ce59e51c8e404b5dbbc02911473aed1c"}
{"OrderListHash", "f837879b96f5e565b60fd040299d2123"}
};
}
}

View File

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

View File

@@ -101,7 +101,7 @@ namespace QuantConnect.Algorithm.CSharp
return;
}
foreach (var symbol in ActiveSecurities.Keys)
foreach (var symbol in ActiveSecurities.Keys.OrderBy(symbol => symbol))
{
if (!Portfolio.ContainsKey(symbol) || !Portfolio[symbol].Invested)
{
@@ -194,30 +194,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "5"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "36.294%"},
{"Compounding Annual Return", "19.147%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0.340%"},
{"Sharpe Ratio", "21.2"},
{"Probabilistic Sharpe Ratio", "99.990%"},
{"Net Profit", "0.192%"},
{"Sharpe Ratio", "31.331"},
{"Probabilistic Sharpe Ratio", "88.448%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.274"},
{"Beta", "0.138"},
{"Annual Standard Deviation", "0.011"},
{"Alpha", "0.138"},
{"Beta", "0.04"},
{"Annual Standard Deviation", "0.004"},
{"Annual Variance", "0"},
{"Information Ratio", "7.202"},
{"Tracking Error", "0.068"},
{"Treynor Ratio", "1.722"},
{"Information Ratio", "4.767"},
{"Tracking Error", "0.077"},
{"Treynor Ratio", "3.223"},
{"Total Fees", "$307.50"},
{"Estimated Strategy Capacity", "$2800000.00"},
{"Fitness Score", "0.173"},
{"Estimated Strategy Capacity", "$2600000.00"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0.106"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0.173"},
{"Portfolio Turnover", "0.106"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -231,7 +232,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "6b1b205e5a6461ffd5bed645099714cd"}
{"OrderListHash", "0069f402ffcd2d91b9018b81badfab81"}
};
}
}

View File

@@ -0,0 +1,188 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Brokerages;
using QuantConnect.Securities;
using System.Collections.Generic;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Data.Custom.AlphaStreams;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Example algorithm consuming an alpha streams portfolio state and trading based on it
/// </summary>
public class AlphaStreamsBasicTemplateAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Dictionary<Symbol, HashSet<Symbol>> _symbolsPerAlpha = new Dictionary<Symbol, HashSet<Symbol>>();
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2018, 04, 04);
SetEndDate(2018, 04, 06);
SetExecution(new ImmediateExecutionModel());
Settings.MinimumOrderMarginPortfolioPercentage = 0.01m;
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
SetSecurityInitializer(new BrokerageModelSecurityInitializer(BrokerageModel,
new FuncSecuritySeeder(GetLastKnownPrices)));
foreach (var alphaId in new [] { "623b06b231eb1cc1aa3643a46", "9fc8ef73792331b11dbd5429a" })
{
AddData<AlphaStreamsPortfolioState>(alphaId);
}
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
foreach (var portfolioState in data.Get<AlphaStreamsPortfolioState>().Values)
{
ProcessPortfolioState(portfolioState);
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
Log($"OnOrderEvent: {orderEvent}");
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
changes.FilterCustomSecurities = false;
foreach (var addedSecurity in changes.AddedSecurities)
{
if (addedSecurity.Symbol.IsCustomDataType<AlphaStreamsPortfolioState>())
{
if (!_symbolsPerAlpha.ContainsKey(addedSecurity.Symbol))
{
_symbolsPerAlpha[addedSecurity.Symbol] = new HashSet<Symbol>();
}
// warmup alpha state, adding target securities
ProcessPortfolioState(addedSecurity.Cache.GetData<AlphaStreamsPortfolioState>());
}
}
Log($"OnSecuritiesChanged: {changes}");
}
private bool UsedBySomeAlpha(Symbol asset)
{
return _symbolsPerAlpha.Any(pair => pair.Value.Contains(asset));
}
private void ProcessPortfolioState(AlphaStreamsPortfolioState portfolioState)
{
if (portfolioState == null)
{
return;
}
var alphaId = portfolioState.Symbol;
if (!_symbolsPerAlpha.TryGetValue(alphaId, out var currentSymbols))
{
_symbolsPerAlpha[alphaId] = currentSymbols = new HashSet<Symbol>();
}
var newSymbols = new HashSet<Symbol>(currentSymbols.Count);
foreach (var symbol in portfolioState.PositionGroups?.SelectMany(positionGroup => positionGroup.Positions).Select(state => state.Symbol) ?? Enumerable.Empty<Symbol>())
{
// only add it if it's not used by any alpha (already added check)
if (newSymbols.Add(symbol) && !UsedBySomeAlpha(symbol))
{
AddSecurity(symbol, resolution: UniverseSettings.Resolution, extendedMarketHours: UniverseSettings.ExtendedMarketHours);
}
}
_symbolsPerAlpha[alphaId] = newSymbols;
foreach (var symbol in currentSymbols.Where(symbol => !UsedBySomeAlpha(symbol)))
{
RemoveSecurity(symbol);
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <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"},
{"Average Win", "0%"},
{"Average Loss", "-0.12%"},
{"Compounding Annual Return", "-14.722%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.116%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "2.474"},
{"Tracking Error", "0.339"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$83000.00"},
{"Lowest Capacity Asset", "BTCUSD XJ"},
{"Fitness Score", "0.017"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-138.588"},
{"Portfolio Turnover", "0.034"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "2b94bc50a74caebe06c075cdab1bc6da"}
};
}
}

View File

@@ -0,0 +1,93 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Example algorithm with existing holdings consuming an alpha streams portfolio state and trading based on it
/// </summary>
public class AlphaStreamsDifferentAccountCurrencyBasicTemplateAlgorithm : AlphaStreamsWithHoldingsBasicTemplateAlgorithm
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetAccountCurrency("EUR");
base.Initialize();
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0.01%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-78.502%"},
{"Drawdown", "3.100%"},
{"Expectancy", "7.797"},
{"Net Profit", "-1.134%"},
{"Sharpe Ratio", "-2.456"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "16.59"},
{"Alpha", "0.008"},
{"Beta", "1.012"},
{"Annual Standard Deviation", "0.343"},
{"Annual Variance", "0.117"},
{"Information Ratio", "-0.57"},
{"Tracking Error", "0.004"},
{"Treynor Ratio", "-0.831"},
{"Total Fees", "$2.89"},
{"Estimated Strategy Capacity", "$8900000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.506"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
{"Portfolio Turnover", "0.506"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "€0"},
{"Total Accumulated Estimated Alpha Value", "€0"},
{"Mean Population Estimated Insight Value", "€0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "a9dd0a0ab6070455479d1b9caaa4e69c"}
};
}
}

View File

@@ -0,0 +1,87 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Data.Custom.AlphaStreams;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Selection;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Example algorithm consuming an alpha streams portfolio state and trading based on it
/// </summary>
public class AlphaStreamsUniverseSelectionTemplateAlgorithm : AlphaStreamsBasicTemplateAlgorithm
{
/// <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(2018, 04, 04);
SetEndDate(2018, 04, 06);
SetExecution(new ImmediateExecutionModel());
Settings.MinimumOrderMarginPortfolioPercentage = 0.01m;
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
SetUniverseSelection(new ScheduledUniverseSelectionModel(
DateRules.EveryDay(),
TimeRules.Midnight,
SelectAlphas,
new UniverseSettings(UniverseSettings)
{
SubscriptionDataTypes = new List<Tuple<Type, TickType>>
{new(typeof(AlphaStreamsPortfolioState), TickType.Trade)},
FillForward = false,
}
));
}
private IEnumerable<Symbol> SelectAlphas(DateTime dateTime)
{
Log($"SelectAlphas() {Time}");
foreach (var alphaId in new[] {"623b06b231eb1cc1aa3643a46", "9fc8ef73792331b11dbd5429a"})
{
var alphaSymbol = new Symbol(SecurityIdentifier.GenerateBase(typeof(AlphaStreamsPortfolioState), alphaId, Market.USA),
alphaId);
yield return alphaSymbol;
}
}
/// <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
{
get
{
var result = base.ExpectedStatistics;
result["Compounding Annual Return"] = "-13.200%";
result["Information Ratio"] = "2.827";
result["Tracking Error"] = "0.248";
result["Fitness Score"] = "0.011";
result["Return Over Maximum Drawdown"] = "-113.513";
result["Portfolio Turnover"] = "0.023";
return result;
}
}
}
}

View File

@@ -0,0 +1,144 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Orders;
using System.Collections.Generic;
using QuantConnect.Data.Custom.AlphaStreams;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Example algorithm with existing holdings consuming an alpha streams portfolio state and trading based on it
/// </summary>
public class AlphaStreamsWithHoldingsBasicTemplateAlgorithm : AlphaStreamsBasicTemplateAlgorithm
{
private decimal _expectedSpyQuantity;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2018, 04, 04);
SetEndDate(2018, 04, 06);
SetCash(100000);
SetExecution(new ImmediateExecutionModel());
UniverseSettings.Resolution = Resolution.Hour;
Settings.MinimumOrderMarginPortfolioPercentage = 0.001m;
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
// AAPL should be liquidated since it's not hold by the alpha
// This is handled by the PCM
var aapl = AddEquity("AAPL", Resolution.Hour);
aapl.Holdings.SetHoldings(40, 10);
// SPY will be bought following the alpha streams portfolio
// This is handled by the PCM + Execution Model
var spy = AddEquity("SPY", Resolution.Hour);
spy.Holdings.SetHoldings(246, -10);
AddData<AlphaStreamsPortfolioState>("94d820a93fff127fa46c15231d");
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (_expectedSpyQuantity == 0 && orderEvent.Symbol == "SPY" && orderEvent.Status == OrderStatus.Filled)
{
var security = Securities["SPY"];
var priceInAccountCurrency = Portfolio.CashBook.ConvertToAccountCurrency(security.AskPrice, security.QuoteCurrency.Symbol);
_expectedSpyQuantity = (Portfolio.TotalPortfolioValue - Settings.FreePortfolioValue) / priceInAccountCurrency;
_expectedSpyQuantity = _expectedSpyQuantity.DiscretelyRoundBy(1, MidpointRounding.ToZero);
}
base.OnOrderEvent(orderEvent);
}
public override void OnEndOfAlgorithm()
{
if (Securities["AAPL"].HoldStock)
{
throw new Exception("We should no longer hold AAPL since the alpha does not");
}
// we allow some padding for small price differences
if (Math.Abs(Securities["SPY"].Holdings.Quantity - _expectedSpyQuantity) > _expectedSpyQuantity * 0.03m)
{
throw new Exception($"Unexpected SPY holdings. Expected {_expectedSpyQuantity} was {Securities["SPY"].Holdings.Quantity}");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0.01%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-87.617%"},
{"Drawdown", "3.100%"},
{"Expectancy", "8.518"},
{"Net Profit", "-1.515%"},
{"Sharpe Ratio", "-2.45"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "18.04"},
{"Alpha", "0.008"},
{"Beta", "1.015"},
{"Annual Standard Deviation", "0.344"},
{"Annual Variance", "0.118"},
{"Information Ratio", "-0.856"},
{"Tracking Error", "0.005"},
{"Treynor Ratio", "-0.83"},
{"Total Fees", "$3.09"},
{"Estimated Strategy Capacity", "$8900000000.00"},
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
{"Fitness Score", "0.511"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "6113.173"},
{"Portfolio Turnover", "0.511"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "788eb2c74715a78476ba0db3b2654eb6"}
};
}
}

View File

@@ -1,117 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Custom.Benzinga;
using QuantConnect.Data.UniverseSelection;
namespace QuantConnect.Algorithm.CSharp.AltData
{
/// <summary>
/// Benzinga is a provider of news data. Their news is made in-house
/// and covers stock related news such as corporate events.
/// </summary>
public class BenzingaNewsAlgorithm : QCAlgorithm
{
// Predefine a dictionary of words with scores to scan for in the description
// of the Benzinga news article
private readonly Dictionary<string, double> _words = new Dictionary<string, double>()
{
{"bad", -0.5}, {"good", 0.5},
{"negative", -0.5}, {"great", 0.5},
{"growth", 0.5}, {"fail", -0.5},
{"failed", -0.5}, {"success", 0.5},
{"nailed", 0.5}, {"beat", 0.5},
{"missed", -0.5}
};
// Trade only every 5 days
private DateTime _lastTrade = DateTime.MinValue;
/// <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(2018, 6, 5);
SetEndDate(2018, 8, 4);
SetCash(100000);
var aapl = AddEquity("AAPL", Resolution.Hour).Symbol;
var ibm = AddEquity("IBM", Resolution.Hour).Symbol;
AddData<BenzingaNews>(aapl);
AddData<BenzingaNews>(ibm);
}
public override void OnData(Slice data)
{
if ((Time - _lastTrade) < TimeSpan.FromDays(5))
{
return;
}
// Get rid of our holdings after 5 days, and start fresh
Liquidate();
// Get all Benzinga data and loop over it
foreach (var article in data.Get<BenzingaNews>().Values)
{
// Select the same Symbol we're getting a data point for
// from the articles list so that we can get the sentiment of the article.
// We use the underlying Symbol because the Symbols included in the `Symbols` property
// are equity Symbols.
var selectedSymbol = article.Symbols.SingleOrDefault(s => s == article.Symbol.Underlying);
if (selectedSymbol == null)
{
throw new Exception($"Could not find current Symbol {article.Symbol.Underlying} even though it should exist");
}
// The intersection of the article contents and the pre-defined words are the words that are included in both collections
var intersection = article.Contents.ToLowerInvariant().Split(' ').Intersect(_words.Keys);
// Get the words, then get the aggregate sentiment
var sentimentSum = intersection.Select(x => _words[x]).Sum();
if (sentimentSum >= 0.5)
{
Log($"Longing {article.Symbol.Underlying} with sentiment score of {sentimentSum}");
SetHoldings(article.Symbol.Underlying, sentimentSum / 5);
_lastTrade = Time;
}
if (sentimentSum <= -0.5)
{
Log($"Shorting {article.Symbol.Underlying} with sentiment score of {sentimentSum}");
SetHoldings(article.Symbol.Underlying, sentimentSum / 5);
_lastTrade = Time;
}
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var r in changes.RemovedSecurities)
{
// If removed from the universe, liquidate and remove the custom data from the algorithm
Liquidate(r.Symbol);
RemoveSecurity(QuantConnect.Symbol.CreateBase(typeof(BenzingaNews), r.Symbol, Market.USA));
}
}
}
}

View File

@@ -1,66 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using QuantConnect.Data;
using QuantConnect.Data.Custom.CBOE;
using QuantConnect.Data.Custom.Fred;
using QuantConnect.Data.Custom.USEnergy;
namespace QuantConnect.Algorithm.CSharp.AltData
{
public class CachedAlternativeDataAlgorithm : QCAlgorithm
{
private Symbol _cboeVix;
private Symbol _usEnergy;
private Symbol _fredPeakToTrough;
public override void Initialize()
{
SetStartDate(2003, 1, 1);
SetEndDate(2019, 10, 11);
SetCash(100000);
// QuantConnect caches a small subset of alternative data for easy consumption for the community.
// You can use this in your algorithm as demonstrated below:
_cboeVix = AddData<CBOE>("VIX", Resolution.Daily).Symbol;
// United States EIA data: https://eia.gov/
_usEnergy = AddData<USEnergy>(USEnergy.Petroleum.UnitedStates.WeeklyGrossInputsIntoRefineries, Resolution.Daily).Symbol;
// FRED data
_fredPeakToTrough = AddData<Fred>(Fred.OECDRecessionIndicators.UnitedStatesFromPeakThroughTheTrough, Resolution.Daily).Symbol;
}
public override void OnData(Slice data)
{
if (data.ContainsKey(_cboeVix))
{
var vix = data.Get<CBOE>(_cboeVix);
Log($"VIX: {vix}");
}
if (data.ContainsKey(_usEnergy))
{
var inputIntoRefineries = data.Get<USEnergy>(_usEnergy);
Log($"U.S. Input Into Refineries: {Time}, {inputIntoRefineries.Value}");
}
if (data.ContainsKey(_fredPeakToTrough))
{
var peakToTrough = data.Get<Fred>(_fredPeakToTrough);
Log($"OECD based Recession Indicator for the United States from the Peak through the Trough: {peakToTrough}");
}
}
}
}

View File

@@ -1,62 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Custom.Quiver;
namespace QuantConnect.Algorithm.CSharp.AltData
{
/// <summary>
/// Quiver Quantitative is a provider of alternative data.
/// This algorithm shows how to consume the <see cref="QuiverWallStreetBets"/>
/// </summary>
public class QuiverWallStreetBetsDataAlgorithm : QCAlgorithm
{
/// <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(2019, 1, 1);
SetEndDate(2020, 6, 1);
SetCash(100000);
var aapl = AddEquity("AAPL", Resolution.Daily).Symbol;
var quiverWSBSymbol = AddData<QuiverWallStreetBets>(aapl).Symbol;
var history = History<QuiverWallStreetBets>(quiverWSBSymbol, 60, Resolution.Daily);
Debug($"We got {history.Count()} items from our history request");
}
public override void OnData(Slice data)
{
var points = data.Get<QuiverWallStreetBets>();
foreach (var point in points.Values)
{
// Go long in the stock if it was mentioned more than 5 times in the WallStreetBets daily discussion
if (point.Mentions > 5)
{
SetHoldings(point.Symbol.Underlying, 1);
}
// Go short in the stock if it was mentioned less than 5 times in the WallStreetBets daily discussion
if (point.Mentions < 5)
{
SetHoldings(point.Symbol.Underlying, -1);
}
}
}
}
}

View File

@@ -1,99 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Data;
using QuantConnect.Data.Custom.SEC;
using QuantConnect.Data.UniverseSelection;
namespace QuantConnect.Algorithm.CSharp
{
public class SECReport8KAlgorithm : QCAlgorithm
{
/// <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(2019, 1, 1);
SetEndDate(2019, 8, 21);
SetCash(100000);
UniverseSettings.Resolution = Resolution.Minute;
AddUniverseSelection(new CoarseFundamentalUniverseSelectionModel(CoarseSelector));
// Request underlying equity data.
var ibm = AddEquity("IBM", Resolution.Minute).Symbol;
// Add SEC report 10-Q data for the underlying IBM asset
var earningsFiling = AddData<SECReport10Q>(ibm, Resolution.Daily).Symbol;
// Request 120 days of history with the SECReport10Q IBM custom data Symbol.
var history = History<SECReport10Q>(earningsFiling, 120, Resolution.Daily);
// Count the number of items we get from our history request
Debug($"We got {history.Count()} items from our history request");
}
public IEnumerable<Symbol> CoarseSelector(IEnumerable<CoarseFundamental> coarse)
{
// Add SEC data from the filtered coarse selection
var symbols = coarse.Where(x => x.HasFundamentalData && x.DollarVolume > 50000000)
.Select(x => x.Symbol)
.Take(10);
foreach (var symbol in symbols)
{
AddData<SECReport8K>(symbol);
}
return symbols;
}
public override void OnData(Slice data)
{
// Store the symbols we want to long in a list
// so that we can have an equal-weighted portfolio
var longEquitySymbols = new List<Symbol>();
// Get all SEC data and loop over it
foreach (var report in data.Get<SECReport8K>().Values)
{
// Get the length of all contents contained within the report
var reportTextLength = report.Report.Documents.Select(x => x.Text.Length).Sum();
if (reportTextLength > 20000)
{
longEquitySymbols.Add(report.Symbol.Underlying);
}
}
foreach (var equitySymbol in longEquitySymbols)
{
SetHoldings(equitySymbol, 1m / longEquitySymbols.Count);
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var r in changes.RemovedSecurities)
{
// If removed from the universe, liquidate and remove the custom data from the algorithm
Liquidate(r.Symbol);
RemoveSecurity(QuantConnect.Symbol.CreateBase(typeof(SECReport8K), r.Symbol, Market.USA));
}
}
}
}

View File

@@ -1,90 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Data;
using QuantConnect.Data.Custom.SmartInsider;
using QuantConnect.Data.UniverseSelection;
namespace QuantConnect.Algorithm.CSharp
{
public class SmartInsiderTransactionAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2019, 3, 1);
SetEndDate(2019, 7, 4);
SetCash(1000000);
AddUniverseSelection(new CoarseFundamentalUniverseSelectionModel(CoarseUniverse));
// Request underlying equity data.
var ibm = AddEquity("IBM", Resolution.Minute).Symbol;
// Add Smart Insider stock buyback transaction data for the underlying IBM asset
var si = AddData<SmartInsiderTransaction>(ibm).Symbol;
// Request 60 days of history with the SmartInsiderTransaction IBM Custom Data Symbol.
var history = History<SmartInsiderTransaction>(si, 60, Resolution.Daily);
// Count the number of items we get from our history request
Debug($"We got {history.Count()} items from our history request");
}
public IEnumerable<Symbol> CoarseUniverse(IEnumerable<CoarseFundamental> coarse)
{
var symbols = coarse.Where(x => x.HasFundamentalData && x.DollarVolume > 50000000)
.Select(x => x.Symbol)
.Take(10);
foreach (var symbol in symbols)
{
AddData<SmartInsiderTransaction>(symbol);
}
return symbols;
}
public override void OnData(Slice data)
{
// Get all SmartInsider data available
var transactions = data.Get<SmartInsiderTransaction>();
foreach (var transaction in transactions.Values)
{
if (transaction.VolumePercentage == null || transaction.EventType == null)
{
continue;
}
// Using the Smart Insider transaction information, buy when company does a stock buyback
if (transaction.EventType == SmartInsiderEventType.Transaction && transaction.VolumePercentage > 5)
{
SetHoldings(transaction.Symbol.Underlying, (decimal)transaction.VolumePercentage / 100);
}
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var r in changes.RemovedSecurities)
{
// If removed from the universe, liquidate and remove the custom data from the algorithm
Liquidate(r.Symbol);
RemoveSecurity(QuantConnect.Symbol.CreateBase(typeof(SmartInsiderTransaction), r.Symbol, Market.USA));
}
}
}
}

View File

@@ -1,85 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Custom.Tiingo;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Look for positive and negative words in the news article description
/// and trade based on the sum of the sentiment
/// </summary>
public class TiingoNewsAlgorithm : QCAlgorithm
{
private Symbol _tiingoSymbol;
// Predefine a dictionary of words with scores to scan for in the description
// of the Tiingo news article
private readonly Dictionary<string, double> _words = new Dictionary<string, double>()
{
{"bad", -0.5}, {"good", 0.5},
{ "negative", -0.5}, {"great", 0.5},
{"growth", 0.5}, {"fail", -0.5},
{"failed", -0.5}, {"success", 0.5},
{"nailed", 0.5}, {"beat", 0.5},
{"missed", -0.5}
};
public override void Initialize()
{
SetStartDate(2019, 6, 10);
SetEndDate(2019, 10, 3);
SetCash(100000);
var aapl = AddEquity("AAPL", Resolution.Hour).Symbol;
_tiingoSymbol = AddData<TiingoNews>(aapl).Symbol;
// Request underlying equity data
var ibm = AddEquity("IBM", Resolution.Minute).Symbol;
// Add news data for the underlying IBM asset
var news = AddData<TiingoNews>(ibm).Symbol;
// Request 60 days of history with the TiingoNews IBM Custom Data Symbol.
var history = History<TiingoNews>(news, 60, Resolution.Daily);
// Count the number of items we get from our history request
Debug($"We got {history.Count()} items from our history request");
}
public override void OnData(Slice data)
{
//Confirm that the data is in the collection
if (!data.ContainsKey(_tiingoSymbol)) return;
// Gets the first piece of data from the Slice
var article = data.Get<TiingoNews>(_tiingoSymbol);
// Article descriptions come in all caps. Lower and split by word
var descriptionWords = article.Description.ToLowerInvariant().Split(' ');
// Take the intersection of predefined words and the words in the
// description to get a list of matching words
var intersection = _words.Keys.Intersect(descriptionWords);
// Get the sum of the article's sentiment, and go long or short
// depending if it's a positive or negative description
var sentiment = intersection.Select(x => _words[x]).Sum();
SetHoldings(article.Symbol.Underlying, sentiment);
}
}
}

View File

@@ -1,80 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Custom.TradingEconomics;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Trades on interest rate announcements from data provided by Trading Economics
/// </summary>
public class TradingEconomicsAlgorithm : QCAlgorithm
{
private Symbol _interestRate;
public override void Initialize()
{
SetStartDate(2013, 11, 1);
SetEndDate(2019, 10, 3);
SetCash(100000);
AddEquity("AGG", Resolution.Hour);
AddEquity("SPY", Resolution.Hour);
_interestRate = AddData<TradingEconomicsCalendar>(TradingEconomics.Calendar.UnitedStates.InterestRate).Symbol;
// Request 365 days of interest rate history with the TradingEconomicsCalendar custom data Symbol.
// We should expect no historical data because 2013-11-01 is before the absolute first point of data
var history = History<TradingEconomicsCalendar>(_interestRate, 365, Resolution.Daily);
// Count the number of items we get from our history request (should be zero)
Debug($"We got {history.Count()} items from our history request");
}
public override void OnData(Slice data)
{
// Make sure we have an interest rate calendar event
if (!data.ContainsKey(_interestRate))
{
return;
}
var announcement = data.Get<TradingEconomicsCalendar>(_interestRate);
// Confirm it's a FED Rate Decision
if (announcement.Event != TradingEconomics.Event.UnitedStates.FedInterestRateDecision)
{
return;
}
// In the event of a rate increase, rebalance 50% to Bonds.
var interestRateDecreased = announcement.Actual <= announcement.Previous;
if (interestRateDecreased)
{
SetHoldings("SPY", 1);
SetHoldings("AGG", 0);
}
else
{
SetHoldings("SPY", 0.5);
SetHoldings("AGG", 0.5);
}
}
}
}

View File

@@ -1,87 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Custom.USTreasury;
namespace QuantConnect.Algorithm.CSharp
{
public class USTreasuryYieldCurveRateAlgorithm : QCAlgorithm
{
private Symbol _yieldCurve;
private Symbol _spy;
private DateTime _lastInversion = DateTime.MinValue;
public override void Initialize()
{
SetStartDate(2000, 3, 1);
SetEndDate(2019, 9, 15);
SetCash(100000);
_spy = AddEquity("SPY", Resolution.Hour).Symbol;
_yieldCurve = AddData<USTreasuryYieldCurveRate>("USTYCR", Resolution.Daily).Symbol;
// Request 60 days of history with the USTreasuryYieldCurveRate custom data Symbol.
var history = History<USTreasuryYieldCurveRate>(_yieldCurve, 60, Resolution.Daily);
// Count the number of items we get from our history request
Debug($"We got {history.Count()} items from our history request");
}
public override void OnData(Slice data)
{
if (!data.ContainsKey(_yieldCurve))
{
return;
}
// Preserve null values by getting the data with `slice.Get<T>`
// Accessing the data using `data[_yieldCurve]` results in null
// values becoming `default(decimal)` which is equal to 0
var rates = data.Get<USTreasuryYieldCurveRate>().Values.First();
// Check for null before using the values
if (!rates.TenYear.HasValue || !rates.TwoYear.HasValue)
{
return;
}
// Only advance if a year has gone by
if (Time - _lastInversion < TimeSpan.FromDays(365))
{
return;
}
// if there is a yield curve inversion after not having one for a year, short SPY for two years
if (!Portfolio.Invested && rates.TwoYear > rates.TenYear)
{
Debug($"{Time} - Yield curve inversion! Shorting the market for two years");
SetHoldings(_spy, -0.5);
_lastInversion = Time;
return;
}
// If two years have passed, liquidate our position in SPY
if (Time - _lastInversion >= TimeSpan.FromDays(365 * 2))
{
Liquidate(_spy);
}
}
}
}

View File

@@ -78,32 +78,33 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "65"},
{"Total Trades", "52"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "0.145%"},
{"Compounding Annual Return", "0.096%"},
{"Drawdown", "0.100%"},
{"Expectancy", "2.190"},
{"Net Profit", "0.134%"},
{"Sharpe Ratio", "0.993"},
{"Probabilistic Sharpe Ratio", "49.669%"},
{"Loss Rate", "29%"},
{"Win Rate", "71%"},
{"Profit-Loss Ratio", "3.50"},
{"Expectancy", "3.321"},
{"Net Profit", "0.089%"},
{"Sharpe Ratio", "0.868"},
{"Probabilistic Sharpe Ratio", "44.482%"},
{"Loss Rate", "24%"},
{"Win Rate", "76%"},
{"Profit-Loss Ratio", "4.67"},
{"Alpha", "0.001"},
{"Beta", "0"},
{"Beta", "-0"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.168"},
{"Tracking Error", "0.099"},
{"Treynor Ratio", "-5.187"},
{"Total Fees", "$65.00"},
{"Estimated Strategy Capacity", "$16000000000.00"},
{"Information Ratio", "-2.148"},
{"Tracking Error", "0.101"},
{"Treynor Ratio", "-4.168"},
{"Total Fees", "$52.00"},
{"Estimated Strategy Capacity", "$32000000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "1.51"},
{"Return Over Maximum Drawdown", "1.819"},
{"Sortino Ratio", "1.266"},
{"Return Over Maximum Drawdown", "1.622"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
@@ -118,7 +119,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "c4c9c272037cfd8f6887052b8d739466"}
{"OrderListHash", "cf43585a8d1781f04b53a4f1ee3380cb"}
};
}
}

View File

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

View File

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

View File

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

View File

@@ -89,6 +89,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$85000.00"},
{"Lowest Capacity Asset", "BTCEUR XJ"},
{"Fitness Score", "0.506"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

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

View File

@@ -0,0 +1,130 @@
/*
* 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.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Brokerages;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Basic template algorithm for the Atreyu brokerage
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="using quantconnect" />
/// <meta name="tag" content="trading and orders" />
public class BasicTemplateAtreyuAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);
SetCash(100000);
SetBrokerageModel(BrokerageName.Atreyu);
AddEquity("SPY", Resolution.Minute);
DefaultOrderProperties = new AtreyuOrderProperties
{
// Can specify the default exchange to execute an order on.
// If not specified will default to the primary exchange
Exchange = Exchange.NASDAQ,
// Currently only support order for the day
TimeInForce = TimeInForce.Day
};
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
// will set 25% of our buying power with a market order that will be routed to exchange set in the default order properties (NASDAQ)
SetHoldings("SPY", 0.25m);
// will increase our SPY holdings to 50% of our buying power with a market order that will be routed to ARCA
SetHoldings("SPY", 0.50m, orderProperties: new AtreyuOrderProperties { Exchange = Exchange.ARCA });
Debug("Purchased SPY!");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "93.443%"},
{"Drawdown", "1.100%"},
{"Expectancy", "0"},
{"Net Profit", "0.847%"},
{"Sharpe Ratio", "6.515"},
{"Probabilistic Sharpe Ratio", "67.535%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0.11"},
{"Annual Variance", "0.012"},
{"Information Ratio", "6.515"},
{"Tracking Error", "0.11"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.52"},
{"Estimated Strategy Capacity", "$8600000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.124"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "78.376"},
{"Portfolio Turnover", "0.124"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "cb542eaaeab5eac3bcae5d915ded30da"}
};
}
}

View File

@@ -1,53 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Data.UniverseSelection;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Basic template algorithm which showcases <see cref="ConstituentsUniverse"/> simple use case
/// </summary>
public class BasicTemplateConstituentUniverseAlgorithm : QCAlgorithm
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);
// by default will use algorithms UniverseSettings
AddUniverse(Universe.Constituent.Steel());
// we specify the UniverseSettings it should use
AddUniverse(Universe.Constituent.AggressiveGrowth(
new UniverseSettings(Resolution.Hour,
2,
false,
false,
UniverseSettings.MinimumTimeInUniverse)));
SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(1)));
SetExecution(new ImmediateExecutionModel());
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
}
}
}

View File

@@ -224,6 +224,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "$85.34"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTCEUR XJ"},
{"Fitness Score", "0.5"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

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

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 Language[] Languages { get; } = { Language.CSharp, Language.Python };
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
@@ -92,29 +92,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "-1.01%"},
{"Compounding Annual Return", "254.782%"},
{"Compounding Annual Return", "261.134%"},
{"Drawdown", "2.200%"},
{"Expectancy", "-1"},
{"Net Profit", "1.632%"},
{"Sharpe Ratio", "8.371"},
{"Probabilistic Sharpe Ratio", "66.555%"},
{"Net Profit", "1.655%"},
{"Sharpe Ratio", "8.505"},
{"Probabilistic Sharpe Ratio", "66.840%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.088"},
{"Alpha", "-0.091"},
{"Beta", "1.006"},
{"Annual Standard Deviation", "0.221"},
{"Annual Variance", "0.049"},
{"Information Ratio", "-32.586"},
{"Annual Standard Deviation", "0.224"},
{"Annual Variance", "0.05"},
{"Information Ratio", "-33.445"},
{"Tracking Error", "0.002"},
{"Treynor Ratio", "1.839"},
{"Total Fees", "$9.77"},
{"Treynor Ratio", "1.893"},
{"Total Fees", "$10.32"},
{"Estimated Strategy Capacity", "$27000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.747"},
{"Kelly Criterion Estimate", "38.64"},
{"Kelly Criterion Probability Value", "0.229"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "85.209"},
{"Return Over Maximum Drawdown", "85.095"},
{"Portfolio Turnover", "0.747"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
@@ -122,14 +123,14 @@ namespace QuantConnect.Algorithm.CSharp
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$126657.6305"},
{"Total Accumulated Estimated Alpha Value", "$20405.9516"},
{"Mean Population Estimated Insight Value", "$206.1207"},
{"Mean Population Direction", "54.5455%"},
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"},
{"OrderListHash", "17e29d58e5dabd93569da752c4552c70"}
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "ad2216297c759d8e5aef48ff065f8919"}
};
}
}

View File

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

View File

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

View File

@@ -161,6 +161,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

@@ -123,15 +123,16 @@ namespace QuantConnect.Algorithm.CSharp
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Alpha", "-0.908"},
{"Beta", "0.468"},
{"Annual Standard Deviation", "0.139"},
{"Annual Variance", "0.019"},
{"Information Ratio", "-4.217"},
{"Tracking Error", "0.139"},
{"Treynor Ratio", "0"},
{"Information Ratio", "-9.003"},
{"Tracking Error", "0.142"},
{"Treynor Ratio", "-1.251"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$14000000.00"},
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
{"Fitness Score", "0.044"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

@@ -0,0 +1,132 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using QuantConnect.Data;
using QuantConnect.Orders;
using System.Collections.Generic;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Basic template India algorithm simply initializes the date range and cash. This is a skeleton
/// framework you can use for designing an algorithm.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="using quantconnect" />
/// <meta name="tag" content="trading and orders" />
public class BasicTemplateIndiaAlgorithm : QCAlgorithm
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2003, 10, 07); //Set Start Date
SetEndDate(2003, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
// Find more symbols here: http://quantconnect.com/data
// Equities Resolutions: Tick, Second, Minute, Hour, Daily.
AddEquity("UNIONBANK", Resolution.Second, Market.India);
//Set Order Prperties as per the requirements for order placement
DefaultOrderProperties = new IndiaOrderProperties(exchange: Exchange.NSE);
//override default productType value set in config.json if needed - order specific productType value
//DefaultOrderProperties = new IndiaOrderProperties(exchange: Exchange.NSE, IndiaOrderProperties.IndiaProductType.CNC);
// General Debug statement for acknowledgement
Debug("Intialization Done");
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
var marketTicket = MarketOrder("UNIONBANK", 1);
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Status.IsFill())
{
Debug($"Purchased Complete: {orderEvent.Symbol}");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = false;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "0%"},
{"Average Loss", "-1.01%"},
{"Compounding Annual Return", "261.134%"},
{"Drawdown", "2.200%"},
{"Expectancy", "-1"},
{"Net Profit", "1.655%"},
{"Sharpe Ratio", "8.505"},
{"Probabilistic Sharpe Ratio", "66.840%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.091"},
{"Beta", "1.006"},
{"Annual Standard Deviation", "0.224"},
{"Annual Variance", "0.05"},
{"Information Ratio", "-33.445"},
{"Tracking Error", "0.002"},
{"Treynor Ratio", "1.893"},
{"Total Fees", "$10.32"},
{"Estimated Strategy Capacity", "$27000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.747"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "85.095"},
{"Portfolio Turnover", "0.747"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
{"Total Insights Analysis Completed", "99"},
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "ad2216297c759d8e5aef48ff065f8919"}
};
}
}

View File

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

View File

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

View File

@@ -132,6 +132,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$1300000.00"},
{"Lowest Capacity Asset", "GOOCV 30AKMEIPOSS1Y|GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

@@ -123,6 +123,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

@@ -162,6 +162,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "$3.00"},
{"Estimated Strategy Capacity", "$74000.00"},
{"Lowest Capacity Asset", "AAPL 2ZQGWTSSZ0WLI|AAPL R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0.327"},
{"Kelly Criterion Probability Value", "1"},

View File

@@ -1,63 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Custom.SEC;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp.Benchmarks
{
public class SECReportBenchmarkAlgorithm : QCAlgorithm
{
private List<Security> _securities;
/// <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(2018, 1, 1);
SetEndDate(2019, 1, 1);
var tickers = new List<string> {"AAPL", "AMZN", "MSFT", "IBM", "FB", "QQQ",
"IWM", "BAC", "BNO", "AIG", "UW", "WM" };
_securities = new List<Security>();
foreach (var ticker in tickers)
{
var equity = AddEquity(ticker);
_securities.Add(equity);
AddData<SECReport8K>(equity.Symbol, Resolution.Daily);
AddData<SECReport10K>(equity.Symbol, Resolution.Daily);
}
}
public override void OnData(Slice data)
{
foreach (var security in _securities)
{
SECReport8K report8K = security.Data.Get<SECReport8K>();
SECReport10K report10K = security.Data.Get<SECReport10K>();
if (!security.HoldStock && report8K != null && report10K != null)
{
SetHoldings(security.Symbol, 1d / _securities.Count);
}
}
}
}
}

View File

@@ -1,81 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Custom.SmartInsider;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp.Benchmarks
{
public class SmartInsiderEventBenchmarkAlgorithm : QCAlgorithm
{
private List<Security> _securities;
private List<Symbol> _customSymbols;
private int _historySymbolCount;
/// <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(2010, 1, 1);
SetEndDate(2019, 1, 1);
var tickers = new List<string> {"AAPL", "AMZN", "MSFT", "IBM", "FB", "QQQ",
"IWM", "BAC", "BNO", "AIG", "UW", "WM" };
_securities = new List<Security>();
_customSymbols = new List<Symbol>();
foreach (var ticker in tickers)
{
var equity = AddEquity(ticker, Resolution.Hour);
_securities.Add(equity);
_customSymbols.Add(
AddData<SmartInsiderIntention>(equity.Symbol, Resolution.Daily).Symbol);
_customSymbols.Add(
AddData<SmartInsiderTransaction>(equity.Symbol, Resolution.Daily).Symbol);
}
Schedule.On(DateRules.EveryDay(), TimeRules.At(16, 0), () =>
{
foreach (var slice in History(_customSymbols, TimeSpan.FromDays(5)))
{
_historySymbolCount += slice.Count;
}
foreach (var security in _securities)
{
SmartInsiderIntention intention = security.Data.Get<SmartInsiderIntention>();
SmartInsiderTransaction transaction = security.Data.Get<SmartInsiderTransaction>();
if (!security.HoldStock && intention != null && transaction != null)
{
SetHoldings(security.Symbol, 1d / _securities.Count);
}
}
});
}
public override void OnData(Slice data)
{
var intentions = data.Get<SmartInsiderIntention>();
var transactions = data.Get<SmartInsiderTransaction>();
}
}
}

View File

@@ -37,6 +37,10 @@ namespace QuantConnect.Algorithm.CSharp
// Set requested data resolution
UniverseSettings.Resolution = Resolution.Minute;
// Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
// Commented so regression algorithm is more sensitive
//Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;
SetStartDate(2013, 10, 07); //Set Start Date
SetEndDate(2013, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
@@ -74,47 +78,48 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "18"},
{"Total Trades", "20"},
{"Average Win", "0%"},
{"Average Loss", "-0.16%"},
{"Compounding Annual Return", "72.164%"},
{"Average Loss", "-0.13%"},
{"Compounding Annual Return", "62.435%"},
{"Drawdown", "1.100%"},
{"Expectancy", "-1"},
{"Net Profit", "0.747%"},
{"Sharpe Ratio", "4.086"},
{"Probabilistic Sharpe Ratio", "61.091%"},
{"Net Profit", "0.667%"},
{"Sharpe Ratio", "3.507"},
{"Probabilistic Sharpe Ratio", "59.181%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.305"},
{"Alpha", "-0.384"},
{"Beta", "0.564"},
{"Annual Standard Deviation", "0.113"},
{"Annual Standard Deviation", "0.116"},
{"Annual Variance", "0.013"},
{"Information Ratio", "-10.007"},
{"Tracking Error", "0.09"},
{"Treynor Ratio", "0.82"},
{"Total Fees", "$41.70"},
{"Estimated Strategy Capacity", "$3000000.00"},
{"Fitness Score", "0.634"},
{"Kelly Criterion Estimate", "13.656"},
{"Kelly Criterion Probability Value", "0.228"},
{"Information Ratio", "-10.791"},
{"Tracking Error", "0.092"},
{"Treynor Ratio", "0.718"},
{"Total Fees", "$46.20"},
{"Estimated Strategy Capacity", "$2300000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Fitness Score", "0.645"},
{"Kelly Criterion Estimate", "13.787"},
{"Kelly Criterion Probability Value", "0.231"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "80.05"},
{"Portfolio Turnover", "0.634"},
{"Total Insights Generated", "17"},
{"Total Insights Closed", "14"},
{"Total Insights Analysis Completed", "14"},
{"Return Over Maximum Drawdown", "65.642"},
{"Portfolio Turnover", "0.645"},
{"Total Insights Generated", "13"},
{"Total Insights Closed", "10"},
{"Total Insights Analysis Completed", "10"},
{"Long Insight Count", "6"},
{"Short Insight Count", "7"},
{"Long/Short Ratio", "85.71%"},
{"Estimated Monthly Alpha Value", "$72447.6813"},
{"Total Accumulated Estimated Alpha Value", "$12477.1007"},
{"Mean Population Estimated Insight Value", "$891.2215"},
{"Mean Population Direction", "50%"},
{"Mean Population Magnitude", "50%"},
{"Rolling Averaged Population Direction", "12.6429%"},
{"Rolling Averaged Population Magnitude", "12.6429%"},
{"OrderListHash", "3edd51956c7c97af4863aa6059c11f1a"}
{"Estimated Monthly Alpha Value", "$52003.0716"},
{"Total Accumulated Estimated Alpha Value", "$8956.0846"},
{"Mean Population Estimated Insight Value", "$895.6085"},
{"Mean Population Direction", "70%"},
{"Mean Population Magnitude", "70%"},
{"Rolling Averaged Population Direction", "94.5154%"},
{"Rolling Averaged Population Magnitude", "94.5154%"},
{"OrderListHash", "0945ff7a39bb8f8a07b3dcc817c070aa"}
};
}
}

View File

@@ -148,6 +148,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$370000.00"},
{"Lowest Capacity Asset", "ETHUSD XJ"},
{"Fitness Score", "0.501"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,119 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Interfaces;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Custom.Tiingo;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Example algorithm of a custom universe selection using coarse data and adding TiingoNews
/// If conditions are met will add the underlying and trade it
/// </summary>
public class CoarseTiingoNewsUniverseSelectionAlgorithm : QCAlgorithm
{
private const int NumberOfSymbols = 3;
private List<Symbol> _symbols;
public override void Initialize()
{
SetStartDate(2014, 03, 24);
SetEndDate(2014, 04, 07);
UniverseSettings.FillForward = false;
AddUniverse(new CustomDataCoarseFundamentalUniverse(UniverseSettings, SecurityInitializer, CoarseSelectionFunction));
_symbols = new List<Symbol>();
}
// sort the data by daily dollar volume and take the top 'NumberOfSymbols'
public IEnumerable<Symbol> CoarseSelectionFunction(IEnumerable<CoarseFundamental> coarse)
{
// sort descending by daily dollar volume
var sortedByDollarVolume = coarse.OrderByDescending(x => x.DollarVolume);
// take the top entries from our sorted collection
var top = sortedByDollarVolume.Take(NumberOfSymbols);
// we need to return only the symbol objects
return top.Select(x => QuantConnect.Symbol.CreateBase(typeof(TiingoNews), x.Symbol, x.Symbol.ID.Market));
}
public override void OnData(Slice data)
{
var articles = data.Get<TiingoNews>();
foreach (var kvp in articles)
{
var news = kvp.Value;
if (news.Title.IndexOf("Stocks Drop", 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
if (!Securities.ContainsKey(kvp.Key.Underlying))
{
// add underlying we want to trade
AddSecurity(kvp.Key.Underlying);
_symbols.Add(kvp.Key.Underlying);
}
}
}
foreach (var symbol in _symbols)
{
if (Securities[symbol].HasData)
{
SetHoldings(symbol, 1m / _symbols.Count);
}
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
changes.FilterCustomSecurities = false;
Log($"{Time} {changes}");
}
private class CustomDataCoarseFundamentalUniverse : CoarseFundamentalUniverse
{
public CustomDataCoarseFundamentalUniverse(UniverseSettings universeSettings, ISecurityInitializer securityInitializer, Func<IEnumerable<CoarseFundamental>, IEnumerable<Symbol>> selector)
: base(universeSettings, securityInitializer, selector)
{ }
public override IEnumerable<SubscriptionRequest> GetSubscriptionRequests(Security security, DateTime currentTimeUtc, DateTime maximumEndTimeUtc,
ISubscriptionDataConfigService subscriptionService)
{
var config = subscriptionService.Add(
typeof(TiingoNews),
security.Symbol,
UniverseSettings.Resolution,
UniverseSettings.FillForward,
UniverseSettings.ExtendedMarketHours,
dataNormalizationMode: UniverseSettings.DataNormalizationMode);
return new[]{new SubscriptionRequest(isUniverseSubscription: false,
universe: this,
security: security,
configuration: config,
startTimeUtc: currentTimeUtc,
endTimeUtc: maximumEndTimeUtc)};
}
}
}
}

View File

@@ -74,29 +74,30 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "7"},
{"Average Win", "0.01%"},
{"Average Loss", "-0.40%"},
{"Compounding Annual Return", "1114.772%"},
{"Compounding Annual Return", "1143.086%"},
{"Drawdown", "1.800%"},
{"Expectancy", "-0.319"},
{"Net Profit", "3.244%"},
{"Sharpe Ratio", "23.478"},
{"Probabilistic Sharpe Ratio", "80.383%"},
{"Net Profit", "3.275%"},
{"Sharpe Ratio", "23.495"},
{"Probabilistic Sharpe Ratio", "80.494%"},
{"Loss Rate", "33%"},
{"Win Rate", "67%"},
{"Profit-Loss Ratio", "0.02"},
{"Alpha", "4.314"},
{"Beta", "1.239"},
{"Annual Standard Deviation", "0.285"},
{"Annual Variance", "0.081"},
{"Information Ratio", "47.452"},
{"Tracking Error", "0.101"},
{"Treynor Ratio", "5.409"},
{"Total Fees", "$67.00"},
{"Estimated Strategy Capacity", "$3200000.00"},
{"Alpha", "4.366"},
{"Beta", "1.255"},
{"Annual Standard Deviation", "0.292"},
{"Annual Variance", "0.085"},
{"Information Ratio", "47.955"},
{"Tracking Error", "0.102"},
{"Treynor Ratio", "5.461"},
{"Total Fees", "$71.37"},
{"Estimated Strategy Capacity", "$3500000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Fitness Score", "0.501"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "148.636"},
{"Return Over Maximum Drawdown", "1502.912"},
{"Sortino Ratio", "148.07"},
{"Return Over Maximum Drawdown", "1487.238"},
{"Portfolio Turnover", "0.501"},
{"Total Insights Generated", "2"},
{"Total Insights Closed", "0"},
@@ -111,7 +112,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "ba44309886ea8ff515ef593a24456c47"}
{"OrderListHash", "5a171f804d47cd27f84aaef791da8594"}
};
}
}

View File

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

View File

@@ -37,6 +37,10 @@ namespace QuantConnect.Algorithm.CSharp
// Set requested data resolution
UniverseSettings.Resolution = Resolution.Minute;
// Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
// Commented so regression algorithm is more sensitive
//Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;
SetStartDate(2013, 10, 07); //Set Start Date
SetEndDate(2013, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
@@ -74,47 +78,48 @@ namespace QuantConnect.Algorithm.CSharp
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "6"},
{"Average Win", "0.00%"},
{"Total Trades", "17"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "38.059%"},
{"Compounding Annual Return", "37.229%"},
{"Drawdown", "0.600%"},
{"Expectancy", "-0.502"},
{"Net Profit", "0.413%"},
{"Sharpe Ratio", "5.518"},
{"Probabilistic Sharpe Ratio", "66.933%"},
{"Loss Rate", "67%"},
{"Win Rate", "33%"},
{"Profit-Loss Ratio", "0.50"},
{"Alpha", "-0.178"},
{"Beta", "0.249"},
{"Expectancy", "-1"},
{"Net Profit", "0.405%"},
{"Sharpe Ratio", "5.424"},
{"Probabilistic Sharpe Ratio", "66.818%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.191"},
{"Beta", "0.247"},
{"Annual Standard Deviation", "0.055"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-9.844"},
{"Tracking Error", "0.165"},
{"Treynor Ratio", "1.212"},
{"Total Fees", "$6.00"},
{"Estimated Strategy Capacity", "$42000000.00"},
{"Fitness Score", "0.063"},
{"Kelly Criterion Estimate", "38.64"},
{"Kelly Criterion Probability Value", "0.229"},
{"Information Ratio", "-10.052"},
{"Tracking Error", "0.168"},
{"Treynor Ratio", "1.207"},
{"Total Fees", "$17.00"},
{"Estimated Strategy Capacity", "$45000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Fitness Score", "0.067"},
{"Kelly Criterion Estimate", "38.796"},
{"Kelly Criterion Probability Value", "0.228"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "70.188"},
{"Portfolio Turnover", "0.063"},
{"Return Over Maximum Drawdown", "65.855"},
{"Portfolio Turnover", "0.067"},
{"Total Insights Generated", "100"},
{"Total Insights Closed", "99"},
{"Total Insights Analysis Completed", "99"},
{"Long Insight Count", "100"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$126657.6305"},
{"Total Accumulated Estimated Alpha Value", "$20405.9516"},
{"Mean Population Estimated Insight Value", "$206.1207"},
{"Mean Population Direction", "54.5455%"},
{"Mean Population Magnitude", "54.5455%"},
{"Rolling Averaged Population Direction", "59.8056%"},
{"Rolling Averaged Population Magnitude", "59.8056%"},
{"OrderListHash", "07eb3e2c199575b547459a534057eb5e"}
{"Estimated Monthly Alpha Value", "$135639.1761"},
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
{"Mean Population Estimated Insight Value", "$220.7372"},
{"Mean Population Direction", "53.5354%"},
{"Mean Population Magnitude", "53.5354%"},
{"Rolling Averaged Population Direction", "58.2788%"},
{"Rolling Averaged Population Magnitude", "58.2788%"},
{"OrderListHash", "8a8c913e5ad4ea956a345c84430649c2"}
};
}
}

View File

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

View File

@@ -35,7 +35,7 @@ namespace QuantConnect.Algorithm.CSharp
SetCash(100000); // Set Strategy Cash
// Add QC500 Universe
AddUniverse(Universe.Index.QC500);
AddUniverse(Universe.QC500);
}
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -172,4 +172,4 @@ namespace QuantConnect.Algorithm.CSharp
}
}
}
}
}

View File

@@ -124,14 +124,15 @@ namespace QuantConnect.Algorithm.CSharp
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.736"},
{"Beta", "0.136"},
{"Beta", "0.142"},
{"Annual Standard Deviation", "0.84"},
{"Annual Variance", "0.706"},
{"Information Ratio", "1.925"},
{"Tracking Error", "0.846"},
{"Treynor Ratio", "12.904"},
{"Treynor Ratio", "12.334"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTC.Bitcoin 2S"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -259,4 +260,4 @@ namespace QuantConnect.Algorithm.CSharp
}
}
}
}
}

View File

@@ -94,14 +94,15 @@ namespace QuantConnect.Algorithm.CSharp
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.736"},
{"Beta", "0.136"},
{"Beta", "0.142"},
{"Annual Standard Deviation", "0.84"},
{"Annual Variance", "0.706"},
{"Information Ratio", "1.925"},
{"Tracking Error", "0.846"},
{"Treynor Ratio", "12.903"},
{"Treynor Ratio", "12.333"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTC.Bitcoin 2S"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -229,4 +230,4 @@ namespace QuantConnect.Algorithm.CSharp
}
}
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -114,11 +114,12 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.096"},
{"Tracking Error", "0.212"},
{"Information Ratio", "-0.111"},
{"Tracking Error", "0.207"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

@@ -112,6 +112,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

@@ -106,14 +106,15 @@ namespace QuantConnect.Algorithm.CSharp
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.006"},
{"Beta", "0.158"},
{"Beta", "0.157"},
{"Annual Standard Deviation", "0.033"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-4.942"},
{"Tracking Error", "0.08"},
{"Treynor Ratio", "0.517"},
{"Information Ratio", "-4.901"},
{"Tracking Error", "0.081"},
{"Treynor Ratio", "0.519"},
{"Total Fees", "$3.70"},
{"Estimated Strategy Capacity", "$270000000.00"},
{"Estimated Strategy Capacity", "$170000000.00"},
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
{"Fitness Score", "0.019"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

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

View File

@@ -160,7 +160,8 @@ namespace QuantConnect.Algorithm.CSharp
{"Tracking Error", "0.155"},
{"Treynor Ratio", "1.589"},
{"Total Fees", "$55.05"},
{"Estimated Strategy Capacity", "$0"},
{"Estimated Strategy Capacity", "$43000.00"},
{"Lowest Capacity Asset", "AAA SEVKGI6HF885"},
{"Fitness Score", "0.002"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
@@ -180,7 +181,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "61f4d3c109fc4b6b9eb14d2e4eec4843"}
{"OrderListHash", "e357cfa77fd5e5b974c68d550fa66490"}
};
}
}

View File

@@ -119,11 +119,12 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-1.187"},
{"Tracking Error", "0.115"},
{"Treynor Ratio", "1.545"},
{"Information Ratio", "-1.182"},
{"Tracking Error", "0.117"},
{"Treynor Ratio", "1.617"},
{"Total Fees", "$37.00"},
{"Estimated Strategy Capacity", "$400000.00"},
{"Estimated Strategy Capacity", "$860000000.00"},
{"Lowest Capacity Asset", "DC V5E8P9SH0U0X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

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

View File

@@ -45,6 +45,10 @@ namespace QuantConnect.Algorithm.CSharp
{
UniverseSettings.Resolution = Resolution.Daily;
// Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
// Commented so regression algorithm is more sensitive
//Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;
SetStartDate(2017, 07, 04);
SetEndDate(2018, 07, 04);
@@ -187,30 +191,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "6441"},
{"Average Win", "0.07%"},
{"Average Loss", "-0.07%"},
{"Compounding Annual Return", "13.331%"},
{"Drawdown", "10.700%"},
{"Expectancy", "0.061"},
{"Net Profit", "13.331%"},
{"Sharpe Ratio", "0.963"},
{"Probabilistic Sharpe Ratio", "46.232%"},
{"Compounding Annual Return", "14.802%"},
{"Drawdown", "10.400%"},
{"Expectancy", "0.068"},
{"Net Profit", "14.802%"},
{"Sharpe Ratio", "1.077"},
{"Probabilistic Sharpe Ratio", "50.578%"},
{"Loss Rate", "46%"},
{"Win Rate", "54%"},
{"Profit-Loss Ratio", "0.97"},
{"Alpha", "0.124"},
{"Beta", "-0.066"},
{"Annual Standard Deviation", "0.121"},
{"Annual Variance", "0.015"},
{"Information Ratio", "0.006"},
{"Tracking Error", "0.171"},
{"Treynor Ratio", "-1.761"},
{"Total Fees", "$8669.41"},
{"Alpha", "0.137"},
{"Beta", "-0.069"},
{"Annual Standard Deviation", "0.119"},
{"Annual Variance", "0.014"},
{"Information Ratio", "0.046"},
{"Tracking Error", "0.169"},
{"Treynor Ratio", "-1.869"},
{"Total Fees", "$7495.19"},
{"Estimated Strategy Capacity", "$320000.00"},
{"Fitness Score", "0.675"},
{"Lowest Capacity Asset", "BNO UN3IMQ2JU1YD"},
{"Fitness Score", "0.695"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "1.127"},
{"Return Over Maximum Drawdown", "1.246"},
{"Portfolio Turnover", "1.64"},
{"Sortino Ratio", "1.269"},
{"Return Over Maximum Drawdown", "1.424"},
{"Portfolio Turnover", "1.613"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -224,7 +229,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "0b6746b5759ecd45ab21360fd40858bb"}
{"OrderListHash", "df66ec72bb4332b14bbe31ec9bea7ffc"}
};
}
}

View File

@@ -49,6 +49,10 @@ namespace QuantConnect.Algorithm.CSharp
// this sets the resolution for data subscriptions added by our universe
UniverseSettings.Resolution = Resolution.Daily;
// Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
// Commented so regression algorithm is more sensitive
//Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;
// set our start and end for backtest mode
SetStartDate(2017, 07, 04);
SetEndDate(2018, 07, 04);
@@ -160,30 +164,31 @@ namespace QuantConnect.Algorithm.CSharp
{"Total Trades", "5059"},
{"Average Win", "0.08%"},
{"Average Loss", "-0.08%"},
{"Compounding Annual Return", "14.950%"},
{"Drawdown", "10.600%"},
{"Expectancy", "0.075"},
{"Net Profit", "14.950%"},
{"Sharpe Ratio", "1.072"},
{"Probabilistic Sharpe Ratio", "50.327%"},
{"Compounding Annual Return", "16.153%"},
{"Drawdown", "10.300%"},
{"Expectancy", "0.081"},
{"Net Profit", "16.153%"},
{"Sharpe Ratio", "1.17"},
{"Probabilistic Sharpe Ratio", "54.048%"},
{"Loss Rate", "45%"},
{"Win Rate", "55%"},
{"Profit-Loss Ratio", "0.97"},
{"Alpha", "0.137"},
{"Beta", "-0.066"},
{"Annual Standard Deviation", "0.121"},
{"Annual Variance", "0.015"},
{"Information Ratio", "0.083"},
{"Tracking Error", "0.171"},
{"Treynor Ratio", "-1.971"},
{"Total Fees", "$6806.67"},
{"Alpha", "0.147"},
{"Beta", "-0.068"},
{"Annual Standard Deviation", "0.119"},
{"Annual Variance", "0.014"},
{"Information Ratio", "0.11"},
{"Tracking Error", "0.169"},
{"Treynor Ratio", "-2.057"},
{"Total Fees", "$5869.25"},
{"Estimated Strategy Capacity", "$320000.00"},
{"Fitness Score", "0.694"},
{"Lowest Capacity Asset", "BNO UN3IMQ2JU1YD"},
{"Fitness Score", "0.711"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "1.265"},
{"Return Over Maximum Drawdown", "1.409"},
{"Portfolio Turnover", "1.296"},
{"Sortino Ratio", "1.389"},
{"Return Over Maximum Drawdown", "1.564"},
{"Portfolio Turnover", "1.271"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
@@ -197,7 +202,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "a7a893a17a5afa7c2f73a444a7aea507"}
{"OrderListHash", "5f08ae4997156d48171559e452dda9d3"}
};
}
}

View File

@@ -106,11 +106,12 @@ namespace QuantConnect.Algorithm.CSharp
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-7.068"},
{"Tracking Error", "0.193"},
{"Information Ratio", "-7.163"},
{"Tracking Error", "0.195"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

View File

@@ -1,71 +0,0 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Custom.SEC;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Provides an example algorithm showcasing the <see cref="Security.Data"/> features
/// </summary>
public class DynamicSecurityDataAlgorithm : QCAlgorithm
{
private Security GOOGL;
private const string Ticker = "GOOGL";
public override void Initialize()
{
SetStartDate(2015, 10, 22);
SetEndDate(2015, 10, 30);
GOOGL = AddEquity(Ticker, Resolution.Daily);
AddData<SECReport8K>(Ticker, Resolution.Daily);
AddData<SECReport10K>(Ticker, Resolution.Daily);
AddData<SECReport10Q>(Ticker, Resolution.Daily);
}
public override void OnData(Slice slice)
{
// The Security object's Data property provides convenient access
// to the various types of data related to that security. You can
// access not only the security's price data, but also any custom
// data that is mapped to the security, such as our SEC reports.
// 1. Get the most recent data point of a particular type:
// 1.a Using the C# generic method, Get<T>:
SECReport8K googlSec8kReport = GOOGL.Data.Get<SECReport8K>();
SECReport10K googlSec10kReport = GOOGL.Data.Get<SECReport10K>();
Log($"{Time:o}: 8K: {googlSec8kReport}");
Log($"{Time:o}: 10K: {googlSec10kReport}");
// 2. Get the list of data points of a particular type for the most recent time step:
// 2.a Using the C# generic method, GetAll<T>:
List<SECReport8K> googlSec8kReports = GOOGL.Data.GetAll<SECReport8K>();
List<SECReport10K> googlSec10kReports = GOOGL.Data.GetAll<SECReport10K>();
Log($"{Time:o}: List: 8K: {googlSec8kReports.Count}");
Log($"{Time:o}: List: 10K: {googlSec10kReports.Count}");
if (!Portfolio.Invested)
{
Buy(GOOGL.Symbol, 10);
}
}
}
}

View File

@@ -0,0 +1,147 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using QuantConnect.Data;
using QuantConnect.Data.Custom.IconicTypes;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Provides an example algorithm showcasing the <see cref="Security.Data"/> features
/// </summary>
public class DynamicSecurityDataRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Security Equity;
private const string Ticker = "GOOGL";
public override void Initialize()
{
SetStartDate(2015, 10, 22);
SetEndDate(2015, 10, 30);
Equity = AddEquity(Ticker, Resolution.Daily);
var customLinkedEquity = AddData<LinkedData>(Ticker, Resolution.Daily).Symbol;
// Adding linked data manually to cache for example purposes, since
// LinkedData is a type used for testing and doesn't point to any real data.
Equity.Cache.AddDataList(new List<LinkedData>
{
new LinkedData
{
Count = 100,
Symbol = customLinkedEquity,
EndTime = StartDate,
},
new LinkedData
{
Count = 50,
Symbol = customLinkedEquity,
EndTime = StartDate
}
}, typeof(LinkedData), false);
}
public override void OnData(Slice slice)
{
// The Security object's Data property provides convenient access
// to the various types of data related to that security. You can
// access not only the security's price data, but also any custom
// data that is mapped to the security, such as our SEC reports.
// 1. Get the most recent data point of a particular type:
// 1.a Using the C# generic method, Get<T>:
LinkedData customLinkedData = Equity.Data.Get<LinkedData>();
Log($"{Time:o}: LinkedData: {customLinkedData}");
// 2. Get the list of data points of a particular type for the most recent time step:
// 2.a Using the C# generic method, GetAll<T>:
List<LinkedData> customLinkedDataList = Equity.Data.GetAll<LinkedData>();
Log($"{Time:o}: List: LinkedData: {customLinkedDataList.Count}");
if (!Portfolio.Invested)
{
Buy(Equity.Symbol, 10);
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "28.411%"},
{"Drawdown", "0.100%"},
{"Expectancy", "0"},
{"Net Profit", "0.618%"},
{"Sharpe Ratio", "9.975"},
{"Probabilistic Sharpe Ratio", "99.752%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.23"},
{"Beta", "-0.031"},
{"Annual Standard Deviation", "0.022"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.899"},
{"Tracking Error", "0.101"},
{"Treynor Ratio", "-6.961"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$1000000000.00"},
{"Lowest Capacity Asset", "GOOG T1AZ164W5VTX"},
{"Fitness Score", "0.008"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "383.48"},
{"Portfolio Turnover", "0.008"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "668caaf6ff8f35e16f05228541e99720"}
};
}
}

View File

@@ -92,6 +92,7 @@ namespace QuantConnect.Algorithm.CSharp
{"Treynor Ratio", "0"},
{"Total Fees", "$14.92"},
{"Estimated Strategy Capacity", "$85000.00"},
{"Lowest Capacity Asset", "BTCEUR XJ"},
{"Fitness Score", "0.258"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},

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