Basic Shannon Entropy & Derivatives
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mtbdork

//@version=5
indicator("Shannon Entropy", precision=6)

Source = close
RANGE = input.int(defval = 30,    title = "Tail Length",  minval = 2, maxval = 365*4, step=5)
Entropy = input.bool(title="Shannon Entropy", defval=true)
EntropyR = input.bool(title="Shannon Entropy RMSt", defval=true)
EntropyRate = input.bool(title="Shannon Entropy Rate of Change", defval=false)
EntropyRateR = input.bool(title="Shannon Entropy Rate of Change RMSt", defval=false)
EntropyConc = input.bool(title="Shannon Entropy Concavity (second derivative)", defval=false)
EntropyConcR = input.bool(title="Shannon Entropy Concavity (second derivative) RMSt", defval=false)


ddt(a) => (a - a[1])
d2dt2(a) => (a - 2*a[1] + a[2] )/4

RMSt(a) =>
    n = 1
    v = a*a
    float R = 0
    for i = 1 to RANGE
        v := v + a[i] * a[i]
        n := n + 1
    R := math.sqrt(v/n)


P = Source/RANGE

S = ta.cum(P*math.log(P))

plot(
     Entropy ? S : na
     ,color=color.red)
plot(
     EntropyR ? RMSt(S) : na
     ,color=color.orange)
plot(
     EntropyRate ? ddt(S) : na
     ,color=color.white)
plot(
     EntropyRateR ? RMSt(ddt(S)) : na
     ,color=color.aqua)
plot(
     EntropyConc ? d2dt2(S) : na
     ,color=color.blue)
plot(
     EntropyConcR ? RMSt(d2dt2(S)) : na
     ,color=color.green)
//Enjoy!