mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-18 10:38:05 +00:00
Add Stochastic Oscillator implementation and validation tests
- Implemented Stochastic Oscillator (%K and %D) in Stoch.cs with streaming and batch processing capabilities. - Added validation tests for the Stochastic Oscillator in Stoch.Validation.Tests.cs, ensuring consistency with Skender.Stock.Indicators. - Created documentation for the Stochastic Oscillator in Stoch.md, detailing its mathematical formula, architecture, parameters, and common pitfalls. - Updated project file to include necessary numeric libraries for highest and lowest calculations.
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
using QuanTAlib;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class BbbIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void BbbIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new BbbIndicator();
|
||||
|
||||
Assert.Equal(20, indicator.Period);
|
||||
Assert.Equal(2.0, indicator.Multiplier);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("BBB - Bollinger %B", indicator.Name);
|
||||
Assert.True(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BbbIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new BbbIndicator { Period = 20 };
|
||||
|
||||
Assert.Equal(0, BbbIndicator.MinHistoryDepths);
|
||||
IWatchlistIndicator watchlistIndicator = indicator;
|
||||
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BbbIndicator_ShortName_IncludesParameters()
|
||||
{
|
||||
var indicator = new BbbIndicator { Period = 10, Multiplier = 2.5 };
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Contains("BBB", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("10", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("2.5", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BbbIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new BbbIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Bbb.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BbbIndicator_Initialize_CreatesInternalBbb()
|
||||
{
|
||||
var indicator = new BbbIndicator { Period = 20, Multiplier = 2.0 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BbbIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new BbbIndicator { Period = 5, Multiplier = 2.0 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
indicator.ProcessUpdate(args);
|
||||
}
|
||||
|
||||
double value = indicator.LinesSeries[0].GetValue(0);
|
||||
Assert.True(double.IsFinite(value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BbbIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new BbbIndicator { Period = 5, Multiplier = 2.0 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
}
|
||||
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(20), 120, 130, 110, 125);
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
|
||||
|
||||
Assert.Equal(2, indicator.LinesSeries[0].Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BbbIndicator_Parameters_CanBeChanged()
|
||||
{
|
||||
var indicator = new BbbIndicator { Period = 20, Multiplier = 2.0 };
|
||||
|
||||
indicator.Period = 10;
|
||||
indicator.Multiplier = 1.5;
|
||||
|
||||
Assert.Equal(10, indicator.Period);
|
||||
Assert.Equal(1.5, indicator.Multiplier);
|
||||
Assert.Equal(0, BbbIndicator.MinHistoryDepths);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class BbbIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 1, 1000, 1, 0)]
|
||||
public int Period { get; set; } = 20;
|
||||
|
||||
[InputParameter("Multiplier", sortIndex: 2, 0.1, 10.0, 0.1, 1)]
|
||||
public double Multiplier { get; set; } = 2.0;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput(sortIndex: 3)]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Bbb _bbb = null!;
|
||||
private readonly LineSeries _series;
|
||||
|
||||
public static int MinHistoryDepths => 0;
|
||||
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
|
||||
|
||||
public override string ShortName => $"BBB ({Period},{Multiplier:F1})";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/oscillators/bbb/Bbb.Quantower.cs";
|
||||
|
||||
public BbbIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = true;
|
||||
Name = "BBB - Bollinger %B";
|
||||
Description = "Position of price within Bollinger Bands";
|
||||
|
||||
_series = new LineSeries("BBB", Color.Gold, 2, LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnInit()
|
||||
{
|
||||
_bbb = new Bbb(Period, Multiplier);
|
||||
base.OnInit();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnUpdate(UpdateArgs args)
|
||||
{
|
||||
var priceSelector = Source.GetPriceSelector();
|
||||
var item = HistoricalData[0, SeekOriginHistory.End];
|
||||
double price = priceSelector(item);
|
||||
|
||||
TValue input = new(item.TimeLeft, price);
|
||||
TValue result = _bbb.Update(input, args.IsNewBar());
|
||||
|
||||
if (!_bbb.IsHot && !ShowColdValues)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_series.SetValue(result.Value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
using Xunit;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class BbbTests
|
||||
{
|
||||
[Fact]
|
||||
public void Constructor_ValidParameters()
|
||||
{
|
||||
var bbb = new Bbb(period: 20, multiplier: 2.0);
|
||||
|
||||
Assert.NotNull(bbb);
|
||||
Assert.Equal("Bbb(20,2.0)", bbb.Name);
|
||||
Assert.Equal(20, bbb.WarmupPeriod);
|
||||
Assert.False(bbb.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_InvalidPeriod_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Bbb(period: 0, multiplier: 2.0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_InvalidMultiplier_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Bbb(period: 20, multiplier: 0.0));
|
||||
Assert.Equal("multiplier", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ZeroWidth_ReturnsNeutral()
|
||||
{
|
||||
var bbb = new Bbb(period: 3, multiplier: 2.0);
|
||||
DateTime time = DateTime.UtcNow;
|
||||
|
||||
bbb.Update(new TValue(time, 10.0), isNew: true);
|
||||
bbb.Update(new TValue(time.AddSeconds(1), 10.0), isNew: true);
|
||||
var result = bbb.Update(new TValue(time.AddSeconds(2), 10.0), isNew: true);
|
||||
|
||||
Assert.Equal(0.5, result.Value, 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PercentB_AtMiddle_IsHalf()
|
||||
{
|
||||
var bbb = new Bbb(period: 3, multiplier: 2.0);
|
||||
DateTime time = DateTime.UtcNow;
|
||||
|
||||
// Window [0, 3, 1.5] has mean 1.5 and non-zero stddev.
|
||||
bbb.Update(new TValue(time, 0.0), isNew: true);
|
||||
bbb.Update(new TValue(time.AddSeconds(1), 3.0), isNew: true);
|
||||
var result = bbb.Update(new TValue(time.AddSeconds(2), 1.5), isNew: true);
|
||||
|
||||
Assert.Equal(0.5, result.Value, 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNew_False_RollsBackCorrectly()
|
||||
{
|
||||
var bbb = new Bbb(period: 3, multiplier: 2.0);
|
||||
DateTime time = DateTime.UtcNow;
|
||||
|
||||
bbb.Update(new TValue(time, 10.0), isNew: true);
|
||||
bbb.Update(new TValue(time.AddSeconds(1), 12.0), isNew: true);
|
||||
bbb.Update(new TValue(time.AddSeconds(2), 14.0), isNew: true);
|
||||
double before = bbb.Last.Value;
|
||||
|
||||
bbb.Update(new TValue(time.AddSeconds(2), 15.0), isNew: false);
|
||||
double after = bbb.Last.Value;
|
||||
|
||||
Assert.NotEqual(before, after);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NaN_HandledGracefully()
|
||||
{
|
||||
var bbb = new Bbb(period: 3, multiplier: 2.0);
|
||||
DateTime time = DateTime.UtcNow;
|
||||
|
||||
bbb.Update(new TValue(time, 10.0), isNew: true);
|
||||
bbb.Update(new TValue(time.AddSeconds(1), 12.0), isNew: true);
|
||||
bbb.Update(new TValue(time.AddSeconds(2), double.NaN), isNew: true);
|
||||
|
||||
Assert.True(double.IsFinite(bbb.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Infinity_HandledGracefully()
|
||||
{
|
||||
var bbb = new Bbb(period: 3, multiplier: 2.0);
|
||||
DateTime time = DateTime.UtcNow;
|
||||
|
||||
bbb.Update(new TValue(time, 10.0), isNew: true);
|
||||
bbb.Update(new TValue(time.AddSeconds(1), 12.0), isNew: true);
|
||||
bbb.Update(new TValue(time.AddSeconds(2), double.PositiveInfinity), isNew: true);
|
||||
|
||||
Assert.True(double.IsFinite(bbb.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WarmupPeriod_IsHotTransition()
|
||||
{
|
||||
var bbb = new Bbb(period: 5, multiplier: 2.0);
|
||||
DateTime time = DateTime.UtcNow;
|
||||
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
bbb.Update(new TValue(time.AddSeconds(i), 10.0 + i));
|
||||
Assert.False(bbb.IsHot);
|
||||
}
|
||||
|
||||
bbb.Update(new TValue(time.AddSeconds(4), 14.0));
|
||||
Assert.True(bbb.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateTSeries_ReturnsValidSeries()
|
||||
{
|
||||
int period = 5;
|
||||
var bbb = new Bbb(period, multiplier: 2.0);
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
var bars = gbm.Fetch(50, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
TSeries source = bars.Close;
|
||||
|
||||
TSeries result = bbb.Update(source);
|
||||
|
||||
Assert.Equal(source.Count, result.Count);
|
||||
Assert.True(bbb.IsHot);
|
||||
|
||||
var streaming = new Bbb(period, multiplier: 2.0);
|
||||
for (int i = Math.Max(0, source.Count - period); i < source.Count; i++)
|
||||
{
|
||||
streaming.Update(source[i], isNew: true);
|
||||
}
|
||||
Assert.Equal(streaming.Last.Value, result[^1].Value, 8);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_MatchesStreaming()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 7);
|
||||
var bars = gbm.Fetch(200, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
TSeries source = bars.Close;
|
||||
|
||||
var streaming = new Bbb(period: 20, multiplier: 2.0);
|
||||
foreach (var item in source)
|
||||
{
|
||||
streaming.Update(item);
|
||||
}
|
||||
|
||||
TSeries batch = Bbb.Batch(source, period: 20, multiplier: 2.0);
|
||||
|
||||
Assert.Equal(batch[^1].Value, streaming.Last.Value, 8);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanBatch_EmptyArrays_DoesNotThrow()
|
||||
{
|
||||
double[] source = [];
|
||||
double[] output = [];
|
||||
|
||||
var ex = Record.Exception(() => Bbb.Batch(source.AsSpan(), output.AsSpan(), 20, 2.0));
|
||||
Assert.Null(ex);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanBatch_InvalidLength_Throws()
|
||||
{
|
||||
double[] source = new double[10];
|
||||
double[] output = new double[9];
|
||||
|
||||
var ex = Assert.Throws<ArgumentException>(() => Bbb.Batch(source.AsSpan(), output.AsSpan(), 20, 2.0));
|
||||
Assert.Equal("output", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanBatch_InvalidPeriod_Throws()
|
||||
{
|
||||
double[] source = new double[10];
|
||||
double[] output = new double[10];
|
||||
|
||||
var ex = Assert.Throws<ArgumentException>(() => Bbb.Batch(source.AsSpan(), output.AsSpan(), 0, 2.0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanBatch_InvalidMultiplier_Throws()
|
||||
{
|
||||
double[] source = new double[10];
|
||||
double[] output = new double[10];
|
||||
|
||||
var ex = Assert.Throws<ArgumentException>(() => Bbb.Batch(source.AsSpan(), output.AsSpan(), 20, 0.0));
|
||||
Assert.Equal("multiplier", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Calculate_ReturnsResultsAndHotIndicator()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
var bars = gbm.Fetch(50, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
TSeries source = bars.Close;
|
||||
|
||||
var (results, indicator) = Bbb.Calculate(source, period: 5, multiplier: 2.0);
|
||||
|
||||
Assert.Equal(50, results.Count);
|
||||
Assert.True(indicator.IsHot);
|
||||
Assert.True(double.IsFinite(indicator.Last.Value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using Skender.Stock.Indicators;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class BbbValidationTests : IDisposable
|
||||
{
|
||||
private readonly ValidationTestData _testData;
|
||||
private readonly ITestOutputHelper _output;
|
||||
private bool _disposed;
|
||||
|
||||
public BbbValidationTests(ITestOutputHelper output)
|
||||
{
|
||||
_output = output;
|
||||
_testData = new ValidationTestData();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
}
|
||||
|
||||
private void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
|
||||
if (disposing)
|
||||
{
|
||||
_testData?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Streaming_Batch_Span_Agree()
|
||||
{
|
||||
int period = 20;
|
||||
double multiplier = 2.0;
|
||||
|
||||
// Streaming
|
||||
var streaming = new Bbb(period, multiplier);
|
||||
var streamValues = new List<double>(_testData.Data.Count);
|
||||
foreach (var item in _testData.Data)
|
||||
{
|
||||
streamValues.Add(streaming.Update(item).Value);
|
||||
}
|
||||
|
||||
// Batch (TSeries)
|
||||
TSeries batchSeries = Bbb.Batch(_testData.Data, period, multiplier);
|
||||
|
||||
// Span
|
||||
double[] src = _testData.RawData.ToArray();
|
||||
double[] spanOutput = new double[src.Length];
|
||||
Bbb.Batch(src.AsSpan(), spanOutput.AsSpan(), period, multiplier);
|
||||
|
||||
// Compare last 200 samples for stability
|
||||
int start = Math.Max(0, src.Length - 200);
|
||||
for (int i = start; i < src.Length; i++)
|
||||
{
|
||||
Assert.Equal(batchSeries[i].Value, streamValues[i], 9);
|
||||
Assert.Equal(batchSeries[i].Value, spanOutput[i], 9);
|
||||
}
|
||||
|
||||
_output.WriteLine("BBB validation: streaming, batch, and span outputs agree.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Skender_PercentB()
|
||||
{
|
||||
int[] periods = { 5, 10, 20, 50, 100 };
|
||||
double multiplier = 2.0;
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// QuanTAlib
|
||||
var bbb = new Bbb(period, multiplier);
|
||||
var qResult = bbb.Update(_testData.Data);
|
||||
|
||||
// Skender Bollinger Bands PercentB
|
||||
var sResult = _testData.SkenderQuotes.GetBollingerBands(period, multiplier).ToList();
|
||||
|
||||
ValidationHelper.VerifyData(qResult, sResult, s => s.PercentB);
|
||||
}
|
||||
|
||||
_output.WriteLine("BBB validated successfully against Skender PercentB.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// BBB: Bollinger %B
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Bollinger %B measures where price sits within Bollinger Bands:
|
||||
/// <c>%B = (Price - Lower) / (Upper - Lower)</c>
|
||||
/// </para>
|
||||
///
|
||||
/// This implementation uses O(1) rolling sums for mean and variance.
|
||||
///
|
||||
/// Formula:
|
||||
/// <c>Basis = SMA(source, period)</c>
|
||||
/// <c>StdDev = sqrt(E[x^2] - E[x]^2)</c>
|
||||
/// <c>Upper = Basis + multiplier * StdDev</c>
|
||||
/// <c>Lower = Basis - multiplier * StdDev</c>
|
||||
/// <c>BBB = (source - Lower) / (Upper - Lower)</c>
|
||||
///
|
||||
/// When band width is zero, returns 0.5 (neutral).
|
||||
///
|
||||
/// References:
|
||||
/// - John Bollinger, "Bollinger on Bollinger Bands"
|
||||
/// - PineScript reference: bbb.pine
|
||||
/// </remarks>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Bbb : AbstractBase
|
||||
{
|
||||
private readonly int _period;
|
||||
private readonly double _multiplier;
|
||||
private readonly RingBuffer _buffer;
|
||||
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
private record struct State(
|
||||
double Sum,
|
||||
double SumSq,
|
||||
double LastValid);
|
||||
private State _state;
|
||||
private State _p_state;
|
||||
|
||||
private const int ResyncInterval = 1000;
|
||||
private int _tickCount;
|
||||
|
||||
/// <summary>
|
||||
/// Creates BBB with specified period and multiplier.
|
||||
/// </summary>
|
||||
/// <param name="period">Lookback period (must be > 0)</param>
|
||||
/// <param name="multiplier">Standard deviation multiplier (must be > 0)</param>
|
||||
public Bbb(int period = 20, double multiplier = 2.0)
|
||||
{
|
||||
if (period <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(period));
|
||||
}
|
||||
|
||||
if (multiplier <= 0)
|
||||
{
|
||||
throw new ArgumentException("Multiplier must be greater than 0", nameof(multiplier));
|
||||
}
|
||||
|
||||
_period = period;
|
||||
_multiplier = multiplier;
|
||||
_buffer = new RingBuffer(period);
|
||||
Name = $"Bbb({period},{multiplier:F1})";
|
||||
WarmupPeriod = period;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates BBB with specified source, period, and multiplier.
|
||||
/// </summary>
|
||||
public Bbb(ITValuePublisher source, int period = 20, double multiplier = 2.0) : this(period, multiplier)
|
||||
{
|
||||
source.Pub += Handle;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
|
||||
|
||||
/// <summary>
|
||||
/// True if the indicator has enough data for valid results.
|
||||
/// </summary>
|
||||
public override bool IsHot => _buffer.IsFull;
|
||||
|
||||
/// <summary>
|
||||
/// Period of the indicator.
|
||||
/// </summary>
|
||||
public int Period => _period;
|
||||
|
||||
/// <summary>
|
||||
/// Standard deviation multiplier.
|
||||
/// </summary>
|
||||
public double Multiplier => _multiplier;
|
||||
|
||||
/// <inheritdoc/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public override TValue Update(TValue input, bool isNew = true)
|
||||
{
|
||||
double value = input.Value;
|
||||
|
||||
// Sanitize input
|
||||
if (!double.IsFinite(value))
|
||||
{
|
||||
value = double.IsFinite(_state.LastValid) ? _state.LastValid : 0.0;
|
||||
}
|
||||
else
|
||||
{
|
||||
_state.LastValid = value;
|
||||
}
|
||||
|
||||
if (isNew)
|
||||
{
|
||||
_p_state = _state;
|
||||
|
||||
// Remove oldest value contribution if buffer full
|
||||
if (_buffer.Count == _buffer.Capacity)
|
||||
{
|
||||
double oldest = _buffer.Oldest;
|
||||
_state.Sum -= oldest;
|
||||
_state.SumSq -= oldest * oldest;
|
||||
}
|
||||
|
||||
// Add new value
|
||||
_state.Sum += value;
|
||||
_state.SumSq += value * value;
|
||||
_buffer.Add(value);
|
||||
|
||||
_tickCount++;
|
||||
if (_buffer.IsFull && _tickCount >= ResyncInterval)
|
||||
{
|
||||
_tickCount = 0;
|
||||
RecalculateSums();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_state = _p_state;
|
||||
|
||||
// Update the newest value in buffer
|
||||
_buffer.UpdateNewest(value);
|
||||
RecalculateSums();
|
||||
}
|
||||
|
||||
int count = _buffer.Count;
|
||||
if (count == 0)
|
||||
{
|
||||
Last = new TValue(input.Time, 0.5);
|
||||
PubEvent(Last, isNew);
|
||||
return Last;
|
||||
}
|
||||
|
||||
double mean = _state.Sum / count;
|
||||
double variance = Math.Max(0.0, (_state.SumSq / count) - (mean * mean));
|
||||
double stddev = Math.Sqrt(variance);
|
||||
double dev = _multiplier * stddev;
|
||||
|
||||
double upper = mean + dev;
|
||||
double lower = mean - dev;
|
||||
double width = upper - lower;
|
||||
|
||||
double bbb = width > 0.0 ? (value - lower) / width : 0.5;
|
||||
|
||||
Last = new TValue(input.Time, bbb);
|
||||
PubEvent(Last, isNew);
|
||||
return Last;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override TSeries Update(TSeries source)
|
||||
{
|
||||
Reset();
|
||||
int len = source.Count;
|
||||
var t = new List<long>(len);
|
||||
var v = new List<double>(len);
|
||||
CollectionsMarshal.SetCount(t, len);
|
||||
CollectionsMarshal.SetCount(v, len);
|
||||
|
||||
var tSpan = CollectionsMarshal.AsSpan(t);
|
||||
var vSpan = CollectionsMarshal.AsSpan(v);
|
||||
source.Times.CopyTo(tSpan);
|
||||
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
vSpan[i] = Update(new TValue(tSpan[i], source.Values[i]), isNew: true).Value;
|
||||
}
|
||||
|
||||
return new TSeries(t, v);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates BBB for entire series.
|
||||
/// </summary>
|
||||
public static TSeries Batch(TSeries source, int period = 20, double multiplier = 2.0)
|
||||
{
|
||||
int len = source.Count;
|
||||
var t = new List<long>(len);
|
||||
var v = new List<double>(len);
|
||||
CollectionsMarshal.SetCount(t, len);
|
||||
CollectionsMarshal.SetCount(v, len);
|
||||
|
||||
var tSpan = CollectionsMarshal.AsSpan(t);
|
||||
var vSpan = CollectionsMarshal.AsSpan(v);
|
||||
|
||||
Batch(source.Values, vSpan, period, multiplier);
|
||||
source.Times.CopyTo(tSpan);
|
||||
|
||||
return new TSeries(t, v);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Batch BBB calculation with O(1) rolling variance.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period = 20, double multiplier = 2.0)
|
||||
{
|
||||
if (source.Length != output.Length)
|
||||
{
|
||||
throw new ArgumentException("Source and output must have the same length", nameof(output));
|
||||
}
|
||||
|
||||
if (period <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(period));
|
||||
}
|
||||
|
||||
if (multiplier <= 0)
|
||||
{
|
||||
throw new ArgumentException("Multiplier must be greater than 0", nameof(multiplier));
|
||||
}
|
||||
|
||||
int len = source.Length;
|
||||
if (len == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
double sum = 0.0;
|
||||
double sumSq = 0.0;
|
||||
double lastValid = 0.0;
|
||||
double mult = multiplier;
|
||||
|
||||
var valueBuffer = new RingBuffer(period);
|
||||
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
double val = source[i];
|
||||
|
||||
if (!double.IsFinite(val))
|
||||
{
|
||||
val = lastValid;
|
||||
}
|
||||
else
|
||||
{
|
||||
lastValid = val;
|
||||
}
|
||||
|
||||
if (i >= period)
|
||||
{
|
||||
double oldest = valueBuffer.Oldest;
|
||||
sum -= oldest;
|
||||
sumSq -= oldest * oldest;
|
||||
}
|
||||
|
||||
sum += val;
|
||||
sumSq += val * val;
|
||||
valueBuffer.Add(val);
|
||||
|
||||
int count = Math.Min(i + 1, period);
|
||||
double mean = sum / count;
|
||||
double variance = Math.Max(0.0, (sumSq / count) - (mean * mean));
|
||||
double stddev = Math.Sqrt(variance);
|
||||
double dev = mult * stddev;
|
||||
|
||||
double upper = mean + dev;
|
||||
double lower = mean - dev;
|
||||
double width = upper - lower;
|
||||
|
||||
output[i] = width > 0.0 ? (val - lower) / width : 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates BBB and returns both results and the warm indicator.
|
||||
/// </summary>
|
||||
public static (TSeries Results, Bbb Indicator) Calculate(TSeries source, int period = 20, double multiplier = 2.0)
|
||||
{
|
||||
var indicator = new Bbb(period, multiplier);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void RecalculateSums()
|
||||
{
|
||||
_state.Sum = 0.0;
|
||||
_state.SumSq = 0.0;
|
||||
for (int i = 0; i < _buffer.Count; i++)
|
||||
{
|
||||
double v = _buffer[i];
|
||||
_state.Sum += v;
|
||||
_state.SumSq += v * v;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
|
||||
{
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
Update(new TValue(DateTime.UtcNow, source[i]), isNew: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Reset()
|
||||
{
|
||||
_buffer.Clear();
|
||||
_state = default;
|
||||
_p_state = default;
|
||||
_tickCount = 0;
|
||||
Last = default;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
# BBB: Bollinger %B
|
||||
|
||||
> "Price oscillates, but %B tells you where it lives inside the band."
|
||||
|
||||
Bollinger %B quantifies where the current price sits within Bollinger Bands. A value of `0` is at the lower band, `1` is at the upper band, and `0.5` is centered at the middle band. The value can overshoot outside `[0, 1]` when price pierces the bands.
|
||||
|
||||
## Calculation
|
||||
|
||||
1. Compute the SMA and standard deviation over the lookback period.
|
||||
2. Construct upper/lower bands using the standard deviation multiplier.
|
||||
3. Normalize the price position within the bands.
|
||||
|
||||
Formula:
|
||||
|
||||
```
|
||||
Basis = SMA(source, period)
|
||||
StdDev = sqrt(E[x^2] - E[x]^2)
|
||||
Upper = Basis + multiplier * StdDev
|
||||
Lower = Basis - multiplier * StdDev
|
||||
BBB = (Price - Lower) / (Upper - Lower)
|
||||
```
|
||||
|
||||
If the band width is zero, BBB returns `0.5` (neutral).
|
||||
|
||||
## Interpretation
|
||||
|
||||
- `BBB = 1.0` → price at upper band (overbought risk)
|
||||
- `BBB = 0.0` → price at lower band (oversold risk)
|
||||
- `BBB > 1.0` → price above upper band (breakout)
|
||||
- `BBB < 0.0` → price below lower band (breakdown)
|
||||
|
||||
## Parameters
|
||||
|
||||
| Name | Type | Default | Range | Description |
|
||||
| :--- | :--- | :------ | :---- | :---------- |
|
||||
| `period` | `int` | `20` | `>0` | Lookback period for SMA and StdDev. |
|
||||
| `multiplier` | `double` | `2.0` | `>0` | Standard deviation multiplier for band width. |
|
||||
|
||||
## API
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
class Bbb {
|
||||
+Name : string
|
||||
+WarmupPeriod : int
|
||||
+IsHot : bool
|
||||
+Update(TValue input, bool isNew) TValue
|
||||
+Update(TSeries source) TSeries
|
||||
+Prime(ReadOnlySpan~double~ source, TimeSpan? step) void
|
||||
+Reset() void
|
||||
+Batch(TSeries source, int period, double multiplier) TSeries
|
||||
+Batch(ReadOnlySpan~double~ source, Span~double~ output, int period, double multiplier) void
|
||||
+Calculate(TSeries source, int period, double multiplier) (TSeries Results, Bbb Indicator)
|
||||
}
|
||||
```
|
||||
|
||||
## Usage Example
|
||||
|
||||
```csharp
|
||||
using QuanTAlib;
|
||||
|
||||
// Initialize
|
||||
var bbb = new Bbb(period: 20, multiplier: 2.0);
|
||||
|
||||
foreach (var bar in bars)
|
||||
{
|
||||
var value = bbb.Update(bar.Close);
|
||||
|
||||
if (bbb.IsHot)
|
||||
{
|
||||
Console.WriteLine($"{bar.Time}: %B={value.Value:F3}");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Performance Profile
|
||||
|
||||
| Metric | Score | Notes |
|
||||
| :--- | :--- | :--- |
|
||||
| **Throughput** | 9 | O(1) rolling sums and variance. |
|
||||
| **Allocations** | 0 | Zero allocations in hot path. |
|
||||
| **Complexity** | O(1) | Constant time per update. |
|
||||
| **Accuracy** | 10 | Matches Pine reference and standard formula. |
|
||||
| **Timeliness** | 7 | Period-length lag similar to SMA. |
|
||||
| **Overshoot** | 8 | Can exceed [0, 1] on strong moves. |
|
||||
| **Smoothness** | 6 | Moderate smoothing via SMA and StdDev. |
|
||||
|
||||
## Validation
|
||||
|
||||
No direct TA-Lib/Tulip/Skender equivalent exists for Bollinger %B. Validation is performed against the PineScript reference and internal consistency checks (batch vs streaming vs span).
|
||||
|
||||
## Sources
|
||||
|
||||
- John Bollinger, *Bollinger on Bollinger Bands*
|
||||
- [PineScript reference](bbb.pine)
|
||||
@@ -3,13 +3,6 @@
|
||||
//@version=6
|
||||
indicator("Bollinger %B", "BBB", overlay=false)
|
||||
|
||||
//@function Calculates Bollinger Bands components for %B calculation
|
||||
//@doc https://github.com/mihakralj/pinescript/blob/main/indicators/oscillators/bbb.md
|
||||
//@param source Series to calculate from
|
||||
//@param period Lookback period for SMA and standard deviation
|
||||
//@param multiplier Standard deviation multiplier for band width
|
||||
//@returns Bollinger %B value (typically 0-1 range; can overshoot)
|
||||
//@optimized Uses circular buffer with running sums, O(1) complexity per bar
|
||||
bbb(series float source, simple int period, simple float multiplier) =>
|
||||
if period <= 0 or multiplier <= 0.0
|
||||
runtime.error("Period and multiplier must be greater than 0")
|
||||
@@ -66,8 +59,6 @@ bbb(series float source, simple int period, simple float multiplier) =>
|
||||
|
||||
result
|
||||
|
||||
// ---------- Main loop ----------
|
||||
|
||||
// Inputs
|
||||
i_period = input.int(20, "Period", minval=1)
|
||||
i_source = input.source(close, "Source")
|
||||
|
||||
Reference in New Issue
Block a user