Class: DhanHQ::Indicators::MACD

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

Overview

Moving Average Convergence Divergence (MACD)

Trend-following momentum indicator showing relationship between two EMAs.

Examples:

Calculate MACD

closes = (0..99).map { |i| 100 + Math.sin(i * 0.1) * 10 }
macd = DhanHQ::Indicators::MACD.calculate(closes)
#=> { macd_line: [...], signal_line: [...], histogram: [...] }

Class Method Summary collapse

Class Method Details

.calculate(data, fast_period: 12, slow_period: 26, signal_period: 9) ⇒ Hash

Calculate MACD for the given data.

Parameters:

  • data (Array<Numeric>)

    Input price data

  • fast_period (Integer) (defaults to: 12)

    Fast EMA period (default: 12)

  • slow_period (Integer) (defaults to: 26)

    Slow EMA period (default: 26)

  • signal_period (Integer) (defaults to: 9)

    Signal line period (default: 9)

Returns:

  • (Hash)

    Hash with :macd_line, :signal_line, and :histogram arrays



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/DhanHQ/indicators.rb', line 145

def self.calculate(data, fast_period: 12, slow_period: 26, signal_period: 9)
  return { macd_line: [], signal_line: [], histogram: [] } if data.nil? || data.empty?

  # Calculate fast and slow EMAs
  fast_ema = EMA.calculate(data, period: fast_period)
  slow_ema = EMA.calculate(data, period: slow_period)

  # Calculate MACD line (fast EMA - slow EMA)
  macd_line = fast_ema.zip(slow_ema).map do |fast, slow|
    next nil if fast.nil? || slow.nil?

    fast - slow
  end

  # Calculate signal line (EMA of MACD line)
  valid_macd = macd_line.compact
  signal_line_raw = valid_macd.empty? ? [] : EMA.calculate(valid_macd, period: signal_period)

  # Align signal line with MACD line
  signal_line = Array.new(macd_line.length - signal_line_raw.length, nil) + signal_line_raw

  # Calculate histogram (MACD line - signal line)
  histogram = macd_line.zip(signal_line).map do |macd, signal|
    next nil if macd.nil? || signal.nil?

    macd - signal
  end

  {
    macd_line: macd_line,
    signal_line: signal_line,
    histogram: histogram
  }
end