chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 13:02:50 +08:00
commit 0fc60fdcb1
5008 changed files with 910633 additions and 0 deletions
+87
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 Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QuantConnect.Util;
using System;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace QuantConnect.Optimizer.Objectives
{
/// <summary>
/// A backtest optimization constraint.
/// Allows specifying statistical constraints for the optimization, eg. a backtest can't have a DrawDown less than 10%
/// </summary>
public class Constraint : Objective
{
/// <summary>
/// The target comparison operation, eg. 'Greater'
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public ComparisonOperatorTypes Operator { get; set; }
/// <summary>
/// Empty Constraint constructor
/// </summary>
public Constraint()
{
}
/// <summary>
/// Creates a new instance
/// </summary>
public Constraint(string target, ComparisonOperatorTypes @operator, decimal? targetValue) : base(target, targetValue)
{
Operator = @operator;
if (!TargetValue.HasValue)
{
throw new ArgumentNullException(nameof(targetValue), Messages.Constraint.ConstraintTargetValueNotSpecified);
}
}
/// <summary>
/// Asserts the constraint is met
/// </summary>
public bool IsMet(string jsonBacktestResult)
{
if (string.IsNullOrEmpty(jsonBacktestResult))
{
throw new ArgumentNullException(nameof(jsonBacktestResult), $"Constraint.IsMet(): {Messages.OptimizerObjectivesCommon.NullOrEmptyBacktestResult}");
}
var token = Objectives.Target.GetTokenInJsonBacktest(jsonBacktestResult, Target);
if (token == null)
{
return false;
}
return Operator.Compare(
token.Value<string>().ToNormalizedDecimal(),
TargetValue.Value);
}
/// <summary>
/// Pretty representation of a constraint
/// </summary>
public override string ToString()
{
return $"{Target} '{Operator}' {TargetValue.Value}";
}
}
}
+47
View File
@@ -0,0 +1,47 @@
/*
* 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;
namespace QuantConnect.Optimizer.Objectives
{
/// <summary>
/// Define the way to compare current real-values and the new one (candidates).
/// It's encapsulated in different abstraction to allow configure the direction of optimization, i.e. max or min.
/// </summary>
[JsonConverter(typeof(ExtremumJsonConverter))]
public class Extremum
{
private Func<decimal, decimal, bool> _comparer;
/// <summary>
/// Create an instance of <see cref="Extremum"/> to compare values.
/// </summary>
/// <param name="comparer">The way old and new values should be compared</param>
public Extremum(Func<decimal, decimal, bool> comparer)
{
_comparer = comparer;
}
/// <summary>
/// Compares two values; identifies whether condition is met or not.
/// </summary>
/// <param name="current">Left operand</param>
/// <param name="candidate">Right operand</param>
/// <returns>Returns the result of comparer with this arguments</returns>
public bool Better(decimal current, decimal candidate) => _comparer(current, candidate);
}
}
@@ -0,0 +1,56 @@
/*
* 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.Util;
namespace QuantConnect.Optimizer.Objectives
{
/// <summary>
/// Class for converting string values to Maximization or Minimization strategy objects
/// </summary>
public class ExtremumJsonConverter : TypeChangeJsonConverter<Extremum, string>
{
/// <summary>
/// Don't populate any property
/// </summary>
protected override bool PopulateProperties => false;
/// <summary>
/// Converts a Extremum object into a string
/// </summary>
protected override string Convert(Extremum value)
{
return value.GetType() == typeof(Maximization)
? "max"
: "min";
}
/// <summary>
/// Converts a string into its corresponding Extremum object
/// </summary>
/// <param name="value"></param>
protected override Extremum Convert(string value)
{
switch (value.ToLowerInvariant())
{
case "max": return new Maximization();
case "min": return new Minimization();
default:
throw new InvalidOperationException($"ExtremumJsonConverter.Convert: {Messages.ExtremumJsonConverter.UnrecognizedTargetDirection}");
}
}
}
}
@@ -0,0 +1,30 @@
/*
* 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.
*/
namespace QuantConnect.Optimizer.Objectives
{
/// <summary>
/// Defines standard maximization strategy, i.e. right operand is greater than left
/// </summary>
public class Maximization : Extremum
{
/// <summary>
/// Creates an instance of <see cref="Maximization"/>
/// </summary>
public Maximization() : base((v1, v2) => v1 < v2)
{
}
}
}
@@ -0,0 +1,30 @@
/*
* 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.
*/
namespace QuantConnect.Optimizer.Objectives
{
/// <summary>
/// Defines standard minimization strategy, i.e. right operand is less than left
/// </summary>
public class Minimization : Extremum
{
/// <summary>
/// Creates an instance of <see cref="Minimization"/>
/// </summary>
public Minimization() : base((v1, v2) => v1 > v2)
{
}
}
}
+99
View File
@@ -0,0 +1,99 @@
/*
* 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 System.Text.RegularExpressions;
using Newtonsoft.Json;
namespace QuantConnect.Optimizer.Objectives
{
/// <summary>
/// Base class for optimization <see cref="Objectives.Target"/> and <see cref="Constraint"/>
/// </summary>
public abstract class Objective
{
private readonly Regex _targetTemplate = new Regex("['(.+)']");
private string _target;
/// <summary>
/// Target; property of json file we want to track
/// </summary>
public string Target
{
get => _target;
set
{
_target = value != null ? string.Join(".", value.Split('.').Select(s => _targetTemplate.Match(s).Success ? s : $"['{s}']")) : value;
}
}
/// <summary>
/// Target value
/// </summary>
/// <remarks>For <see cref="Objectives.Target"/> if defined and backtest complies with the targets then finish optimization</remarks>
/// <remarks>For <see cref="Constraint"/> non optional, the value of the target constraint</remarks>
public decimal? TargetValue { get; set; }
/// <summary>
/// Creates a new instance of Objective class
/// </summary>
protected Objective()
{
}
/// <summary>
/// Creates a new instance
/// </summary>
protected Objective(string target, decimal? targetValue)
{
if (string.IsNullOrEmpty(target))
{
throw new ArgumentNullException(nameof(target), Messages.Objective.NullOrEmptyObjective);
}
var objective = target;
if (!objective.Contains('.', StringComparison.InvariantCulture))
{
// default path
objective = $"Statistics.{objective}";
}
// escape empty space in json path
Target = objective;
TargetValue = targetValue;
}
#region Backwards Compatibility
/// <summary>
/// Target value
/// </summary>
/// <remarks>For <see cref="Objectives.Target"/> if defined and backtest complies with the targets then finish optimization</remarks>
/// <remarks>For <see cref="Constraint"/> non optional, the value of the target constraint</remarks>
[JsonProperty("target-value")]
public decimal? OldTargetValue
{
set
{
TargetValue = value;
}
get
{
return TargetValue;
}
}
#endregion
}
}
+133
View File
@@ -0,0 +1,133 @@
/*
* 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 Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
namespace QuantConnect.Optimizer.Objectives
{
/// <summary>
/// The optimization statistical target
/// </summary>
public class Target: Objective
{
/// <summary>
/// Defines the direction of optimization, i.e. maximization or minimization
/// </summary>
public Extremum Extremum { get; set; }
/// <summary>
/// Current value
/// </summary>
[JsonIgnore]
public decimal? Current { get; private set; }
/// <summary>
/// Fires when target complies specified value
/// </summary>
public event EventHandler Reached;
/// <summary>
/// Creates a new instance
/// </summary>
public Target(string target, Extremum extremum, decimal? targetValue): base(target, targetValue)
{
Extremum = extremum;
}
/// <summary>
/// Creates a new instance
/// </summary>
public Target()
{
}
/// <summary>
/// Pretty representation of this optimization target
/// </summary>
public override string ToString()
{
return Messages.Target.ToString(this);
}
/// <summary>
/// Check backtest result
/// </summary>
/// <param name="jsonBacktestResult">Backtest result json</param>
/// <returns>true if found a better solution; otherwise false</returns>
public bool MoveAhead(string jsonBacktestResult)
{
if (string.IsNullOrEmpty(jsonBacktestResult))
{
throw new ArgumentNullException(nameof(jsonBacktestResult), $"Target.MoveAhead(): {Messages.OptimizerObjectivesCommon.NullOrEmptyBacktestResult}");
}
var token = GetTokenInJsonBacktest(jsonBacktestResult, Target);
if (token == null)
{
return false;
}
var computedValue = token.Value<string>().ToNormalizedDecimal();
if (!Current.HasValue || Extremum.Better(Current.Value, computedValue))
{
Current = computedValue;
return true;
}
return false;
}
/// <summary>
/// Try comply target value
/// </summary>
public void CheckCompliance()
{
if (IsComplied())
{
Reached?.Invoke(this, EventArgs.Empty);
}
}
public static JToken GetTokenInJsonBacktest(string jsonBacktestResult, string target)
{
var jObject = JObject.Parse(jsonBacktestResult);
var path = target.Replace("[", string.Empty, StringComparison.InvariantCultureIgnoreCase)
.Replace("]", string.Empty, StringComparison.InvariantCultureIgnoreCase)
.Replace("\'", string.Empty, StringComparison.InvariantCultureIgnoreCase).Split(".");
JToken token = null;
foreach (var key in path)
{
if (jObject.TryGetValue(key, StringComparison.OrdinalIgnoreCase, out token))
{
if (token is not JValue)
{
jObject = token.ToObject<JObject>();
}
}
else
{
return null;
}
}
return token;
}
private bool IsComplied() => TargetValue.HasValue && Current.HasValue && (TargetValue.Value == Current.Value || Extremum.Better(TargetValue.Value, Current.Value));
}
}