Brett
Brett

Reputation: 352

Pine-Script: Is there a way to get the close X years ago, that doesn't involve looping backwards X years?

Is there a way to get the close X years ago and use it in calculations on the current bar, that doesn't involve looping backwards X years?

EDIT:

For example, I would like to do the following:

plot(close[1Y])
plot(close[2Y])

The following does not work, due to unknown closed days in each market and leap years:

plot(close[365])
plot(close[730])

The only way I have been able to figure this out is to use a loop which is extremely inefficient especially once you start considering more than a few years into the past. enter image description here

@AnyDozer: Both our code overlapping enter image description here

Upvotes: 0

Views: 675

Answers (3)

AnyDozer
AnyDozer

Reputation: 2568

If the answer is you will not be satisfied, then I have nothing to add.

//@version=4
study("Help (time back) v2", overlay=true)

// YB = input(0, title= "Years back",  minval = 0) 
// MB = input(1, title= "Months back", minval = 0) // one month back
// DB = input(0, title= "Days back",   minval = 0) 

inback (_YB, _MB, _DB) =>
    _bg = time >= timestamp(year(timenow)-_YB, month(timenow)-_MB, dayofmonth(timenow)-_DB, 0, 0, 0) ? true : false
    if _bg and not _bg[1]
        close


tmp1 = inback(1, 0, 0) // one year ago
tmp2 = inback(2, 0, 0) // two years ago

close1Yago = 0.0
close2Yago = 0.0
closenow   = close
close1Yago := na(tmp1) ? close1Yago[1] : tmp1
close2Yago := na(tmp2) ? close2Yago[1] : tmp2

l=label.new(bar_index, high, yloc=yloc.abovebar, text="Closenow = " + tostring(closenow) + "\nClose1Yago = " + tostring(close1Yago) + "\nClose2Yago = " + tostring(close2Yago) )
label.delete(l[1])

plot((closenow + close1Yago + close2Yago) / 3, linewidth=2)

enter image description here

new screen shot enter image description here

Upvotes: 1

kmarryat
kmarryat

Reputation: 206

Check out this post: How to get bar index on specific date

You could use the code provided by AnyDozer above to get the date, then use the code in the answer linked above to get whatever value you're looking for on that date.

Upvotes: 0

AnyDozer
AnyDozer

Reputation: 2568

//@version=4
study("Help (time back)", overlay=true)

YB = input(0, title= "Years back",  minval = 0) 
MB = input(1, title= "Months back", minval = 0) // one month back
DB = input(0, title= "Days back",   minval = 0) 

bg = time >= timestamp(year(timenow)-YB, month(timenow)-MB, dayofmonth(timenow)-DB, 0, 0, 0) ? true : false

if bg and not bg[1]
    label.new(bar_index, high, yloc=yloc.abovebar, text="Close = " + tostring(close))

bgcolor(bg and not bg[1] ? color.silver : na)

On the chart there is the label with the closing price a month ago, that doesn't involve looping backwards. enter image description here

Upvotes: 0

Related Questions