Indicator · Pine Script v4 · On the chart

Time Series Decomposition and Forecasting

by capissimo

Time Series Decomposition and Forecasting is an experimental overlay indicator that decomposes historical price action into trend, centered moving average, and seasonality components using array calculations.

View on GitHub

GitHub stars114on the repository
Pine versionv4older, still runs
Lines of code139
Settings3inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago7 Nov 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

139 lines of Pine Script v4 from banned-scripts/Time-Series-Decomposition.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Time-Series-Decomposition.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © capissimo

//@version=4
study("Time Series Decomposition and Forecasting", overlay=true)
// for details see https://www.datavedas.com/smoothing-techniques-and-time-series-decomposition/

// EXPERIMENTAL

// General functions
print(data, txt) => 
    var lbl = label.new(bar_index, data, txt, xloc.bar_index, yloc.price, color.new(color.white,100), label.style_label_left, color.new(color.black,0), size.normal, text.align_left)
    label.set_xy(lbl, bar_index, data), label.set_text(lbl, txt)

// Stat module functions
mean(v) => array.avg(v)

std(v)  => array.stdev(v)

corr(v, w) => 
    std_v = std(v), std_w = std(w)
    std_v > 0 and std_w > 0 ? array.covariance(v, w) / std_v / std_w : 0 

best_fit(v, w) => // alpha = slope, beta = intercept
    beta  = corr(v, w) * std(w) / std(v)
    alpha = mean(w) - beta * mean(v)
    [alpha, beta]

getInts(sze) =>                 // vector with integer ids
    vec = array.new_int(sze, 0)
    for i=0 to sze-1
        array.set(vec, i, i)
    vec

getFloats(sze, floats) =>       // vector with floats
    vec = array.new_float(sze)
    for i=sze-1 to 0
        array.set(vec, i, nz(floats[i]))
    vec

calcComponents(v, n) => // n = season
    sze = array.size(v)
    ma = array.new_float(sze, 0)     // moving average (ma)
    for i=0 to sze-n
        slc = array.slice(v, i, i+n)
        array.set(ma, i, array.avg(slc))
    array.unshift(ma, 0)
    array.unshift(ma, 0)
    array.pop(ma)
    array.pop(ma)
    
    cma = array.new_float(sze, 0)    // centered ma
    si  = array.new_float(sze, 0)    // seasonality/irregularity 
    idx  = array.new_float(n, 0)     // seasonality index and 
    des  = array.new_float(sze, 0)   // deseasoned sample
    for i=2 to sze-3
        array.set(cma, i, (array.get(ma, i) + array.get(ma, i+1)) / 2)
        array.set(si,  i, array.get(v, i) / array.get(cma, i))
        array.set(idx, i%n, array.get(idx, i%n) + array.get(si, i))
    for i=0 to n-1
        array.set(idx,  i, array.get(idx, i) / 3)
    for i=0 to sze-1
        array.set(des,  i, array.get(v, i) /  array.get(idx, i%n))
    
    
    [ma, cma, si, idx, des]

trend(ints, al, bt) =>
    sze = array.size(ints)
    trd = array.new_float(sze, 0)
    for i=0 to sze-1
        array.set(trd, i, array.get(ints, i) * bt + al)
    trd
    
forecast(trd, idx) =>
    sze = array.size(trd)
    n   = array.size(idx)
    fct = array.new_float(sze, 0)
    for i=0 to sze-1
        array.set(fct, i, array.get(trd, i) * array.get(idx, i%n))
    fct

get_sample() =>  // sample of data from the above paper
    samp = array.new_float(0)
    array.push(samp,50),  array.push(samp,61), array.push(samp,73),  array.push(samp,84),  array.push(samp,59)
    array.push(samp,72),  array.push(samp,89), array.push(samp,100), array.push(samp,72),  array.push(samp,93)
    array.push(samp,110), array.push(samp,126), array.push(samp,80), array.push(samp,100), array.push(samp,123), array.push(samp,140)
    samp

// Inputs
lkb = input(16, 'Number of data points', options=[8,12,16,20,24,28,32,36,40,44,48]) 
n   = input(4,  'Season length', minval=4, maxval=4)  
dbg = input(true)

// Calculations
//samp = get_sample()          // get ficticious data sample
samp = getFloats(lkb, close)   // get real data sample

[ma, cma, si, idx, des] = calcComponents(samp, n)  // calculate ma, centered ma, seasonality/irregularity, seasonality index and deseasoned sample

// get variable ‘t’ which will be nothing but a time code in the form of concecutive indexes
t = getInts(lkb)             // get indexes of data items

[al, bt] = best_fit(t, des)  // next take regression of sample, getting its alpha & beta 

t2 = getInts(lkb+n)          // extend lookback window of 16 by a period of 4

trd = trend(t2, al, bt)      // extract trend

// forecast for the upcoming 4-part season. We do this by using the seasonality and trend component and by multiplying them.
fct = forecast(trd, idx)     // finally forecast including for the next period of 4

sz1 = array.size(ma), sz2 = array.size(cma), sz3 = array.size(si)  // array sizes for debugging purposes
sz4 = array.size(idx)
sz5 = array.size(des), sz6 = array.size(trd), sz7 = array.size(fct)

// Rendering
// find which bar is hours away from the current time
milliseconds_in_nhours = 1000 * 60 * 60 * n  // millisecs * secs * min * hours

var line ln = line.new(x1=time, y1=0, x2=time, y2=0, xloc=xloc.bar_time, color=color.new(color.blue,0), width=4)
// for i=sz2-2 to 1
//     line.set_xloc(ln, time[i-1],  time[i], xloc.bar_time)
//     line.set_y1(ln, array.get(cma, i-1))
//     line.set_y2(ln, array.get(cma, i))

if barstate.islast and dbg
    print(ohlc4, 'MA/4           ' + tostring(sz1) + ':' +tostring(ma)  +'\n'+
                 'Centered MA/4  ' + tostring(sz2) + ':' +tostring(cma) +'\n'+
                 'Seas & Irreg   ' + tostring(sz3) + ':' +tostring(si)  +'\n'+
                 'Seas Idx       ' + tostring(sz4) + ':' +tostring(idx) +'\n'+ 
                 'Deseas         ' + tostring(sz5) + ':' +tostring(des) +'\n'+
                 'Regression a/b ' + tostring(al)  +'--' +tostring(bt)  +'\n'+
                 'Trend          ' + tostring(sz6) + ':' +tostring(trd) +'\n'+
                 'Forecast       ' + tostring(sz7) + ':' +tostring(fct))
             
if barstate.islast 
    ln := line.new(x1=time[lkb], y1=array.get(fct, lkb-1), x2=time+milliseconds_in_nhours, y2=array.get(fct, 0), xloc=xloc.bar_time, color=color.new(color.black,0), width=3)
    line.delete(ln[1])

Overview

Time Series Decomposition and Forecasting calculates multiplicative seasonal indexes and fits a linear regression trend line over a specified lookback window to generate a forecast. Key inputs allow users to adjust the lookback window size and season length. The script outputs forecasting labels and decomposed values directly on the price chart. It functions purely as an analytical tool without automated trade entry or exit rules.

Details

Published by

capissimo on GitHub

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

Trend

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Number of data pointsint16lkb
Season lengthint4n
dbgbooltruedbg
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

948 stars

The Adaptive Laguerre Filter calculates a smoothed, dynamically adjusted trendline plotted directly on the main price chart. It dynamically adjusts its damping factor (alpha) based on recent price range variations and median percentile calculations over a spec

Indicator v4 TrendMoving averages
Updated 10 days ago · GPL-3.0 GitHub repository of Adaptive Laguerre Filter
575 stars

This indicator detects equal highs and lows by comparing prices within user-defined left and right bars using a tolerance percentage. It plots horizontal lines on the price chart for equal highs in one color and lows in another. A screener allows input of mult

Indicator v5 Support & resistanceTrend
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows with Screener
330 stars

This script plots three moving averages on the price chart: a fast EMA or SMA with 10 periods, a slow EMA or SMA with 20 periods, and a trend EMA or SMA with 100 periods. It signals trend changes by drawing a white cross when the fast moving average crosses ab

Indicator v4 TrendMoving averages
Updated 2 months ago · None stated GitHub repository of 3 EMA/SMA + Cross [Alorse]
318 stars

This indicator calculates an ATR trailing stop line derived from the highest high minus an average true range multiple over a specified lookback period. It plots the trailing stop line directly on the price chart and colors price bars based on whether the clos

Indicator v5 TrendVolatility & bands
Updated 2 months ago · MIT GitHub repository of ATR Trailing Stoploss

All Candlestick Patterns

by shunjizhan
292 stars

All Candlestick Patterns detects and highlights a wide range of bullish, bearish, and neutral candlestick patterns directly on the price chart. It features optional trend filtering using either a 50-period simple moving average or a combination of 50-period an

Indicator v4 Candlestick patternsTrend
Updated 3 years ago · None stated GitHub repository of All Candlestick Patterns

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers