OPEN-SOURCE SCRIPT

TrailingPE

83
//version=6
indicator("TrailingPE", shorttitle="TPE", overlay=true)

// === USER INPUTS ===
pos_x = input.string("Right", "Horizontal Position", options=["Left", "Center", "Right"])
pos_y = input.string("Top", "Vertical Position", options=["Top", "Middle", "Bottom"])
text_color = input.color(color.white, "Text Color")
bg_color = input.color(color.new(color.blue, 80), "Background Color")
text_size = input.string("Normal", "Font Size", options=["Tiny", "Small", "Normal", "Large", "Huge"])

// === POSITION MAPPING ===
get_position_y() =>
switch pos_y
"Top" =>
switch pos_x
"Left" => position.top_left
"Center" => position.top_center
"Right" => position.top_right
"Middle" =>
switch pos_x
"Left" => position.middle_left
"Center" => position.middle_center
"Right" => position.middle_right
"Bottom" =>
switch pos_x
"Left" => position.bottom_left
"Center" => position.bottom_center
"Right" => position.bottom_right

get_text_size() =>
switch text_size
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge

// === PE CALCULATION ===
eps_ttm = request.financial(syminfo.tickerid, "EARNINGS_PER_SHARE_DILUTED", "TTM")

if na(eps_ttm)
eps_ttm := request.financial(syminfo.tickerid, "EARNINGS_PER_SHARE_BASIC", "TTM")

current_price = close
pe_ratio = eps_ttm > 0 ? current_price / eps_ttm : na
is_data_valid = not na(pe_ratio) and eps_ttm > 0

// === COMPACT SINGLE-LINE DISPLAY ===
if barstate.islast
var table pe_table = table.new(get_position_y(), 1, 1,
bgcolor=bg_color,
border_width=1,
border_color=color.gray)

table.clear(pe_table, 0, 0, 0, 0)

if is_data_valid
// Single line: "PE : Value" - removed text_style parameter
pe_rounded = math.ceil(pe_ratio)
pe_text = "PE : " + str.tostring(pe_rounded)

table.cell(pe_table, 0, 0, pe_text,
text_color=text_color,
text_size=get_text_size(),
bgcolor=bg_color)
else
table.cell(pe_table, 0, 0, "PE : N/A",
text_color=color.red,
text_size=get_text_size(),
bgcolor=bg_color)

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.