Drawdown - Price vs Fundamentals
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed

//@version=4
study("Drawdown - Price vs Fundamentals")
i_reference = input("ath", title="Reference", options=["ath", "window"], group="Reference")
i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Start Time", type = input.time, group="Reference")
i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "End Time", type = input.time, group="Reference")
inDateRange = time >= i_startTime and time <= i_endTime
var ath = high
var drawdown = 0.0
f_getFinancials(financial_id, period) => financial(syminfo.tickerid, financial_id, period)
f_getOptimalFinancialBasic(financial_id) =>
    f_getFinancials(financial_id, syminfo.currency == "USD"? "FQ" : "FY")
    
f_get_ath_and_drawdown(ath, drawdown, value)=>
    _ath = ath
    _drawdown = drawdown
    _ath := na(ath) or value > _ath? value : _ath
    _drawdown := round((abs(_ath-value)/abs(_ath))*100)
    [_ath, _drawdown]

tso = financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")

bvps = financial(syminfo.tickerid, "BOOK_VALUE_PER_SHARE", "FQ")
eps = financial(syminfo.tickerid, "EARNINGS_PER_SHARE", "TTM")
feps = earnings(syminfo.tickerid, earnings.estimate, lookahead = barmerge.lookahead_on)
rps = financial(syminfo.tickerid, "TOTAL_REVENUE", "TTM")/tso
frps = f_getOptimalFinancialBasic("SALES_ESTIMATES")/tso

var bvpsAth = bvps
var epsAth = eps
var fepsAth = feps
var rpsAth = rps
var frpsAth = frps

var bvpsDrawdown = 0.0
var epsDrawdown = 0.0
var fepsDrawdown = 0.0
var rpsDrawdown = 0.0
var frpsDrawdown = 0.0

if(i_reference == "ath" or inDateRange)
    ath := high > ath? high : ath
    drawdown := round(((ath-high)/ath)*100)
    [_ath, _drawdown] = f_get_ath_and_drawdown(ath, drawdown, high)
    ath := _ath
    drawdown := _drawdown
    
    [_bvpsAth, _bvpsDrawdown] = f_get_ath_and_drawdown(bvpsAth, bvpsDrawdown, bvps)
    bvpsAth := _bvpsAth
    bvpsDrawdown := _bvpsDrawdown

    [_epsAth, _epsDrawdown] = f_get_ath_and_drawdown(epsAth, epsDrawdown, eps)
    epsAth := _epsAth
    epsDrawdown := _epsDrawdown

    [_fepsAth, _fepsDrawdown] = f_get_ath_and_drawdown(fepsAth, fepsDrawdown, feps)
    fepsAth := _fepsAth
    fepsDrawdown := _fepsDrawdown
    
    [_rpsAth, _rpsDrawdown] = f_get_ath_and_drawdown(rpsAth, rpsDrawdown, rps)
    rpsAth := _rpsAth
    rpsDrawdown := _rpsDrawdown

    [_frpsAth, _frpsDrawdown] = f_get_ath_and_drawdown(frpsAth, frpsDrawdown, frps)
    frpsAth := _frpsAth
    frpsDrawdown := _frpsDrawdown
    
plot(drawdown, color = color.green, title="Price")
plot(bvpsDrawdown, color=color.red, title="Book Value")
plot(epsDrawdown, color=color.orange, title="Earnings")
plot(fepsDrawdown, color=color.fuchsia, title="Earning Estimates")
plot(rpsDrawdown, color=color.teal, title="Revenue")
plot(frpsDrawdown, color=color.aqua, title="Revenue Estimates")