Running ZScore

jarym
Posts: 58
Joined: 16 Feb 2015
Has thanked: 14 times
Been thanked: 6 times

Running ZScore

Postby jarym » 19 Jul 2019

Hi,

Thought I'd share this - I am using a running Score to normalise a few indicator outputs and its been very useful for pre-preparing my data for Machine Learning. Have also coded the P2 algorithm to efficiently provide running estimate of various quartiles. Sharing the code here.

Code: Select all

using System;

namespace PowerLanguage
{
namespace Function
{
public sealed class ZScore : FunctionSeries<double>
{
public ZScore(CStudyControl _master) : base(_master) { }
public ZScore(CStudyControl _master, int _ds) : base(_master, _ds) { }

private int k; // Num samples
private double M; // Mean average
private double S; // Sum of differences squared

public ISeries<double> Price;
public double stdDev;
public double variance;

protected override void Create()
{
}

protected override void StartCalc()
{
k = 0;
M = 0;
S = 0;
}

protected override double CalcBar()
{
if ( Bars.Status != EBarState.Close ) return this[0];

// Inspired from https://www.embeddedrelated.com/showarticle/785.php and
// https://dsp.stackexchange.com/questions/811/determining-the-mean-and-standard-deviation-in-real-time

double x = Price.Value;

k += 1;
double mNext = M + (x - M) / k;
S = S + (x - M) * (x - mNext);
M = mNext;

if (M == 0 || k < 2) return Price.Value;

variance = S / (k - 1);
stdDev = Math.Sqrt(variance);
// Z-score is (current value minus mean) divided by standard deviation
return (Price.Value - M) / stdDev;
}
}
}
}

Return to “User Contributed Studies”