Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Challenge: Signal Visualization with Moving Averages | Visualizing Market Trends and Indicators
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Python for Traders

bookChallenge: Signal Visualization with Moving Averages

In real-world trading, visualizing moving averages and their crossovers can help you spot potential buy or sell signals. You will work with a hardcoded set of closing prices, calculate two moving averages, and plot both together. Your goal is to clearly mark every point where the short-term average (3-day) crosses above or below the long-term average (5-day), highlighting possible trading signals.

123456789101112131415161718192021222324252627282930313233343536373839404142
import pandas as pd import matplotlib.pyplot as plt import numpy as np # Hardcoded closing prices for 15 days data = { "date": pd.date_range("2024-01-01", periods=15, freq="D"), "close": [100, 102, 101, 105, 108, 110, 107, 106, 108, 109, 111, 113, 112, 114, 115] } df = pd.DataFrame(data) df.set_index("date", inplace=True) # Calculate 3-day and 5-day simple moving averages df["SMA_3"] = df["close"].rolling(window=3).mean() df["SMA_5"] = df["close"].rolling(window=5).mean() # Find crossover points df["signal"] = 0 df["signal"][df["SMA_3"] > df["SMA_5"]] = 1 df["signal"][df["SMA_3"] < df["SMA_5"]] = -1 df["crossover"] = df["signal"].diff() # Plotting plt.figure(figsize=(12, 6)) plt.plot(df.index, df["close"], label="Close Price", color="black", linewidth=2) plt.plot(df.index, df["SMA_3"], label="3-Day SMA", color="blue", linestyle="--") plt.plot(df.index, df["SMA_5"], label="5-Day SMA", color="red", linestyle="-.") # Mark crossover points buy_signals = df[df["crossover"] == 2] sell_signals = df[df["crossover"] == -2] plt.scatter(buy_signals.index, buy_signals["close"], marker="^", color="green", s=100, label="Buy Signal (3>5)") plt.scatter(sell_signals.index, sell_signals["close"], marker="v", color="red", s=100, label="Sell Signal (3<5)") plt.title("Moving Average Crossover Signals") plt.xlabel("Date") plt.ylabel("Price") plt.legend() plt.grid(True) plt.tight_layout() plt.show()
copy
Note
Definition

Definition: A moving average crossover occurs when a short-term moving average crosses above (bullish) or below (bearish) a longer-term moving average. Traders often use these crossovers to generate buy or sell signals.

Tarea

Swipe to start coding

Plot the closing prices and both moving averages using the provided hardcoded data. Then, mark all crossover points with buy (when the 3-day SMA crosses above the 5-day SMA) and sell (when the 3-day crosses below the 5-day) markers. Your plot should:

  • Display the close price, 3-day SMA, and 5-day SMA.
  • Mark every crossover with a green upward triangle for buy signals.
  • Mark every crossover with a red downward triangle for sell signals.
  • Include a legend and axis labels.

Solución

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 7
single

single

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

close

bookChallenge: Signal Visualization with Moving Averages

Desliza para mostrar el menú

In real-world trading, visualizing moving averages and their crossovers can help you spot potential buy or sell signals. You will work with a hardcoded set of closing prices, calculate two moving averages, and plot both together. Your goal is to clearly mark every point where the short-term average (3-day) crosses above or below the long-term average (5-day), highlighting possible trading signals.

123456789101112131415161718192021222324252627282930313233343536373839404142
import pandas as pd import matplotlib.pyplot as plt import numpy as np # Hardcoded closing prices for 15 days data = { "date": pd.date_range("2024-01-01", periods=15, freq="D"), "close": [100, 102, 101, 105, 108, 110, 107, 106, 108, 109, 111, 113, 112, 114, 115] } df = pd.DataFrame(data) df.set_index("date", inplace=True) # Calculate 3-day and 5-day simple moving averages df["SMA_3"] = df["close"].rolling(window=3).mean() df["SMA_5"] = df["close"].rolling(window=5).mean() # Find crossover points df["signal"] = 0 df["signal"][df["SMA_3"] > df["SMA_5"]] = 1 df["signal"][df["SMA_3"] < df["SMA_5"]] = -1 df["crossover"] = df["signal"].diff() # Plotting plt.figure(figsize=(12, 6)) plt.plot(df.index, df["close"], label="Close Price", color="black", linewidth=2) plt.plot(df.index, df["SMA_3"], label="3-Day SMA", color="blue", linestyle="--") plt.plot(df.index, df["SMA_5"], label="5-Day SMA", color="red", linestyle="-.") # Mark crossover points buy_signals = df[df["crossover"] == 2] sell_signals = df[df["crossover"] == -2] plt.scatter(buy_signals.index, buy_signals["close"], marker="^", color="green", s=100, label="Buy Signal (3>5)") plt.scatter(sell_signals.index, sell_signals["close"], marker="v", color="red", s=100, label="Sell Signal (3<5)") plt.title("Moving Average Crossover Signals") plt.xlabel("Date") plt.ylabel("Price") plt.legend() plt.grid(True) plt.tight_layout() plt.show()
copy
Note
Definition

Definition: A moving average crossover occurs when a short-term moving average crosses above (bullish) or below (bearish) a longer-term moving average. Traders often use these crossovers to generate buy or sell signals.

Tarea

Swipe to start coding

Plot the closing prices and both moving averages using the provided hardcoded data. Then, mark all crossover points with buy (when the 3-day SMA crosses above the 5-day SMA) and sell (when the 3-day crosses below the 5-day) markers. Your plot should:

  • Display the close price, 3-day SMA, and 5-day SMA.
  • Mark every crossover with a green upward triangle for buy signals.
  • Mark every crossover with a red downward triangle for sell signals.
  • Include a legend and axis labels.

Solución

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 7
single

single

some-alt