Files

51 lines
2.0 KiB
Plaintext

// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Weighted Root Mean Squared Error", "WRMSE", overlay=false)
//@function Calculates Weighted Root Mean Squared Error
//@param actual Series of actual values
//@param predicted Series of predicted/forecast values
//@param weight Series of weights for each observation
//@param length Rolling window for calculation
//@returns WRMSE value in same units as original data
wrmse(series float actual, series float predicted, series float weight, simple int length) =>
float epsilon = 1e-10
// Compute weighted squared error for current bar
float diff = nz(actual, 0.0) - nz(predicted, 0.0)
float w = math.max(nz(weight, 1.0), 0.0) // Ensure non-negative weight
float weightedSqError = w * diff * diff
// Rolling sums
float sumWeightedError = ta.sum(weightedSqError, length)
float sumWeight = ta.sum(w, length)
// WRMSE = √(Σ(w*e²) / Σ(w))
float result = sumWeight > epsilon ? math.sqrt(sumWeightedError / sumWeight) : 0.0
result
//@function Calculates WRMSE with uniform weights (equivalent to RMSE)
//@param actual Series of actual values
//@param predicted Series of predicted/forecast values
//@param length Rolling window for calculation
//@returns WRMSE value (same as RMSE when weights are uniform)
wrmse_uniform(series float actual, series float predicted, simple int length) =>
wrmse(actual, predicted, 1.0, length)
// ---------- Main loop ----------
// Inputs
i_length = input.int(14, "Length", minval=1)
i_use_volume_weights = input.bool(false, "Use Volume as Weights", tooltip="When enabled, errors are weighted by volume")
i_actual = input.source(close, "Actual")
i_predicted = input.source(open, "Predicted")
// Calculation
weight = i_use_volume_weights ? volume : 1.0
wrmse_value = wrmse(i_actual, i_predicted, weight, i_length)
// Plot
plot(wrmse_value, "WRMSE", color=color.yellow, linewidth=2)
hline(0, "Perfect", color=color.green, linestyle=hline.style_dotted)