// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tim_amblard

//@version=6
indicator("Sharpe Ratio Indicator (180)", shorttitle="Sharpe Ratio (180)", overlay=false)

// Input parameters
riskFreeRate = input.float(defval=0.04, title="Risk-Free Rate (annualized, in decimal)", minval=0.0)
lookback180 = input.int(defval=180, title="Lookback Period (180 Days)", minval=1)
OverValued = input.float(5.0)
UnderValued = input.float(-1.0)
CriticallyUnderValued = input.float(-3.0)

// Daily Return
dailyReturn = (close - close[1]) / close[1]

// Mean and Standard Deviation for Sharpe Ratio (180 days)
mean180 = ta.sma(dailyReturn, lookback180)
stdDev180 = ta.stdev(dailyReturn, lookback180) * math.sqrt(lookback180)
sharpe180 = (mean180 * 365 - riskFreeRate) / stdDev180

// Define valuation zones
isOverValued = sharpe180 > OverValued
isUnderValued = sharpe180 < UnderValued and sharpe180 > CriticallyUnderValued
isCriticallyUnderValued = sharpe180 < CriticallyUnderValued
isNeutral = not isOverValued and not isUnderValued and not isCriticallyUnderValued

// Assign plot colors based on valuation state
sharpeColor = isOverValued ? color.red : isUnderValued ? color.green : isCriticallyUnderValued ? color.blue : color.yellow

// Plot the Sharpe Ratio (180 days)
plot(sharpe180, color=sharpeColor, title="Sharpe Ratio (180)", linewidth=2)

// Highlighting Sharpe Zones
hline(OverValued, "Overvalued Zone", color=color.red, linestyle=hline.style_dashed)
hline(UnderValued, "Undervalued Zone", color=color.green, linestyle=hline.style_dashed)
hline(CriticallyUnderValued, "Critically Undervalued Zone", color.blue, hline.style_dashed)
hline(0, "Neutral Zone", color=color.gray, linestyle=hline.style_dotted)
