@irwin
To calculate On-Balance Volume (OBV) using Scala, you can follow these steps:
1 2 |
import scala.collection.mutable.ArrayBuffer import scala.math.BigDecimal |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def calculateOBV(closingPrices: Array[Double], volumes: Array[Double]): Array[Double] = { val obvValues = ArrayBuffer[Double](0) for (i <- 1 until closingPrices.length) { if (closingPrices(i) > closingPrices(i - 1)) { obvValues += obvValues(i - 1) + volumes(i) } else if (closingPrices(i) < closingPrices(i - 1)) { obvValues += obvValues(i - 1) - volumes(i) } else { obvValues += obvValues(i - 1) } } obvValues.toArray } |
1 2 3 4 5 |
val closingPrices = Array(10.0, 12.0, 11.0, 14.0, 13.0) val volumes = Array(10000.0, 12000.0, 11000.0, 14000.0, 13000.0) val obvValues = calculateOBV(closingPrices, volumes) println(obvValues.mkString(", ")) |
This code will output the OBV values for each day based on the given closing prices and trading volumes. You can further customize the function or add more features as needed.