Skip to content

Simple Moving Average (SMA)

Simple Moving Average is the average price over a lookback window. An extended SMA analysis option includes mean absolute deviation (MAD), mean square error (MSE), and mean absolute percentage error (MAPE). [Discuss] 💬

csharp
// C# usage syntax (with Close price)
IReadOnlyList<SmaResult> results =
  bars.ToSma(lookbackPeriods);

Parameters

paramtypedescription
lookbackPeriodsintNumber of periods (N) in the lookback window. Must be greater than 0.

Historical price bars requirements

You must have at least N periods of bars to cover the warmup periods.

bars is a collection of generic TBar historical price bars. It should have a consistent frequency (day, hour, minute, etc). See the Guide for more information.

Response

csharp
IReadOnlyList<SmaResult>
  • This method returns a time series of all available indicator values for the bars provided.
  • It always returns the same number of elements as there are in the historical price bars.
  • It does not return a single incremental indicator value.
  • The first N-1 periods will have null values since there's not enough data to calculate.

SmaResult

propertytypedescription
TimestampDateTimeDate from evaluated TBar
SmadoubleSimple moving average

Utilities

See Utilities and helpers for more information.

Analysis

This indicator has an extended version with more analysis. See SMA with extended analysis for the full documentation including streaming support.

csharp
// C# usage syntax
IReadOnlyList<SmaAnalysisResult> analysis =
  bars.ToSmaAnalysis(lookbackPeriods);

SmaAnalysisResult

propertytypedescription
TimestampDateTimeDate from evaluated TBar
SmadoubleSimple moving average
MaddoubleMean absolute deviation
MsedoubleMean square error
MapedoubleMean absolute percentage error

Chaining

This indicator may be generated from any chain-enabled indicator or method.

csharp
// example
var results = bars
    .Use(CandlePart.Volume)
    .ToSma(..);

Results can be further processed on Sma with additional chain-enabled indicators.

csharp
// example
var results = bars
    .ToSma(..)
    .ToRsi(..);

See Chaining indicators for more.

Streaming

Use the buffer-style List<T> when you need incremental calculations without a hub:

csharp
SmaList smaList = new(lookbackPeriods);

foreach (IBar bar in bars)  // simulating stream
{
  smaList.Add(bar);
}

// based on `ICollection<SmaResult>`
IReadOnlyList<SmaResult> results = smaList;

Subscribe to a BarHub for advanced streaming scenarios:

csharp
BarHub barHub = new();
SmaHub observer = barHub.ToSmaHub(lookbackPeriods);

foreach (IBar bar in bars)  // simulating stream
{
  barHub.Add(bar);
}

IReadOnlyList<SmaResult> results = observer.Results;

See Buffer lists and Stream hubs for full usage guides.