a4f66628fd
* 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>
302 lines
12 KiB
C#
302 lines
12 KiB
C#
/*
|
|
* 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 Newtonsoft.Json;
|
|
using NUnit.Framework;
|
|
using QuantConnect.Optimizer;
|
|
using QuantConnect.Util;
|
|
using System.Collections.Generic;
|
|
using System.Threading;
|
|
using QuantConnect.Configuration;
|
|
using QuantConnect.Optimizer.Objectives;
|
|
using QuantConnect.Optimizer.Parameters;
|
|
using QuantConnect.Optimizer.Strategies;
|
|
|
|
namespace QuantConnect.Tests.Optimizer
|
|
{
|
|
[TestFixture, Parallelizable(ParallelScope.Children)]
|
|
public class LeanOptimizerTests
|
|
{
|
|
[TestCase("QuantConnect.Optimizer.Strategies.GridSearchOptimizationStrategy")]
|
|
[TestCase("QuantConnect.Optimizer.Strategies.EulerSearchOptimizationStrategy")]
|
|
public void MaximizeNoTarget(string strategyName)
|
|
{
|
|
var resetEvent = new ManualResetEvent(false);
|
|
var packet = new OptimizationNodePacket
|
|
{
|
|
OptimizationStrategy = strategyName,
|
|
Criterion = new Target("Profit",
|
|
new Maximization(),
|
|
null),
|
|
OptimizationParameters = new HashSet<OptimizationParameter>
|
|
{
|
|
new OptimizationStepParameter("ema-slow", 1, 10, 1),
|
|
new OptimizationStepParameter("ema-fast", 10, 100, 3)
|
|
},
|
|
MaximumConcurrentBacktests = 20,
|
|
OptimizationStrategySettings = new StepBaseOptimizationStrategySettings { DefaultSegmentAmount = 10 }
|
|
};
|
|
var optimizer = new FakeLeanOptimizer(packet);
|
|
|
|
OptimizationResult result = null;
|
|
optimizer.Ended += (s, solution) =>
|
|
{
|
|
result = solution;
|
|
optimizer.DisposeSafely();
|
|
resetEvent.Set();
|
|
};
|
|
|
|
optimizer.Start();
|
|
|
|
resetEvent.WaitOne();
|
|
Assert.NotNull(result);
|
|
Assert.AreEqual(
|
|
110,
|
|
JsonConvert.DeserializeObject<BacktestResult>(result.JsonBacktestResult).Statistics.Profit);
|
|
|
|
Assert.AreEqual(10, result.ParameterSet.Value["ema-slow"].ToDecimal());
|
|
Assert.AreEqual(100, result.ParameterSet.Value["ema-fast"].ToDecimal());
|
|
}
|
|
|
|
[TestCase("QuantConnect.Optimizer.Strategies.GridSearchOptimizationStrategy")]
|
|
[TestCase("QuantConnect.Optimizer.Strategies.EulerSearchOptimizationStrategy")]
|
|
public void MinimizeWithTarget(string strategyName)
|
|
{
|
|
var resetEvent = new ManualResetEvent(false);
|
|
var packet = new OptimizationNodePacket
|
|
{
|
|
OptimizationStrategy = strategyName,
|
|
Criterion = new Target("Profit", new Minimization(), 20),
|
|
OptimizationParameters = new HashSet<OptimizationParameter>
|
|
{
|
|
new OptimizationStepParameter("ema-slow", 1, 10, 1),
|
|
new OptimizationStepParameter("ema-fast", 10, 100, 3)
|
|
},
|
|
MaximumConcurrentBacktests = 20,
|
|
OptimizationStrategySettings = new StepBaseOptimizationStrategySettings { DefaultSegmentAmount = 10 }
|
|
};
|
|
var optimizer = new FakeLeanOptimizer(packet);
|
|
|
|
OptimizationResult result = null;
|
|
optimizer.Ended += (s, solution) =>
|
|
{
|
|
result = solution;
|
|
optimizer.DisposeSafely();
|
|
resetEvent.Set();
|
|
};
|
|
|
|
optimizer.Start();
|
|
|
|
resetEvent.WaitOne();
|
|
Assert.NotNull(result);
|
|
Assert.GreaterOrEqual(
|
|
20,
|
|
JsonConvert.DeserializeObject<BacktestResult>(result.JsonBacktestResult).Statistics.Profit);
|
|
}
|
|
|
|
[Test]
|
|
public void MaximizeGridWithConstraints()
|
|
{
|
|
var resetEvent = new ManualResetEvent(false);
|
|
var packet = new OptimizationNodePacket
|
|
{
|
|
Criterion = new Target("Profit", new Maximization(), null),
|
|
OptimizationParameters = new HashSet<OptimizationParameter>
|
|
{
|
|
new OptimizationStepParameter("ema-slow", 1, 10, 1m),
|
|
new OptimizationStepParameter("ema-fast", 10, 100, 3m)
|
|
},
|
|
Constraints = new List<Constraint>
|
|
{
|
|
new Constraint("Drawdown", ComparisonOperatorTypes.LessOrEqual, 0.15m)
|
|
},
|
|
MaximumConcurrentBacktests = 20
|
|
};
|
|
var optimizer = new FakeLeanOptimizer(packet);
|
|
|
|
OptimizationResult result = null;
|
|
optimizer.Ended += (s, solution) =>
|
|
{
|
|
result = solution;
|
|
optimizer.DisposeSafely();
|
|
resetEvent.Set();
|
|
};
|
|
|
|
optimizer.Start();
|
|
|
|
resetEvent.WaitOne();
|
|
Assert.NotNull(result);
|
|
Assert.AreEqual(
|
|
15,
|
|
JsonConvert.DeserializeObject<BacktestResult>(result.JsonBacktestResult).Statistics.Profit);
|
|
Assert.AreEqual(
|
|
0.15m,
|
|
JsonConvert.DeserializeObject<BacktestResult>(result.JsonBacktestResult).Statistics.Drawdown);
|
|
|
|
}
|
|
|
|
[Test]
|
|
public void MaximizeEulerWithConstraints()
|
|
{
|
|
var resetEvent = new ManualResetEvent(false);
|
|
var packet = new OptimizationNodePacket
|
|
{
|
|
OptimizationStrategy = "QuantConnect.Optimizer.Strategies.EulerSearchOptimizationStrategy",
|
|
Criterion = new Target("Profit", new Maximization(), null),
|
|
OptimizationParameters = new HashSet<OptimizationParameter>
|
|
{
|
|
new OptimizationStepParameter("ema-slow", 1, 10, 1),
|
|
new OptimizationStepParameter("ema-fast", 10, 100, 10m, 0.1m)
|
|
},
|
|
Constraints = new List<Constraint>
|
|
{
|
|
new Constraint("Drawdown", ComparisonOperatorTypes.LessOrEqual, 0.15m)
|
|
},
|
|
MaximumConcurrentBacktests = 20,
|
|
OptimizationStrategySettings = new StepBaseOptimizationStrategySettings { DefaultSegmentAmount = 10 }
|
|
};
|
|
var optimizer = new FakeLeanOptimizer(packet);
|
|
|
|
OptimizationResult result = null;
|
|
optimizer.Ended += (s, solution) =>
|
|
{
|
|
result = solution;
|
|
optimizer.DisposeSafely();
|
|
resetEvent.Set();
|
|
};
|
|
|
|
optimizer.Start();
|
|
|
|
resetEvent.WaitOne();
|
|
Assert.NotNull(result);
|
|
Assert.AreEqual(
|
|
15,
|
|
JsonConvert.DeserializeObject<BacktestResult>(result.JsonBacktestResult).Statistics.Profit);
|
|
Assert.AreEqual(
|
|
0.15m,
|
|
JsonConvert.DeserializeObject<BacktestResult>(result.JsonBacktestResult).Statistics.Drawdown);
|
|
|
|
}
|
|
|
|
[Test]
|
|
public void MinimizeWithTargetAndConstraints()
|
|
{
|
|
var resetEvent = new ManualResetEvent(false);
|
|
var packet = new OptimizationNodePacket
|
|
{
|
|
Criterion = new Target("Profit", new Minimization(), 20),
|
|
OptimizationParameters = new HashSet<OptimizationParameter>
|
|
{
|
|
new OptimizationStepParameter("ema-slow", 1, 10, 1),
|
|
new OptimizationStepParameter("ema-fast", 10, 100, 3)
|
|
},
|
|
Constraints = new List<Constraint>
|
|
{
|
|
new Constraint("Drawdown", ComparisonOperatorTypes.LessOrEqual, 0.15m)
|
|
},
|
|
MaximumConcurrentBacktests = 20
|
|
};
|
|
var optimizer = new FakeLeanOptimizer(packet);
|
|
|
|
OptimizationResult result = null;
|
|
optimizer.Ended += (s, solution) =>
|
|
{
|
|
result = solution;
|
|
optimizer.DisposeSafely();
|
|
resetEvent.Set();
|
|
};
|
|
|
|
optimizer.Start();
|
|
|
|
resetEvent.WaitOne();
|
|
Assert.NotNull(result);
|
|
Assert.GreaterOrEqual(
|
|
20,
|
|
JsonConvert.DeserializeObject<BacktestResult>(result.JsonBacktestResult).Statistics.Profit);
|
|
Assert.GreaterOrEqual(
|
|
0.15m,
|
|
JsonConvert.DeserializeObject<BacktestResult>(result.JsonBacktestResult).Statistics.Drawdown);
|
|
|
|
}
|
|
|
|
[Test]
|
|
public void TrackEstimation()
|
|
{
|
|
Config.Set("optimization-update-interval", 1);
|
|
OptimizationEstimate estimate = null;
|
|
OptimizationResult result = null;
|
|
var resetEvent = new ManualResetEvent(false);
|
|
var packet = new OptimizationNodePacket
|
|
{
|
|
Criterion = new Target("Profit", new Minimization(), null),
|
|
OptimizationParameters = new HashSet<OptimizationParameter>
|
|
{
|
|
new OptimizationStepParameter("ema-slow", 1, 10, 1),
|
|
new OptimizationStepParameter("ema-fast", 10, 100, 3)
|
|
},
|
|
Constraints = new List<Constraint>
|
|
{
|
|
new Constraint("Drawdown", ComparisonOperatorTypes.LessOrEqual, 0.15m)
|
|
},
|
|
MaximumConcurrentBacktests = 5
|
|
};
|
|
var optimizer = new FakeLeanOptimizer(packet);
|
|
// keep stats up-to-date
|
|
int totalBacktest = optimizer.GetCurrentEstimate().TotalBacktest;
|
|
int totalUpdates = 0;
|
|
int completedTests = 0;
|
|
int failed = 0;
|
|
optimizer.Update += (s, e) =>
|
|
{
|
|
estimate = optimizer.GetCurrentEstimate();
|
|
Assert.LessOrEqual(estimate.RunningBacktest, packet.MaximumConcurrentBacktests);
|
|
Assert.LessOrEqual(completedTests, estimate.CompletedBacktest);
|
|
Assert.LessOrEqual(failed, estimate.FailedBacktest);
|
|
|
|
Assert.AreEqual(totalBacktest, estimate.TotalBacktest);
|
|
|
|
completedTests = estimate.CompletedBacktest;
|
|
failed = estimate.FailedBacktest;
|
|
|
|
if (completedTests > 0)
|
|
{
|
|
Assert.Greater(estimate.AverageBacktest, TimeSpan.Zero);
|
|
}
|
|
|
|
totalUpdates++;
|
|
};
|
|
optimizer.Ended += (s, solution) =>
|
|
{
|
|
result = solution;
|
|
estimate = optimizer.GetCurrentEstimate();
|
|
optimizer.DisposeSafely();
|
|
resetEvent.Set();
|
|
};
|
|
|
|
optimizer.Start();
|
|
|
|
resetEvent.WaitOne();
|
|
|
|
Assert.NotZero(estimate.CompletedBacktest);
|
|
Assert.NotZero(estimate.FailedBacktest);
|
|
// we have 2 force updates at least, expect a few more over it.
|
|
Assert.Greater(totalUpdates, 2);
|
|
Assert.AreEqual(estimate.CompletedBacktest + estimate.FailedBacktest + estimate.RunningBacktest, totalBacktest);
|
|
}
|
|
}
|
|
}
|