Search code examples
pine-scriptpine-script-v5quantitative-finance

How do I reference a previous financial value in pinescript so that I can calculate the growth rate of that value?


I am attempting to calculate the change in earnings per share on a continual basis (in order to later calculate the growth rate). I currently have:

eps = request.financial(syminfo.tickerid, "EARNINGS_PER_SHARE_DILUTED", "FY")

I would like to be able to retrieve the prior reporting period's value for EARNINGS_PER_SHARE_DILUTED so I can calculate the change in EPS. Is there a way to reference the prior reporting period's value?


Solution

  • You can use a var variable to store the last financial data in memory.

    In the below example, I used the security() call with barmerge.gaps_on so that it would only update my variables once when there is new data available. Once there is new data, simply update your "last" and "current" variables.

    //@version=5
    indicator("My script", overlay=true)
    
    var float current_financial_val = na
    var float last_financial_val = na
    
    eps = request.financial(syminfo.tickerid, "EARNINGS_PER_SHARE_DILUTED", "FY")
    eps_gap = request.financial(syminfo.tickerid, "EARNINGS_PER_SHARE_DILUTED", "FY", barmerge.gaps_on)
    
    if (not na(eps_gap))    // New financial data
        last_financial_val := current_financial_val
        current_financial_val := eps_gap
    
    plot(eps, color=color.white)
    plot(current_financial_val, color=color.green)
    plot(last_financial_val, color=color.red)
    

    Note: You don't need the eps variable. I just left it there so you can see what is going on.