How To Calculate Average True Range (ATR) using Scala?

Member

by susan , in category: SEO Tools , 9 months ago

How To Calculate Average True Range (ATR) using Scala?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by delpha , 9 months ago

@susan 

To calculate the Average True Range (ATR) using Scala, you can follow these steps:

  1. Create a list of historical price data, which includes the high, low, and close prices of the asset for each trading period.
  2. Define a function that calculates the true range (TR) for each trading period. The true range is the greatest of the following values: The current high minus the current low The absolute value of the current high minus the previous close The absolute value of the current low minus the previous close
1
2
3
4
5
6
def trueRange(high: Double, low: Double, close: Double, prevClose: Double): Double = {
  val tr1 = high - low
  val tr2 = math.abs(high - prevClose)
  val tr3 = math.abs(low - prevClose)
  math.max(tr1, math.max(tr2, tr3))
}


  1. Calculate the ATR by taking the average of the true range values over a specified number of periods. You can use a simple moving average (SMA) function to calculate the ATR.
1
2
3
4
5
6
7
8
def atr(data: List[(Double, Double, Double)], periods: Int): List[Double] = {
  val initialTR = trueRange(data.head._1, data.head._2, data.head._3, data.head._3)
  val trs = data.sliding(2).toList.map {
    case List((h, l, c), (prevH, prevL, prevC)) => trueRange(h, l, c, prevC)
  }
  val atrs = trs.sliding(periods).toList.map(_.sum / periods)
  initialTR :: atrs
}


  1. Call the atr function with your historical price data and the number of periods you want to calculate the ATR for.
1
2
3
val historicalData = List((100.0, 90.0, 95.0), (105.0, 97.0, 102.0), (110.0, 100.0, 105.0), (108.0, 98.0, 103.0))

val atrValues = atr(historicalData, 14)


  1. The atrValues list will contain the ATR values for each period in the historical data. You can use these values to analyze the volatility and potential trend changes in the asset's price movements.


This is a basic example of how you can calculate the Average True Range (ATR) using Scala. You can further customize the function to suit your specific needs and requirements.