Skip to content

Commit

Permalink
Addressed review comments
Browse files Browse the repository at this point in the history
  • Loading branch information
JosueNina committed Dec 30, 2024
1 parent 9a19b64 commit b122657
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 44 deletions.
53 changes: 25 additions & 28 deletions Common/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ namespace QuantConnect
/// </summary>
public static class Extensions
{
private static readonly Dictionary<string, bool> _emptyDirectories = new();
private static readonly Dictionary<string, bool> _emptyDirectories = new ();
private static readonly HashSet<string> InvalidSecurityTypes = new HashSet<string>();
private static readonly Regex DateCheck = new Regex(@"\d{8}", RegexOptions.Compiled);
private static RecyclableMemoryStreamManager MemoryManager = new RecyclableMemoryStreamManager();
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -790,8 +790,7 @@ public static IEnumerable<IPortfolioTarget> 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
Expand All @@ -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));
Expand Down Expand Up @@ -901,8 +900,7 @@ public static byte[] GetBytes(this Stream stream)
public static void Clear<T>(this ConcurrentQueue<T> queue)
{
T item;
while (queue.TryDequeue(out item))
{
while (queue.TryDequeue(out item)) {
// NOP
}
}
Expand Down Expand Up @@ -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);
}

Expand Down Expand Up @@ -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;
}

/// <summary>
Expand Down Expand Up @@ -1679,8 +1677,7 @@ public static decimal GetDecimalEpsilon()
/// </summary>
/// <param name="str">String we're looking for the extension for.</param>
/// <returns>Last 4 character string of string.</returns>
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<string> { ".zip", ".csv", ".json", ".tsv" };
if (!allowedExt.Contains(ext))
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -2140,7 +2137,7 @@ public static bool TryParseSecurityType(this string value, out SecurityType secu
/// <returns>The converted value</returns>
public static T ConvertTo<T>(this string value)
{
return (T)value.ConvertTo(typeof(T));
return (T) value.ConvertTo(typeof (T));
}

/// <summary>
Expand All @@ -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;
}

Expand Down Expand Up @@ -2200,7 +2197,7 @@ public static bool WaitOne(this WaitHandle waitHandle, CancellationToken cancell
/// <exception cref="T:System.InvalidOperationException">The maximum number of waiters has been exceeded. </exception><exception cref="T:System.ObjectDisposedException">The object has already been disposed or the <see cref="T:System.Threading.CancellationTokenSource"/> that created <paramref name="cancellationToken"/> has been disposed.</exception>
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);
}

/// <summary>
Expand Down Expand Up @@ -2783,7 +2780,7 @@ public static bool TryConvert<T>(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;
}
Expand Down Expand Up @@ -3281,7 +3278,7 @@ public static IEnumerable<List<T>> BatchBy<T>(this IEnumerable<T> enumerable, in
{
if (list == null)
{
list = new List<T> { enumerator.Current };
list = new List<T> {enumerator.Current};
}
else if (list.Count < batchSize)
{
Expand All @@ -3290,7 +3287,7 @@ public static IEnumerable<List<T>> BatchBy<T>(this IEnumerable<T> enumerable, in
else
{
yield return list;
list = new List<T> { enumerator.Current };
list = new List<T> {enumerator.Current};
}
}

Expand Down Expand Up @@ -3510,7 +3507,7 @@ public static IEnumerator<BaseData> SubscribeWithMapping(this IDataQueueHandler
/// <returns>Enumeration of lines in file</returns>
public static IEnumerable<string> ReadLines(this IDataProvider dataProvider, string file)
{
if (dataProvider == null)
if(dataProvider == null)
{
throw new ArgumentException(Messages.Extensions.NullDataProvider);
}
Expand Down Expand Up @@ -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);
}
Expand Down
9 changes: 4 additions & 5 deletions Indicators/Beta.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public class Beta : DualSymbolIndicator<decimal>
/// <summary>
/// Beta of the target used in relation with the reference
/// </summary>
private decimal _beta;
//private decimal _beta;

/// <summary>
/// Gets a flag indicating when the indicator is ready and fully initialized
Expand Down Expand Up @@ -109,8 +109,7 @@ public Beta(string name, int period, Symbol targetSymbol, Symbol referenceSymbol
/// <returns>The computed beta value between the target and reference symbols.</returns>
protected override decimal ComputeNextValue(IBaseDataBar input)
{
CheckAndCompute(input, ComputeBeta);
return _beta;
return CheckAndCompute(input, ComputeBeta);
}

/// <summary>
Expand Down Expand Up @@ -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);
}

/// <summary>
Expand All @@ -175,7 +174,7 @@ public override void Reset()
{
_targetReturns.Reset();
_referenceReturns.Reset();
_beta = 0;
IndicatorValue = 0;
base.Reset();
}
}
Expand Down
9 changes: 4 additions & 5 deletions Indicators/Correlation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public class Correlation : DualSymbolIndicator<double>
/// <summary>
/// Correlation of the target used in relation with the reference
/// </summary>
private decimal _correlation;
//private decimal _correlation;

/// <summary>
/// Correlation type
Expand Down Expand Up @@ -94,8 +94,7 @@ public Correlation(Symbol targetSymbol, Symbol referenceSymbol, int period, Corr
/// <returns>The computed correlation value between the target and reference symbols.</returns>
protected override decimal ComputeNextValue(IBaseDataBar input)
{
CheckAndCompute(input, ComputeCorrelation);
return _correlation;
return CheckAndCompute(input, ComputeCorrelation);
}

/// <summary>
Expand Down Expand Up @@ -138,15 +137,15 @@ private void ComputeCorrelation()
{
newCorrelation = 0;
}
_correlation = Extensions.SafeDecimalCast(newCorrelation);
IndicatorValue = Extensions.SafeDecimalCast(newCorrelation);
}

/// <summary>
/// Resets this indicator to its initial state
/// </summary>
public override void Reset()
{
_correlation = 0;
IndicatorValue = 0;
base.Reset();
}
}
Expand Down
19 changes: 13 additions & 6 deletions Indicators/DualSymbolIndicator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ public abstract class DualSymbolIndicator<T> : BarIndicator, IIndicatorWarmUpPer
/// <summary>
/// Time zone of the target symbol.
/// </summary>
private DateTimeZone _targetTimeZone;
private readonly DateTimeZone _targetTimeZone;

/// <summary>
/// Time zone of the reference symbol.
/// </summary>
private DateTimeZone _referenceTimeZone;
private readonly DateTimeZone _referenceTimeZone;

/// <summary>
/// Stores the previous input data point.
Expand Down Expand Up @@ -72,6 +72,11 @@ public abstract class DualSymbolIndicator<T> : BarIndicator, IIndicatorWarmUpPer
/// </summary>
protected bool IsTimezoneDifferent { get; }

/// <summary>
/// The most recently computed value of the indicator.
/// </summary>
protected decimal IndicatorValue { get; set; }

/// <summary>
/// Required period, in data points, for the indicator to be ready and fully initialized.
/// </summary>
Expand Down Expand Up @@ -107,13 +112,14 @@ protected DualSymbolIndicator(string name, Symbol targetSymbol, Symbol reference
/// </summary>
/// <param name="input">The input data point (e.g., TradeBar for a symbol).</param>
/// <param name="computeAction">The action to take when data is ready for computation.</param>
public void CheckAndCompute(IBaseDataBar input, Action computeAction)
/// <returns>The most recently computed value of the indicator.</returns>
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);
Expand All @@ -125,13 +131,14 @@ public void CheckAndCompute(IBaseDataBar input, Action computeAction)
computeAction();
}
_previousInput = input;
return IndicatorValue;
}

/// <summary>
/// Determines the resolution of the input data based on the time difference between its start and end times.
/// Returns <see cref="Resolution.Daily"/> if the difference exceeds 1 hour; otherwise, calculates a higher equivalent resolution.
/// </summary>
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);
Expand Down Expand Up @@ -166,7 +173,7 @@ private DateTime AdjustDateToResolution(DateTime date)
/// <param name="currentEndTime">The end time of the current data point.</param>
/// <param name="previousEndTime">The end time of the previous data point.</param>
/// <returns>True if the end times match after considering time zones and resolution.</returns>
protected bool CompareEndTimes(DateTime currentEndTime, DateTime previousEndTime)
private bool CompareEndTimes(DateTime currentEndTime, DateTime previousEndTime)
{
var previousSymbolIsTarget = _previousInput.Symbol == TargetSymbol;
if (IsTimezoneDifferent)
Expand Down

0 comments on commit b122657

Please sign in to comment.