I am trying to translate a Swing High and Low function from Pine to R, and I cannot really get the logic behind the Pine code.
Basically, this function loops over a time series database of high and low prices, and yields:
A swing high: as the position of the highest price after the price moves below the prior swing high OR as the position of a new price that reaches a new high in the given prior time period.
Then moves to find the
Swing low: as the lowest value after the price moves above the prior swing low OR as the position of a new price that reaches a new low in the given prior time period.
Is any one familiar of a similar function in R?
Here is the function in Pine:
//@version=3
study("Swings", overlay=true)
barsback = input(7, title='Bars back to check for a swing')
swing_detection(index)=>
swing_high = false
swing_low = false
start = (index*2) - 1 // -1 so we have an even number of
swing_point_high = high[index]
swing_point_low = low[index]
//Swing Highs
for i = 0 to start
swing_high := true
if i < index
if high[i] > swing_point_high
swing_high := false
break
// Have to do checks before pivot and after separately because we can get
// two highs of the same value in a row. Notice the > and >= difference
if i > index
if high[i] >= swing_point_high
swing_high := false
break
//Swing lows
for i = 0 to start
swing_low := true
if i < index
if low[i] < swing_point_low
swing_low := false
break
// Have to do checks before pivot and after seperately because we can get
// two lows of the same value in a row. Notice the > and >= difference
if i > index
if low[i] <= swing_point_low
swing_low := false
break
[swing_high, swing_low]
// Check for a swing
[swing_high, swing_low] = swing_detection(barsback)
// Plotting
plotshape(swing_high, style=shape.arrowdown, location=location.abovebar, color=red, text='SH', offset=-barsback)
plotshape(swing_low, style=shape.arrowup, location=location.belowbar, color=green, text='SL', offset=-barsback)
Here is a sample data:
library(quantmod)
DT <- getSymbols('rdwr', auto.assign=FALSE)
DT=data.frame(DT$RDWR.Low, DT$RDWR.High)
colnames(DT)=c("Low","High")