Commit Graph

64 Commits

Author SHA1 Message Date
Adalyat Nazirov a4f66628fd Lean Optimization interface in QCAlgorithm (#4923)
* initial commit

* run parametrized algorithm with command line parameters

* skeleton: top level structure

* OptimizationNodePacket scheme

* pass parameters as HashSet

* run Lean and read results

* call method on optimization completion

* refactor public interfaces

- close ParameterSet collection; allow only get operations
- explicit method to start LeanOptimizer

* synchronize RunLean method; the result could come in before the backtest id is set in the collections

* another portion of refactoring and interface changes

* comments

* comments & tests for Extremum, Minimization and Maximization classes

* unify optimization paramater values (min, max, step) & mode GridSearch tests

- swap min&max if necessary
- iterate left => right (negate step value if necessary) & provide default step value if step == 0
- no StackOverflow Exception
- parameterSet Id should be global for current generator and retain between steps
- test signle point boundary (min == max)

* BruteForceStrategy tests

* more comments

* Update Optimizer assembly information

- Update Optimizer projects assembly information to match behavior of
  the other projects

* Tweaks

- Adding comments
- Replace OnComplete for Ended event
- Replace Abort for Dispose
- ConsoleLeanOptimizer will keep track of running processes
- Each backtest will store results in a separated directory, so they
  don't fight for the log.txt file.
- Adding cmdline option for lean to close automatically
- Adding concurrent execution backtest limit
- Console optimizer will start Lean minimized
- Escape spaces in Json path

* remove parameter set generator abstraction layer

we don't need this flexibility now.

* refactor public methods; Step shouldn't be public

* constraints: wip

* define contract

* comparison operators and tests

* specify JsonProperty values

* Move SafeMultiply100 to extensions

* Throw exception on failed Optimizer.Start

* constraints: wip

* change finish & dispose process

* minor fixes

- handle force lean abort
- notify consumer if target has been reached

* target & constraints; adapt unit tests

* Minor Tweaks and fixes

- Some logging improvements
- Remove Public since not required

* Ignore empty ParameterValue

* simplify condition

* avoid reinitialization

* reduce type; force immutable

* unit tests for constraints  and target value

* parse & normalize percent values, i.e. 20% => 0.2

* fixup

* Target & Constraint & OptimizationNodePacket unit tests

* Add more json unit tests

- Adding more json conversion unit tests. Fix bug for Extremum which
  wasn't using the converter.

* LeanOptimizer tests

* Estimation results

* User thread safe counters

* LeanOptimizer unit tests; push OptimizationResult on Ended event

* more unit tests

* Minor tweaks

-Estimate ToString in a single line.
-Typos and missing header file

* Add base SendUpdate method

- Add base SendUpdate method for LeanOptimizer

* fix LeanOptimizer test; rely on internal Update rather than timer

* Add OptimizationStatus

- Add missing commments and OptimizationStatus

* EulerSearch implementation: wip

* OptimizationParameter custom converter

* change the type

* make step optional

* change folder structure

* enumerate optimization parameter using IEnumerable & IEnumerator

* unit tests: parameters & objectives

* unit tests: strategies

* remove redundant TODO

* change Euler search boundaries

* more Euler tests

* prevent race condition

* Add account/read endpoint

- Adding account/read endpoint. Adding unit test

* Add status check before running lean

* Minor self review

- Adding missing comments, minor changes

* remove array parameters

* minor changes

- tidy up config file, rename variable
- accept min less or equal than max

* move OptimizationParameter methods to strategies

* Minor improvements for BaseResultHandler derivates

* minor changes

- strict requirements for Step and MinStep values
- strategy specific settigs

* Add TotalRuntime to estimate

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2020-12-02 20:10:40 -03:00
Alexandre Catarino dd8dc473b3 Improve Error Message For Arithmetic Overflow In Decimal Cast of Double (#4728)
* SafeDecimalCast Throws Exception For Non-Finite Numbers

* Fixes Arithmetic Overflow Exception in QCAlgorithm.Trading Methods

Replace decimal cast for `SafeDecimalCast()`.

If the algorithm uses a non-finite number in QCAlgorithm trading methods, it will throw with an user-frieldly exception message.

* Fixes KellyCriterionProbabilityValue Calculation
2020-09-18 09:17:09 -03:00
Jack Simonson 0d791ec39a Update Unit Tests and Portfolio Statistics
Updated new unit tests to use TestFixtureSetUp and TestFixtureTearDown. Changed updated PortfolioStatistics to call methods from Statistics.
2020-03-27 10:41:52 -07:00
Jack Simonson 61432ffc29 Update Lean Statistics
Clean branch to update Tracking Error and Annual Performance statistics.
2020-03-26 16:54:59 -07:00
Gerardo Salazar 3266b1a4e5 Address Martin's review - code refactoring and cleaning
* Removed Sample[a-zA-Z]+ methods from IResultHandler definition
* Converted Sample[a-zA-Z]+ methods from public to protected
* Updated inheritors of BaseResultHandler to use new accessibility
modifiers
* Removes useless code in ResolutionSwitchingAlgorithm
2020-01-16 14:03:54 -08:00
Gerardo Salazar dfee825ef6 Refactors sampling strategy in AlgorithmManager loop
* Refactors AlgorithmManager loop
* Refactors StatisticsBuilder methods and strategy for series alignment
* Move sampling logic to the corresponding IResultHandler
* Changes benchmark resolution to Resolution.Hour
* Modifies IResultHandler to enable external sampling
* Adds BacktestResultHandler unit tests
* Adds ResolutionSwitchingAlgorithm to test misalignment
* Adds support to AlgorithmRunner to store algorithm IResultHandler

Warning: this commit breaks accurate calculations for algorithms that
only make use of `Daily` resolution data. Previously, because
the benchmark was added in Daily resolution in backtesting, any
algorithm that only made use of daily data would have an accurate
calculation for beta and various other statistics.

These changes serve to fix the statistics calculations of non-daily
resolution algorithms, with daily resolution to be revisited at a later
time.
2020-01-16 14:03:54 -08:00
Martin Molinero 4439a070fa Address reviews
- Will use a deannualized sharpe ratio of 1 as benchmark
2019-10-21 20:21:26 -03:00
Martin Molinero 324556db62 Add ProbabilisticSharpeRatio
- Add `ProbabilisticSharpeRatio` to `PortfolioStatistics`
- `Probabilistic Sharpe Ratio` will be added to the `RunTimeStatistics`
sent by the `ResultHandlers`
- Making `TradeBuilder.ClosedTrades` thread safe since its accessed by
the `ResultHandlers`
- Removing `:` from live runtime statistics
- Adding unit tests
2019-10-21 15:54:42 -03:00
Michael Handschuh d709d1c4e0 Update Common to respect CA1304 and CA1305
Updates all occurrences of parsing/ToString-ing to go through the new
StringExtensions methods that use CultureInfo.InvariantCulture

See #3045
2019-09-12 14:13:24 -04:00
AlexCatarino 6defc92a60 Verify Whether There is Recorded Portfolio Equity Before Computing Performace
When there is no recorded portfolio equity for a given period, we don't need to compute the algorithm performance (it is all zeroes). This procedure prevents the unrepresented `DateTime` error in `CreateBenchmarkDifferences`.
2019-08-09 01:56:52 +01:00
AlexCatarino 046fa38200 Removes White Space 2019-08-09 01:46:57 +01:00
Martin Molinero a4dfa708c5 Address reviews 2019-07-26 20:19:38 -03:00
Martin Molinero a79cc16b03 Add Kelly Criterion values
- New `KellyCriterionManager` will be used by the
`StatisticsInsightManagerExtension` to calculate and update the
`AlphaRuntimeStatistics` with the new Kelly Criterion values, on a daily
basis.
2019-07-26 19:16:36 -03:00
Oleg Sheyner 06a8d22f23 #3386 Trade Builder creates incorrect trades: finalize fixes + add regression tests 2019-07-11 12:52:02 -04:00
Oleg Sheyner bb020fc5ff Fix #3386 2019-07-11 12:52:02 -04:00
Martin Molinero 78a9d2566f Address review 2019-06-06 20:28:54 -03:00
Martin Molinero 168fb98e20 Fix Turnover Ratio for Futures/CFDs
- `Futures` and `CFDs` sales value will use `ContractMultiplier` as the
rest of the securities.
- `FitnessScore` values will be truncated, not rounded, to 3 decimal places.
- Reducing code duplication for calculating the
`CompoundingAnnualPerformance`
2019-06-06 20:06:54 -03:00
Martin Molinero e7641edf25 Shift Sigmoidal Scale 2019-06-04 18:18:43 -03:00
Martin Molinero 877f59285b Update Portfolio Turnover to be average daily 2019-06-04 11:58:37 -03:00
Martin Molinero 050bbcaba1 Fix Sortino Ratio 2019-06-03 21:42:45 -03:00
Martin Molinero 9e493f16a4 Annualize downside returns 2019-06-03 19:49:23 -03:00
Martin Molinero 761974ab5a PortfolioTurnover will use whole backtest (not last rolling year) 2019-06-03 15:15:50 -03:00
Martin Molinero 61db544817 Address reviews 2019-06-03 15:10:19 -03:00
Martin Molinero 61bab7439b Address reviews 2019-06-03 15:10:18 -03:00
Martin Molinero c015d4ca1f Add Fitness Score
- Adding new `FitnessScore`, score of the strategys performance, and
suitability for the Alpha Stream Market
2019-06-03 15:10:18 -03:00
Douglas Stridsberg 921ae391ad Merge branch 'master' into feature-3146-median-trade-durations 2019-04-30 20:34:30 +01:00
Martin Molinero 412eccebc9 Address reviews
- Revert charting rouding
- Add statistics rouding
- Json converter will ignore null order values
- Remove `type` field in `Symbol` json
- Add default type value for the `TimeInForceJsonConverter`
2019-04-30 11:45:07 -03:00
Douglas Stridsberg 05d206ee0d Calculating medians on longs is ~20% faster 2019-04-30 10:10:55 +01:00
Douglas Stridsberg 37cbfd1270 Median trading durations (all/winning/losing) added to TradeStatistics 2019-04-29 17:50:02 +01:00
Martin Molinero b7930aff67 Performance improvements
- Using `Aggregate(lambda)` vs `Sum(lambda)` since the later is slower
due to performing an extra `Select`
- For `QCAlgorithm.Framework.OnFrameworkData()` will avoid calling
`ToArray()` on empty `Enumerables` due to its cost * the number of
calls. If the `Enumerable` is the empty instance, which is static,
will create a new empty array and return it instead.
- Replacing `SecurityIdentifier` `SecurityType` and `GetHashCode`
implementations for `Lazy` versions, that are performed just once, since
these values do not change and are used multiple times.
- For the different `DataDictionary<T>` implementations adding `this[
Symbol] get; set` since existing overload `this [string]` produces an
extra round operations `Symbol->string->Symbol` with a significant
impact.
- Adding `PortfolioTargetCollection.AddRange()` overload using an array
to avoid unnecessary convertions.
2019-04-11 19:01:27 -03:00
Martin Molinero 0af7ba14f5 Address reviews
- `CashBook[NullCurrency] { get; }` will throw an exception
- Revert `Currencies.USD` changes in user facing algorithms
- Improve some documentation
- Revert some format changes
- Adding more asserts for regression test
- Adding new regression tests using a custom fee model which returns
`OrderFee.Zero`
- Adding a non-usd account currency test to the cash book tests
- Adding some unit tests for `NullCurrency` and `OrderFee.Zero`
2018-12-14 12:38:55 -03:00
Martin Molinero 0933da9303 Refactor previous commits
- Removing `AccountCurrency` from `Cash` and `Brokerage` classes.
`ICurrencyConverter` will now provide the `AccountCurrency`
- Adding new static `OrderFee.Zero` which will return a 0 order fee in
`NullCurrency`
- Adding static `Currencies.USD` value, replacing all "USD".
- Addin new static `Currencies.NullCurrency`
- Updating Bitfinex `FeeModel` so it return fees in quote currency.
Adding unit tests
2018-12-13 11:30:40 -03:00
Martin Molinero b7bcdbef04 Adding OrderFee to OrderEvent
- Replacing `decimal` for `OrderFee` at the `OrderEvent`.
- Adding `FeeModelNotUsingAccountCurrency` regression test
- Adding unit tests for `CashBuyingPowerModel` and `SecurityMarginModel`
with non account currency fees
2018-12-10 13:18:41 -03:00
Martin Molinero 75ffa300f1 Adding new IAlgorithm.AccountCurrency
- Adding new `IAlgorithm.AccountCurrency { get; }` that will point to the
`Portfolio.CashBook.AccountCurrency`. Setter will be added in a
following PR.
- Base `Brokerage` class will now have a `AccountCurrency { get }`
pointing to the `IAccountCurrencyProvider`. Will be used by the different
brokerages implementations.
2018-12-10 11:59:02 -03:00
Michael Handschuh 94bfaf115b Compute net profit even if no trades
In live mode it is very possible for a deployment to not have any closed
trades but still experience a profit (or loss) due to pre-existig holdings.

Additionally, this changes backtesting statistics for all backtests that did
not close a single position.
2017-11-07 15:13:20 -05:00
Stefano Raggi 84555a80ad Fix AlgorithmPerformance property setters for JSON deserialization
AlgorithmPerformance, PortfolioStatistics and TradeStatistics had private setters, so JSON deserialization could not populate their properties.
2017-06-26 17:21:48 +02:00
Jared 24fcd239a7 Merge pull request #982 from QuantConnect/issue-330/decimal-quantity
Order and Holding Decimalization Support
2017-06-26 09:51:51 -04:00
Stefano Raggi 8c248a1165 Fix formatting bug in StatisticsBuilder.GetSummary
This bug was causing regression tests to fail on a machine with non-US regional settings.
2017-06-20 22:10:49 +02:00
Stefano Raggi 9139ca7c40 Merge master into issue-330/decimal-quantity 2017-06-19 23:50:26 +02:00
Stefano Raggi fd5f4bc64f Add ITradeBuilder interface 2017-03-21 19:57:21 +01:00
Stefano Raggi e052afebba In StatisticsBuilder ensure daily performance has same dates as benchmark performance 2017-02-14 14:34:22 +01:00
quant1729 8af29aca3c Updated trade builder to support derivatives (multiplier > 1). Tests. 2016-11-28 15:16:15 +01:00
jameschch@outlook.com 7763efdc83 Changes related to #330 order quantity decimalized 2016-06-24 11:28:21 +01:00
AlexCatarino 4158a11367 Fixes Beta (PortfolioStatistics) calculation
In CreateBenchmarkDifference method, a list of values of banchmark daily performance were not created properly. It added an extra zero entry in the beggining of the list and did not include the last day. That caused an one-day lag between the algorithm and benchmark performances.
Reference: [Strange backtester beta results](https://www.quantconnect.com/forum/discussion/1118)

Changes RegressionTests to reflect this correction.
2016-04-22 22:18:11 -03:00
Michael Handschuh e9e6472dd0 Fixes number overflow in statistics generation 2016-03-31 20:00:45 -04:00
Stefano Raggi 96930a1c26 Fixes speed bug in StatisticsBuilder.CreateBenchmarkDifferences 2016-01-27 15:25:57 -05:00
snugs be950e756a Log full errors/stack traces
Many places in the code used Log.Error(err.Message) or equivalent which
strips out all the really useful information, such as the stack trace
and inner exceptions. Using Log.Error(exception) is the correct way to
log an error as it will correctly write all the message details, also,
by passing the full Exception object we can improve the logging in this
one place and all call sites will automatically benefit from the improvements
2015-12-02 12:35:33 -05:00
snugs e29236cc2d Remove reliance on Symbol implcits from core libraries 2015-11-12 13:55:39 -05:00
Stefano Raggi 11c6753297 Changed Padded Performance log Error to Trace 2015-10-24 18:49:51 -04:00
Stefano Raggi dfcdcf58cc Added check for division by zero in CompoundingAnnualPerformance 2015-10-24 23:41:24 +02:00