02 Representation Learning: Extracting Core Insights from High-Dimensional Data

90-Minute Main Lesson: From Scale to PCA Evidence

  • Objectives: Diagnose scale and missingness; calculate a two-dimensional PCA by hand; interpret variance ratios and loadings; distinguish PCA, LDA, and exploratory nonlinear embeddings.

  • learning path:

    • prerequisites and preprocessing 15 min → PCA intuition, calculation, and derivation 30 min → LDA comparison and check 15 min → Yangtze Delta main case 25 min → synthesis 5 min.

    • MDS, manifold learning, and sparse representation are extensions.

  • Answer first: If variable A has 100 times the standard deviation of B, what happens when PCA uses the raw covariance matrix?

  • Feedback: A may dominate PC1 only because of units. Unless units carry intended economic meaning, fit the scaler on training data only.

Welcome to Chapter 2: Representation Learning

Today’s Agenda:

  1. Introduction: Why do Economics and Finance need ‘dimensionality reduction’?
  2. Data Preprocessing: The cornerstone of success
  3. Part 1: Linear Methods (PCA, LDA, MDS)
  4. Part 2: Nonlinear Manifold Learning (Isomap, LLE, t-SNE)
  5. Part 3: Advanced Topics (Sparse Representation)
  6. Conclusion: How to choose the right tool for your problem

Core Question: Why Study ‘Dimensionality Reduction’ in Economics?

Imagine we want to predict a company’s stock return. How many variables might we have?

  • Firm-Level Data: Hundreds of financial ratios (P/E, ROA, leverage…)
  • Market Data: Historical prices, trading volumes, volatility…
  • Macroeconomic Data: GDP, interest rates, inflation, unemployment…
  • Alternative Data: Satellite imagery, news sentiment, supply chain info…

We can easily end up with a dataset of hundreds or even thousands of dimensions.

We Face a ‘Data-Rich, Insight-Poor’ Dilemma

The explosive growth in data volume does not directly translate to an increase in insight. The goal of representation learning is to extract the signal from the noise.

From High-Dimensional Chaos to Low-Dimensional Clarity A diagram showing noisy high-dimensional data being processed by representation learning to reveal clear, low-dimensional insights. The Curse of Dimensionality High-D: noisy and redundant Representation learning Low-D: clear and actionable

This is the so-called ‘Curse of Dimensionality’.

What is the ‘Curse of Dimensionality’?

As dimensionality d increases, a fixed sample becomes progressively sparser. Maintaining the same grid resolution can require exponentially many cells or samples; whether distances concentrate still depends on the distribution, metric, and scaling.

Curse of Dimensionality A three-panel diagram showing six data points becoming sparser as the dimension increases from 1D to 2D to 3D. Curse of Dimensionality 1D Space Dense 2D Space Sparse 3D Space Very sparse

The Curse of Dimensionality is an Enemy of Modeling and Analysis

When data dimensionality d is too high, a series of serious problems arise:

Problem Category Specific Manifestation Impact on Economic Research
Computational Efficiency Grid search or exhaustive state counts can grow exponentially; many specific algorithms remain polynomial-time Separate sample requirements and search-space growth from the complexity of the implemented algorithm.
Data Sparsity A fixed number of samples becomes very sparse Samples are not representative; hard to find significant relationships.
Model Overfitting The model learns noise, not the true pattern Perfect in-sample performance, but poor out-of-sample (predictive) power.
Multicollinearity Many features are highly correlated Difficult to identify the true impact of individual variables; unstable parameter estimates.

Representation learning (or dimensionality reduction) is the key to solving this problem.

The Goal of Representation Learning: Simplify with Minimal Information Loss

Our goal is to map a high-dimensional sample set \(X \in \mathbb{R}^{d \times N}\) to a low-dimensional space \(Z \in \mathbb{R}^{l \times N}\), where \(l \ll d\).

\[ \large{ \underbrace{ \begin{pmatrix} z_{1,n} \\ \vdots \\ z_{l,n} \end{pmatrix} }_{Z_n \in \mathbb{R}^{l \times 1}} = \underbrace{ \begin{pmatrix} w_{1,1} & \cdots & w_{1,d} \\ \vdots & \ddots & \vdots \\ w_{l,1} & \cdots & w_{l,d} \end{pmatrix} }_{W^T \in \mathbb{R}^{l \times d}} \underbrace{ \begin{pmatrix} x_{1,n} \\ \vdots \\ x_{d,n} \end{pmatrix} }_{X_n \in \mathbb{R}^{d \times 1}} } \]

Core Requirement

The new representation \(Z\) must preserve the most important ‘structure’ or ‘information’ from the original data \(X\). Different algorithms define ‘structure’ differently, leading to various reduction methods.

Before We Begin: Preprocessing is the Foundation of Success

Before applying any complex dimensionality reduction algorithm, we must clean the raw data. This is like laying the foundation before building a house.

Data Preprocessing Steps A three-step flowchart: Raw Data -> Clean & Impute -> Standardize -> Ready Data. Raw dataOutliersMixed scales 1. Clean& imputeOutliersNaNs 2. RescaleOne scale Ready

Preprocessing Issue 1: Outliers

Extreme values can severely distort a model’s variance calculation (e.g., in PCA), pulling it towards the direction of the outlier.

Effect of Outliers on PCA A two-panel diagram showing that an outlier skews the direction of the first principal component (PC1). Effect of Outliers on Principal Component Analysis (PCA) No Outliers PC1 (Direction of Max Variance) With Outliers Outlier Skewed PC1

Common Treatments: Winsorization, log transformation, or direct removal.

Preprocessing Issue 2: Missing Data

Most algorithms cannot handle missing values (NaN).

  • Common Strategies:
    1. Deletion: If the missing proportion is small, delete the row or column.
    2. Imputation: Fill with the mean, median, or more complex models (like K-Nearest Neighbors).

Preprocessing Issue 3: Inconsistent Scales

If ‘Market Cap’ (trillions) and ‘P/E Ratio’ (tens) are analyzed together, market cap will completely dominate the results.

  • Solution: Feature Scaling. The most common is Standardization, which transforms data to have a mean of 0 and a variance of 1.
  • Formula: \(x'_{i} = \large{\frac{x_i - \mu_i}{\sigma_i}}\)

Part 1: Linear Dimensionality Reduction Methods

Principal Component Analysis (PCA): Finding the Directions of Maximum Variance

PCA is the most classic and commonly used linear dimensionality reduction method.

  • Core Idea: Rotate the coordinate system so that the new axes (principal components) explain the maximum possible variance in the data.
  • Goal: Preserve the largest sample variance; this does not automatically preserve information most relevant to prediction, causal identification, or economic interpretation.

PCA Geometry: PC1 Follows the Maximum-Variance Direction

Principal Component Analysis Intuition A scatter plot showing PC1 aligned with the maximum variance direction. PC1: maximum variance PC2

PCA’s Objective Function: Maximizing Projected Variance

PCA seeks a projection direction (a unit vector \(w\)) that maximizes the variance of the projected data.

  • One-direction projection: Under the feature-by-sample convention \(X\in\mathbb{R}^{d\times N}\), \(\mathbf z=X^T\mathbf w\in\mathbb{R}^{N}\).
  • Projected variance: \(\operatorname{Var}(\mathbf z)=\mathbf w^T S\mathbf w\), where \(S=XX^T/N\in\mathbb{R}^{d\times d}\) is the covariance matrix of centered data.

The optimization problem is:

\[ \large{\max_{w} \quad w^T S w} \]

\[ \large{\text{s.t.} \quad w^T w = 1} \]

PCA’s Derivation: The Lagrangian

We use the method of Lagrange multipliers to solve this constrained optimization problem.

  1. Formulate the Lagrangian: The goal is to maximize \(w^T S w\) subject to the constraint that \(w\) is a unit vector, i.e., \(w^T w = 1\).

    \[ \large{L(w, \lambda) = w^T S w - \lambda(w^T w - 1)} \]

PCA’s Derivation: The First-Order Condition

  1. Take the derivative with respect to \(w\) and set it to zero: This finds the critical points of the Lagrangian function.

    \[ \large{\frac{\partial L}{\partial w} = 2Sw - 2\lambda w = 0} \]

PCA’s Derivation: A Classic Eigenvalue Problem

  1. Rearrange to get the final form: This reveals the core mathematical identity of PCA.

    \[ \large{Sw = \lambda w} \]

Conclusion

  • The optimal projection directions (the principal components) \(w\) are the eigenvectors of the covariance matrix \(S\).

  • The corresponding variance explained by each component is its eigenvalue \(\lambda\).

  • The eigenvector with the largest eigenvalue is the first principal component.

PCA as a Five-Step Workflow

This translates the abstract mathematical theory into a clear operational workflow.

PCA Algorithm Steps A five-step flowchart: standardize data, compute the covariance matrix, find eigenvalues and eigenvectors, select the leading components, and transform the data. 1. Standardizethe data 2. Computecovariancematrix S 3. Findeigenvalues &eigenvectors 4. Keep top ℓcomponents 5. Project dataZ = WᵀX

PCA by Hand: Predict the Principal Direction

Consider \(\mathbf{x}_1=(2,1)^\top\), \(\mathbf{x}_2=(0,0)^\top\), and \(\mathbf{x}_3=(-2,-1)^\top\).

  1. Compute the mean \(\bar{\mathbf{x}}\) and sample covariance \(\mathbf{S}\).
  2. Compare unit directions \(\mathbf{v}_1=(2,1)^\top/\sqrt5\) and \(\mathbf{v}_2=(-1,2)^\top/\sqrt5\).
  3. Compute the sample variance of \(z_i=\mathbf{v}^\top(\mathbf{x}_i-\bar{\mathbf{x}})\).

Predict first: Which direction retains more variance? Finish the calculation before opening the solution slide.

PCA by Hand: Step-by-Step Solution

The mean is \(\bar{\mathbf{x}}=(0,0)^\top\). Using \(n-1=2\):

\[ \large{\mathbf{S}=\frac{1}{2}\sum_{i=1}^{3}\mathbf{x}_i\mathbf{x}_i^\top=\begin{bmatrix}4&2\\2&1\end{bmatrix}} \]

  • Along \(\mathbf{v}_1\): \(z=(\sqrt5,0,-\sqrt5)\) and \(s_z^2=(5+0+5)/2=5\).
  • Along \(\mathbf{v}_2\): \(z=(0,0,0)\) and \(s_z^2=0\).
  • Check: \(\mathbf{S}\mathbf{v}_1=5\mathbf{v}_1\) and \(\mathbf{S}\mathbf{v}_2=0\mathbf{v}_2\).

Thus PC1 is \(\mathbf{v}_1\) and explains \(5/(5+0)=100\%\) of variance. It also retains more variation than the raw horizontal direction, whose projected variance is \(4\).

Linear Discriminant Analysis (LDA): Reduction for Classification

  • LDA is a supervised learning algorithm for dimensionality reduction.

  • Unlike PCA, which seeks maximum variance, LDA’s goal is to find a projection direction that maximizes the separation between different classes while minimizing the variance within each class.

LDA Objective LDA aims to maximize between-class distance and minimize within-class distance. Maximize between-class distance Minimize within-class distance

LDA’s Objective: The Within-Class Scatter Matrix

  • Within-class Scatter Matrix (\(S_w\)): Measures the scatter of data points within each class.
    • \(S_w = \sum_{c=1}^{C} \sum_{x_i \in c} (x_i - \mu_c)(x_i - \mu_c)^T\)
    • We want to minimize this. It represents how compact each class is.

LDA’s Objective: The Between-Class Scatter Matrix

  • Between-class Scatter Matrix (\(S_b\)): Measures the scatter of the class means around the overall mean.
    • \(S_b = \sum_{c=1}^{C} N_c (\mu_c - \mu)(\mu_c - \mu)^T\)
    • We want to maximize this. It represents how far apart the classes are from each other.

LDA’s Objective Function: Maximizing the Ratio

For one direction \(w\), Fisher’s criterion is a generalized Rayleigh quotient. For a multidimensional projection, take leading generalized eigen-directions; equivalently, maximize projected between-class scatter under an \(S_w\)-orthonormality constraint:

\[ \begin{aligned} J(w)&=\frac{w^T S_b w}{w^T S_w w},\\ \max_W\;&\operatorname{tr}(W^T S_b W) \quad\text{s.t.}\quad W^T S_w W=I. \end{aligned} \]

If \(S_w\) is singular, use regularization or a generalized-eigenvalue/SVD solver rather than a literal inverse.

PCA: Maximum Variance Can Preserve Class Overlap

PCA: maximizes overall variance; here the horizontal PC1 still leaves substantial class overlap.

PCA Projection PCA projects data along the axis of maximum variance, resulting in poor separation of the two classes. PC1

LDA: Supervision Rotates the Projection Toward Separation

LDA improves between-class relative to within-class scatter, helping separation without guaranteeing perfection.

LDA Projection LDA projects data along an axis that best separates the classes, leading to clear distinction. LD1

Solving LDA: A Generalized Eigenvalue Problem

Maximizing the ratio \(J(W)\) can be transformed into solving a generalized eigenvalue problem:

\[ \large{S_b w = \lambda S_w w} \]

Multiplying both sides by \(S_w^{-1}\), we get a more familiar form:

\[ \large{S_w^{-1} S_b w = \lambda w} \]

Conclusion

The optimal projection directions \(w\) for LDA are the eigenvectors of the matrix \(S_w^{-1} S_b\).

Multidimensional Scaling (MDS): Reconstructing a ‘Map’ from Distances

Optional topic: after the PCA/LDA comparison, Core goes directly to the Yangtze Delta main case. MDS and the following nonlinear/sparse methods form a returnable extension branch.

MDS has a completely different starting point from PCA and LDA. It doesn’t work with the feature matrix \(X\) directly but starts from a known distance (or dissimilarity) matrix \(D\).

  • Core Idea: Find a set of points \(Z\) in a low-dimensional space such that the Euclidean distances between these points are as close as possible to the original distance matrix \(D\).
  • Use Case: When we don’t have the original features but can measure the dissimilarity between objects. For example, survey data on ‘brand similarity’ or the ‘edit distance’ between genetic sequences.

MDS Analogy: Reconstructing a City Map

Imagine you only know the straight-line flight distances between major cities, but you have no latitude or longitude information.

MDS Analogy with Cities An illustration showing the concept of reconstructing a map of cities from a distance matrix using MDS. Input: Distance Matrix (km) City A City B City A City B 0 1080 1080 0 MDS Output: 2D Coordinates (Map) City A City B City C

The goal of MDS is to find the optimal 2D coordinates for each city based on this distance matrix.

Part 2: Nonlinear Dimensionality Reduction (Manifold Learning)

The Limitation of Linear Methods: When Data Structure is Curved

Linear methods like PCA and LDA assume that the data lies on a flat hyperplane. But what if the data’s intrinsic structure is curved?

PCA Failure on Swiss Roll Manifold A diagram showing that linear PCA projection incorrectly maps distant points on a curved manifold close together in the 2D space. 1. Curved manifold A B Far along the manifold Linear PCA 2. PCA projection A′ B′ A′ ≈ B′ after PCA Misleading shortcut

A linear method like PCA would incorrectly project distant points (like A and B) close together, failing to ‘unroll’ the data.

The Core Idea of Manifold Learning: Data Lives on a Low-Dimensional Manifold

  • Manifold Hypothesis: The high-dimensional data we observe is actually generated by a few latent variables (the intrinsic dimension), and these data points lie on a low-dimensional manifold embedded in the high-dimensional space.
  • Goal: To ‘unroll’ this manifold and find low-dimensional coordinates that reflect the true neighborhood relationships of the data.
  • Difference from Linear Methods: Manifold learning focuses on local structure, assuming that Euclidean distances are only reliable between nearby points.

Isomap: Measuring Distance Along the ‘Surface’

Isomap is a clever extension of MDS that replaces Euclidean distance with Geodesic Distance.

Isomap intuition: Euclidean versus geodesic distance Two framed panels compare a straight Euclidean path in flat space with surface-constrained geodesic and shortcut paths on a curved manifold. 1. Flat space AB Euclidean distance The shortest pathis a straight line. 2. Curved manifold AB Geodesic path Euclidean shortcut:invalid for Isomap

Steps:

  1. Construct Neighborhood Graph: For each point, connect it only to its K-nearest neighbors.
  2. Compute Shortest Paths: Use a graph algorithm (like Dijkstra’s) to compute the shortest path between all pairs of points, approximating the geodesic distance.
  3. Apply MDS: Use the resulting shortest-path distance matrix as input to the classical MDS algorithm.

Locally Linear Embedding (LLE): Preserving Local Linear Relationships

LLE assumes that each data point can be linearly reconstructed by its neighbors, and this local geometric relationship should be preserved in the low-dimensional space.

Locally Linear Embedding (LLE): Unrolling a Manifold A diagram showing that LLE preserves local reconstruction weights, not necessarily distances or angles, when mapping from a high-dimensional manifold to a low-dimensional space. LLE preserves local reconstruction weights 1. Reconstruct locally Xᵢ Compute local weights Wᵢⱼ High-D manifold LLE 2. Preserve weights Zᵢ Low-D embedding Same weights Wᵢⱼ Distances and angles may change

The Heart of LLE: Preserve Reconstruction Weights, Not Distances

LLE Core Idea: Preserving Weights, Not Distances A three-panel diagram showing that LLE preserves the relative weights (proportional position) of a point within its neighborhood, even if the neighborhood's shape is distorted in the lower dimension. This is contrasted with a rigid embedding that would preserve distances. Reconstruction weights survive geometric distortion 1. Source Xᵢ Compute Wᵢⱼ Relative position 2. LLE weights Zᵢ = Σ Wᵢⱼ Zⱼ Zᵢ Same Wᵢⱼ Shape may change 3. Rigid geometry Rigid alternative Distances stay fixed

t-SNE: The Swiss Army Knife of Data Visualization

t-SNE (t-distributed Stochastic Neighbor Embedding) is a widely used exploratory visualization tool that embeds local neighborhoods into 2D or 3D; it does not establish a “most powerful” ranking or clustering correctness.

  • Core Idea (Probabilistic Matching):
    1. In high-D space, convert Euclidean distances between points into conditional probabilities that represent the likelihood that point \(i\) would pick point \(j\) as its neighbor (using a Gaussian distribution).
    2. In low-D space, define a similar conditional probability (using a heavier-tailed t-distribution).
    3. Adjust the positions of points in the low-D space to make the two probability distributions as similar as possible (by minimizing the KL divergence).
  • Advantage: It can reveal local neighborhoods and possible group structure; confirm any apparent clusters with a validation measure chosen before viewing the result.

t-SNE Key Parameter: Perplexity

  • Perplexity:
    • This is the most important parameter. It can be loosely interpreted as the ‘effective number of neighbors’ each point considers.
    • Typical values are between 5 and 50.
    • A lower value focuses on local structure, while a higher value considers more of the global structure.

Important Cautions for Interpreting t-SNE plots

  1. Do not over-interpret distances between clusters: The distance between two clusters on a t-SNE plot does not meaningfully represent how ‘far apart’ they are in the original space.
  2. Do not over-interpret the size of clusters: The area of a cluster on the plot does not mean it contains more data points or has a larger variance.
  3. t-SNE is an exploratory visualization tool, not a rigorous clustering analysis method.

Part 3: Advanced Topic: Sparse Representation

Sparse Representation: Building Signals with the Fewest ‘Blocks’

Previous methods aimed to ‘compress’ data, but sparse representation has a different starting point.

  • Core Idea: Any signal (e.g., an economic time series) can be represented as a linear combination of a few ‘atoms’ (basis vectors) from a ‘dictionary’ \(\Psi\).

    \[ \large{x = \Psi s} \]

    Here, \(s\) is a sparse vector, meaning most of its elements are zero.

Visual: Dictionary × Sparse Coefficients Builds a Signal

Sparse Representation Analogy A complex signal is constructed by a few active elements from a large dictionary. Signal x = Dictionary Ψ × Sparse Coeff. s 0.8 1.2

Sparse Representation: Economic Intuition

Economic Intuition

The complex dynamics of the market might be driven by a combination of only a few ‘latent economic states’ or ‘shocks’. Sparse representation aims to find these core drivers.

Compressed Sensing: Recovering the Full Signal from Fewer Samples

The sparsity assumption leads to a surprising conclusion: compressed sensing.

  • If \(x=\Psi s\) has a \(k\)-sparse coefficient vector and \(\Theta=\Phi\Psi\) satisfies a restricted-isometry or suitable incoherence condition, roughly \(l\gtrsim Ck\log(d/k)\) measurements can support stable recovery.

  • Exact recovery is possible only in the noiseless case under the theorem’s solver conditions; with noise, the guarantee is an error bound.

\[ \large{z = \Phi x = \Phi \Psi s = \Theta s} \]

  • \(z\): a small number of observations (\(l \times 1\))
  • \(\Phi\): the measurement matrix (\(l \times d\), \(l \ll d\))
  • \(\Theta\): the sensing matrix

Compressed Sensing: Recovery Conditions and Failure Modes

  • Recovery conditions: sparsity, sensing geometry, sample size, and solver assumptions must hold together; sparsity alone is insufficient.
  • Failure cases: recovery may be biased or non-unique when sensing and dictionary atoms are highly coherent, \(l\) is too small, noise is large, or the signal is only approximately sparse.
  • Goal: Given \(z\) and \(\Theta\), solve for the sparse vector \(s\). This is the foundation of modern signal processing, MRI, and more.

Reconstruction Algorithm: Matching Pursuit

Finding the sparse vector \(s\) from \(z\) and \(\Theta\) is an NP-hard problem. Matching Pursuit is a greedy algorithm that approximates the solution iteratively.

  1. Initialize: Residual \(r_0 = z\), sparse solution \(s=0\).
  2. Find Most Correlated Atom: Find the atom in the dictionary \(\Theta\) that is most correlated with the current residual \(r\) (has the largest inner product).
  3. Update Solution: Add the contribution of this atom to the solution \(s\).
  4. Update Residual: Subtract the contribution of this atom from the current residual \(r\).
  5. Iterate: Repeat steps 2-4 until the residual is small enough or a maximum number of iterations is reached.

Economic Application: Screening Sparse Jumps and Outliers

With an identity dictionary, sparse first differences screen unusual jumps; a spike alone does not establish a structural break.

  • Signal (x): The first difference of an economic time series.

  • Dictionary (Ψ): An identity matrix.

  • Sparse Coefficients (s): With an identity dictionary, s is the differenced series; a large nonzero entry marks a candidate jump.

  • Ordinary innovations, outliers, seasonality, and volatility shifts can create the same spike.

  • A regime-change claim needs a change-point model that names the changing parameter, states noise/dependence assumptions, and validates false positives out of sample.

After the optional topic: after the MDS/manifold/sparse branch, continue to the final thought without replaying the main case or re-entering the branch.

Core Learning Review

  • Core (90 min): preprocessing → PCA → LDA → evaluation and interpretation. After-class Extension: MDS, Isomap, LLE, t-SNE, sparse representation, and compressed sensing.

Retrieve the Core objectives: diagnose scale/missingness, interpret PCA eigenvalues, distinguish unsupervised PCA from supervised LDA, and evaluate a representation on a held-out test period.

  • Retrieval prompt: If variable A’s standard deviation is 100 times variable B’s, what happens in covariance-based PCA?
  • Answer: A may dominate PC1 through units alone. Unless units carry the intended economics, standardize using training-period moments only.

Formative Check 1: A PCA Calculation

A standardized two-dimensional covariance matrix has eigenvalues 1.6 and 0.4. What variance share does one principal component explain?

Answer

\(1.6/(1.6+0.4)=0.8\), or 80%. Eigenvectors give directions; eigenvalues give variance along those directions.

Main Case: Yangtze Delta Stock PCA

  • Data used in this example:
    • Source: data/stock/stock_price_pre_adjusted.h5, key=data, four representative Yangtze River Delta A-shares.

    • Scope: 2018–2024 pre-adjusted close on common trading days only.

    • Boundary: the scaler and PCA use only 2018–2022 training observations.

  • Nearby method source: Jolliffe & Cadima (2016), PCA review; both loadings and explained variance below are estimated from training observations only.
Code
from pathlib import Path  # Locate the downloaded data file

import pandas as pd  # Read and align local quotes in a table
from sklearn.preprocessing import StandardScaler  # Unify stock yield scales during the training period
from sklearn.decomposition import PCA  # Extract Common Direction of Fluctuation with Principal Component
# Public download: https://assets.qiufei.site/data/stock/stock_price_pre_adjusted.h5
# After downloading, change the next line to the file's actual location on your device.
# Course-relative option: Path("data/stock/stock_price_pre_adjusted.h5")
# Windows: Path(r"C:\qiufei\data\stock\stock_price_pre_adjusted.h5")
# macOS: Path("/Users/your_name/data/stock/stock_price_pre_adjusted.h5")
# Linux: Path("/home/your_name/data/stock/stock_price_pre_adjusted.h5")
price_path = Path("/home/ubuntu/r2_data_mount/data/stock/stock_price_pre_adjusted.h5")
company_ids = ['600276.XSHG', '600660.XSHG', '002648.XSHE', '002920.XSHE']  # Select representative listed company codes in the Yangtze River Delta
price_parts = [pd.read_hdf(price_path, key='data', where=[f'order_book_id=="{company_id}"', 'date>=Timestamp("2018-01-01")', 'date<=Timestamp("2024-12-31")'], columns=['close']) for company_id in company_ids]  # Selective Loading of Closing Prices by Company and Period
price_panel = pd.concat(price_parts).reset_index().pivot(index='date', columns='order_book_id', values='close')  # Construct Date Multiplied by Company's Price Panel
return_panel = price_panel.pct_change(fill_method=None).dropna()  # Calculate the common trading day yield and delete the missing rows
training_returns = return_panel.loc[:'2022-12-31']  # Fixed 2018-2022 as Training Period
return_scaler = StandardScaler().fit(training_returns)  # Estimate means and standard deviations from the training period only
scaled_training_returns = return_scaler.transform(training_returns)  # Convert the training yield to a comparable scale
return_pca = PCA(n_components=2).fit(scaled_training_returns)  # Extracts the first two common fluctuating principal components
pca_loadings = pd.DataFrame(return_pca.components_.T, index=training_returns.columns, columns=['PC1', 'PC2'])  # Map the load back to the real stock code
pd.concat([pd.Series(return_pca.explained_variance_ratio_, index=['PC1', 'PC2'], name='variance_ratio'), pca_loadings.stack().rename('loading')], axis=0)  # Output variance evidence and loads for interpretation
PC1                   0.471032
PC2                   0.206372
(002648.XSHE, PC1)    0.483942
(002648.XSHE, PC2)   -0.322402
(002920.XSHE, PC1)    0.515698
(002920.XSHE, PC2)   -0.390399
(600276.XSHG, PC1)    0.426722
(600276.XSHG, PC2)    0.862146
(600660.XSHG, PC1)    0.563705
(600660.XSHG, PC2)   -0.018706
dtype: float64

Formative Check 2: What Does the Plot Support?

Two clusters are far apart on a t-SNE map. May we conclude they are equally far apart in the original space?

Answer

No. t-SNE prioritizes local neighborhoods; global distance, area, and direction are generally not quantitative evidence. Vary seeds/perplexity and validate in the original space.

Step-by-Step Exercise: Why Standardize?

  • Task: Fit PCA to raw and standardized returns over the same training period; compare PC1 variance share and loading rank.
  • Complete solution:
    • Fit raw_pca = PCA(2).fit(training_returns) on the same dates.

    • Compare explained_variance_ratio_ and rank absolute values of both components_[0] vectors.

    • Interpret a changed rank as scale/volatility sensitivity—not causal importance.

Code
raw_pca = PCA(n_components=2).fit(training_returns)  # Fit Non-standardized PCA on Same Training Date
raw_rank = training_returns.columns[abs(raw_pca.components_[0]).argsort()[::-1]].tolist()  # Raw return variables by PC1 Absolute Load
scaled_rank = training_returns.columns[abs(return_pca.components_[0]).argsort()[::-1]].tolist()  # Standardized Variables by PC1 Absolute Load
pd.DataFrame({'input version': ['raw returns', 'standardized returns'], 'pc1_variance_ratio': [raw_pca.explained_variance_ratio_[0], return_pca.explained_variance_ratio_[0]], 'absolute_loading_rank': [raw_rank, scaled_rank]})  # Compare the two PCA results side by side
Table 1
input version pc1_variance_ratio absolute_loading_rank
0 raw returns 0.500617 [002920.XSHE, 002648.XSHE, 600660.XSHG, 600276...
1 standardized returns 0.471032 [600660.XSHG, 002920.XSHE, 002648.XSHE, 600276...

Apply It to a New Case

  • From local financial_statement.h5/financial_data, select four Yangtze Delta firms, at least 12 quarters, and five financial ratios; compare two-dimensional PCA and LDA.

  • The income-statement fields in this file are cumulative year-to-date, so the target is whether cumulative net profit disclosed for the exact next calendar quarter is positive.

Complete-answer reminder

  • report fields and units, respect when information became available, fit preprocessing on training data only, interpret PCA variance and loadings, report the LDA target and out-of-sample result, and discuss limitations.

  • Features must use the version disclosed by the decision time, and later restatements or full-sample moments must not enter earlier decisions.

Complete Solution for the New Case: Financial-Ratio Panel

Table 2
Code
from pathlib import Path  # Locate the downloaded data file

import pandas as pd  # Read and Organize Local Quarterly Financial Statements
from sklearn.preprocessing import StandardScaler  # Estimate Unified Ratio Scale by Training Period Moment Only
from sklearn.decomposition import PCA  # Extract Unsupervised 2D Financial Representation
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis  # Estimating supervised linear discriminant directions
# Public download: https://assets.qiufei.site/data/stock/financial_statement.h5
# After downloading, change the next line to the file's actual location on your device.
# Course-relative option: Path("data/stock/financial_statement.h5")
# Windows: Path(r"C:\qiufei\data\stock\financial_statement.h5")
# macOS: Path("/Users/your_name/data/stock/financial_statement.h5")
# Linux: Path("/home/your_name/data/stock/financial_statement.h5")
statement_path = Path("/home/ubuntu/r2_data_mount/data/stock/financial_statement.h5")
transfer_ids = ['600418.XSHG', '600460.XSHG', '600537.XSHG', '600596.XSHG']  # Select four Yangtze River Delta companies
statement_columns = ['order_book_id', 'quarter', 'info_date', 'operating_revenue', 'net_profit', 'total_assets', 'total_liabilities', 'equity_parent_company']  # Define the original field
statement_parts = [pd.read_hdf(statement_path, key='financial_data', where=f'order_book_id=="{company_id}"', columns=statement_columns) for company_id in transfer_ids]  # Selective Loading of Required Columns by Company
statement_frame = pd.concat(statement_parts, ignore_index=True)  # Merging Four Companies for Quarterly Panel
Table 3
Code
statement_frame['info_date'] = pd.to_datetime(statement_frame['info_date'])  # Unifying Disclosure Date Types
statement_frame['quarter_period'] = pd.PeriodIndex(statement_frame['quarter'], freq='Q')  # Convert Quarterly Label to Sortable Period
statement_frame = statement_frame[statement_frame['quarter_period'] <= pd.Period('2024Q4')]
statement_frame = statement_frame.sort_values(['order_book_id', 'quarter_period', 'info_date']).drop_duplicates(['order_book_id', 'quarter_period'], keep='first')  # Keep the first disclosed version of each quarter and exclude later restatements
ratio_definitions = {'profit_margin': ('net_profit', 'operating_revenue'), 'roa': ('net_profit', 'total_assets'), 'debt_ratio': ('total_liabilities', 'total_assets'), 'asset_turnover': ('operating_revenue', 'total_assets'), 'equity_turnover': ('operating_revenue', 'equity_parent_company')}  # Define Five Dimensionless Ratios
for ratio_name, (numerator_name, denominator_name) in ratio_definitions.items():  # Construct a ratio under the same accounting convention
    statement_frame[ratio_name] = statement_frame[numerator_name] / statement_frame[denominator_name]  # Calculate ratios with a report original value
statement_frame = statement_frame.sort_values(['order_book_id', 'quarter_period'])  # Inside the Company Maintain Quarterly Order
statement_frame['target_quarter'] = statement_frame.groupby('order_book_id')['quarter_period'].shift(-1)  # Retain the next record's quarter so exact calendar adjacency can be verified
statement_frame['next_profit'] = statement_frame.groupby('order_book_id')['net_profit'].shift(-1)  # keep next quarter net profit consecutive value
statement_frame['target_available_at'] = statement_frame.groupby('order_book_id')['info_date'].shift(-1)  # Record when the next-quarter outcome first becomes verifiable
statement_frame = statement_frame.replace([float('inf'), float('-inf')], pd.NA).dropna()  # Remove missing ratios, unknown outcomes, and non-finite records
statement_frame = statement_frame[(statement_frame['target_quarter'] == statement_frame['quarter_period'] + 1) & (statement_frame['info_date'] < statement_frame['target_available_at'])]  # Reject skipped quarters and tasks whose outcomes are not disclosed later
statement_frame['next_profit_positive'] = (statement_frame['next_profit'] > 0).astype(int)  # Construct symbol labels only for observed profits
assert (statement_frame['target_quarter'] == statement_frame['quarter_period'] + 1).all()  # Verify that every target is the exact next calendar quarter
assert (statement_frame['info_date'] < statement_frame['target_available_at']).all()  # Verify that every feature disclosure precedes its outcome disclosure
  • All five ratios are unit-free;

  • Raw amount fields: retain the HDF data dictionary’s RMB unit.

  • Accounting convention: operating_revenue and net_profit are cumulative year-to-date values.

  • Target: the sign of cumulative net profit disclosed for the exact next calendar quarter—not single-quarter profit.

Complete Solution for the New Case: PCA and LDA Evidence

Code
from sklearn.metrics import balanced_accuracy_score, confusion_matrix  # Evaluate Classification Performance of fixed Test Period
ratio_names = list(ratio_definitions)  # Fixed Five Dimension Model Input Sequence
statement_train = statement_frame[statement_frame['target_available_at'] <= pd.Timestamp('2022-12-31')]  # Require both features and outcomes to be known by the training cutoff
statement_test = statement_frame[(statement_frame['info_date'] >= pd.Timestamp('2023-01-01')) & (statement_frame['target_available_at'] <= pd.Timestamp('2024-12-31'))]
assert statement_train['target_available_at'].max() < statement_test['info_date'].min()  # Verify that training outcomes precede the first test feature disclosure
ratio_scaler = StandardScaler().fit(statement_train[ratio_names])  # Use only the training period to estimate the scale
scaled_statement_train = ratio_scaler.transform(statement_train[ratio_names])  # Transform Training Period Ratio
scaled_statement_test = ratio_scaler.transform(statement_test[ratio_names])  # Transform test-period ratios with the training-period scaler
statement_pca = PCA(n_components=2).fit(scaled_statement_train)  # Only extracting two principal components during the training period
statement_test_scores = statement_pca.transform(scaled_statement_test)  # Generate 2D Coordinates for Test Period
statement_lda = LinearDiscriminantAnalysis().fit(scaled_statement_train, statement_train['next_profit_positive'])  # Learning the direction of supervision only during the training period
statement_lda_prediction = statement_lda.predict(scaled_statement_test)  # Forecast Profit Symbol for fixed Test Period
pd.Series({'train_n': len(statement_train), 'test_n': len(statement_test), 'pc1_share': statement_pca.explained_variance_ratio_[0], 'pc2_share': statement_pca.explained_variance_ratio_[1], 'lda_balanced_accuracy': balanced_accuracy_score(statement_test['next_profit_positive'], statement_lda_prediction), 'confusion_matrix': confusion_matrix(statement_test['next_profit_positive'], statement_lda_prediction).tolist(), 'first_test_score': statement_test_scores[0].round(3).tolist()})  # Output verifiable comparison of real key results with two-dimensional coordinate samples
Table 4
train_n                                174
test_n                                  18
pc1_share                         0.487445
pc2_share                         0.336838
lda_balanced_accuracy                  0.5
confusion_matrix         [[0, 5], [0, 13]]
first_test_score           [-1.293, 1.121]
dtype: object
  • The run has 174 training and 18 test rows.

  • PC1/PC2 explain 0.4874/0.3368; LDA balanced accuracy is 0.5000 and the confusion matrix is \([[0,5],[0,13]]\).

  • Every test quarter is classified as profitable, so all loss quarters are missed and this is not robust predictive evidence.

Formative Check 3: Compressed-Sensing Conditions

“The signal is sparse, so any three measurements must recover a 100-dimensional signal.” True or false?

Answer: False. Measurements must scale with \(k\log(d/k)\), the sensing geometry needs RIP/incoherence, and noiseless exact recovery must be separated from noisy stable recovery.

Sources and Further Reading

  • Jolliffe & Cadima (2016), “Principal component analysis: a review and recent developments.”
  • van der Maaten & Hinton (2008), “Visualizing Data using t-SNE.”
  • Candès & Tao (2005/2006), original compressed-sensing and RIP papers.
  • Data: local data/stock/financial_statement.h5, HDF key=financial_data, with the fields and cumulative convention stated in the transfer task; the PCA worked example separately uses the local pre-adjusted A-share data.

Core Summary: Choosing Between PCA and LDA

Optional topic: after Core, optionally enter MDS, manifold learning, and sparse representation; when the branch ends, continue to the final thought without replaying the main case.

Method Type Core Idea Pros Cons
PCA Linear, Unsupervised Maximize variance Simple, fast, highly interpretable Cannot handle nonlinear structures
LDA Linear, Supervised Maximize class separability Excellent for classification Requires class labels, has assumptions about class distribution

Extension Summary: Distance, Manifold, and Sparse Methods

Method Preserves Key boundary
MDS Pairwise distances Depends on the metric; computationally expensive
Isomap / LLE Geodesics / local reconstruction Sensitive to neighborhoods and noise
t-SNE Local neighborhood probabilities Exploratory only; global distances are not quantitative evidence
Sparse / compressed sensing A few atoms Requires sensing geometry, sample size, and solver conditions

Final Thought: Reduction is a Means to an End, Not the Goal Itself

In this chapter, we have explored a range of representation learning (dimensionality reduction) methods, from linear to nonlinear.

  • They are powerful tools for exploratory data analysis, helping us discover hidden structures like factors, clusters, and low-dimensional manifolds in seemingly chaotic high-dimensional data.
  • They are also a crucial preprocessing step for building predictive models, effectively improving model stability and generalization.

The key is to always combine your domain knowledge (economics, finance) to interpret the results of dimensionality reduction, giving real-world meaning to these abstract dimensions and structures.

Thank You!

Questions & Discussion