mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-07-28 01:37:43 +00:00
45 lines
1.6 KiB
Plaintext
45 lines
1.6 KiB
Plaintext
// Licensed under the Apache License, Version 2.0
|
|
// © mihakralj
|
|
//@version=6
|
|
indicator("Root Mean Squared Error (RMSE)", "RMSE")
|
|
|
|
//@function Calculates Root Mean Squared Error between two sources using SMA for averaging
|
|
//@param source1 First series to compare
|
|
//@param source2 Second series to compare
|
|
//@param period Lookback period for error averaging
|
|
//@returns RMSE value averaged over the specified period using SMA
|
|
rmse(series float source1, series float source2, simple int period) =>
|
|
squared_error = math.pow(source1 - source2, 2)
|
|
if period <= 0
|
|
runtime.error("Period must be greater than 0")
|
|
int p = math.min(math.max(1, period), 4000)
|
|
var float[] buffer = array.new_float(p, na)
|
|
var int head = 0
|
|
var float sum = 0.0
|
|
var int valid_count = 0
|
|
float oldest = array.get(buffer, head)
|
|
if not na(oldest)
|
|
sum := sum - oldest
|
|
valid_count := valid_count - 1
|
|
if not na(squared_error)
|
|
sum := sum + squared_error
|
|
valid_count := valid_count + 1
|
|
array.set(buffer, head, squared_error)
|
|
head := (head + 1) % p
|
|
float mse = valid_count > 0 ? sum / valid_count : squared_error
|
|
math.sqrt(mse)
|
|
|
|
// ---------- Main loop ----------
|
|
|
|
// Inputs
|
|
i_source1 = input.source(close, "Source")
|
|
i_period = input.int(100, "Period", minval=1)
|
|
i_source2 = ta.ema(i_source1, i_period)
|
|
|
|
// Calculation
|
|
error = rmse(i_source1, i_source2, i_period)
|
|
|
|
// Plot
|
|
plot(error, "RMSE", color=color.new(color.red, 60), linewidth=2, style = plot.style_area)
|
|
plot(i_source2, "EMA", color=color.yellow, linewidth=1, style = plot.style_line, force_overlay = true)
|