Z-Score Weighted Moving Averages
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © federalTacos5392b

//@version=5
indicator("Z-Score Weighted Moving Averages", overlay = true)

// Input parameters
lookback_period = input(14, title = "Lookback Period")
smoothing_period = input(14, title = "Smoothing Period")
src = input(close, title = "Source")

// Choose which plot to display
plot_wma_smoothed = input(true, title = "Display Smoothed WMA")
plot_wma_dynamic = input(true, title = "Display Dynamic WMA")

// Calulate Mean absolute devaition around median

median = ta.median(src, lookback_period)
deviation = math.abs(src - median)
MAD = ta.sma(deviation, lookback_period)

// Calculate z-scores

z_scores = (src - ta.sma(src, lookback_period)) / (MAD*1.2533)

// Calculate weights based on absolute value of inverse of z-scores
weights = 1 / (1 + math.abs(z_scores))

// Calculate z_score weighted moving average
wma_sum = 0.0
sum_weights = 0.0
for i = 0 to smoothing_period - 1
    wma_sum := wma_sum + src[i] * weights[i]
    sum_weights := sum_weights + weights[i]
wma_smoothed = wma_sum / sum_weights

// Calculate weights based on absolute value of z-scores
weight_dynamic = math.abs(z_scores)

// Calculate weighted moving average
wma_sum1 = 0.0
sum_weights1 = 0.0
for i = 0 to smoothing_period - 1
    wma_sum1 := wma_sum1 + src[i] * weight_dynamic[i]
    sum_weights1 := sum_weights1 + weight_dynamic[i]
wma_dynamic = wma_sum1 / sum_weights1

// Determine trend direction of smoothed WMA and dynamic WMA
var float prev_wma_smoothed = na
var float prev_wma_dynamic = na

wma_smoothed_trend = 0
if not na(prev_wma_smoothed)
    wma_smoothed_trend := wma_smoothed > prev_wma_smoothed ? 1 : wma_smoothed < prev_wma_smoothed ? -1 : 0

wma_dynamic_trend = 0
if not na(prev_wma_dynamic)
    wma_dynamic_trend := wma_dynamic > prev_wma_dynamic ? 1 : wma_dynamic < prev_wma_dynamic ? -1 : 0

prev_wma_smoothed := wma_smoothed
prev_wma_dynamic := wma_dynamic

// Plot the chosen plots with customized colors
plot(plot_wma_smoothed ? wma_smoothed : na, color = wma_smoothed_trend > 0 ? color.green : color.red, title = "Smoothed Weighted Moving Average")
plot(plot_wma_dynamic ? wma_dynamic : na, color = wma_dynamic_trend > 0 ? color.blue : color.orange, title = "Dynamic Weighted Moving Average")
