Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте 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.

Завдання

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.

Рішення

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 7
single

single

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

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

Свайпніть щоб показати меню

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.

Завдання

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.

Рішення

Switch to desktopПерейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів
Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 7
single

single

some-alt