Pandas Time Series Analysis
Time series analysis is an important part of data analysis. Pandas provides rich features for processing and analyzing time series data, including resampling, rolling calculations, moving averages, and more.
Basic Time Series Operations
Create a Time Series
Example
import
pandas
as
pd
import
numpy
as
np
Create time series data
np.
random
.
seed
(
42
)
dates
=
pd.
date_range
(
"2024-01-01"
,
periods
=
100
,
freq
=
"D"
)
ts
=
pd.
Series
(
np.
random
.
randn
(
100
)
.
cumsum
(
)
100
,
index
=
dates
)
(
"Time series data (first 10 entries):"
)
(
ts.
head
(
10
)
)
(
)
View Information
(
f
"Index type: {type(ts.index)}"
)
(
f
"Start time: {ts.index.min()}"
)
(
f
"End time: {ts.index.max()}"
)
(
f
"Time span: {ts.index.max() - ts.index.min()}"
)
Set Dates as the Index
Example
import
pandas
as
pd
import
numpy
as
np
Create a DataFrame and Set the Date Index
df
=
pd.
DataFrame
(
{
"date"
: pd.
date_range
(
"2024-01-01"
,
periods
=
30
,
freq
=
"D"
)
,
"Sales"
: np.
random
.
randint
(
100
,
500
,
30
)
,
"Number of visitors"
: np.
random
.
randint
(
50
,
200
,
30
)
}
)
(
"Before setting:"
)
(
df.
head
(
)
)
(
)
Set Dates as the Index
df
=
df.
set_index
(
"date"
)
(
"After setting:"
)
(
df.
head
(
)
)
(
)
Query by Date Using loc
(
"Query from 2024-01-05 to 2024-01-10:"
)
(
df.
loc
[
"2024-01-05"
:
"2024-01-10"
]
)
Resampling
Resampling is the process of converting time series data from one frequency to another, including upsampling (increasing data points) and downsampling (decreasing data points).
Downsampling
Example
import
pandas
as
pd
import
numpy
as
np
Create daily data
np.
random
.
seed
(
42
)
dates
=
pd.
date_range
(
"2024-01-01"
,
periods
=
90
,
freq
=
"D"
)
ts
=
pd.
Series
(
np.
random
.
randint
(
100
,
500
,
90
)
,
index
=
dates
)
(
"Daily data (first 10 entries):"
)
(
ts.
head
(
10
)
)
(
)
Resample by month (sum)
monthly
=
ts.
resample
(
"M"
)
.
sum
(
)
(
"Monthly sum:"
)
(
monthly
)
(
)
Resample by month (mean)
monthly_mean
=
ts.
resample
(
"M"
)
.
mean
(
)
(
"Monthly mean:"
)
(
monthly_mean
)
Upsampling
Example
import
pandas
as
pd
Create low-frequency data
dates
=
pd.
date_range
(
"2024-01-01"
,
periods
=
3
,
freq
=
"M"
)
ts
=
pd.
Series
(
[
100
,
200
,
150
]
,
index
=
dates
)
(
"Monthly data:"
)
(
ts
)
(
)
Upsample to daily (requires a fill method)
ts_daily
=
ts.
resample
(
"D"
)
.
ffill
(
)
(
"Upsampled to daily (first 10 entries):"
)
(
ts_daily.
head
(
10
)
)
Common Resampling Methods
| Method | Description |
|---|---|
sum() |
Sum |
mean() |
Mean |
max() / min() |
Max/Min Value |
first() / last() |
First/Last Value |
count() |
Number of non-null values |
ohlc() |
Open, High, Low, Close |
Rolling Calculations
Rolling calculations apply a sliding window computation to time series data, commonly used to compute moving averages, moving standard deviations, etc.
Moving Average
Example
import
pandas
as
pd
import
numpy
as
np
Create data
np.
random
.
seed
(
42
)
dates
=
pd.
date_range
(
"2024-01-01"
,
periods
=
30
,
freq
=
"D"
)
ts
=
pd.
Series
(
np.
random
.
randint
(
100
,
200
,
30
)
,
index
=
dates
)
Calculate the 7-day moving average
rolling_mean
=
ts.
rolling
(
window
=
7
)
.
mean
(
)
(
"7-day moving average (first 10 entries):"
)
(
rolling_mean.
head
(
10
)
)
(
)
Calculate the 7-day moving standard deviation
rolling_std
=
ts.
rolling
(
window
=
7
)
.
std
(
)
(
"7-day moving standard deviation:"
)
(
rolling_std.
head
(
10
)
)
Apply Custom Functions with Rolling
Example
import
pandas
as
pd
import
numpy
as
np
ts
=
pd.
Series
(
range
(
1
,
11
)
)
(
"Original data:"
)
(
ts
)
(
)
Rolling sum
(
"Rolling sum over 3:"
)
(
ts.
rolling
(
3
)
.
sum
(
)
)
(
)
Rolling Maximum
(
"Rolling max over 3:"
)
(
ts.
rolling
(
3
)
.
max
(
)
)
(
)
Using apply
(
"Rolling custom function over 3 (range):"
)
(
ts.
rolling
(
3
)
.
apply
(
lambda
x: x.
max
(
)
- x.
min
(
)
)
)
Time Series Data Visualization
Example
import
pandas
as
pd
import
numpy
as
np
Create sample data
np.
random
.
seed
(
42
)
dates
=
pd.
date_range
(
"2024-01-01"
,
periods
=
100
,
freq
=
"D"
)
ts
=
pd.
Series
(
np.
random
.
randn
(
100
)
.
cumsum
(
)
100
,
index
=
dates
)
Compute the moving averages
ma_7
=
ts.
rolling
(
7
)
.
mean
(
)
ma_30
=
ts.
rolling
(
30
)
.
mean
(
)
Display Data
(
"Time series + moving average:"
)
(
f
"Original data (first 5): {ts.head().tolist()}"
)
(
f
"7-day MA (first 10): {ma_7.dropna().head().tolist()}"
)
(
f
"30-day MA (last 5): {ma_30.dropna().tail().tolist()}"
)
Time Series Feature Extraction
Example
import
pandas
as
pd
Create a Time Series
ts
=
pd.
Series
(
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
]
,
index
=
pd.
date_range
(
"2024-01-01"
,
periods
=
10
,
freq
=
"D"
)
)
Differencing
diff
=
ts.
diff
(
)
(
"First-order difference:"
)
(
diff
)
(
)
Percentage Change
pct
=
ts.
pct_change
(
)
(
"Percentage change:"
)
(
pct
)
(
)
Shift
shifted
=
ts.
shift
(
1
)
(
"Shift back by 1:"
)
(
shifted
)
Practical: Stock Data Analysis
Example
import
pandas
as
pd
import
numpy
as
np
Simulate Stock Data
np.
random
.
seed
(
42
)
n_days
=
60
df
=
pd.
DataFrame
(
{
"date"
: pd.
date_range
(
"2024-01-01"
,
periods
=
n_days
,
freq
=
"D"
)
,
"Open"
:
100
- np.
random
.
randn
(
n_days
)
.
cumsum
(
)
,
"Closing price"
:
100
- np.
random
.
randn
(
n_days
)
.
cumsum
(
)
,
"Volume"
: np.
random
.
randint
(
1000000
,
10000000
,
n_days
)
}
)
df
=
df.
set_index
(
"date"
)
Compute the daily returns
df
[
"Returns"
]
=
df
[
"Closing price"
]
.
pct_change
(
)
Calculate Volatility (7-Day Rolling Standard Deviation)
df
[
"Volatility"
]
=
df
[
"Returns"
]
.
rolling
(
7
)
.
std
(
)
- np.
sqrt
(
252
)
Annualize
Calculate Moving Averages
df
[
"MA5"
]
=
df
[
"Closing price"
]
.
rolling
(
5
)
.
mean
(
)
df
[
"MA20"
]
=
df
[
"Closing price"
]
.
rolling
(
20
)
.
mean
(
)
Generate Trading Signals (Golden Cross / Death Cross)
df
[
"Signal"
]
=
0
df.
loc
[
df
[
"MA5"
]
df
[
"MA20"
]
,
"Signal"
]
=
1
df.
loc
[
df
[
"MA5"
]
<
df
[
"MA20"
]
,
"Signal"
]
=
1
print
("Stock Data Analysis Results:"
)
(
df.
tail
(
10
)
)
Common questions
1. Non-Continuous Dates
Some time series do not have data every day (holidays, etc.), so you need to use asfreq or reindex to handle them.
2. Time Zone Issues
When handling cross-time-zone data, use tz_localize and tz_convert to set and convert time zones.
3. Impact of Missing Values
Rolling calculations skip missing values by default, but this may affect the continuity of the results.
Time series analysis is a fundamental skill in fields such as finance, meteorology, and IoT; Pandas provides a complete toolchain for processing such data.