Olav, Kai and I used the Survey of Consumer Expectations for our Tech2 coursework. The notebook compares expectations across demographic groups and explores correlations with realised inflation.
The original notebook is rendered below with its saved outputs. Open a code cell to inspect it, or download the notebook.
Contents
Project overview
- Focus: Patterns and correlations in expectations across demographic groups
- Tools: Python, pandas, NumPy and Matplotlib
- Material: Original code, commentary and saved figures
The notebook contains data preparation, comparisons and figures. Its saved outputs are shown without rerunning the analysis.
Explore the notebook
Part 1 · Reading in Survey Data
Import monthly SCE CSV files, harmonize column names, and report baseline sample statistics.
1.1
In this section we import the necessary Python packages, and read in all SCE files and combine them into a single DataFrame
Python code
1import glob
2import matplotlib.pyplot as plt
3import numpy as np
4import pandas as pdPython code · In [2]
1# Pattern to match every SCE monthly CSV in the data folder
2pattern = "data/SCE-*.csv"
3
4# List that contains data frame
5data = []
6for file in glob.glob(pattern):
7 # Files use semicolons as separators, so we need sep=';'
8 d = pd.read_csv(file, sep=";")
9 data.append(d)
10
11# Stack all the csv files into one DataFrame and reset the index
12df = pd.concat(data, ignore_index=True)
13
14# Ensure the date column behaves like a datetime, then sort chronologically
15df["date"] = pd.to_datetime(df["date"])
16df = df.sort_values("date").reset_index(drop=True)1.2
The following is a report to understand the sample sizes of the Survey of Consumer Expectations (SCE)
Python code · In [3]
1def sample_stats(df):
2 """Print SCE panel statistics."""
3 # Functions to get statistics
4 n_individuals = df["userid"].nunique()
5 n_observations = len(df)
6 n_waves = df["wid"].nunique()
7 date_min = df["date"].min().date()
8 date_max = df["date"].max().date()
9
10 # Present the statistics in a compact block
11 format_length = 40
12 print("=" * format_length)
13 print("SCE Survey Data Summary".center(format_length))
14 print("=" * format_length)
15 print(f"Number of unique individuals: {n_individuals:,}".center(format_length))
16 print(f"Total observations (rows): {n_observations:,}".center(format_length))
17 print(f"Number of survey waves: {n_waves}".center(format_length))
18 print(f"The first date observed is: {date_min}".center(format_length))
19 print(f"The last date observed is: {date_max}".center(format_length))
20 print("=" * format_length)Python code · In [4]
1sample_stats(df)========================================
SCE Survey Data Summary
========================================
Number of unique individuals: 23,369
Total observations (rows): 176,101
Number of survey waves: 139
The first date observed is: 2013-06-01
The last date observed is: 2024-12-31
========================================
Part 2 · Data pre-processing
Dropping/filling missing observations and creating additional variables
2.1
Filling in the missing numeracy variables according to the values from the first observation
Python code · In [5]
1# Use list comprehention to collect every “num_lit_*_correct” column so we can work with the whole set at once
2numeracy_cols = [
3 col for col in df.columns if col.startswith("num_lit_") and col.endswith("correct")
4]
5
6# Within each respondent, forward/back-fill their numeracy answers to fill gaps
7df[numeracy_cols] = df.groupby("userid")[numeracy_cols].transform(
8 lambda s: s.ffill().bfill()
9)2.2
Dropping all observations with missing values for specific variables
Python code · In [6]
1# Defining the column groups in order to drop the missing values
2demographic_cols = ["female", "age", "educ"]
3expectations_cols = ["inflation", "house_price_change", "prob_stocks_up"]Python code · In [7]
1def drop_missing(df, cols):
2 """Drop rows that miss any column in 'cols' and report how many were dropped.
3
4 Parameters
5 ----------
6 df : pandas.DataFrame
7 Input table to clean.
8 cols : Iterable[str]
9 Column names that must be present (non-null) in each retained row.
10
11 Returns
12 -------
13 pandas.DataFrame
14 Filtered copy of `df` with required columns non-missing.
15 int
16 Count of rows removed by the filter.
17 """
18 observations_before_drop = len(df)
19 df_drop = df.dropna(subset=cols)
20 return df_drop, observations_before_drop - len(df_drop)Python code · In [8]
1# Define the column groups and their labels
2data_groups = {
3 "demographic": demographic_cols,
4 "expectation": expectations_cols,
5 "numeracy": numeracy_cols,
6}
7
8
9# Variables to help with formatting
10initial_rows = len(df)
11total_dropped = 0
12lines = []
13format_length = 66
14
15# Loop to drop missing values from each group
16for name, cols in data_groups.items():
17 df, dropped = drop_missing(df, cols)
18 total_dropped += dropped
19 lines.append(
20 f"Dropped {dropped:,} observations (rows) due to missing {name} data.".center(
21 format_length
22 )
23 )
24
25# Formatting and displaying all observations dropped at each step + total observations
26print("=" * format_length)
27print("Dropped Observations Summary".center(format_length))
28print("=" * format_length)
29print("\n".join(lines))
30print("-" * format_length)
31print(f"Total dropped observations: {total_dropped:,}".center(format_length))
32print(f"Remaining total observations: {len(df):,}".center(format_length))
33print("=" * format_length)==================================================================
Dropped Observations Summary
==================================================================
Dropped 868 observations (rows) due to missing demographic data.
Dropped 1,683 observations (rows) due to missing expectation data.
Dropped 35,974 observations (rows) due to missing numeracy data.
------------------------------------------------------------------
Total dropped observations: 38,525
Remaining total observations: 137,576
==================================================================
2.3
Dropping outliers with implausible small or large values
Python code · In [9]
1def drop_outliers(df, col, lower_q=0.001, upper_q=0.999):
2 """Trim extreme values in `col` by keeping only the quantile range [lower_q, upper_q].
3
4 Parameters
5 ----------
6 df : pandas.DataFrame
7 Source data.
8 col : str
9 Column name to filter.
10 lower_q : float, optional
11 Lower quantile cutoff (default 0.001).
12 upper_q : float, optional
13 Upper quantile cutoff (default 0.999).
14
15 Returns
16 -------
17 pandas.DataFrame
18 Copy of `df` with rows outside the quantile band removed.
19 """
20 # Compute quantile thresholds
21 low_thresh = df[col].quantile(lower_q)
22 high_thresh = df[col].quantile(upper_q)
23
24 # Create masks for outliers
25 below_mask = df[col] < low_thresh
26 above_mask = df[col] > high_thresh
27
28 # Variables to keep track of outliers
29 dropped_low = below_mask.sum()
30 dropped_high = above_mask.sum()
31
32 # Drop the outliers
33 clean_df = df[(df[col] >= low_thresh) & (df[col] <= high_thresh)].copy()
34 print(f"{col}:".center(format_length))
35 print(f"Dropped {dropped_low} rows below {low_thresh:.1f}%".center(format_length))
36 print(f"Dropped {dropped_high} rows above {high_thresh:.1f}%".center(format_length))
37 print(f"Remaining rows: {len(clean_df)}".center(format_length))
38 return clean_dfPython code · In [10]
1# Drop extreme values in each expectations series
2format_length = 30
3print("=" * format_length)
4print("Dropped Outliers Summary".center(format_length))
5print("=" * format_length)
6for col in expectations_cols:
7 df = drop_outliers(df, col)
8 print("=" * format_length)==============================
Dropped Outliers Summary
==============================
inflation:
Dropped 92 rows below -75.0%
Dropped 27 rows above 100.0%
Remaining rows: 137457
==============================
house_price_change:
Dropped 133 rows below -50.0%
Dropped 46 rows above 100.0%
Remaining rows: 137278
==============================
prob_stocks_up:
Dropped 0 rows below 0.0%
Dropped 0 rows above 100.0%
Remaining rows: 137278
==============================
2.4
New column ‘college’ that equals 1 if the respondent has a bachelor’s degree or higher and 0 otherwise
Python code · In [11]
1df["college"] = (df["educ"] == 4).astype(int)2.5
Summarizing the numeracy scores and defining new column ’num_lit_high’ for above-median performance.
Python code · In [12]
1# Reporting % of the sample of correct responses
2# For each individual compute the number of correct responses
3numeracy_by_person = df.groupby("userid", as_index=False)[numeracy_cols].first()
4numeracy_by_person["num_correct"] = numeracy_by_person[numeracy_cols].sum(axis=1)
5
6# Share of respondents at each score
7count_per_score = numeracy_by_person["num_correct"].value_counts().sort_index()
8share_per_score = (count_per_score / len(numeracy_by_person) * 100).round(2)
9
10# Flag anyone above the median number correct as "high numeracy"
11median_correct = numeracy_by_person["num_correct"].median()
12numeracy_by_person["num_lit_high"] = (
13 numeracy_by_person["num_correct"] > median_correct
14).astype(int)
15
16# Merge the high-numeracy indicator back to the data frame
17df = df.merge(numeracy_by_person[["userid", "num_lit_high"]], on="userid", how="left")
18
19# Print score distribution
20format_length = 35
21print("=" * format_length)
22print("Numerical Literacy Scores".center(format_length))
23print("=" * format_length)
24for score, pct in share_per_score.items():
25 print(f"{pct}% of individuals got {int(score)} correct".center(format_length))
26print("=" * format_length)===================================
Numerical Literacy Scores
===================================
0.14% of individuals got 0 correct
0.73% of individuals got 1 correct
2.4% of individuals got 2 correct
5.71% of individuals got 3 correct
10.51% of individuals got 4 correct
16.94% of individuals got 5 correct
27.41% of individuals got 6 correct
36.17% of individuals got 7 correct
===================================
2.6
The following is an updated report of the sample statistics for the Survey of Consumer Expectations (SCE)
Python code · In [13]
1sample_stats(df)========================================
SCE Survey Data Summary
========================================
Number of unique individuals: 17,701
Total observations (rows): 137,278
Number of survey waves: 117
The first date observed is: 2015-04-02
The last date observed is: 2024-12-31
========================================
Part 3 · Average expectations by group
Analysing the three different variables gender, college and numeracy individually
Python code · In [14]
1def compute_group_means(df, group_col, exp_cols):
2 """Compute average expectation values within each subgroup.
3
4 Parameters
5 ----------
6 df : pandas.DataFrame
7 Cleaned survey data.
8 group_col : str
9 Column name whose categories define the groups (e.g., 'female').
10 exp_cols : Iterable[str]
11 Expectation columns to average, such as ['inflation', 'prob_stocks_up'].
12
13 Returns
14 -------
15 pandas.DataFrame
16 One row per group with the mean of each expectation column.
17 """
18 # Collapse to group-level averages for the requested expectation columns
19 group_means = df.groupby(group_col)[exp_cols].mean().reset_index()
20 return group_means3.1
Computing the average expectations for inflation, house prices, stock market for each of the three variables
Average expectations for males vs. females
Python code · In [15]
1gender_means = compute_group_means(df, "female", expectations_cols)Average expectations for non-college vs. college
Python code · In [16]
1college_means = compute_group_means(df, "college", expectations_cols)Average expectations for low vs. high numeracy
Python code · In [17]
1num_means = compute_group_means(df, "num_lit_high", expectations_cols)3.2
Computing the average expectations for inflation, house prices, stock market for each of the three variables
Python code · In [18]
1def plot_group_bars(
2 group_means, group_labels, expectations_cols, title, colour1, colour2
3):
4 """Render side-by-side bar charts comparing expectations across two groups.
5
6 Parameters
7 ----------
8 group_means : pandas.DataFrame
9 Two-row table with one column per expectation metric.
10 group_labels : Sequence[str]
11 Display names for each group (order must match the rows in `group_means`).
12 expectations_cols : Sequence[str]
13 Expectation variables to plot, e.g. ['inflation', 'prob_stocks_up'].
14 title : str
15 Figure title describing the split (e.g., "Expectations by Gender").
16 colour1 : str
17 Colour for the first group’s bars (Matplotlib format).
18 colour2 : str
19 Colour for the second group’s bars (Matplotlib format).
20
21 Returns
22 -------
23 matplotlib.figure.Figure
24 Figure containing three bar charts (one per expectation variable).
25 """
26 fig, axes = plt.subplots(1, 3, figsize=(12, 4), sharey=False)
27 fig.suptitle(title, fontsize=14, fontweight="bold")
28 palette = [colour1, colour2]
29
30 # Compare the two group averages for this expectation metric
31 for i, col in enumerate(expectations_cols):
32 axes[i].bar(group_labels, group_means[col], color=palette, width=0.6)
33 axes[i].set_title(col.replace("_", " ").capitalize(), fontsize=12)
34 axes[i].set_ylabel("Average (%)")
35 axes[i].margins(y=0.10)
36
37 # Annotate bar heights for quick reading
38 ymax = max(group_means[col])
39 for idx, val in enumerate(group_means[col]):
40 axes[i].text(idx, val + ymax * 0.03, f"{val:.1f}", ha="center", fontsize=10)
41 plt.tight_layout()Average expectations by gender
Python code · In [19]
1plot_group_bars(
2 gender_means,
3 group_labels=["Male", "Female"],
4 expectations_cols=expectations_cols,
5 title="Average Expectations by Gender",
6 colour1="#4A1D14D4",
7 colour2="#DD4343",
8)The cleaned SCE data frame shows that the average expectations vary across gender. Males are overall more optimistic, expecting lower inflation and housing price change and higher probability that stocks go up.
Average expectations by education
Python code · In [20]
1plot_group_bars(
2 college_means,
3 group_labels=["Non-college", "College"],
4 expectations_cols=expectations_cols,
5 title="Average Expectations by Education Level",
6 colour1="#7EE411D4",
7 colour2="#226F15F9",
8)Overall, the chart focusing on education levels shows that less-educated households anticipate a higher inflation and stronger growth in house prices, while being more skeptical about stock-market performance. In contrast, college-educated respondents appear more moderate in their inflation and housing expectations but show greater optimism regarding the stock market.
Average expectations by numeracy
Python code · In [21]
1plot_group_bars(
2 num_means,
3 group_labels=["Low numeracy", "High numeracy"],
4 expectations_cols=expectations_cols,
5 title="Average Expectations by Numerical Literacy",
6 colour1="#1F7A8C",
7 colour2="#BFDBF7",
8)Respondents with below-median numerical literacy expect higher inflation and stronger growth in the housing market but expect a lower probability of stock prices increasing, compared to those with higher numerical literacy. This suggests that a higher numerical literacy is associated with more moderate price expectations and greater confidence in the stock market.
Conclusion
Overall, the three bar charts reveal that groups who tend to be more financially informed or advantaged (men, college-educated, and high-numerical literacy) expect a lower inflation and increase for house prices but are more optimistic about stock market gains. Whereas women, lower education, and low-numeracy respondents expect a higher inflation and house price changes but show less confidence in the stock market.
Part 4 · Expectation dynamics by group
Investigating how average expectations evolved over time for the period of 2015-2024
4.1
Monthly averages grouped by gender, college degree and literacy regarding inflation, house prices, stock market
Python code · In [22]
1def compute_monthly_expectations(
2 df, group_col, exp_cols, start="2015-01-01", end="2024-12-31"
3):
4 """Collapse to monthly averages for each expectation variable within group
5
6 Parameters
7 ----------
8 df : pandas.DataFrame
9 Cleaned, dated survey microdata.
10 group_col : str
11 Column used to split the sample (e.g., 'female', 'college').
12 exp_cols : Iterable[str]
13 Expectation variables to aggregate.
14 start : str or pandas.Timestamp, optional
15 end : str or pandas.Timestamp, optional
16
17 Returns
18 -------
19 pandas.DataFrame
20 Monthly averages with columns ['date', group_col, *exp_cols].
21 """
22 # Resample within each group to month-end means
23 monthly = (
24 df.set_index("date")
25 .groupby(group_col)[exp_cols]
26 .resample("ME")
27 .mean()
28 .reset_index()
29 )
30 mask = (monthly["date"] >= start) & (monthly["date"] <= end)
31 monthly = monthly.loc[mask].sort_values(["date", group_col]).reset_index(drop=True)
32 return monthly.dropna(subset=exp_cols)Python code · In [23]
1grouping_cols = ["female", "college", "num_lit_high"]
2
3monthly_expectations = {}
4for group_col in grouping_cols:
5 monthly_expectations[group_col] = compute_monthly_expectations(
6 df,
7 group_col,
8 expectations_cols,
9 )4.2
Figure that shows the monthly expectations of stocks increasing, changes in house prices, and inflation, differentiatet by gender, college, and numerical literacy.
Python code · In [24]
1# Plot monthly expectation time series by group (Task 4.2)
2def plot_group_timeseries(
3 monthly_data, group_col, expectation_cols, heading, colour1, colour2
4):
5 """Plot a 3×1 panel of average monthly expectations for a given grouping.
6
7 Parameters
8 ----------
9 monthly_data : pandas.DataFrame
10 Output from `compute_monthly_expectations`; must include `date`,
11 `group_col`, and all columns listed in `expectation_cols`.
12 group_col : str
13 Grouping variable whose categories define the separate lines (e.g., 'female').
14 expectation_cols : Sequence[str]
15 Expectation series to chart (e.g., ['inflation', 'house_price_change', 'prob_stocks_up']).
16 heading : str
17 Text appended to the figure title (e.g., 'Gender').
18 colour1 : str
19 Matplotlib-compatible colour for the first group.
20 colour2 : str
21 Matplotlib-compatible colour for the second group.
22
23 Returns
24 -------
25 matplotlib.figure.Figure
26 Figure containing the three time-series panels stacked vertically.
27 """
28 groups = sorted(monthly_data[group_col].dropna().unique())
29 labels = {
30 "female": {0: "Male", 1: "Female"},
31 "college": {0: "No College", 1: "College"},
32 "num_lit_high": {0: "Low Numeracy", 1: "High Numeracy"},
33 }.get(group_col, {})
34
35 fig, axes = plt.subplots(3, 1, sharex=False, figsize=(12, 9))
36 fig.suptitle(f"Monthly Expectations by {heading}", fontsize=14)
37 palette = {g: c for g, c in zip(groups, [colour1, colour2])}
38
39 # Plot each expectation series with one line per subgroup
40 for ax, column in zip(axes, expectation_cols):
41 for group in groups:
42 mask = monthly_data[group_col] == group
43 label = labels.get(group, str(group))
44 ax.plot(
45 monthly_data.loc[mask, "date"],
46 monthly_data.loc[mask, column],
47 label=label,
48 color=palette.get(group, colour1),
49 )
50 ax.set_ylabel(f"Average {column.replace('_', ' ').title()} (%)")
51 ax.legend()
52
53 events = {
54 "Trump elected (1st)": "2016-11-08",
55 "COVID-19 global": "2020-02-01",
56 "Biden elected": "2020-11-03",
57 "Ukraine invasion": "2022-02-24",
58 "Jon Fosse Nobel": "2023-10-03",
59 "Trump elected (2nd)": "2024-11-05",
60 }
61 # Annotate key events on every subplot
62 for ax in axes:
63 for label, date in events.items():
64 d = pd.to_datetime(date)
65 ax.axvline(d, color="gray", linestyle="--", linewidth=1, alpha=0.8)
66 ymin, ymax = ax.get_ylim()
67 ax.text(
68 d,
69 ymax * 0.98,
70 label,
71 rotation=90,
72 va="top",
73 ha="right",
74 fontsize=8,
75 color="gray",
76 )
77
78 axes[-1].set_xlabel("Date")
79 plt.tight_layout()
80 return figPython code · In [25]
1# Plot monthly expectations split by gender (Male vs Female)
2fig = plot_group_timeseries(
3 # pre-computed monthly averages for the gender split
4 monthly_expectations["female"],
5 "female",
6 expectations_cols,
7 "Gender",
8 "#4A1D14D4",
9 "#DD4343",
10)Several geopolitical and economic events appear to have significant changes on monthly expectations with differances between male and female.
Trump’s first election (Nov 2016): Both genders recorded an almost equally sharp increase in the expected average probability of stock prices rising. Since the reaction was similar across genders, it likely reflects optimism about market performance driven by expectations of pro-business policies, such as tax cuts and deregulation. Because it likely was driven by macroeconomic sentiment, it also explains why there was an equal jump across genders.
Covid-19 outbreak (Feb 2020): The pandemic led to a significant decline in the expected average housing price change across both genders, correlating with uncertainty and declining economic activity. At the same time, both males and females exhibited an equally sharp increase in the average expected probability that stock prices would rise. To mitigate the risk of a long-lasting economic decline, governments and central banks created fiscal and monetary stimulus packages, which helped lower the risk premia and increased the expected returns on equity. Another contributing factor was lower interest rates to stimulate the economy, which made equity more attractive compared to safe assets. In addition, there was a greater decrease in average expected inflation by females than by males, suggesting stronger short-term deflation concerns.
Biden’s election: Around Biden’s election, male respondents exhibited a decline in the expected average probability of increasing stock prices, possibly due to expectations of tightened regulations. However, the graph does not change for females, suggesting lower sensitivity to political change.
Full-scale invasion of Ukraine: Both men and women expected rises in inflation after the Ukraine invasion, with women anticipating a large spike.
Trump’s second election: Female inflation expectations became more volatile. Whereas male expectations represented a more stable curve with a slight rise. Suggesting a different view on future polices.
Summary: In summary, female inflation expectations appear more volatile, possibly being more reactive to household price pressures, such as groceries and rent. Whereas men’s expectations seem more anchored and long-term. In regards of housing-price expectations, there is almost no changes across gender, besides males beeing generally more optimistic. The same goes for expected stock prices.
Python code · In [26]
1# Plot the monthly expectations panels for education groups (non-college vs college)
2fig = plot_group_timeseries(
3 monthly_expectations["college"],
4 "college",
5 expectations_cols,
6 "Education Level",
7 "#7EE411D4",
8 "#226F15F9",
9)Geopolitical and economic events also shift monthly expectations for both college-educated and non-college groups.
Trump’s first election (Nov 2016): After Trump was elected, both groups expected a price increase in the stock-market. The reason for this can be interpreted in the same way as stated in the graph for Expectations by Gender. Although respondents with no bachelor’s degree showed a greater confidence, comperad to graduates. Respondents with no bachelor’s degree likely turned more optimistic about stocks after Trump’s win because they expected his pro-business agenda to boost industries and jobs they rely on, while college-educated respondents remained more cautious.
Covid-19 outbreak (Feb 2020): After COVID hit, both education groups reacted similar to the Expectations by Gender graph and reflects the same reasoning. They also expected a sharp drop in house prices, converging on almost the same decline. Later though the respondents with no bachelor’s degree peeled away and expected a larger increase in house prices unlike graduates. Expected inflation also diverged sharply. Graduates stayed roughly level, while non-graduates expected a much higher inflation once COVID’s impact became clear. This split, both for house prices and inflation, reflects tight supply and stimulus-fueled demand in the starter-home market.
Biden’s election: As the Democrats got back into office, expected growth for stocks and changes in house prices moved almost in parallel for both groups. Inflation expectations rose for both groups, yet non-graduates were noticeably more concerned with a higher inflation.
Full scale invasion of Ukraine: Similar to male and female expectations, both groups anticipate a rising inflation after the invasion and non-graduates expect a much higher inflation overall.
Trump’s second election: Expected inflation grew after Trump regained his presidency. Graduates expected this earlier than non-graduates.
Summary: Geopolitical shocks kept reshaping expectations, reset expectations for both education groups, but non-graduates swung harder. They embraced Trump’s pro-business agenda, braced more for inflation through COVID and Biden’s victory, and reacted more sharply to the Ukraine invasion and Trump’s return, while graduates stayed steadier.
Python code · In [27]
1# Plot monthly expectations for low- vs high-numeracy respondents
2fig = plot_group_timeseries(
3 monthly_expectations["num_lit_high"],
4 "num_lit_high",
5 expectations_cols,
6 "Numerical Literacy",
7 colour1="#1F7A8C",
8 colour2="#BFDBF7",
9)There are also Geopolitical and economic events that shift monthly expectations for both higher numerical literacy and below-median numerical literacy groups.
Although these fluctuations can be compared with the fluctuations within the Education level. The similarity likely comes from the strong overlap between the two groups. Many college graduates also fall into the high-numeracy category. As a result, changes linked to education tend to move the numeracy groups in the same direction.
For stocks, the numeracy gap widens more: High-numeracy respondents are generally more optimistic in their expectations than low-numeracy, even when the college gap shrinks. This indicates that high numeracy boosts confidence in stocks beyond what education alone explains.
Part 5
Compare monthly SCE inflation expectations with realized CPI inflation. Looking forward 12 months and backward 12 months to assess whether expectations anticipate future outcomes or if they are anchored in recent experience.
5.1 Realized future inflation
Compare the expectations to realized future inflation
Python code · In [28]
1# Load CPI data
2cpi = pd.read_csv("data/CPI.csv", parse_dates=["DATE"])
3# Align CPI timestamps with month-end to match survey aggregates
4cpi["DATE"] = cpi["DATE"] + pd.offsets.MonthEnd(0)
5# Keep date as the index for easier alignment
6cpi = cpi.set_index("DATE")5.1.1 Compute realized inflation
Using this monthly CPI data, computing the annual realized inflation over the next 12 months for each month
Python code · In [29]
1def compute_realized_inflation(cpi_df, months, column_name):
2 """
3 Calculate realized inflation over a forward or backward window.
4
5 Parameters
6 ----------
7 cpi_df : pandas.DataFrame
8 CPI series indexed by date with a `CPI` column.
9 months : int
10 Window length in months. Use positive values for forward-looking
11 inflation (t to t+months) and negative values for backward-looking
12 inflation (t-months to t).
13 column_name : str
14 Name for the resulting inflation column.
15
16 Returns
17 -------
18 pandas.DataFrame
19 Single-column DataFrame indexed by date containing the realized
20 inflation percentage for each month in the usable window.
21 """
22 if months > 0:
23 # Forward-looking: compare current CPI to the value months ahead
24 base = cpi_df["CPI"]
25 comparator = cpi_df["CPI"].shift(-months)
26 else:
27 # Backward-looking: compare CPI months ago to the current value
28 lag = abs(months)
29 base = cpi_df["CPI"].shift(lag)
30 comparator = cpi_df["CPI"]
31 rate = (comparator - base) / base * 100
32 return rate.dropna().to_frame(column_name)Python code · In [30]
1forward_inflation = compute_realized_inflation(
2 cpi,
3 months=12,
4 column_name="inflation_realized_forward_12m",
5)5.1.2 Merge Expected Inflation with Realized Inflation
Merge the gender-level expected inflation series with the CPI-based realized inflation so each month has both numbers side by side.
Python code · In [31]
1# compute monthly expectations for the entire period, not juust 2015-2024
2monthly_expectations_whole_period = compute_monthly_expectations(
3 df, "female", expectations_cols, start="2013-01-01", end="2024-12-31"
4)
5
6# Start from the gender-specific monthly averages and keep only the columns we need
7gender_expect = monthly_expectations_whole_period[
8 ["date", "female", "inflation"]
9].assign(gender=lambda s: s["female"].map({0: "Male", 1: "Female"}))
10
11# Pivot to place the two gender series in separate columns indexed by month
12gender_expect_pivot = gender_expect.pivot(
13 index="date", columns="gender", values="inflation"
14).rename(
15 columns={"Male": "expected_inflation_male", "Female": "expected_inflation_female"}
16)
17
18# Join expected inflation with realized forward inflation so each month has both measures
19gender_expect_vs_realized = gender_expect_pivot.join(forward_inflation, how="inner")5.1.3 Scatter Plot and Correlation
Ploting male and female expectations against realized forward inflation, and displaing each panel’s correlation so we can judge how correlated they are
Python code · In [32]
1def plot_expected_vs_realized_scatter(
2 data, expected_cols, realized_col, realized_label
3):
4 """
5 Plot expected vs. realized inflation for each group and return the figure.
6
7 Parameters
8 ----------
9 data : pandas.DataFrame
10 Table containing the expected and realized inflation series, indexed by date.
11 expected_cols : dict[str, str]
12 Mapping from display label (e.g., 'Male') to the column holding that group's
13 expected inflation.
14 realized_col : str
15 Column name with the realized inflation measure to plot on the y-axis.
16 realized_label : str
17 Human-readable label for the realized inflation axis (used in axis titles).
18
19 Returns
20 -------
21 matplotlib.figure.Figure
22 The figure object containing one scatter subplot per group.
23 """
24 fig, axes = plt.subplots(
25 1, len(expected_cols), sharex=True, sharey=True, figsize=(12, 5)
26 )
27 axes = np.atleast_1d(axes)
28
29 # Determine a common min/max so both axes use the same numeric range
30 bounds = []
31 for col in expected_cols.values():
32 subset = data[[col, realized_col]].dropna()
33 if subset.empty:
34 continue
35 bounds.append(subset.values.min())
36 bounds.append(subset.values.max())
37
38 lower = min(bounds)
39 upper = max(bounds)
40 pad = (upper - lower) * 0.05 or 0.5
41 lower -= pad
42 upper += pad
43
44 for ax, (label, expected_col) in zip(axes, expected_cols.items()):
45 subset = data[[expected_col, realized_col]].dropna()
46 ax.scatter(
47 subset[expected_col], subset[realized_col], alpha=0.8, edgecolor="none"
48 )
49 ax.set(
50 title=label,
51 xlabel="Expected inflation (%)",
52 ylabel=f"{realized_label} (%)",
53 xlim=(lower, upper),
54 ylim=(lower, upper),
55 )
56 ax.tick_params(labelleft=True)
57 ax.grid(True, linestyle="--", alpha=0.4)
58 ax.text(
59 0.04,
60 0.94,
61 rf"$\rho$ = {subset[expected_col].corr(subset[realized_col]):.2f}",
62 transform=ax.transAxes,
63 ha="left",
64 va="top",
65 fontsize=14,
66 bbox={"facecolor": "white", "alpha": 0.8, "edgecolor": "none"},
67 )
68
69 return figPython code · In [33]
1# Map the panel labels to the corresponding expected-inflation columns
2expected_cols = {
3 "Male": "expected_inflation_male",
4 "Female": "expected_inflation_female",
5}
6
7fig = plot_expected_vs_realized_scatter(
8 gender_expect_vs_realized,
9 expected_cols,
10 "inflation_realized_forward_12m",
11 "Realized forward inflation",
12)5.2 Merge with past realized inflation and compare correlations
Repeat steps from 5.1, but with past realized inflation
Python code · In [34]
1# Compute backward-looking (past 12 months) realized inflation from the CPI series
2past_inflation = compute_realized_inflation(
3 cpi,
4 months=-12,
5 column_name="inflation_realized_backward_12m",
6)
7
8# Align expected inflation with the past-realized series so each month has both values
9gender_expect_vs_past = gender_expect_pivot.join(past_inflation, how="inner")
10
11fig = plot_expected_vs_realized_scatter(
12 gender_expect_vs_past,
13 expected_cols,
14 "inflation_realized_backward_12m",
15 "Realized past inflation",
16)Evaluation of the scatter plots:
What the correlations show:
Forward-looking correlations (ρ=0.54 for men, 0.58 for women) are only moderate, whereas the backward-looking correlations increase to 0.80 and 0.82. This shows that future expectations are significantly anchored in recent inflation rather than accurately anticipating future inflation. In other words, instead of anticipating future inflation rationally, one instead extrapolates from past trends, adaptive rather than rational behaviour.
Gender comparison:
In both forward- and backward-looking correlations, the gender gap is negligible, supporting the idea of information sharing being equal among genders influenced by news, prices, etc. As discussed earlier, women tend to expect slightly higher inflation on average; however, the difference in correlation between expectations and realized inflation is insignificant. The male data hugs the 45° line (correlation line) a bit more closely, so their expectations sit nearer to realized forward inflation, though not a strong correlation. Both males and females are generally too pessimistic when predicting future inflation (they “fear” more inflation than what actually occurs) and therefore bias upwards to realized inflation.
Summary:
Overall, both groups exhibit adaptive expectations, and neither gender stands out as a significantly better forecaster. This indicates a general pessimistic bias in their inflation expectations.
AI statement and sources:
This term paper was written and coded by the group members. AI helped polish wording, formatting docstrings, comments and looking over the final product. We used the lectures and workshops in tech2 as sources.
[!NOTE] The outputs have been preserved so you can trace the intermediate calculations that shaped the final results.
Reading the analysis
This is exploratory coursework. Group comparisons and correlations do not establish that demographic characteristics or the named events caused the observed differences. Read the commentary alongside the code and source data. The notebook itself is preserved as the original working artifact.







