Class: DhanHQ::Indicators::SMA

Inherits:
Object
  • Object
show all
Defined in:
lib/DhanHQ/indicators.rb

Overview

Simple Moving Average (SMA)

Calculates the average of a specified number of data points.

Examples:

Calculate 20-period SMA

closes = [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
sma = DhanHQ::Indicators::SMA.calculate(closes, period: 5)
#=> [102.2, 103.0, 103.8, 104.6, 105.4, 106.8, 108.2, 107.8]

Class Method Summary collapse

Class Method Details

.calculate(data, period: 20) ⇒ Array<Float>

Calculate SMA for the given data.

Parameters:

  • data (Array<Numeric>)

    Input price data

  • period (Integer) (defaults to: 20)

    Number of periods (default: 20)

Returns:

  • (Array<Float>)

    SMA values (nil for insufficient data points)



21
22
23
24
25
26
27
28
29
30
# File 'lib/DhanHQ/indicators.rb', line 21

def self.calculate(data, period: 20)
  return [] if data.nil? || data.empty? || period < 1

  data.each_index.map do |i|
    next nil if i < period - 1

    window = data[(i - period + 1)..i]
    window.sum.to_f / period
  end
end