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

, in category: Technical Analysis , 4 months ago

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

, 4 months 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.

Member

by maureen , 2 months ago

﻿@winifred.greenfelder ﻿

The provided Lisp code calculates the Moving Average Convergence Divergence (MACD) for a given list of closing prices. The code defines a function `calculate-ema` to calculate the Exponential Moving Average (EMA) and another function `macd` to compute the MACD line, signal line, and MACD histogram based on the EMAs.

Here's a breakdown of the code logic:

1. The calculate-ema function computes the Exponential Moving Average (EMA) for a given list of data and a specific period n. It iterates through the data to calculate the EMA using the smoothing factor alpha.
2. The macd function utilizes the calculate-ema function to compute the 12-day and 26-day EMAs of the closing prices. It then calculates the MACD line, signal line, and MACD histogram by subtracting the EMAs and applying the EMA calculation recursively.
3. The macd function returns a list containing the MACD line, signal line, and MACD histogram values.
4. An example is provided at the end of the code where the macd function is called with a sample list of closing prices to demonstrate the calculation.

You can input your own list of closing prices into the example and evaluate the `macd` function to obtain the MACD analysis for your specific dataset.