Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions Indicators/Variance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,20 @@ public Variance(string name, int period)
/// <returns>A new value for this indicator</returns>
protected override decimal ComputeNextValue(IReadOnlyWindow<IndicatorDataPoint> window, IndicatorDataPoint input)
{
_rollingSum += input.Value;
_rollingSumOfSquares += input.Value * input.Value;
var previousRollingSum = _rollingSum;
var previousRollingSumOfSquares = _rollingSumOfSquares;
try
{
_rollingSum += input.Value;
_rollingSumOfSquares += input.Value * input.Value;
}
catch (OverflowException)
{
_rollingSum = previousRollingSum;
_rollingSumOfSquares = previousRollingSumOfSquares;
//Log.Error($"Variance.ComputeNextValue: Decimal overflow detected when adding value {input.Value}. The previous variance value will be returned.");
return Current.Value;
}

if (Samples < 2)
return 0m;
Expand Down
18 changes: 18 additions & 0 deletions Tests/Indicators/VarianceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
* limitations under the License.
*/

using System;
using NUnit.Framework;
using QuantConnect.Indicators;

Expand All @@ -29,5 +30,22 @@ protected override IndicatorBase<IndicatorDataPoint> CreateIndicator()
protected override string TestFileName => "spy_var.txt";

protected override string TestColumnName => "Var";

[Test]
public void DoesNotThrowOnDecimalOverflow()
{
var variance = new Variance(3);
var time = new DateTime(2020, 1, 1);

variance.Update(time, 100m);
variance.Update(time.AddSeconds(1), 200m);
variance.Update(time.AddSeconds(2), 150m);
var previousValue = variance.Current.Value;

var overflowValue = 300000000000000m; // 3e14 squared will exceed decimal.MaxValue

Assert.DoesNotThrow(() => variance.Update(time.AddSeconds(3), overflowValue));
Assert.AreEqual(previousValue, variance.Current.Value);
}
}
}
Loading