Rolling CAGR
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jamiedubauskas

//@version=5
indicator(title = "Rolling CAGR", shorttitle = "Rolling CAGR", overlay = false, format = format.percent)

// input for the selected source
src = input.source(title = "Data Source", defval = close, tooltip = "Selected data source to find the rolling CAGR on")
varip first_value = barstate.isfirst ? src[0] : src

// input for the number of trading days in a year for the specified ticker
trading_days_in_a_year = input.int(title = "Trading Days in a Year", defval = 365, minval = 0, tooltip = "Use to input how many trading days are in a year for the specified ticker that this indicator is on. Use 365 for crypto & use 252 for stocks")

// finding the number of bars (a.k.a "N" in the CAGR formula)
n = ta.cum(src == src ? 1 : 0) - 1

// finding the number of bars equal a year
n_years = n / trading_days_in_a_year

// finding the start value and end value
startValue = first_value
endValue = src[0]

// calculating the CAGR
CAGR_(v1, v2) => (math.pow((v1 / v2), (1 / n_years)) - 1) * 100
cagr = timeframe.isdaily ? CAGR_(endValue, startValue) : na

plot(cagr)
