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  [JsonConverter(typeof(StringEnumConverter))]
35  public ComparisonOperatorTypes Operator { get; set; }
36 
37  public Constraint()
38  {
39 
40  }
41 
42  /// <summary>
43  /// Creates a new instance
44  /// </summary>
45  public Constraint(string target, ComparisonOperatorTypes @operator, decimal? targetValue) : base(target, targetValue)
46  {
47  Operator = @operator;
48 
49  if (!TargetValue.HasValue)
50  {
51  throw new ArgumentNullException(nameof(targetValue), Messages.Constraint.ConstraintTargetValueNotSpecified);
52  }
53  }
54 
55  /// <summary>
56  /// Asserts the constraint is met
57  /// </summary>
58  public bool IsMet(string jsonBacktestResult)
59  {
60  if (string.IsNullOrEmpty(jsonBacktestResult))
61  {
62  throw new ArgumentNullException(nameof(jsonBacktestResult), $"Constraint.IsMet(): {Messages.OptimizerObjectivesCommon.NullOrEmptyBacktestResult}");
63  }
64 
65  var token = JObject.Parse(jsonBacktestResult).SelectToken(Target);
66  if (token == null)
67  {
68  return false;
69  }
70 
71  return Operator.Compare(
72  token.Value<string>().ToNormalizedDecimal(),
73  TargetValue.Value);
74  }
75 
76  /// <summary>
77  /// Pretty representation of a constraint
78  /// </summary>
79  public override string ToString()
80  {
81  return $"{Target} '{Operator}' {TargetValue.Value}";
82  }
83  }
84 }