How To Calculate Moving Average Convergence Divergence (MACD) in Lisp?

by winifred.greenfelder , in category: Technical Analysis , a month ago

How To Calculate Moving Average Convergence Divergence (MACD) in Lisp?

Facebook Twitter LinkedIn Whatsapp

1 answer

by norberto_waelchi , a month ago

@winifred.greenfelder 

To calculate the Moving Average Convergence Divergence (MACD) in Lisp, you can follow these steps:

  1. Define the input data as a list of closing prices.
  2. Calculate the 12-day Exponential Moving Average (EMA) of the closing prices.
  3. Calculate the 26-day EMA of the closing prices.
  4. Subtract the 26-day EMA from the 12-day EMA to get the MACD line.
  5. Calculate the 9-day EMA of the MACD line to get the signal line.
  6. Subtract the signal line from the MACD line to get the MACD histogram.


Here is a sample Lisp code to calculate the MACD:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
(defun calculate-ema (data n)
  (let ((alpha (/ 2 (+ n 1))))
    (loop for i from 0 to (- (length data) 1)
          for ema = (if (= i 0)
                        (nth i data)
                        (+ (* alpha (nth i data)) (* (- 1 alpha) ema)))
          collect ema)))

(defun macd (closing-prices)
  (let* ((ema12 (calculate-ema closing-prices 12))
         (ema26 (calculate-ema closing-prices 26))
         (macd-line (mapcar #'- ema26 ema12))
         (signal-line (calculate-ema macd-line 9))
         (macd-histogram (mapcar #'- macd-line signal-line)))
    (list macd-line signal-line macd-histogram)))

;; Usage example
(let ((closing-prices '(10 12 13 15 16 17 18 20 22 25)))
  (macd closing-prices))


You can replace the closing-prices list with your own list of closing prices to calculate the MACD for your specific data. This code calculates the MACD line, signal line, and MACD histogram based on the input closing prices.