MAD - Mean Absolute Deviation 
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator("Mean Absolute Deviation", shorttitle="MAD", overlay=true)
// author : patmaba
// purpose :implementation of MAD Mean Absolute Deviation in pinescript

// Mean absolute deviation
// The mean absolute deviation of a dataset is the average distance between each data point and the mean. It gives us an idea about the variability in a dataset.
// Here's how to calculate the median absolute deviation.
// Step 1: Calculate the mean.
// Step 2: Calculate how far away each data point is from the mean using positive distances. These are called absolute deviations.
// Step 3: Add those deviations together.
// Step 4: Divide the sum by the number of data points.
//
// Source :
// https://www.khanacademy.org/math/statistics-probability/summarizing-quantitative-data/other-measures-of-spread/a/mean-absolute-deviation-mad-review
//
// Formula :
//
//        ∑ |xi−µ| 
// MAD = ----------
//           n
//
// where 
//          xi = the value of a data point
//    |xi − µ| = absolute deviation
//           ​µ = mean
//           n = sample size

// inputs 
x = input.source(title="source", defval=close)
p = input.int(title="period", defval=50, minval=1, maxval=520)
// Constant scale factor dependent on the distribution. Default is 1.4826 expecting the data is normally distributed.
float k = 1.4826
mult = input.float(title="multiply factor k", defval=k, minval=0.01, maxval=12.0)


// Function to find mean absolute
// deviation of given elements.
mad(p_x, p_mean_value) =>  
    float _absSum = 0.0
    
    // Step 2: Calculate how far away each data point is from the mean using positive distances. These are called absolute deviations.    
    for _i = 0 to p
        _absSum := _absSum + math.abs(p_x[_i] - p_mean_value)
    
    // Step 4: Divide the sum by the number of data points.
    _mad_value = (_absSum/p)

    // Return mean absolute deviation about mean.                
    _mad_value
// end mad -------------------------------------


// Step 1: Calculate the mean.
med = ta.sma(x,p)

// Get the mad value
mad_value = mad(close, med)

// Step 3: Add those deviations together.
mad_boundaries = mad_value*mult

// add boundaries
mad_hb = med+(mad_boundaries)
mad_lb = med-(mad_boundaries)

// apply a color information
// gray is trending
// orange warning be carreful place stop
// red bear market

var indicator_color=color.gray
if (mad_lb > close) and ( high < med )
    indicator_color:=color.purple
else if (hl2 < med )
    indicator_color:=color.orange
else     
    indicator_color:=color.gray

// Draw all
plot(mad_hb, title="mad high bound", color=indicator_color)
plot(med, title="mean", color=indicator_color)
plot(mad_lb, title="mad low bound", color=indicator_color)

