Class: DhanHQ::Indicators::ATR
- Inherits:
-
Object
- Object
- DhanHQ::Indicators::ATR
- Defined in:
- lib/DhanHQ/indicators.rb
Overview
Average True Range (ATR)
Volatility indicator measuring market volatility.
Class Method Summary collapse
-
.calculate(data, period: 14) ⇒ Array<Float>
Calculate ATR for the given OHLC data.
Class Method Details
.calculate(data, period: 14) ⇒ Array<Float>
Calculate ATR for the given OHLC data.
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 |
# File 'lib/DhanHQ/indicators.rb', line 248 def self.calculate(data, period: 14) return [] if data.nil? || data.empty? || period < 1 return [] if data.length < 2 # Calculate true ranges true_ranges = data.each_cons(2).map do |prev, curr| high = curr[:high] || curr["high"] low = curr[:low] || curr["low"] prev_close = prev[:close] || prev["close"] [high - low, (high - prev_close).abs, (low - prev_close).abs].max end # Calculate ATR using smoothed average atr_values = [nil] # First value has no true range # First ATR is simple average if true_ranges.length >= period first_atr = true_ranges[0...period].sum.to_f / period atr_values.concat(Array.new(period - 1, nil)) atr_values << first_atr # Subsequent ATRs use smoothing true_ranges[period..].each do |tr| previous_atr = atr_values.last atr_values << (((previous_atr * (period - 1)) + tr) / period) end else atr_values.concat(Array.new(true_ranges.length, nil)) end atr_values end |