Lean  $LEAN_TAG$
Objective.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 System;
17 using System.Linq;
18 using System.Text.RegularExpressions;
19 using Newtonsoft.Json;
20 
22 {
23  /// <summary>
24  /// Base class for optimization <see cref="Objectives.Target"/> and <see cref="Constraint"/>
25  /// </summary>
26  public abstract class Objective
27  {
28  private readonly Regex _targetTemplate = new Regex("['(.+)']");
29  private string _target;
30 
31  /// <summary>
32  /// Target; property of json file we want to track
33  /// </summary>
34  public string Target
35  {
36  get => _target;
37  set
38  {
39  _target = value != null ? string.Join(".", value.Split('.').Select(s => _targetTemplate.Match(s).Success ? s : $"['{s}']")) : value;
40  }
41  }
42 
43  /// <summary>
44  /// Target value
45  /// </summary>
46  /// <remarks>For <see cref="Objectives.Target"/> if defined and backtest complies with the targets then finish optimization</remarks>
47  /// <remarks>For <see cref="Constraint"/> non optional, the value of the target constraint</remarks>
48  public decimal? TargetValue { get; set; }
49 
50  protected Objective()
51  {
52 
53  }
54 
55  /// <summary>
56  /// Creates a new instance
57  /// </summary>
58  protected Objective(string target, decimal? targetValue)
59  {
60  if (string.IsNullOrEmpty(target))
61  {
62  throw new ArgumentNullException(nameof(target), Messages.Objective.NullOrEmptyObjective);
63  }
64 
65  var objective = target;
66  if (!objective.Contains("."))
67  {
68  // default path
69  objective = $"Statistics.{objective}";
70  }
71  // escape empty space in json path
72  Target = objective;
73  TargetValue = targetValue;
74  }
75 
76  #region Backwards Compatibility
77  /// <summary>
78  /// Target value
79  /// </summary>
80  /// <remarks>For <see cref="Objectives.Target"/> if defined and backtest complies with the targets then finish optimization</remarks>
81  /// <remarks>For <see cref="Constraint"/> non optional, the value of the target constraint</remarks>
82  [JsonProperty("target-value")]
83  private decimal? OldTargetValue
84  {
85  set
86  {
87  TargetValue = value;
88  }
89  }
90  #endregion
91  }
92 }