Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda 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.

Tarefa

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.

Solução

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 7
single

single

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

close

bookChallenge: Signal Visualization with Moving Averages

Deslize para mostrar o menu

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.

Tarefa

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.

Solução

Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 7
single

single

some-alt