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
@@ -0,0 +1,110 @@
/*
* 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 NUnit.Framework;
using QuantConnect.Optimizer.Objectives;
using QuantConnect.Util;
using System;
namespace QuantConnect.Tests.Optimizer.Objectives
{
[TestFixture, Parallelizable(ParallelScope.All)]
public class ConstraintTests
{
[TestCase(101.0)]
[TestCase(1000.0)]
public void Meet(decimal value)
{
var constraint = new Constraint("Profit", ComparisonOperatorTypes.Greater, 100m);
Assert.IsTrue(constraint.IsMet(BacktestResult.Create(value).ToJson()));
}
[TestCase(1.0)]
[TestCase(99.9)]
[TestCase(100d)]
public void Fails(decimal value)
{
var constraint = new Constraint("Profit", ComparisonOperatorTypes.Greater, 100m);
Assert.IsFalse(constraint.IsMet(BacktestResult.Create(value).ToJson()));
}
[Test]
public void ThrowIfTargetNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var constraint = new Constraint("Drawdown", ComparisonOperatorTypes.Less, null);
});
}
[TestCase("")]
[TestCase(null)]
public void ThrowIfResultNullOrEmpty(string json)
{
var constraint = new Constraint("Drawdown", ComparisonOperatorTypes.Less, 10);
Assert.Throws<ArgumentNullException>(() =>
{
constraint.IsMet(json);
});
}
[Test]
public void IgnoreBadJson()
{
var constraint = new Constraint("Drawdown", ComparisonOperatorTypes.Less, 0.1m);
Assert.IsFalse(constraint.IsMet("{\"Drawdown\":\"10.0%\"}"));
}
[TestCase("Drawdown")]
[TestCase("Statistics.Drawdown")]
[TestCase("['Statistics'].['Drawdown']")]
public void ParseName(string targetName)
{
var target = new Constraint(targetName, ComparisonOperatorTypes.Equals, 100);
Assert.AreEqual("['Statistics'].['Drawdown']", target.Target);
}
[Test]
public void FromJson()
{
var json = "{\"operator\": \"equals\",\"target\": \"pin ocho.Gepetto\",\"targetValue\": 11}";
var constraint = (Constraint)JsonConvert.DeserializeObject(json, typeof(Constraint));
Assert.AreEqual("['pin ocho'].['Gepetto']", constraint.Target);
Assert.AreEqual(ComparisonOperatorTypes.Equals, constraint.Operator);
Assert.AreEqual(11, constraint.TargetValue.Value);
}
[Test]
public void RoundTrip()
{
var origin = new Constraint("['Statistics'].['Drawdown']", ComparisonOperatorTypes.Equals, 100);
var json = JsonConvert.SerializeObject(origin);
var actual = JsonConvert.DeserializeObject<Constraint>(json);
Assert.NotNull(actual);
Assert.AreEqual(origin.Target, actual.Target);
Assert.AreEqual(origin.Operator, actual.Operator);
Assert.AreEqual(origin.TargetValue, actual.TargetValue);
}
}
}
+129
View File
@@ -0,0 +1,129 @@
/*
* 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 NUnit.Framework;
using QuantConnect.Optimizer.Objectives;
using System;
using Newtonsoft.Json;
namespace QuantConnect.Tests.Optimizer.Objectives
{
[TestFixture, Parallelizable(ParallelScope.All)]
public class ExtremumTests
{
private static TestCaseData[] Extremums => new TestCaseData[]
{
new TestCaseData(new Maximization()),
new TestCaseData(new Minimization())
};
[TestCase("\"max\"")]
[TestCase("\"min\"")]
[TestCase("\"Max\"")]
[TestCase("\"miN\"")]
public void Deserialize(string extremum)
{
var actual = JsonConvert.DeserializeObject<Extremum>(extremum);
Extremum expected = extremum.Equals("\"max\"", StringComparison.OrdinalIgnoreCase)
? new Maximization() as Extremum
: new Minimization();
Assert.NotNull(actual);
Assert.AreEqual(expected.GetType(), actual.GetType());
}
[TestCase("\"\"")]
[TestCase("\"n/a\"")]
public void ThrowsIfNotRecognized(string extremum)
{
Assert.Throws<InvalidOperationException>(() =>
{
JsonConvert.DeserializeObject<Extremum>(extremum);
});
}
[Test, TestCaseSource(nameof(Extremums))]
public void Serialize(Extremum extremum)
{
var json = JsonConvert.SerializeObject(extremum);
var actual = JsonConvert.DeserializeObject<Extremum>(json);
Assert.NotNull(actual);
Assert.AreEqual(extremum.GetType(), actual.GetType());
}
[TestCase(0, 10)]
[TestCase(10, 10)]
[TestCase(10, 0)]
public void Linear(decimal current, decimal candidate)
{
Func<decimal, decimal, bool> comparer = (a, b) => a <= b;
var strategy = new Extremum(comparer);
Assert.AreEqual(comparer(current, candidate), strategy.Better(current, candidate));
}
[TestCase(101, 10)]
[TestCase(100, 10)]
[TestCase(99, 10)]
public void NonLinear(decimal current, decimal candidate)
{
Func<decimal, decimal, bool> comparer = (a, b) => a >= b * b;
var strategy = new Extremum(comparer);
Assert.AreEqual(comparer(current, candidate), strategy.Better(current, candidate));
}
[TestFixture]
public class MaximizationTests
{
Maximization _strategy = new Maximization();
[Test]
public void Greater()
{
Assert.IsTrue(_strategy.Better(0, 10));
}
[TestCase(10, 10)]
[TestCase(10, 0)]
public void LessThanOrEqual(decimal current, decimal candidate)
{
Assert.IsFalse(_strategy.Better(current, candidate));
}
}
[TestFixture]
public class MinimizationTests
{
Minimization _strategy = new Minimization();
[Test]
public void Less()
{
Assert.IsTrue(_strategy.Better(10, 0));
}
[TestCase(10, 10)]
[TestCase(0, 10)]
public void GreatThanOrEqual(decimal current, decimal candidate)
{
Assert.IsFalse(_strategy.Better(current, candidate));
}
}
}
}
+171
View File
@@ -0,0 +1,171 @@
/*
* 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 NUnit.Framework;
using QuantConnect.Optimizer.Objectives;
using System;
namespace QuantConnect.Tests.Optimizer.Objectives
{
[TestFixture, Parallelizable(ParallelScope.All)]
public class TargetTests
{
[Test]
public void MoveAheadNoTarget()
{
var target = new Target("Profit", new Maximization(), null);
Assert.IsTrue(target.MoveAhead(BacktestResult.Create(profit: 10m).ToJson()));
Assert.AreEqual(10m, target.Current);
Assert.IsFalse(target.MoveAhead(BacktestResult.Create(profit: 5m).ToJson()));
Assert.AreEqual(10m, target.Current);
Assert.IsTrue(target.MoveAhead(BacktestResult.Create(profit: 15m).ToJson()));
Assert.AreEqual(15m, target.Current);
}
[Test]
public void MoveAheadReachFirst()
{
var target = new Target("Profit", new Minimization(), 100);
bool reached = false;
target.Reached += (s, e) =>
{
reached = true;
};
Assert.IsTrue(target.MoveAhead(BacktestResult.Create(profit: 10m).ToJson()));
target.CheckCompliance();
Assert.AreEqual(10m, target.Current);
Assert.IsTrue(reached);
}
[Test]
public void MoveAheadReachLast()
{
var target = new Target("Profit", new Minimization(), 100);
bool reached = false;
target.Reached += (s, e) =>
{
reached = true;
};
for (var profit = 500m; profit > 0; profit -= 50)
{
Assert.IsTrue(target.MoveAhead(BacktestResult.Create(profit: profit).ToJson()));
Assert.AreEqual(profit, target.Current);
target.CheckCompliance();
}
Assert.IsTrue(reached);
}
[TestCase("")]
[TestCase(null)]
public void ThrowIfNullOrEmpty(string json)
{
var target = new Target("Profit", new Maximization(), null);
Assert.Throws<ArgumentNullException>(() =>
{
target.MoveAhead(json);
});
}
[Test]
public void IgnoreBadJson()
{
var target = new Target("Profit", new Maximization(), null);
Assert.IsFalse(target.MoveAhead("{\"Profit\":10}"));
Assert.AreEqual(null, target.Current);
}
[TestCase("Sharpe Ratio")]
[TestCase("Statistics.Sharpe Ratio")]
[TestCase("['Statistics'].['Sharpe Ratio']")]
public void ParseTargetName(string targetName)
{
var target = new Target(targetName, new Minimization(), 100);
Assert.AreEqual("['Statistics'].['Sharpe Ratio']", target.Target);
}
[TestCase("null")]
[TestCase("11")]
public void FromJson(string value)
{
var json = $"{{\"extremum\": \"max\",\"target\": \"pin ocho.Gepetto\",\"targetValue\": {value}}}";
var target = (Target)JsonConvert.DeserializeObject(json, typeof(Target));
Assert.AreEqual("['pin ocho'].['Gepetto']", target.Target);
Assert.AreEqual(typeof(Maximization), target.Extremum.GetType());
if (value == "null")
{
Assert.IsNull(target.TargetValue);
}
else
{
Assert.AreEqual(11, target.TargetValue);
}
}
[Test]
public void RoundTrip()
{
var origin = new Target("['Statistics'].['Drawdown']", new Maximization(), 100);
var json = JsonConvert.SerializeObject(origin);
var actual = JsonConvert.DeserializeObject<Target>(json);
Assert.NotNull(actual);
Assert.AreEqual(origin.Target, actual.Target);
Assert.AreEqual(origin.Extremum.GetType(), actual.Extremum.GetType());
Assert.AreEqual(origin.TargetValue, actual.TargetValue);
}
[TestCase("['TotalPerformance'].['TradeStatistics'].['ProfitToMaxDrawdownRatio']", "-1")]
[TestCase("['totalPerformance'].['tradeStatistics'].['profitToMaxDrawdownRatio']", "-1")]
[TestCase("['TotalPerformance'].['TradeStatistics'].['lossRate']", "1")]
[TestCase("['totalPerformance'].['tradeStatistics'].['lossRate']", "1")]
[TestCase("['Statistics'].['Start Equity']", "100000")]
[TestCase("['statistics'].['start equity']", "100000")]
[TestCase("['Statistics'].['Sharpe Ratio']", "-5.283")]
[TestCase("['statistics'].['sharpe ratio']", "-5.283")]
[TestCase("['Statistics'].['Sharp Ratio']", null)]
[TestCase("['statistics'].['sharp ratio']", null)]
public void TargetMoveAheadIsCaseInsensitive(string target, string expected)
{
Assert.AreEqual(expected, (Target.GetTokenInJsonBacktest(jsonBacktestResultExample, target))?.Value<string>());
}
private string jsonBacktestResultExample = @"{
""totalPerformance"": {
""tradeStatistics"": {
""lossRate"": ""1"",
""profitToMaxDrawdownRatio"": ""-1"",
}
},
""statistics"": {
""Start Equity"": ""100000"",
""Sharpe Ratio"": ""-5.283"",
}
}";
}
}