#C266. Stock Analysis: MACD Calculation
Stock Analysis: MACD Calculation
Stock Analysis: MACD Calculation
You are given historical stock price data in CSV format with two columns: Date
and Close
. Your task is to compute the 12-day and 26-day Exponential Moving Averages (EMA) for the closing prices, then calculate the MACD line as (\text{MACD} = \text{EMA12} - \text{EMA26}). Next, compute the 9-day EMA of the MACD line (i.e. the Signal line) using (\alpha = \frac{2}{9+1} = 0.2). Finally, generate a trading signal for each day as follows:
- For the first data row, output
Hold
. - For subsequent rows, if the current MACD is above the current Signal and the previous MACD was less than or equal to the previous Signal, output
Buy
. - If the current MACD is below the current Signal and the previous MACD was greater than or equal to the previous Signal, output
Sell
. - Otherwise output
Hold
.
The output should be in CSV format (written to stdout) with the following columns: Date,Close,EMA12,EMA26,MACD,Signal,Signal_Type
. All numeric values must be printed with six decimal places.
inputFormat
The input is provided via standard input (stdin) and consists of CSV data. The first line is the header with exactly two columns: Date
and Close
. Each subsequent line contains a record with the trading date and the closing price. You can assume there is at least one record.
outputFormat
Print to standard output (stdout) a CSV which includes a header line followed by the results. Each row should contain the following columns: Date,Close,EMA12,EMA26,MACD,Signal,Signal_Type
. The numeric values should be formatted to six decimal places.## sample
Date,Close
2023-01-01,100
2023-01-02,110
2023-01-03,105
Date,Close,EMA12,EMA26,MACD,Signal,Signal_Type
2023-01-01,100,100.000000,100.000000,0.000000,0.000000,Hold
2023-01-02,110,101.538462,100.740741,0.797721,0.159544,Buy
2023-01-03,105,102.000000,101.037037,0.962963,0.320228,Hold
</p>