From b122657455c1fc374c6ca34260310cb595ab8349 Mon Sep 17 00:00:00 2001 From: Josue Nina Date: Mon, 30 Dec 2024 16:23:13 -0500 Subject: [PATCH] Addressed review comments --- Common/Extensions.cs | 53 +++++++++++++++---------------- Indicators/Beta.cs | 9 +++--- Indicators/Correlation.cs | 9 +++--- Indicators/DualSymbolIndicator.cs | 19 +++++++---- 4 files changed, 46 insertions(+), 44 deletions(-) diff --git a/Common/Extensions.cs b/Common/Extensions.cs index dce6ccebcb19..ec148d2cbfaa 100644 --- a/Common/Extensions.cs +++ b/Common/Extensions.cs @@ -68,7 +68,7 @@ namespace QuantConnect /// public static class Extensions { - private static readonly Dictionary _emptyDirectories = new(); + private static readonly Dictionary _emptyDirectories = new (); private static readonly HashSet InvalidSecurityTypes = new HashSet(); private static readonly Regex DateCheck = new Regex(@"\d{8}", RegexOptions.Compiled); private static RecyclableMemoryStreamManager MemoryManager = new RecyclableMemoryStreamManager(); @@ -142,7 +142,7 @@ public static bool IsDirectoryEmpty(this string directoryPath) { lock (_emptyDirectories) { - if (!_emptyDirectories.TryGetValue(directoryPath, out var result)) + if(!_emptyDirectories.TryGetValue(directoryPath, out var result)) { // is empty unless it exists and it has at least 1 file or directory in it result = true; @@ -790,8 +790,7 @@ public static IEnumerable OrderTargetsByMarginImpact( && (targetIsDelta ? Math.Abs(x.TargetQuantity) : Math.Abs(x.TargetQuantity - x.ExistingQuantity)) >= x.Security.SymbolProperties.LotSize ) - .Select(x => new - { + .Select(x => new { x.PortfolioTarget, OrderValue = Math.Abs((targetIsDelta ? x.TargetQuantity : (x.TargetQuantity - x.ExistingQuantity)) * x.Security.Price), IsReducingPosition = x.ExistingQuantity != 0 @@ -817,7 +816,7 @@ public static BaseData GetBaseDataInstance(this Type type) } var instance = objectActivator.Invoke(new object[] { type }); - if (instance == null) + if(instance == null) { // shouldn't happen but just in case... throw new ArgumentException(Messages.Extensions.FailedToCreateInstanceOfType(type)); @@ -901,8 +900,7 @@ public static byte[] GetBytes(this Stream stream) public static void Clear(this ConcurrentQueue queue) { T item; - while (queue.TryDequeue(out item)) - { + while (queue.TryDequeue(out item)) { // NOP } } @@ -1195,7 +1193,7 @@ public static void Add(this Ticks dictionary, Symbol key, Tick tick) public static decimal RoundToSignificantDigits(this decimal d, int digits) { if (d == 0) return 0; - var scale = (decimal)Math.Pow(10, Math.Floor(Math.Log10((double)Math.Abs(d))) + 1); + var scale = (decimal)Math.Pow(10, Math.Floor(Math.Log10((double) Math.Abs(d))) + 1); return scale * Math.Round(d / scale, digits); } @@ -1335,9 +1333,9 @@ public static decimal SafeDecimalCast(this double input) ); } - if (input <= (double)decimal.MinValue) return decimal.MinValue; - if (input >= (double)decimal.MaxValue) return decimal.MaxValue; - return (decimal)input; + if (input <= (double) decimal.MinValue) return decimal.MinValue; + if (input >= (double) decimal.MaxValue) return decimal.MaxValue; + return (decimal) input; } /// @@ -1679,8 +1677,7 @@ public static decimal GetDecimalEpsilon() /// /// String we're looking for the extension for. /// Last 4 character string of string. - public static string GetExtension(this string str) - { + public static string GetExtension(this string str) { var ext = str.Substring(Math.Max(0, str.Length - 4)); var allowedExt = new List { ".zip", ".csv", ".json", ".tsv" }; if (!allowedExt.Contains(ext)) @@ -2089,19 +2086,19 @@ public static Resolution ToHigherResolutionEquivalent(this TimeSpan timeSpan, bo { if (requireExactMatch) { - if (TimeSpan.Zero == timeSpan) return Resolution.Tick; + if (TimeSpan.Zero == timeSpan) return Resolution.Tick; if (Time.OneSecond == timeSpan) return Resolution.Second; if (Time.OneMinute == timeSpan) return Resolution.Minute; - if (Time.OneHour == timeSpan) return Resolution.Hour; - if (Time.OneDay == timeSpan) return Resolution.Daily; + if (Time.OneHour == timeSpan) return Resolution.Hour; + if (Time.OneDay == timeSpan) return Resolution.Daily; throw new InvalidOperationException(Messages.Extensions.UnableToConvertTimeSpanToResolution(timeSpan)); } // for non-perfect matches if (Time.OneSecond > timeSpan) return Resolution.Tick; if (Time.OneMinute > timeSpan) return Resolution.Second; - if (Time.OneHour > timeSpan) return Resolution.Minute; - if (Time.OneDay > timeSpan) return Resolution.Hour; + if (Time.OneHour > timeSpan) return Resolution.Minute; + if (Time.OneDay > timeSpan) return Resolution.Hour; return Resolution.Daily; } @@ -2140,7 +2137,7 @@ public static bool TryParseSecurityType(this string value, out SecurityType secu /// The converted value public static T ConvertTo(this string value) { - return (T)value.ConvertTo(typeof(T)); + return (T) value.ConvertTo(typeof (T)); } /// @@ -2156,16 +2153,16 @@ public static object ConvertTo(this string value, Type type) return Enum.Parse(type, value, true); } - if (typeof(IConvertible).IsAssignableFrom(type)) + if (typeof (IConvertible).IsAssignableFrom(type)) { return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); } // try and find a static parse method - var parse = type.GetMethod("Parse", new[] { typeof(string) }); + var parse = type.GetMethod("Parse", new[] {typeof (string)}); if (parse != null) { - var result = parse.Invoke(null, new object[] { value }); + var result = parse.Invoke(null, new object[] {value}); return result; } @@ -2200,7 +2197,7 @@ public static bool WaitOne(this WaitHandle waitHandle, CancellationToken cancell /// The maximum number of waiters has been exceeded. The object has already been disposed or the that created has been disposed. public static bool WaitOne(this WaitHandle waitHandle, TimeSpan timeout, CancellationToken cancellationToken) { - return waitHandle.WaitOne((int)timeout.TotalMilliseconds, cancellationToken); + return waitHandle.WaitOne((int) timeout.TotalMilliseconds, cancellationToken); } /// @@ -2783,7 +2780,7 @@ public static bool TryConvert(this PyObject pyObject, out T result, bool allo { result = (T)pyObject.AsManagedObject(type); // pyObject is a C# object wrapped in PyObject, in this case return true - if (!pyObject.HasAttr("__name__")) + if(!pyObject.HasAttr("__name__")) { return true; } @@ -3281,7 +3278,7 @@ public static IEnumerable> BatchBy(this IEnumerable enumerable, in { if (list == null) { - list = new List { enumerator.Current }; + list = new List {enumerator.Current}; } else if (list.Count < batchSize) { @@ -3290,7 +3287,7 @@ public static IEnumerable> BatchBy(this IEnumerable enumerable, in else { yield return list; - list = new List { enumerator.Current }; + list = new List {enumerator.Current}; } } @@ -3510,7 +3507,7 @@ public static IEnumerator SubscribeWithMapping(this IDataQueueHandler /// Enumeration of lines in file public static IEnumerable ReadLines(this IDataProvider dataProvider, string file) { - if (dataProvider == null) + if(dataProvider == null) { throw new ArgumentException(Messages.Extensions.NullDataProvider); } @@ -4045,7 +4042,7 @@ public static OptionRight Invert(this OptionRight right) switch (right) { case OptionRight.Call: return OptionRight.Put; - case OptionRight.Put: return OptionRight.Call; + case OptionRight.Put: return OptionRight.Call; default: throw new ArgumentOutOfRangeException(nameof(right), right, null); } diff --git a/Indicators/Beta.cs b/Indicators/Beta.cs index f0b88dd3329d..b191327d613e 100644 --- a/Indicators/Beta.cs +++ b/Indicators/Beta.cs @@ -45,7 +45,7 @@ public class Beta : DualSymbolIndicator /// /// Beta of the target used in relation with the reference /// - private decimal _beta; + //private decimal _beta; /// /// Gets a flag indicating when the indicator is ready and fully initialized @@ -109,8 +109,7 @@ public Beta(string name, int period, Symbol targetSymbol, Symbol referenceSymbol /// The computed beta value between the target and reference symbols. protected override decimal ComputeNextValue(IBaseDataBar input) { - CheckAndCompute(input, ComputeBeta); - return _beta; + return CheckAndCompute(input, ComputeBeta); } /// @@ -165,7 +164,7 @@ private void ComputeBeta() // Avoid division with NaN or by zero var variance = !varianceComputed.IsNaNOrZero() ? varianceComputed : 1; var covariance = !covarianceComputed.IsNaNOrZero() ? covarianceComputed : 0; - _beta = (decimal)(covariance / variance); + IndicatorValue = (decimal)(covariance / variance); } /// @@ -175,7 +174,7 @@ public override void Reset() { _targetReturns.Reset(); _referenceReturns.Reset(); - _beta = 0; + IndicatorValue = 0; base.Reset(); } } diff --git a/Indicators/Correlation.cs b/Indicators/Correlation.cs index faf20295fa66..f2ed674e57c3 100644 --- a/Indicators/Correlation.cs +++ b/Indicators/Correlation.cs @@ -39,7 +39,7 @@ public class Correlation : DualSymbolIndicator /// /// Correlation of the target used in relation with the reference /// - private decimal _correlation; + //private decimal _correlation; /// /// Correlation type @@ -94,8 +94,7 @@ public Correlation(Symbol targetSymbol, Symbol referenceSymbol, int period, Corr /// The computed correlation value between the target and reference symbols. protected override decimal ComputeNextValue(IBaseDataBar input) { - CheckAndCompute(input, ComputeCorrelation); - return _correlation; + return CheckAndCompute(input, ComputeCorrelation); } /// @@ -138,7 +137,7 @@ private void ComputeCorrelation() { newCorrelation = 0; } - _correlation = Extensions.SafeDecimalCast(newCorrelation); + IndicatorValue = Extensions.SafeDecimalCast(newCorrelation); } /// @@ -146,7 +145,7 @@ private void ComputeCorrelation() /// public override void Reset() { - _correlation = 0; + IndicatorValue = 0; base.Reset(); } } diff --git a/Indicators/DualSymbolIndicator.cs b/Indicators/DualSymbolIndicator.cs index 7963458cd01f..0e2b6770165b 100644 --- a/Indicators/DualSymbolIndicator.cs +++ b/Indicators/DualSymbolIndicator.cs @@ -30,12 +30,12 @@ public abstract class DualSymbolIndicator : BarIndicator, IIndicatorWarmUpPer /// /// Time zone of the target symbol. /// - private DateTimeZone _targetTimeZone; + private readonly DateTimeZone _targetTimeZone; /// /// Time zone of the reference symbol. /// - private DateTimeZone _referenceTimeZone; + private readonly DateTimeZone _referenceTimeZone; /// /// Stores the previous input data point. @@ -72,6 +72,11 @@ public abstract class DualSymbolIndicator : BarIndicator, IIndicatorWarmUpPer /// protected bool IsTimezoneDifferent { get; } + /// + /// The most recently computed value of the indicator. + /// + protected decimal IndicatorValue { get; set; } + /// /// Required period, in data points, for the indicator to be ready and fully initialized. /// @@ -107,13 +112,14 @@ protected DualSymbolIndicator(string name, Symbol targetSymbol, Symbol reference /// /// The input data point (e.g., TradeBar for a symbol). /// The action to take when data is ready for computation. - public void CheckAndCompute(IBaseDataBar input, Action computeAction) + /// The most recently computed value of the indicator. + protected decimal CheckAndCompute(IBaseDataBar input, Action computeAction) { if (_previousInput == null) { _previousInput = input; _resolution = GetResolution(input); - return; + return decimal.Zero; } var isMatchingTime = CompareEndTimes(input.EndTime, _previousInput.EndTime); @@ -125,13 +131,14 @@ public void CheckAndCompute(IBaseDataBar input, Action computeAction) computeAction(); } _previousInput = input; + return IndicatorValue; } /// /// Determines the resolution of the input data based on the time difference between its start and end times. /// Returns if the difference exceeds 1 hour; otherwise, calculates a higher equivalent resolution. /// - public Resolution GetResolution(IBaseData input) + private Resolution GetResolution(IBaseData input) { var timeDifference = input.EndTime - input.Time; return timeDifference.TotalHours > 1 ? Resolution.Daily : timeDifference.ToHigherResolutionEquivalent(false); @@ -166,7 +173,7 @@ private DateTime AdjustDateToResolution(DateTime date) /// The end time of the current data point. /// The end time of the previous data point. /// True if the end times match after considering time zones and resolution. - protected bool CompareEndTimes(DateTime currentEndTime, DateTime previousEndTime) + private bool CompareEndTimes(DateTime currentEndTime, DateTime previousEndTime) { var previousSymbolIsTarget = _previousInput.Symbol == TargetSymbol; if (IsTimezoneDifferent)