Lean  $LEAN_TAG$
Constraint.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using Newtonsoft.Json;
17 using Newtonsoft.Json.Linq;
18 using QuantConnect.Util;
19 using System;
20 using Newtonsoft.Json.Converters;
21 using Newtonsoft.Json.Serialization;
22 
24 {
25  /// <summary>
26  /// A backtest optimization constraint.
27  /// Allows specifying statistical constraints for the optimization, eg. a backtest can't have a DrawDown less than 10%
28  /// </summary>
29  public class Constraint : Objective
30  {
31  /// <summary>
32  /// The target comparison operation, eg. 'Greater'
33  /// </summary>
34  [JsonProperty("operator"), JsonConverter(typeof(StringEnumConverter), typeof(DefaultNamingStrategy))]
36 
37  /// <summary>
38  /// Creates a new instance
39  /// </summary>
40  public Constraint(string target, ComparisonOperatorTypes @operator, decimal? targetValue) : base(target, targetValue)
41  {
42  Operator = @operator;
43 
44  if (!TargetValue.HasValue)
45  {
46  throw new ArgumentNullException(nameof(targetValue), Messages.Constraint.ConstraintTargetValueNotSpecified);
47  }
48  }
49 
50  /// <summary>
51  /// Asserts the constraint is met
52  /// </summary>
53  public bool IsMet(string jsonBacktestResult)
54  {
55  if (string.IsNullOrEmpty(jsonBacktestResult))
56  {
57  throw new ArgumentNullException(nameof(jsonBacktestResult), $"Constraint.IsMet(): {Messages.OptimizerObjectivesCommon.NullOrEmptyBacktestResult}");
58  }
59 
60  var token = JObject.Parse(jsonBacktestResult).SelectToken(Target);
61  if (token == null)
62  {
63  return false;
64  }
65 
66  return Operator.Compare(
67  token.Value<string>().ToNormalizedDecimal(),
68  TargetValue.Value);
69  }
70 
71  /// <summary>
72  /// Pretty representation of a constraint
73  /// </summary>
74  public override string ToString()
75  {
76  return $"{Target} '{Operator}' {TargetValue.Value}";
77  }
78  }
79 }