Skip to content

Slope and linear regression

Slope of the best fit line is determined by an ordinary least-squares simple linear regression on price. It can be used to help identify trend strength and direction. [Discuss] 💬

csharp
// C# usage syntax
IReadOnlyList<SlopeResult> results =
  bars.ToSlope(lookbackPeriods);

Parameters

paramtypedescription
lookbackPeriodsintNumber of periods (N) for the linear regression. Must be greater than 1.

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<SlopeResult>
  • 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 for Slope since there's not enough data to calculate.
  • Line values are only provided for the last N periods of your bar history

️🖌️ Repaint warning

The Line is continuously repainted since it is based on the last bar and lookback period.

SlopeResult

propertytypedescription
TimestampDateTimeDate from evaluated TBar
SlopedoubleSlope 𝑚 of the best-fit line of price
InterceptdoubleY-intercept 𝑏 of the best-fit line
StdDevdoubleStandard deviation of price over N lookback periods
RSquareddoubleR-squared (R²), aka Coefficient of determination
LinedecimalBest-fit line 𝑦 over the last N periods (i.e. 𝑦=𝑚𝑥+𝑏 using last period values)

Utilities

See Utilities and helpers for more information.

Chaining

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

csharp
// example
var results = bars
    .ToEma(..)
    .ToSlope(..);

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

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

See Chaining indicators for more.

Streaming

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

csharp
SlopeList slopeList = new(lookbackPeriods);

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

// based on `ICollection<SlopeResult>`
IReadOnlyList<SlopeResult> results = slopeList;

Subscribe to a BarHub for advanced streaming scenarios:

csharp
BarHub barHub = new();
SlopeHub observer = barHub.ToSlopeHub(lookbackPeriods);

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

IReadOnlyList<SlopeResult> results = observer.Results;

️🖌️ Repaint warning

The streaming implementation exhibits the same repaint behavior as the series version. Line values are recalculated for the last N periods as new data arrives, matching the series implementation's behavior.

See Buffer lists and Stream hubs for full usage guides.