Group Part II: Data Modeling and Visualization

Q13: Time Series Data Analysis Problem Statement: Analysis and Visualization of Stock Market Data Dataset: "Stock_Prices.csv" Description: The dataset contains historical stock price data for a particular company over a period of time. It includes attributes such as date, closing price, volume, and other relevant features. The goal is to perform time series data analysis on the stock price data to identify trends, patterns, and potential predictors, as well as build models to forecast future stock prices. Tasks to Perform: 1. Import the "Stock_Prices.csv" dataset. 2. Explore the dataset to understand its structure and content. 3. Ensure that the date column is in the appropriate format (e.g., datetime) for time series analysis. 4. Plot line charts or time series plots to visualize the historical stock price trends over time. 5. Calculate and plot moving averages or rolling averages to identify the underlying trends and smooth out noise. 6. Perform seasonality analysis to identify periodic patterns in the stock prices, such as weekly, monthly, or yearly fluctuations. 7. Analyze and plot the correlation between the stock prices and other variables, such as trading volume or market indices. 8. Use autoregressive integrated moving average (ARIMA) models or exponential smoothing models to forecast future stock prices.

Time Series Data Analysis

Solution and implementation for Q13 from Data Modeling & Visualization (dmv).

13_stock_time_series.ipynb Download

Q13: Time Series Data Analysis

Problem Statement: Analysis and Visualization of Stock Market Data

Code Cell [In]
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

stocks = pd.read_csv("Stock_Prices.csv", parse_dates=["Date"]).sort_values("Date").set_index("Date")
print("Rows and columns:", stocks.shape)
print(stocks.head().to_string())
print("Date span:", stocks.index.min().date(), "to", stocks.index.max().date())
Code Cell [In]
# Plot historical prices and 20/50-day rolling averages.
stocks["MA20"] = stocks["Close"].rolling(20).mean()
stocks["MA50"] = stocks["Close"].rolling(50).mean()
stocks[["Close", "MA20", "MA50"]].plot(figsize=(11, 4), title="Closing price and moving averages")
plt.ylabel("Price")
plt.tight_layout()
plt.show()
Code Cell [In]
# Inspect possible weekday/monthly patterns and correlation with the market.
weekday_change = stocks["Close"].pct_change().groupby(stocks.index.day_name()).mean().reindex(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"])
monthly_close = stocks["Close"].resample("MS").mean()
print("Mean daily return by weekday:\n", (weekday_change * 100).round(3).to_string(), "%")
print("Close/volume/market correlations:\n", stocks[["Close", "Volume", "MarketIndex"]].corr().round(3).to_string())
monthly_close.plot.bar(figsize=(10, 3), title="Mean closing price by month")
plt.ylabel("Price")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Code Cell [In]
# Holt's linear exponential smoothing: fit only on the training period.
train = stocks["Close"].iloc[:-30]
test = stocks["Close"].iloc[-30:]
alpha, beta = 0.35, 0.08
level = float(train.iloc[0])
trend = float(train.iloc[1] - train.iloc[0])
for value in train.iloc[1:]:
    old_level = level
    level = alpha * float(value) + (1 - alpha) * (level + trend)
    trend = beta * (level - old_level) + (1 - beta) * trend
forecast = pd.Series(level + np.arange(1, len(test) + 1) * trend, index=test.index, name="Forecast")
mae = (forecast - test).abs().mean()
print("Held-out mean absolute error:", round(mae, 2))
print(pd.DataFrame({"Actual": test, "Forecast": forecast}).head().round(2).to_string())
Code Cell [In]
# Compare the held-out prices with the exponential-smoothing forecast.
ax = train.iloc[-60:].plot(figsize=(10, 4), label="Training close")
test.plot(ax=ax, label="Actual close")
forecast.plot(ax=ax, label="Holt forecast", linestyle="--")
ax.set(title="Held-out stock price forecast", ylabel="Price")
ax.legend()
plt.tight_layout()
plt.show()

Other Questions in Data Modeling & Visualization

See All Available Questions
Download