Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Signal Visualization with Moving Averages | Visualizing Market Trends and Indicators
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.

Opgave

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.

Løsning

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 7
single

single

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Suggested prompts:

Can you explain how the crossover signals are detected in this code?

What do the buy and sell markers represent on the plot?

Can you walk me through the logic for calculating the moving averages?

close

bookChallenge: Signal Visualization with Moving Averages

Stryg for at vise menuen

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.

Opgave

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.

Løsning

Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 7
single

single

some-alt