KF Percentage Change
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TJ_667

//@version=5
indicator('KF Percentage Change')

// ---------- INPUTS ---------- //

src = input(close, "Source")
period_selection = input.string(title = "Period Option", defval="D", options = ["D", "W", "M", "Q", "Y"])
plot_start = input(true, title = 'Show Period Start')

//-------------------- CALCS --------------------//

_period = period_selection == "D" ? "D" : 
         period_selection == "W" ? "W" : 
         period_selection == "M" ? "M" : 
         period_selection == "Q" ? "3M" : 
         period_selection == "Y" ? "12M" : na

newSession = ta.change(time(_period))

// Bars back since period start
var int count = na
count := newSession ? 0 : count + 1
len = count

perc_change(_current, _start) =>
    overall_change = (_current - _start) / _start * 100

var float _startvalue = na
_startvalue := newSession ? open : _startvalue[1]

percentage_change = perc_change(src, _startvalue)

var float p_pc = na 
p_pc := newSession ? percentage_change[1] : p_pc

// ---------- PLOTS ---------- //

hline(0, 'Center Line', color=color.gray, linestyle=hline.style_dotted)

plot(percentage_change, title = "Percentage Change", style = plot.style_histogram, color = percentage_change > 0 ? color.white : percentage_change < 0 ? color.red : color.black)

if plot_start and newSession
    p_start = line.new(bar_index, 0, bar_index, 0.1, color = color.gray, style = line.style_dashed, extend = extend.both, width = 1)


var table PC_Display = table.new(position.bottom_right, 2, 2, bgcolor = color.new(color.teal, 90),frame_color=color.new(color.white, 80), frame_width=1, border_width=2,border_color=color.new(color.white, 80))
if barstate.islast
    table.cell(PC_Display, 0, 0, "PC", text_color = color.gray, text_size = size.small)
    table.cell(PC_Display, 1, 0, str.tostring(math.round(percentage_change, 2)) + '%', text_color = color.gray, text_size = size.small)
    table.cell(PC_Display, 0, 1, "Prev PC", text_color = color.gray, text_size = size.small)
    table.cell(PC_Display, 1, 1, str.tostring(math.round(p_pc, 2)) + '%', text_color = color.gray, text_size = size.small)
