Stock Comparison to S&P 500
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © rodopacapital

//@version=5
indicator("Stock Comparison to S&P 500")

//S&P 500 Earnings growth by quarter
SPX_EG = request.quandl("MULTPL/SP500_EARNINGS_GROWTH_QUARTER", barmerge.gaps_on, 0) 
//Default instrument Earnings growth.
EG_D = request.financial(syminfo.tickerid, "EARNINGS_PER_SHARE_DILUTED_ONE_YEAR_GROWTH", 'FQ' )

//S&P 500 PE Ratio by Month. Price to earnings ratio, based on trailing twelve month as reported earnings.
SPX_PERatio = request.quandl("MULTPL/SP500_PE_RATIO_MONTH", barmerge.gaps_off, 0) 
//Default instrument PE Ratio by quarter.
PE_D = request.financial(syminfo.tickerid, 'PRICE_EARNINGS_FORWARD', 'FQ' )

//S&P 500 price to book value ratio by quarter.
SPX_PriceBook = request.quandl("MULTPL/SP500_PBV_RATIO_QUARTER", barmerge.gaps_on, 0) 
//Default instrument price to book value ratio by quarter.
PB_D = request.financial(syminfo.tickerid, 'PRICE_TO_TANGIBLE_BOOK', 'FQ' )


//S&P 500 Price to Sales Ratio by quarter (P/S or Price to Revenue).
SPX_PriceSales = request.quandl("MULTPL/SP500_PSR_QUARTER", barmerge.gaps_on, 0) 
//Default instrument Price to Sales Ratio by quarter
PS_D = request.financial(syminfo.tickerid, 'PRICE_SALES_FORWARD', 'FQ' )

//Calculating comparsions betweeen S&P500 and default instrument:  Instrument financial - S&P500 financial 

Earnings_growth= EG_D - SPX_EG
Price_earnings = PE_D - SPX_PERatio
Price_book = PB_D - SPX_PriceBook
Price_sales = PS_D - SPX_PriceSales

total = (((0.1*PE_D) + (0.5*PB_D) + (0.4*PS_D)) - ((0.1*SPX_PERatio) + (0.5*SPX_PriceBook) + (0.4*SPX_PriceSales))) * Earnings_growth

//Change color under Zero level 
col1= Earnings_growth > 0 ? color.rgb(82, 146, 97) : color.rgb(255, 63, 63)  
col2= Price_earnings > 0 ? color.rgb(82, 146, 97) : color.rgb(255, 63, 63)
col3= Price_book > 0 ? color.rgb(82, 146, 97) : color.rgb(255, 63, 63)                 
col4= Price_sales > 0 ? color.rgb(82, 146, 97) : color.rgb(255, 63, 63)       
col5= total > 0 ? color.rgb(82, 146, 97) : color.rgb(255, 63, 63)


plot(total, "Overal Comparsion", color=col5,style=plot.style_area)
plot(Earnings_growth, "Earnings growth", color=col1,style=plot.style_area, display = display.none)
plot(Price_earnings, "Price earnings", color=col2,style=plot.style_area, display = display.none)
plot(Price_book, "Price book", color=col3,style=plot.style_area, display = display.none)
plot(Price_sales, "Price sales", color=col4,style=plot.style_area, display = display.none)

hline(0)