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

Analyzing stock prices over time.

Use Stock_Prices.csv from the same folder. This is the existing generated practice dataset, not real observations.

Weekday returns and monthly averages explore possible seasonal patterns. One year of practice data cannot confirm repeated annual seasonality. Simple exponential smoothing produces a constant multi-step forecast, fitted only on the training period.

Code Cell 1
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("Stock_Prices.csv")
df["Date"] = pd.to_datetime(df["Date"])
df = df.sort_values("Date").set_index("Date")

print(df.head())
df.info()
print("Missing Values:")
print(df.isnull().sum())
             Close  Volume  MarketIndex
Date                                   
2024-01-01  102.97  325195     17998.28
2024-01-02  105.27  309874     18004.02
2024-01-03  105.72  106315     17993.29
2024-01-04  106.59  208729     18085.50
2024-01-05  106.40  333653     18070.59
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 260 entries, 2024-01-01 to 2024-12-27
Data columns (total 3 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   Close        260 non-null    float64
 1   Volume       260 non-null    int64  
 2   MarketIndex  260 non-null    float64
dtypes: float64(2), int64(1)
memory usage: 8.1 KB
Missing Values:
Close          0
Volume         0
MarketIndex    0
dtype: int64
Code Cell 2
# Historical closing prices
df["Close"].plot(figsize=(10, 5))
plt.title("Stock Closing Prices")
plt.xlabel("Date")
plt.ylabel("Price")
plt.tight_layout()
plt.show()
Cell 2 output
Code Cell 3
# Moving averages
df["MA20"] = df["Close"].rolling(window=20).mean()
df["MA50"] = df["Close"].rolling(window=50).mean()

df[["Close", "MA20", "MA50"]].plot(figsize=(10, 5))
plt.title("Closing Price and Moving Averages")
plt.xlabel("Date")
plt.ylabel("Price")
plt.tight_layout()
plt.show()
Cell 3 output
Code Cell 4
# Average daily return by weekday
returns = df["Close"].pct_change()
weekday_returns = returns.groupby(df.index.day_name()).mean()
weekday_returns = weekday_returns.reindex([
    "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
]) * 100
print("Average Daily Return (%):")
print(weekday_returns)

weekday_returns.plot(kind="bar", figsize=(8, 5))
plt.title("Average Return by Weekday")
plt.xlabel("Weekday")
plt.ylabel("Average Return (%)")
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()
Average Daily Return (%):
Date
Monday      -0.042060
Tuesday      0.528228
Wednesday   -0.118768
Thursday    -0.171455
Friday       0.587864
Name: Close, dtype: float64
Cell 4 output
Code Cell 5
# Average closing price by month
monthly = df["Close"].resample("MS").mean()
print("Monthly Average Price:")
print(monthly)

monthly.plot(kind="bar", figsize=(10, 5))
plt.title("Monthly Average Closing Price")
plt.xlabel("Month")
plt.ylabel("Average Price")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Monthly Average Price:
Date
2024-01-01    109.585652
2024-02-01    112.958571
2024-03-01    110.513333
2024-04-01    118.510455
2024-05-01    124.925217
2024-06-01    123.669000
2024-07-01    127.022609
2024-08-01    135.920909
2024-09-01    137.650476
2024-10-01    136.816957
2024-11-01    145.705238
2024-12-01    151.547000
Freq: MS, Name: Close, dtype: float64
Cell 5 output
Code Cell 6
# Correlations between price, volume and market index
print(df[["Close", "Volume", "MarketIndex"]].corr())

plt.figure(figsize=(7, 5))
plt.scatter(df["Volume"], df["Close"])
plt.title("Volume and Closing Price")
plt.xlabel("Trading Volume")
plt.ylabel("Closing Price")
plt.tight_layout()
plt.show()
                Close    Volume  MarketIndex
Close        1.000000 -0.060337     0.914943
Volume      -0.060337  1.000000    -0.061249
MarketIndex  0.914943 -0.061249     1.000000
Cell 6 output
Code Cell 7
# Plot the correlation matrix
correlation = df[["Close", "Volume", "MarketIndex"]].corr()
plt.figure(figsize=(6, 5))
plt.imshow(correlation, cmap="coolwarm", vmin=-1, vmax=1)
plt.xticks(range(3), correlation.columns, rotation=45)
plt.yticks(range(3), correlation.columns)
plt.colorbar(label="Correlation")
plt.title("Price, Volume and Market Correlations")
plt.tight_layout()
plt.show()
Cell 7 output
Code Cell 8
# Forecast using simple exponential smoothing
train = df["Close"].iloc[:-30]
test = df["Close"].iloc[-30:]

smoothed = train.ewm(alpha=0.3, adjust=False).mean()
forecast = pd.Series(smoothed.iloc[-1], index=test.index)

print("Forecast and Actual Prices:")
print(pd.DataFrame({"Actual": test, "Forecast": forecast}).head())
mae = (test - forecast).abs().mean()
print("\nMean Absolute Error:", round(mae, 2))
Forecast and Actual Prices:
            Actual    Forecast
Date                          
2024-11-18  145.27  144.626343
2024-11-19  144.78  144.626343
2024-11-20  148.41  144.626343
2024-11-21  147.69  144.626343
2024-11-22  150.78  144.626343

Mean Absolute Error: 5.72
Code Cell 9
# Compare forecast with actual prices
plt.figure(figsize=(10, 5))
plt.plot(train.tail(60), label="Training Prices")
plt.plot(test, label="Actual Prices")
plt.plot(forecast, label="Forecast", linestyle="--")
plt.title("Simple Exponential Smoothing Forecast")
plt.xlabel("Date")
plt.ylabel("Price")
plt.legend()
plt.tight_layout()
plt.show()
Cell 9 output
Stock_Prices.csv Download
Date,Close,Volume,MarketIndex
2024-01-01,102.97,325195,17998.28
2024-01-02,105.27,309874,18004.02
2024-01-03,105.72,106315,17993.29
2024-01-04,106.59,208729,18085.5
2024-01-05,106.4,333653,18070.59
2024-01-08,108.87,224877,18081.25
2024-01-09,109.04,106554,18111.63
2024-01-10,110.1,91960,18097.5
2024-01-11,108.05,296152,18059.61
2024-01-12,108.4,252372,18129.54
2024-01-15,109.77,100078,18113.57
2024-01-16,110.06,167152,18116.32
2024-01-17,112.66,364117,18130.0
2024-01-18,107.27,388224,18103.57
2024-01-19,110.76,129861,18132.25
2024-01-22,113.09,262223,18229.04
2024-01-23,111.47,146881,18181.44
2024-01-24,111.08,314982,18184.72
2024-01-25,111.55,390465,18099.66
2024-01-26,113.11,340118,18327.08
2024-01-29,111.02,163150,18167.16
2024-01-30,113.42,115039,18119.14
2024-01-31,113.8,397487,18267.65
2024-02-01,113.46,250933,18259.76
2024-02-02,115.64,301512,18191.44
2024-02-05,109.95,153565,18281.96
2024-02-06,115.47,373854,18314.09
2024-02-07,114.05,322835,18278.71
2024-02-08,113.79,326321,18216.24
2024-02-09,114.53,306773,18221.24
2024-02-12,112.14,116642,18310.98
2024-02-13,113.78,147512,18224.04
2024-02-14,113.07,235215,18206.26
2024-02-15,113.99,146336,18257.65
2024-02-16,112.09,265547,18246.56
2024-02-19,111.38,360552,18319.6
2024-02-20,112.07,320926,18282.82
2024-02-21,113.78,392622,18229.6
2024-02-22,110.39,262969,18273.3
2024-02-23,116.4,143279,18252.91
2024-02-26,110.93,394413,18275.0
2024-02-27,111.07,346718,18156.09
2024-02-28,111.25,231852,18364.74
2024-02-29,112.9,354891,18230.68
2024-03-01,109.67,176953,18270.26
2024-03-04,111.07,136448,18215.66
2024-03-05,112.23,351242,18316.69
2024-03-06,108.36,99449,18166.28
2024-03-07,108.56,315945,18265.11
2024-03-08,108.76,365181,18248.62
2024-03-11,109.96,189077,18171.54
2024-03-12,111.28,221104,18282.14
2024-03-13,109.23,307473,18223.63
2024-03-14,110.79,357368,18187.25
2024-03-15,107.48,367981,18229.63
2024-03-18,110.76,179622,18273.15
2024-03-19,113.64,332278,18124.79
2024-03-20,111.34,130224,18219.77
2024-03-21,109.81,269423,18174.42
2024-03-22,112.41,398226,18245.94
2024-03-25,110.02,326291,18218.75
2024-03-26,111.84,272866,18137.16
2024-03-27,108.74,399212,18090.04
2024-03-28,109.26,255242,18132.63
2024-03-29,115.57,188521,18204.03
2024-04-01,112.84,198592,18157.61
2024-04-02,114.96,329381,18218.34
2024-04-03,114.07,381394,18169.49
2024-04-04,113.97,332889,18196.51
2024-04-05,116.44,344118,18167.66
2024-04-08,115.82,96289,18230.56
2024-04-09,117.63,354626,18142.37
2024-04-10,120.56,300805,18193.47
2024-04-11,116.85,108263,18126.16
2024-04-12,119.67,206919,18186.8
2024-04-15,119.14,350417,18216.05
2024-04-16,116.64,361399,18206.83
2024-04-17,119.41,236957,18237.95
2024-04-18,119.21,336714,18184.32
2024-04-19,119.5,248493,18211.54
2024-04-22,118.23,196455,18133.33
2024-04-23,120.31,384386,18196.41
2024-04-24,121.51,262692,18200.71
2024-04-25,121.1,146699,18274.63
2024-04-26,122.27,164256,18175.81
2024-04-29,123.33,304381,18162.27
2024-04-30,123.77,310188,18116.76
2024-05-01,123.22,165261,18199.02
2024-05-02,122.76,209698,18288.36
2024-05-03,122.79,237353,18197.79
2024-05-06,124.23,362632,18199.06
2024-05-07,122.36,126836,18241.63
2024-05-08,124.81,221977,18201.32
2024-05-09,124.19,314314,18292.0
2024-05-10,124.67,330701,18322.32
2024-05-13,126.88,189232,18237.64
2024-05-14,125.92,245678,18161.17
2024-05-15,127.65,184007,18289.02
2024-05-16,124.38,127846,18283.34
2024-05-17,124.98,325691,18356.65
2024-05-20,124.11,279841,18258.81
2024-05-21,126.26,145906,18361.16
2024-05-22,124.65,331434,18354.5
2024-05-23,124.95,321446,18370.5
2024-05-24,124.74,260665,18453.22
2024-05-27,125.52,374958,18405.65
2024-05-28,128.41,290477,18431.58
2024-05-29,125.42,106207,18298.74
2024-05-30,125.32,380929,18443.84
2024-05-31,125.06,94331,18452.37
2024-06-03,124.36,249512,18499.8
2024-06-04,124.39,280214,18644.43
2024-06-05,122.68,266367,18495.56
2024-06-06,123.84,132812,18450.5
2024-06-07,125.31,338198,18570.91
2024-06-10,126.62,347722,18427.42
2024-06-11,126.15,209005,18470.47
2024-06-12,122.98,163249,18578.71
2024-06-13,123.33,137535,18565.95
2024-06-14,120.96,362153,18554.24
2024-06-17,123.83,243228,18639.72
2024-06-18,124.08,241701,18556.91
2024-06-19,120.3,277448,18547.92
2024-06-20,123.37,292555,18634.6
2024-06-21,123.46,298313,18551.49
2024-06-24,122.3,271059,18566.29
2024-06-25,123.16,201060,18676.95
2024-06-26,124.38,191422,18745.34
2024-06-27,123.17,201982,18663.34
2024-06-28,124.71,294143,18530.83
2024-07-01,123.65,95944,18681.67
2024-07-02,121.9,290848,18702.96
2024-07-03,122.43,368648,18635.0
2024-07-04,121.37,163728,18720.1
2024-07-05,124.09,359299,18592.69
2024-07-08,127.27,335028,18606.63
2024-07-09,125.75,145237,18699.7
2024-07-10,124.91,124750,18724.8
2024-07-11,126.45,155715,18671.58
2024-07-12,126.5,398799,18776.62
2024-07-15,125.04,97410,18760.4
2024-07-16,126.88,243112,18626.75
2024-07-17,126.48,329182,18694.56
2024-07-18,127.26,281602,18621.12
2024-07-19,126.93,356657,18664.61
2024-07-22,130.17,148191,18684.73
2024-07-23,129.12,356349,18658.6
2024-07-24,131.05,362002,18592.86
2024-07-25,130.83,358068,18676.76
2024-07-26,129.05,182548,18672.78
2024-07-29,131.41,387150,18747.17
2024-07-30,133.1,329747,18750.97
2024-07-31,129.88,389683,18715.19
2024-08-01,133.07,301230,18614.48
2024-08-02,130.77,279543,18675.48
2024-08-05,132.84,292731,18580.15
2024-08-06,134.08,219846,18567.36
2024-08-07,136.76,358362,18664.31
2024-08-08,134.04,218235,18696.87
2024-08-09,133.33,396794,18569.18
2024-08-12,132.33,153842,18660.14
2024-08-13,135.65,168197,18581.47
2024-08-14,136.45,162859,18574.1
2024-08-15,136.61,90505,18706.24
2024-08-16,136.21,250638,18582.86
2024-08-19,137.86,314473,18643.5
2024-08-20,136.77,92964,18753.13
2024-08-21,137.67,175013,18581.98
2024-08-22,137.66,155675,18631.14
2024-08-23,139.13,101519,18572.94
2024-08-26,138.08,346079,18633.45
2024-08-27,137.39,140452,18734.53
2024-08-28,137.24,374267,18614.96
2024-08-29,137.51,114511,18645.17
2024-08-30,138.81,383277,18622.74
2024-09-02,139.06,353456,18634.75
2024-09-03,138.36,221849,18603.79
2024-09-04,138.49,372948,18603.8
2024-09-05,140.59,391023,18555.6
2024-09-06,137.88,316243,18614.46
2024-09-09,137.2,156658,18688.23
2024-09-10,138.37,146362,18539.08
2024-09-11,137.07,289496,18518.32
2024-09-12,137.18,395842,18608.94
2024-09-13,138.97,367294,18516.22
2024-09-16,136.7,157517,18644.73
2024-09-17,138.71,112784,18692.29
2024-09-18,137.94,299302,18557.56
2024-09-19,136.8,237611,18597.85
2024-09-20,136.93,260288,18575.86
2024-09-23,138.06,323489,18674.79
2024-09-24,134.13,287963,18612.11
2024-09-25,136.74,145289,18576.1
2024-09-26,137.8,172156,18644.97
2024-09-27,135.69,308196,18582.65
2024-09-30,137.99,291038,18616.77
2024-10-01,136.56,393692,18713.45
2024-10-02,135.67,158487,18589.44
2024-10-03,134.65,198373,18700.82
2024-10-04,136.62,174611,18629.0
2024-10-07,136.38,353118,18757.59
2024-10-08,136.47,233748,18656.13
2024-10-09,132.1,335374,18720.7
2024-10-10,134.81,359729,18737.58
2024-10-11,135.23,179589,18795.6
2024-10-14,138.68,302700,18771.66
2024-10-15,137.05,122338,18852.56
2024-10-16,134.82,216640,18818.32
2024-10-17,135.72,397718,18821.92
2024-10-18,137.54,100823,18785.84
2024-10-21,132.85,216749,18816.84
2024-10-22,138.14,131039,18857.76
2024-10-23,140.0,330033,18828.97
2024-10-24,138.27,399041,18772.88
2024-10-25,139.95,329874,18883.13
2024-10-28,135.24,315864,18821.89
2024-10-29,140.19,223241,18857.23
2024-10-30,139.97,213984,18939.65
2024-10-31,139.88,365485,18978.45
2024-11-01,142.73,330475,18947.33
2024-11-04,140.1,351217,18837.39
2024-11-05,142.1,182051,19027.85
2024-11-06,143.02,171371,18938.09
2024-11-07,142.93,279687,18945.55
2024-11-08,145.88,220513,19041.14
2024-11-11,143.49,273014,18989.25
2024-11-12,144.02,321315,19027.78
2024-11-13,146.25,172873,18948.93
2024-11-14,144.34,167623,18954.04
2024-11-15,145.38,170378,19135.54
2024-11-18,145.27,128445,18998.3
2024-11-19,144.78,196411,18888.75
2024-11-20,148.41,147810,19201.74
2024-11-21,147.69,105355,19056.87
2024-11-22,150.78,230988,19112.94
2024-11-25,149.51,331532,19043.48
2024-11-26,147.35,270590,19041.08
2024-11-27,147.8,281309,18999.24
2024-11-28,149.93,99115,19025.91
2024-11-29,148.05,202873,18922.67
2024-12-02,149.43,286135,19074.02
2024-12-03,151.78,396726,19070.15
2024-12-04,150.85,239171,19106.28
2024-12-05,150.07,375808,19107.05
2024-12-06,151.06,116356,19122.1
2024-12-09,152.31,266589,19169.31
2024-12-10,151.83,290880,19091.65
2024-12-11,151.77,91364,19069.65
2024-12-12,150.49,235108,19083.84
2024-12-13,152.71,115395,19098.47
2024-12-16,155.43,376169,19079.76
2024-12-17,153.36,374053,19189.06
2024-12-18,151.22,310495,19218.21
2024-12-19,151.34,322374,19109.27
2024-12-20,152.22,323904,19143.84
2024-12-23,152.59,175011,19183.69
2024-12-24,150.55,228434,19152.57
2024-12-25,152.02,238556,19194.7
2024-12-26,150.5,224049,19068.68
2024-12-27,149.41,104280,19060.74

Other Questions in Data Modeling & Visualization

See All Available Questions
Download