Relative Standard 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
// Author = TradeAutomation


indicator("Relative Standard Deviation", shorttitle="Relative Standard Deviation")


// Calculation Inputs //
MALength = input.int(200, "MA Length", tooltip="This is the length of the moving average that you are measuring Standard Deviation against.")
DeviationLength = input.int(200, title="Deviation Lookback Length", tooltip="This is the amount of bars back that you using to measure Standard Deviation against the mean.")
Source = input.source(title="Source", defval=close)

// Population Standard Deviation Calcualtion //
Mean = ta.sma(Source, MALength)
StdDev = math.sqrt(ta.sma(math.pow(Source-Mean, 2), DeviationLength))

// Relative Calculation //
RelativeStdDev = (StdDev/Source)*100

// Visualization Features //
PlotRelStdDevInput = input.bool(true, "Plot Relative Standard Deviation?", tooltip="Blue - This is the Standard Deviation converted to a percentage that is relative to the current instrument's price, as a whole number. I.e. 11 = 11%")
PlotStdDevInput = input.bool(false, "Plot Population Standard Deviation?", tooltip="Purple - This is the traditional calculation for Population Standard Deviation.")
PlotHLineInput = input.bool(false, "Plot Custom Fixed Line?", tooltip="Gray - This is just a feature to make indicators easier to read (I.e. If you want to be able to easily tell if a value is over/under a custom value).")
HLine = input.float(5, "Custom Fixed Line Value")
RelStdDevPlot = PlotRelStdDevInput == true ? RelativeStdDev : na
StdDevPlot = PlotStdDevInput == true ? StdDev : na
HlinePlot = PlotHLineInput == true ? HLine : na
plot(RelStdDevPlot, color=color.blue)
plot(StdDevPlot, color=color.purple)
hline(HlinePlot, color=color.gray)
