Here you go, with explanation in comments.

import pandas as pd
from stockstats import StockDataFrame as Sdf

data   = pd.read_csv('data.csv')

stock  = Sdf.retype(data)

signal = stock['macds']        # Your signal line
macd   = stock['macd']         # The MACD that need to cross the signal line
#                                              to give you a Buy/Sell signal
listLongShort = ["No data"]    # Since you need at least two days in the for loop

for i in range(1, len(signal)):
    #                          # If the MACD crosses the signal line upward
    if macd[i] > signal[i] and macd[i - 1] <= signal[i - 1]:
        listLongShort.append("BUY")
    #                          # The other way around
    elif macd[i] < signal[i] and macd[i - 1] >= signal[i - 1]:
        listLongShort.append("SELL")
    #                          # Do nothing if not crossed
    else:
        listLongShort.append("HOLD")

stock['Advice'] = listLongShort

# The advice column means "Buy/Sell/Hold" at the end of this day or
#  at the beginning of the next day, since the market will be closed

print(stock['Advice'])
Answer from Vincent K on Stack Overflow
🌐
GitHub
github.com › GZotin › RSI_MACD_strategy
GitHub - GZotin/RSI_MACD_strategy: Python script for trading analysis using RSI and MACD indicators.
Python script for crypto trading analysis using RSI and MACD indicators.
Starred by 22 users
Forked by 5 users
Languages   Python 100.0% | Python 100.0%
🌐
Quantified Strategies
quantifiedstrategies.com › python-and-macd-trading-strategy
Python and MACD Trading Strategy: Backtest, Rules, Code, Setup, Performance - QuantifiedStrategies.com
February 9, 2026 - To sum up, today you learned how to backtest a MACD trading strategy in Python. We show you the base code and, with some time and dedication, you should be able to backtest and develop your own trading strategies using other indicators or combinations of indicators.
🌐
Medium
medium.com › @financial_python › building-a-macd-indicator-in-python-190b2a4c1777
Building a MACD Indicator in Python | by Financial Python | Medium
September 22, 2023 - In this article, we’ve coded a MACD indicator in Python using AAPL stock data with a 1-hour timeframe. We’ve also explained why the common values of 12-period and 26-period EMAs are used in MACD calculations. The MACD indicator is a valuable tool for traders and investors to identify potential trends and reversals in price movements. Feel free to adapt this code for other stocks, timeframes, or additional trading strategies.
🌐
Towards Data Science
towardsdatascience.com › home › latest › algorithmic trading with macd and python
Algorithmic Trading with MACD and Python | Towards Data Science
January 21, 2025 - To be efficient when programming, ... signal and the MACD line, and make trades based on signals from the MACD indicator. A good program should also be able to evaluate the profitability of a trading strategy, so as to optimize it....
🌐
AskPython
askpython.com › home › (4/5) macd indicator: python implementation and technical analysis
(4/5) MACD Indicator: Python Implementation and Technical Analysis - AskPython
April 10, 2025 - Let us move on to the next segment, which discusses implementing the MACD line in Python. In the code below, we have randomly generated stock prices for 500 days. We have calculated the MACD line which is the difference between the 12-day EMA and the 26-day EMA.
🌐
GitHub
github.com › topics › macd
macd · GitHub Topics · GitHub
Python script for trading analysis using RSI and MACD indicators. ... quantitative trading strategies including VIX Calculator, Pattern Recognition, Monte Carlo, Heikin-Ashi, Pair Trading
🌐
alpharithms
alpharithms.com › home › tutorials › calculating the macd in python for algorithmic trading
Calculating the MACD in Python for Algorithmic Trading - αlphαrithms
April 10, 2023 - The Moving Average Convergence Divergence (MACD) is one of the most popular technical indicators used to generate signals among stock traders. This indicator serves as a momentum indicator that can help signal shifts in market momentum and help signal potential breakouts. Integrating this signal into your algorithmic trading strategy is easy with Python...
Find elsewhere
🌐
EODHD
eodhd.com › home › increasing stock returns by combining williams %r and macd in python
How to Analyze Stock Returns with Williams R MACD Python | EODHD APIs Academy
March 14, 2024 - Enhance your stock returns with this Python trading strategy. Combine the Williams %R and MACD indicators to filter out false signals
🌐
Medium
medium.com › @teopan00 › macd-indicator-for-algorithmic-trading-in-python-ce2833993550
MACD indicator for algorithmic trading in Python | by Theodoros Panagiotakopoulos | Medium
August 30, 2023 - Within this article, we will explore ... Convergence/Divergence (MACD). Initially, we will delve into comprehending the essence of this trading tool. Subsequently, we will proceed to apply it, creating and subsequently evaluating a trading strategy utilizing Python, thereby gauging its ...
🌐
GitHub
gist.github.com › jimtin › 28dd0025377f661660275f33f1c806b3
Full MACD Crossover Strategy Code - Gist - GitHub
Full MACD Crossover Strategy Code · Raw · macd_crossover_strategy.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Medium
medium.com › codex › algorithmic-trading-with-macd-in-python-1c2769a6ad1b
Algorithmic Trading with MACD in Python | by Nikhil Adithyan | CodeX | Medium
September 19, 2023 - Algorithmic Trading with MACD in Python A step-by-step guide to implementing a powerful strategy Introduction In the previous article of this algorithmic trading series, we saw how Bollinger bands …
🌐
LinkedIn
linkedin.com › pulse › macd-withpython-armando-aguilar-lopez-vmidc
MACD with Python 🐍
January 8, 2024 - Entry and Exit Points: Traders use MACD crossovers as entry or exit signals. Buying when the MACD line crosses above the signal line and selling when it crosses below can be an effective strategy.
🌐
Towards Data Science
towardsdatascience.com › home › latest › cryptocurrency analysis with python – macd
Cryptocurrency Analysis with Python - MACD | Towards Data Science
January 20, 2025 - title = '%s datapoints from %s to %s for %s and %s from %s with MACD strategy' % ( datetime_interval, datetime_from, datetime_to, from_symbol, to_symbol, exchange) p = figure(x_axis_type="datetime", plot_width=1000, title=title)
🌐
GitHub
github.com › QuantConnect › Lean › blob › master › Algorithm.Python › MACDTrendAlgorithm.py
Lean/Algorithm.Python/MACDTrendAlgorithm.py at master · QuantConnect/Lean
class MACDTrendAlgorithm(QCAlgorithm): · def initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' · self.set_start_date(2004, 1, 1) #Set Start Date · self.set_end_date(2015, 1, 1) #Set End Date · self.set_cash(100000) #Set Strategy Cash ·
Author   QuantConnect
🌐
LinkedIn
linkedin.com › pulse › python-tutorial-macd-moving-average-andrew-hamlet
Investing with Python Tutorial: MACD (Moving Average Convergence/Divergence)
February 8, 2021 - For the full article, subscribe to Investing with Python on www.andrewshamlet.net ... As of today the end code works if you use import pandas as pd import pandas_datareader.data as web stocks = ['FB'] def get_stock(stock, start, end): return web.get_data_yahoo(stock, start, end)['Adj Close'] px = pd.DataFrame({n: get_stock(n, '1/1/2016', '12/31/2016') for n in stocks}) px['30 mavg'] = px.rolling(30).mean() px ... Can you please explain ewma code.
🌐
EODHD
eodhd.com › home › using python to create an innovative trading strategy and achieve better results
Python Trading Strategy: Synergizing Stochastic Oscillator and MACD Indicator | EODHD APIs Academy
February 5, 2025 - Profit gained from the STOCH MACD strategy by investing $100k in AAPL : 313585.35 Profit percentage of the STOCH MACD strategy : 313% Code Explanation: Firstly, we calculate returns for Apple stock using NumPy’s ‘diff’ function, storing them as a dataframe in ‘aapl_ret’. We then use a for-loop to calculate returns obtained from our trading strategy, appending them to ‘stoch_macd_strategy_ret’ list.
🌐
LinkedIn
linkedin.com › pulse › python-finance-part-3-macd-henry-meier
Python for Finance Part 3: MACD
March 24, 2023 - Lets test this new strategy on volatile stocks, these work best. I'm going with Gamestop (GME) over the last 3 years. /home/bot/PycharmProjects/finance/venv/bin/python /home/bot/PycharmProjects/finance/macd.py Enter the stock ticker symbol: GME Enter the start date (YYYY-MM-DD): 2020-03-01 Enter the end date (YYYY-MM-DD): 2023-03-01 Enter the initial amount of money: 1000 [*********************100%***********************] 1 of 1 completed Buy 1010.10 shares at 0.99, balance: $0.00 Sell 0.00 shares at 0.93, balance: $934.34 Buy 883.54 shares at 1.06, balance: $0.00 Sell 0.00 shares at 0.94, bal
🌐
Medium
medium.com › @armand_aguilar › macd-with-python-9ddf2548dfb5
🐍 MACD with Python
January 7, 2024 - 🐍 MACD with Python The world of technical analysis in trading can seem daunting for beginners, but fear not — we’re here to unravel the mystery behind one of the most popular indicators: the …