Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Challenge: Visualize Volatility Clusters | Visualizing Market Trends and Indicators
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Python for Traders

bookChallenge: Visualize Volatility Clusters

You will practice visualizing volatility clusters using a small set of closing price data. This exercise will help you spot periods of unusual price movement, which is critical for risk management and trading decisions. Start by using a hardcoded pandas DataFrame containing closing prices. Calculate daily returns, then compute a 3-day rolling standard deviation to measure short-term volatility. Plot both the closing prices and rolling volatility together with matplotlib, using twin axes for clarity. Highlight periods where the rolling volatility rises above a chosen threshold to clearly identify volatility clusters.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
import pandas as pd import matplotlib.pyplot as plt # Hardcoded closing prices data = { "date": pd.date_range(start="2024-01-01", periods=15, freq="D"), "close": [ 100, 102, 101, 103, 102, 105, 107, 106, 104, 108, 110, 112, 111, 115, 117 ] } df = pd.DataFrame(data) df.set_index("date", inplace=True) # Calculate daily returns df["returns"] = df["close"].pct_change() # Calculate 3-day rolling volatility (standard deviation) df["volatility"] = df["returns"].rolling(window=3).std() # Set volatility threshold vol_threshold = 0.015 # Plot price and volatility fig, ax1 = plt.subplots(figsize=(10, 5)) color_price = "tab:blue" ax1.set_xlabel("Date") ax1.set_ylabel("Close Price", color=color_price) ax1.plot(df.index, df["close"], color=color_price, label="Close Price") ax1.tick_params(axis="y", labelcolor=color_price) # Create twin axis for volatility ax2 = ax1.twinx() color_vol = "tab:red" ax2.set_ylabel("3-Day Rolling Volatility", color=color_vol) ax2.plot(df.index, df["volatility"], color=color_vol, label="Volatility", linestyle="--") ax2.tick_params(axis="y", labelcolor=color_vol) # Highlight periods where volatility exceeds threshold high_vol = df["volatility"] > vol_threshold ax2.fill_between(df.index, 0, df["volatility"], where=high_vol, color="orange", alpha=0.3, label="High Volatility") # Add legends lines1, labels1 = ax1.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax1.legend(lines1 + lines2, labels1 + labels2, loc="upper left") plt.title("Close Price and 3-Day Rolling Volatility") plt.tight_layout() plt.show()
copy
Tehtävä

Swipe to start coding

Calculate and visualize volatility clusters using the following steps:

  • Create a DataFrame with columns "date" and "close" using the provided price data.
  • Compute daily returns as the percentage change of the "close" price.
  • Calculate a 3-day rolling standard deviation of the returns to estimate short-term volatility.
  • Set a volatility threshold of 0.015.
  • Plot both the "close" price and "volatility" on the same chart using twin y-axes.
  • Highlight periods where volatility exceeds the threshold.
  • Your plot should clearly show both the price and volatility, with high-volatility periods visible.

Use only the libraries and methods shown in the example.

Ratkaisu

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 3
single

single

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

close

bookChallenge: Visualize Volatility Clusters

Pyyhkäise näyttääksesi valikon

You will practice visualizing volatility clusters using a small set of closing price data. This exercise will help you spot periods of unusual price movement, which is critical for risk management and trading decisions. Start by using a hardcoded pandas DataFrame containing closing prices. Calculate daily returns, then compute a 3-day rolling standard deviation to measure short-term volatility. Plot both the closing prices and rolling volatility together with matplotlib, using twin axes for clarity. Highlight periods where the rolling volatility rises above a chosen threshold to clearly identify volatility clusters.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
import pandas as pd import matplotlib.pyplot as plt # Hardcoded closing prices data = { "date": pd.date_range(start="2024-01-01", periods=15, freq="D"), "close": [ 100, 102, 101, 103, 102, 105, 107, 106, 104, 108, 110, 112, 111, 115, 117 ] } df = pd.DataFrame(data) df.set_index("date", inplace=True) # Calculate daily returns df["returns"] = df["close"].pct_change() # Calculate 3-day rolling volatility (standard deviation) df["volatility"] = df["returns"].rolling(window=3).std() # Set volatility threshold vol_threshold = 0.015 # Plot price and volatility fig, ax1 = plt.subplots(figsize=(10, 5)) color_price = "tab:blue" ax1.set_xlabel("Date") ax1.set_ylabel("Close Price", color=color_price) ax1.plot(df.index, df["close"], color=color_price, label="Close Price") ax1.tick_params(axis="y", labelcolor=color_price) # Create twin axis for volatility ax2 = ax1.twinx() color_vol = "tab:red" ax2.set_ylabel("3-Day Rolling Volatility", color=color_vol) ax2.plot(df.index, df["volatility"], color=color_vol, label="Volatility", linestyle="--") ax2.tick_params(axis="y", labelcolor=color_vol) # Highlight periods where volatility exceeds threshold high_vol = df["volatility"] > vol_threshold ax2.fill_between(df.index, 0, df["volatility"], where=high_vol, color="orange", alpha=0.3, label="High Volatility") # Add legends lines1, labels1 = ax1.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax1.legend(lines1 + lines2, labels1 + labels2, loc="upper left") plt.title("Close Price and 3-Day Rolling Volatility") plt.tight_layout() plt.show()
copy
Tehtävä

Swipe to start coding

Calculate and visualize volatility clusters using the following steps:

  • Create a DataFrame with columns "date" and "close" using the provided price data.
  • Compute daily returns as the percentage change of the "close" price.
  • Calculate a 3-day rolling standard deviation of the returns to estimate short-term volatility.
  • Set a volatility threshold of 0.015.
  • Plot both the "close" price and "volatility" on the same chart using twin y-axes.
  • Highlight periods where volatility exceeds the threshold.
  • Your plot should clearly show both the price and volatility, with high-volatility periods visible.

Use only the libraries and methods shown in the example.

Ratkaisu

Switch to desktopVaihda työpöytään todellista harjoitusta vartenJatka siitä, missä olet käyttämällä jotakin alla olevista vaihtoehdoista
Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 3
single

single

some-alt