joshuaulrich / TTR

Technical analysis and other functions to construct technical trading rules with R
GNU General Public License v2.0
330 stars 103 forks source link

Add Fibonacci Retracements and Extensions #133

Open serkor1 opened 5 months ago

serkor1 commented 5 months ago

I was wondering whether there is any interest in adding Fibonacci retracement and extension levels to TTR. I have created an, albeit messy, function foo to achieve this functionality. At the time of writing I haven't been able to find any peer-reviewed papers on how to actually calculate these levels, but there appears to be consensus on how to calculate it. See, for example, here and here.

Initial function

foo <- function(
    x,
    n) {

  retracement_levels <- c(
    0,0.236, 0.382, 0.500, 0.618, 0.764, 1.00, 1.382, 1.618
  )

  object <- utils::tail(
    x = x,
    n = n
  )

  high <- quantmod::seriesHi(
    object
  )

  low <- quantmod::seriesLo(
    object
  )

  up_trend <- zoo::index(high) > zoo::index(low)

  high <- as.numeric(quantmod::Hi(high))
  low  <- as.numeric(quantmod::Lo(low))

  if (up_trend) {

    object <- vapply(
      retracement_levels,
      FUN = function(pct) {

        rep(
          low + ((high - low) * pct),
          nrow(x)
        )

      },
      FUN.VALUE = numeric(nrow(x))
    )

  } else {

    object <-  vapply(
      retracement_levels,
      FUN = function(pct) {

        rep(
          high - ((high - low) * pct),
          nrow(x)
        )

      },
      FUN.VALUE = numeric(nrow(x))
    )

  }

  colnames(object) <- paste0(
    "level_",
    retracement_levels
  )

  xts::reclass(
    object,
    x
  )
}

Function showcase

SPY <- quantmod::getSymbols(
  "SPY",
  auto.assign = FALSE
)

tail(
  foo(
    SPY,
    n = 20
  )
)

Returns

           level_0 level_0.236 level_0.382 level_0.5 level_0.618 level_0.764 level_1 level_1.382 level_1.618
2024-04-05  508.12    512.0116    514.4192   516.365    518.3108    520.7183  524.61    530.9092    534.8008
2024-04-08  508.12    512.0116    514.4192   516.365    518.3108    520.7183  524.61    530.9092    534.8008
2024-04-09  508.12    512.0116    514.4192   516.365    518.3108    520.7183  524.61    530.9092    534.8008
2024-04-10  508.12    512.0116    514.4192   516.365    518.3108    520.7183  524.61    530.9092    534.8008
2024-04-11  508.12    512.0116    514.4192   516.365    518.3108    520.7183  524.61    530.9092    534.8008
2024-04-12  508.12    512.0116    514.4192   516.365    518.3108    520.7183  524.61    530.9092    534.8008

Visually

These retracements can be charted in visually appealing way in both quantmod and plotly. Below is a simple prototype example,

Rplot


I, personally, think its an welcomed addition to TTR - what do you guys think?

Best,