Lesson 46 · Finance and Stock Market Analytics
Introduction to Time Series in Finance: Key Concepts and Applications
In this lesson, we will explore the basics of financial time series and their applications in analyzing the stock market. You will learn to import real…
- CourseFinance and Stock Market Analytics
- Lesson46 of 16
- Video23 min
- FormatJupyter notebook · 18 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbIntroduction to Time Series in Finance#
- In this lesson, we will explore the basics of financial time series and their applications in analyzing the stock market.
- You will learn to import real stock price data, inspect its structure, and perform key time series analyses using Python.
- Time series analysis is essential for understanding the behavior of markets over time, evaluating risk, and creating trading strategies.
- We will move from basic data exploration to advanced analytics and solve a hands-on finance problem step by step.
- By the end, you will know how to manipulate, visualize, and extract insights from real financial time series data.
import pandas as pd
import numpy as np
import yfinance as yf
import warnings
warnings.filterwarnings('ignore')
Understanding Financial Time Series Data#
- A time series is a sequence of data points recorded at regular time intervals.
- In finance, time series often capture daily stock prices, trading volume, or returns.
- Each row typically represents the value of a financial metric (like close price) for a specific date.
- Data can be organized in 'long' format (one row per date and ticker) or 'wide' format (one column per ticker).
- Beginners often struggle with converting between these formats and handling missing data.
# Beginner Example 1: Load stock prices for multiple tickers
tickers = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA']
df = yf.download(tickers, period='1y', auto_adjust=True, progress=False)
df = df['Close'].reset_index()
df.columns.name = None
print(df.shape)
print(df.head(3))
# Beginner Example 2: Load daily returns for the SPY ETF
data = yf.download('SPY', period='2y', auto_adjust=True, progress=False)
spy_df = data[['Close','Volume']].reset_index()
spy_df.columns = ['date','price','volume']
spy_df['daily_return'] = (spy_df['price'].pct_change() * 100).round(4)
spy_df = spy_df.dropna().reset_index(drop=True)
print(spy_df.shape)
print(spy_df.head(3))
# Beginner Example 3: Load multi-ticker OHLCV data in long format
tickers = ['AAPL','MSFT','GOOGL','AMZN','TSLA']
ohlcv = yf.download(tickers, period='1y', auto_adjust=True, progress=False)
ohlcv = ohlcv.stack(future_stack=True).rename_axis(['Date','Ticker']).reset_index()
ohlcv.columns.name = None
print(ohlcv.shape)
print(ohlcv.head(3))
# Beginner Example 4: Select pricing data for a single ticker from long format
aapl_prices = ohlcv[ohlcv['Ticker'] == 'AAPL']
print(aapl_prices.shape)
print(aapl_prices.head(3))
# Beginner Example 5: Convert long to wide format for close prices
wide_prices = ohlcv.pivot(index='Date', columns='Ticker', values='Close')
print(wide_prices.shape)
print(wide_prices.head(3))
# Intermediate Example 1: Plot the closing prices of all five stocks
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
for tkr in tickers:
plt.plot(wide_prices.index, wide_prices[tkr], label=tkr)
plt.title('Close Prices of Major Tech Stocks (1Y)')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.show()
# Intermediate Example 2: Compute daily returns for all tickers (wide format)
returns = wide_prices.pct_change().dropna() * 100
returns = returns.round(2)
print(returns.head(3))
# Intermediate Example 3: Compute rolling 20-day volatility (standard deviation)
vol_20d = returns.rolling(window=20).std().round(2)
print(vol_20d.tail(3))
# Intermediate Example 4: Correlation between the daily returns of stocks
corr_matrix = returns.corr()
print(corr_matrix)
# Intermediate Example 5: Detect missing data and handle it
print(ohlcv.isnull().sum())
ohlcv_clean = ohlcv.dropna()
print('Data after dropping missing rows:', ohlcv_clean.shape)
# Advanced Example 1: Resample daily returns to monthly returns
monthly_returns = wide_prices.resample('M').last().pct_change().dropna() * 100
monthly_returns = monthly_returns.round(2)
print(monthly_returns.head(3))
# Advanced Example 2: Compute 50-day moving averages as a trend indicator
ma_50 = wide_prices.rolling(window=50).mean()
print(ma_50.tail(3))
# Advanced Example 3: Find the best/worst single-day return for each ticker
best_returns = returns.max()
worst_returns = returns.min()
print('Best single-day returns (%):')
print(best_returns)
print('Worst single-day returns (%):')
print(worst_returns)
# Advanced Example 4: Create trading signals using SMA crossover for AAPL
data = yf.download('AAPL', period='1y', auto_adjust=True, progress=False)
df_sma = data[['Close','Volume']].reset_index()
df_sma.columns = ['date','close','volume']
df_sma['sma20'] = df_sma['close'].rolling(20).mean().round(2)
df_sma['sma50'] = df_sma['close'].rolling(50).mean().round(2)
df_sma['signal'] = np.where(df_sma['sma20'] > df_sma['sma50'], 1, -1)
print(df_sma.tail(3))
# Error Example: Wrong column name in resample
try:
_ = spy_df.resample('M').last()['close']
except Exception as e:
print('Error:', e)
# Error Example: Handling NA values by forward filling
aapl_prices_ffill = aapl_prices.fillna(method='ffill')
print(aapl_prices_ffill.isnull().sum())
Best Practices for Financial Time Series#
- Always check for missing values before any calculation.
- Plot time series data frequently to catch outliers and errors.
- Use long format for flexible filtering and grouping; use wide format for correlation and comparison.
- Set a seed for reproducibility in simulations: np.random.seed(42).
- Remember to handle time zones and market holidays carefully.
# End-to-end Problem: Identify the highest single-day loss for TSLA in the past year and plot it
np.random.seed(42) # for reproducibility
tsla_prices = ohlcv[ohlcv['Ticker'] == 'TSLA'].copy()
tsla_prices['Return'] = tsla_prices['Close'].pct_change() * 100
worst_day = tsla_prices['Return'].idxmin()
print('Worst day for TSLA:', tsla_prices.loc[worst_day, 'Date'], 'Return:', round(tsla_prices.loc[worst_day, 'Return'],2), '%')
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 5))
plt.plot(tsla_prices['Date'], tsla_prices['Close'], label='TSLA Close')
plt.scatter(tsla_prices.loc[worst_day, 'Date'], tsla_prices.loc[worst_day, 'Close'], color='red', label='Worst Day')
plt.title('TSLA Closing Prices with Worst Single-Day Loss Highlighted')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.show()
YouTube#
- Learn more market analytics tips by checking out our channel!
- Subscribe for the latest finance coding tutorials!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



