09 Probabilistic Graphical Models: Taming Uncertainty with Structure
Welcome to Lecture 9
Today’s Agenda
Learning Objectives
By the end of this lecture, you can:
Core: Read a specified conditional-independence statement from a DAG and write a BN local-CPD factorization.
Core: Distinguish observational conditioning \(P(Y\mid X=x)\) from intervention \(P(Y\mid do(X=x))\).
Core: Run an observational pgmpy query and state the extra assumptions needed for causal interpretation.
Extension: Write an MRF potential-function factorization and explain when belief propagation is exact on a tree and why loopy propagation is approximate.
Before You Begin
Write the chain rule for (P(A,B,C)).
If \(A\perp C\mid B\), can learning A after conditioning on B change C’s distribution?
Does association imply that intervening on A changes C?
HMMs and the material that follows are optional topics.
Core Question: Modeling Complex Economic Systems
Imagine forecasting GDP growth. It’s a complex system of numerous interrelated variables.
How can we clearly represent and reason about the complex dependencies between these variables?
Traditional Limitation: The Joint Distribution
In theory, to fully describe a system, we need the joint probability distribution\(P(x_1, x_2, \dots, x_d)\).
But this is an almost impossible task.
The ‘Curse of Dimensionality’ is an Exponential Explosion
Imagine we have d binary economic indicators (e.g., rate hike / no rate hike).
To store their joint probability distribution, we need a parameter table.
# of Variables (d)
2^d probability cells; 2^d − 1 free parameters
Analogy
2
4 / 3
A small note
10
1,024 / 1,023
A single page
20
1,048,576 / 1,048,575
A thick book
30
2^30 / (2^30 − 1)
A small library
50
2^50 / (2^50 − 1)
Already extremely large
This is computationally intractable.
Visualizing the Curse of Dimensionality
Decompose Complexity with Conditional Independence
Most variables are not directly connected to everything else. A variable is typically only directly related to a few others.
From ‘Fully Connected’ to ‘Sparsely Connected’
Instead of storing one massive joint table, a graph supplies local factors. Directed and undirected models normalize differently, so a generic “product of local probabilities” is not a valid common definition.
Pro: Completely general, makes no assumptions, it’s exact.
Con: Doesn’t simplify anything. The last term \(P(x_d|x_1, \dots, x_{d-1})\) has as many parameters as the original joint probability, still facing the curse of dimensionality.
Method 3: The PGM Middle Ground
PGMs offer a testable tradeoff: sparse structure can reduce parameter and inference costs, but the benefit depends on the graph, state cardinalities, and inference algorithm.
PGM Essence: A Smarter Chain Rule
This is the secret to how probabilistic graphical models reduce computational complexity.
Graph Language: Nodes and Edges
9.2 Bayesian Networks
What is a Bayesian Network (BN)?
Bayesian Networks (BNs), also known as Probabilistic Directed Graphical Models (PDGMs), use a Directed Acyclic Graph (DAG) to encode dependencies among variables.
It consists of two parts:
Graph Structure (Qualitative): A DAG that describes the conditional independence relationships among variables.
Parameters (Quantitative): A set of local Conditional Probability Distributions (CPDs) that quantify the strength of these dependencies.
Core Structure: Directed Acyclic Graph (DAG)
Directed: An arrow specifies the parent order of local conditional probabilities: \(A\rightarrow B\) makes B’s local distribution \(P(B\mid A)\). In an ordinary probabilistic BN, this does not prove that A causes B.
Acyclic: Following arrows never returns to the starting node, allowing a topological factorization. Only a separately justified causal structure gives this a causal interpretation.
Probabilistic vs. Causal DAGs
A probabilistic BN commits to: factorization, the local Markov property, and conditional independences readable through d-separation.
Giving a DAG causal semantics requires:
structural-equation/intervention semantics and the causal Markov condition.
Faithfulness is an additional distributional assumption often used for structure learning, not part of the definition of a causal DAG.
Identification is query-specific: for example, back-door adjustment needs the relevant confounding and positivity conditions.
Arrow direction alone cannot establish these conditions from observational data.
Accordingly, this lecture’s pgmpy queries are observational conditioning unless a structural causal model is separately justified.
DAG Example: Legal vs. Illegal
Case: A Simplified Directed Probability Model
Let’s use a graph structure to build a simplified model of some process.
Graph Language: Family Relations
In a directed graph, we use family relationships to describe the connections between nodes:
Parents: The parents of a node are the set of all nodes that point directly to it.
parents(X3) is {X1, X2}.
parents(X6) is {X4, X5}.
Children: The children of a node are the set of all nodes that it points directly to.
children(X1) is {X3, X5}.
A node with no parents (like X1, X2) is a root node in the factorization; calling it an exogenous cause requires an additional structural causal interpretation.
Bayesian Networks: Local Markov Property
The structure of the DAG directly defines a core conditional independence assumption: The Local Markov Property.
A node is conditionally independent of its non-descendants, given its parents.
Based on the local Markov property, any joint probability distribution that is consistent with the DAG can be factorized into the product of the conditional probabilities of all nodes given their parents.
This formula is the heart of Bayesian Networks. It decomposes a vast, complex joint probability distribution into a series of small, manageable local probability models (also known as Conditional Probability Distributions, CPDs).
Comparison: If we used the standard chain rule, the last term would be \(P(X_6|X_1, X_2, X_3, X_4, X_5)\), requiring a huge parameter space.
Advantage: This factorization significantly reduces the number of parameters we need to estimate, making model learning feasible.
Parameterization: Populating the Model with CPTs
Now that we have the structure, we need to provide specific parameters for each local probability model. For discrete variables, this is typically done using Conditional Probability Tables (CPTs).
A CPT lists the probability of a node taking on different values for every possible combination of its parents’ values.
For a root node (like \(X_1\)), the CPT is a simple prior probability distribution \(P(X_1)\).
For a node with parents (like \(X_3\)), the CPT is \(P(X_3 | X_1, X_2)\).
9.2.2 D-Separation
Why Do We Need a General Rule?
The local Markov property tells us about the independence of a node from its ‘non-descendants’. But we often need to answer more general questions:
Are any two arbitrary sets of nodes A and B independent, given a third set E?
D-Separation (Directed Separation) is a complete, general set of rules that allows us to ‘read’ any conditional independence directly from the graph structure.
The Core Idea of D-Separation
The core idea of D-separation is to check if all paths between two sets of nodes are ‘blocked’.
If all paths from A to B are blocked by the set of observed variables E, then A and B are conditionally independent given E.
If at least one path is unblocked, the graph does not guarantee that A and B are conditionally independent. D-connection implies dependence only with an additional faithfulness/no-cancellation assumption.
The Three Basic Structures of D-Separation
Any path in a complex DAG can be broken down into three fundamental connection structures. Understanding these three is the key to mastering D-separation.
Structure 1: Tail-to-Tail (Common Cause)
b <- a -> c
Path: b and c are connected through their common parent a.
Rule: When a is observed (given), the path from b to c is blocked.
Once we directly observe the market interest rates, the specific Fed policy that led to this rate is no longer important for predicting real estate prices.
The interest rate itself contains all the necessary information.
Knowing a professor is talented tells us nothing about their political skills (they are independent beforehand).
However, if we know they got tenure and then find out they aren’t very talented, it strongly suggests they must be very politically skilled.
D-Separation Summary: Is the Path Blocked?
A path from a set of nodes A to B is blocked by a set of observed nodes E if there is a node v on the path such that either:
v is a tail-to-tail or head-to-tail node, and vis in the evidence set E.
v is a head-to-head (collider) node, and neither vnor any of its descendants are in the evidence set E.
If all paths from A to B are blocked by E, we say that A and B are D-separated given E, which implies conditional independence: A \(\perp\) B | E.
Transition Check: What Does Observing a Collider Do?
Predict: in \(A\rightarrow B\leftarrow C\), are A and C independent before B is observed, and after B is observed?
Reveal and remediation:
the collider blocks the path while B and its descendants are unobserved; conditioning on B opens it.
If you assumed “more controls always help,” return to the three basic structures and mark the collider.
9.2.3 Case Study: A More Complete Student Model
Now, let’s apply these concepts to the classic ‘Student’ Bayesian Network. This network models the various factors that influence whether a student gets a good recommendation letter.
Variables:
D (Difficulty): Course difficulty (0=easy, 1=hard)
I (Intelligence): Student’s intelligence (0=low, 1=high)
G (Grade): Student’s grade (0=C, 1=B, 2=A)
S (SAT): SAT score (0=low, 1=high)
L (Letter): Quality of recommendation letter (0=weak, 1=strong)
The Student Model Graph Structure
The structure of this graph encodes our prior beliefs about student performance.
The Student Model Factorization
Core task
first write \(P(I,D,G,S,L)\) using “each node conditions only on its parents,” then reveal.
. . .
Based on the graph structure and Equation 1, the factorized joint probability is:
Note how we’ve simplified the problem! For example, we only need \(P(L|G)\), not the intractable \(P(L|I, D, G, S)\).
The Student Model Parameterization (CPTs)
Now we need to populate each factor with a CPT. These probabilities are typically estimated from domain experts or historical data.
1. Root Nodes (Prior Probabilities)
\(P(I)\): P(I=0) = 0.7, P(I=1) = 0.3
\(P(D)\): P(D=0) = 0.6, P(D=1) = 0.4
2. Conditional Probabilities
\(P(S|I)\): How intelligence affects SAT scores.
\(P(G|I,D)\): How intelligence and difficulty jointly affect grades.
\(P(L|G)\): How the grade affects the letter quality.
CPT Example: P(G | I, D)
This table shows the probability of a student getting an A/B/C grade for different combinations of intelligence and course difficulty.
I (Intelligence)
D (Difficulty)
P(G=A)
P(G=B)
P(G=C)
0 (low)
0 (easy)
0.30
0.40
0.30
0 (low)
1 (hard)
0.05
0.25
0.70
1 (high)
0 (easy)
0.90
0.08
0.02
1 (high)
1 (hard)
0.50
0.30
0.20
Bayesian Network Inference: Answering “After We Observe”
With a fully specified Bayesian Network, we can perform Inference. This means that after observing some variables (Evidence), we can compute the posterior probability distribution of other unobserved variables.
This answers \(P(Y\mid X=x)\): how Y is distributed among observations with \(X=x\). It does not answer what happens if we force X to x.
Conditioning vs. Intervention: A Confounding Example
Let market sentiment \(U\) affect financing constraints \(X\) and investment \(Y\): \(U\rightarrow X, U\rightarrow Y\), with \(X\rightarrow Y\).
Conditioning:\(P(Y\mid X=x)\) mixes the X path with selection induced by common cause U.
Intervention:\(P(Y\mid do(X=x))\) cuts incoming arrows to X before comparing Y under forced X.
Conclusion: If U is unobserved and no alternative identification strategy exists, an ordinary BN query cannot substitute the first distribution for the second.
Check 2: Is deleting arrows into X conditioning or intervention? Does an ordinary pgmpy query perform that deletion? Answer first.
Reveal and remediation: deleting incoming arrows is intervention; an ordinary query only conditions. If these were conflated, redraw the observational and intervention graphs with common cause U.
The Core Problem: Compute \(P(\text{Query Variables} | \text{Evidence Variables})\)
Example Inference Questions
A student received a strong letter (L=1). What’s the probability they are highly intelligent?
\(P(I=1 | L=1) = ?\)
A highly intelligent student (I=1) is in a hard course (D=1). What is their probability of getting an A?
\(P(G=A | I=1, D=1) = ?\) (This can be read directly from the CPT)
A student has a high SAT score (S=1) but a poor grade (G=C). What’s the probability the course was hard?
\(P(D=1 | S=1, G=C) = ?\)
Hands-on: Building and Querying the Student Model with pgmpy
Enough theory, let’s make this real with code. We will use a powerful Python library pgmpy to implement the student model.
Core task
run and inspect model validation and the observational query \(P(D=1\mid I=1,L=1)\). Explain why an ordinary query deletes no incoming arrows and therefore is not an intervention.
Steps:
Define Model Structure (add nodes and edges)
Define CPTs
Associate CPTs with the structure to form a complete model
Create an inference engine
Perform queries
pgmpy Hands-on: Building and Validating the Model
First, we’ll use a complete code block to build the student model.
The query result shows \(P(D=1 | I=1, L=1) \approx 0.3299\).
Prior Probability: With no information, the probability of a hard course is \(P(D=1)=0.4\).
Posterior Probability: After learning that this intelligent student got a strong letter, our belief that the course was hard decreases to about 33.0%.
Intuition:
An intelligent student can earn a good grade and strong letter even in a hard course.
That outcome is still more likely in an easy course.
A strong letter therefore raises the posterior belief in an easy course slightly.
Bayesian inference quantifies this logically consistent update.
9.2.4 Dynamic Bayesian Networks: When BNs Meet Time
Optional topics: The following material covers HMMs, undirected models, and general inference. For the main lesson, continue to real-data practice and the lesson review.
If we ‘unroll’ a Bayesian Network over time, we get a Dynamic Bayesian Network (DBN).
The simplest and most famous DBN is the Hidden Markov Model (HMM).
HMM Intuition: Weather Forecasting from a Cave
Imagine you are trapped in a cave and can’t see the weather outside. But every day, some water seeps into the cave.
Your Observations (Visible): Is the cave ‘dry’, ‘damp’, or ‘dripping’ today?
True State (Hidden): Is the weather outside ‘sunny’, ‘cloudy’, or ‘rainy’?
Your task is to infer the most likely sequence of weather patterns outside based on the sequence of water seepage you observe.
Core Application of HMMs
Modeling time-series data where the true state of the system is unobservable (hidden), and we can only infer it through some visible observations.
Application in Economics:
True State (Hidden): The economy is in an ‘Expansion’ or ‘Recession’ phase.
Observations (Visible): Quarterly GDP growth rates, unemployment data.
The Two Core Assumptions of HMMs
HMMs are built on two key simplifying assumptions, which make the model tractable.
The Markov Assumption (State Transition)
The Observation Independence Assumption (Emission Probability)
Assumption 1: The Markov Assumption (State Transition)
The current true state \(z_t\) depends only on the true state at the previous time step, \(z_{t-1}\).
Economic Interpretation: Whether the economy is in recession or expansion primarily depends on whether it was in recession or expansion last quarter, not on its history long before that (in a first-order model).
Assumption 2: Observation Independence
The current observation \(x_t\) depends only on the current true state \(z_t\).
Interpretation: We believe there’s an 80% chance the economy is in an expansion at the start of our sequence.
Three Core HMM Problems
Once we have a model \(\lambda = (A, B, \pi)\), HMM theory primarily addresses three problems.
HMM Summary
HMMs are powerful tools for analyzing time series, a key special case of DBNs.
They model complex systems by distinguishing between ‘hidden states’ and ‘observations’.
Their core consists of three parameters \((A, B, \pi)\) and classic algorithms for solving the three core problems (Evaluation, Decoding, Learning).
In economics, they are widely used for identifying business cycles, financial market regime switching (bull/bear markets), and more.
9.3 Markov Networks
From Directed to Undirected Factorization: Why Undirected Graphs?
BN arrows are useful for directed conditional-probability factorizations.
When interactions are symmetric, or we do not wish to impose a parent order, an undirected graph is more natural.
Causal semantics remain a separate modeling commitment.
Social Networks: If I am your friend, you are my friend.
Image Pixels: The color of a pixel is highly correlated with the colors of its neighbors, but none is the ‘cause’ of the others.
Spatial Economics: Housing prices in one region mutually influence prices in neighboring regions.
What is a Markov Random Field (MRF)?
For these types of problems, Markov Random Fields (MRFs), also known as Probabilistic Undirected Graphical Models (PUGMs), are a more natural choice.
An MRF is defined by two parts:
An undirected graph\(G=(\mathcal{V}, \mathcal{E})\), where nodes represent random variables and edges represent direct dependencies.
A set of Potential Functions\(\phi_C(\mathbf{x}_C)\) defined on the ‘cliques’ of the graph, used to quantify the ‘compatibility’ between variables.
Conditional Independence in Undirected Graphs
Unlike the complex rules of D-separation, conditional independence in undirected graphs is very intuitive:
If all paths from a set of nodes A to a set of nodes B must pass through a set of nodes C, then A and B are conditionally independent given C.
In other words, C separates A and B.
Case: Reading Independence from an Undirected Graph
MRF Independence: Three Markov Properties
Global Markov Property:
\(A \perp B | C\) if C separates A and B. (As just discussed)
Local Markov Property:
A node is conditionally independent of all other nodes given its neighbors.
The neighbors (or Markov Blanket) are the set of nodes directly connected to it by an edge.
Pairwise Markov Property:
Any two non-adjacent nodes are conditionally independent given all other nodes.
For arbitrary distributions, the global property implies the local property, which implies the pairwise property.
The reverse implications—and hence equivalence—require \(p(\mathbf{x})>0\) for every joint configuration \(\mathbf{x}\) in the full product state space, so structural zeros are excluded.
Joint Factorization: Cliques and Potentials
How does the joint probability of an undirected graph factorize? The answer is through Cliques.
Clique: A subset of nodes in a graph where every two distinct nodes in the subset are adjacent. They are the ‘fully connected’ subgraphs.
Maximal Clique: A clique that cannot be extended by adding any other adjacent vertex.
The joint probability distribution of an MRF can be factorized into a product of potential functions defined on its maximal cliques.
Case: Maximal Cliques
Potential Functions
For each maximal clique \(C\) in the graph, we define a potential function\(\psi_C(\mathbf{x}_C)\).
This function takes a specific configuration of values \(\mathbf{x}_C\) for the variables in that clique and outputs a non-negative real number.
Intuitive Meaning: This number represents the ‘compatibility’ or ‘preference’ for the variables within that clique to be in that specific state. A higher value means the configuration is more ‘harmonious’ and thus more likely.
Important: It is not a probability! It’s just a score.
Hammersley-Clifford Theorem
This important theorem provides the bridge between the joint probability distribution of an MRF and its potential functions:
Positivity: the joint distribution must satisfy \(P(\mathbf{x})>0\) throughout the full product state space.
Graph condition: it obeys the conditional independences encoded by the undirected graph \(G\).
Factorization: the joint probability is a product of potentials \(\psi_C\) over the maximal cliques \(C\) of \(G\):
To ensure that the probabilities of all possible states sum to 1.
Since the product of potential functions is not guaranteed to do so, we need to divide by the sum of this product over all possible configurations to normalize it.
The Challenge:
Computing \(Z\) is often the hardest part of working with MRFs.
It requires summing over all possible configurations of all variables, which is an exponential computation.
This is the main bottleneck for inference and learning in MRFs.
BN vs. MRF Summary
Feature
Bayesian Network (Directed)
Markov Network (Undirected)
Graph Structure
Directed Acyclic Graph (DAG)
Undirected Graph
Core Idea
Factorization of conditional probabilities
Factorization of potential/energy functions
Parameterization
Conditional Probability Distributions (CPDs)
Potential functions on maximal cliques
Normalization
Automatically satisfied (local normalization)
Requires a global partition function Z
Use Cases
Directed generative models; causal models only with causal assumptions
Symmetric interactions, spatial or discriminative models
Interpretability
Strong, easy to understand
Weaker, potential functions are less intuitive
9.3.3 Conditional Random Fields (CRF)
Generative vs. Discriminative Models
Generative Models: Model the joint probability \(P(X, Z)\). They learn how the data is ‘generated’.
Examples: HMM, Bayesian Networks.
Capability: Can be used to generate new sample data.
Discriminative Models: Directly model the conditional probability \(P(Z|X)\) that we often care more about. They learn how to ‘discriminate’ between different Z.
Examples: Logistic Regression, CRF.
Capability: Often perform better on classification and prediction tasks.
The Core Advantage of CRFs
Conditional Random Fields (CRFs) are a special type of MRF that is a discriminative model.
Comparison to HMMs:
CRFs can relax the strict observation independence assumption of HMMs.
In a CRF, the probability of the current state \(z_t\) can depend on features from the entire observation sequence\(X\), making the model much more powerful and flexible.
Linear-Chain CRF
The most common type of CRF is the linear-chain CRF, which is specialized for sequence data.
Its conditional probability \(P(Z|X)\) takes the form:
\(f_k\) are called feature functions. They can be any function of the states and observations (e.g., ‘if the current word is ’bank’ and the previous word was ‘national’’).
\(\lambda_k\) are the weights for each feature, which are learned from data.
\(Z(X)\) is the partition function that depends on the observation sequence \(X\).
9.4 Factor Graphs and Sum–Product
Why a Unifying Framework?
We have learned about directed and undirected graphs. Both represent factorizations of a joint probability, but in different ways.
Is there a more general representation that can unify both models and provide a basis for universal inference algorithms?
The answer is the Factor Graph.
Factor Graphs: A More Refined Representation
A factor graph is a bipartite graph that explicitly represents how a global function (like a joint probability) is factorized into a product of local functions (factors).
Two Types of Nodes:
Variable Nodes: Usually drawn as circles, representing random variables.
Factor Nodes: Usually drawn as squares, representing a factor in the factorization of the global function.
Edges: An edge only exists between a variable node and a factor node. A variable node is connected to a factor node if and only if that variable is an argument of that factor.
Case: Converting a Bayesian Network to a Factor Graph
Case: Converting a Markov Network to a Factor Graph
Recall the MRF factorization: \(P(\mathbf{x}) \propto \psi_1(A,B,E) \psi_2(B,C) \psi_3(E,D)\)
Advantages of Factor Graphs
Makes One Factorization Explicit:
once a factor set is chosen, the graph shows each local function and its variables.
The same global function can still be represented by merging, splitting, or reparameterizing factors, so factor graphs are not unique.
Universal Algorithms: Many important inference algorithms, such as Belief Propagation, are most clearly and generally defined on factor graphs.
Universal Inference: Belief Propagation
Belief Propagation (BP), also known as the Sum-Product Algorithm, is a general algorithm for performing efficient, exact inference on graphical models.
Goal: To compute the Marginal Probability\(P(x_i)\) for each individual variable.
Core Idea: The algorithm works by passing ‘messages’ along the edges of the factor graph. This can be seen as nodes ‘telling’ each other their ‘beliefs’ about the states of variables.
Convergence:
On graphs without cycles (i.e., trees), the algorithm converges after a finite number of message passes and yields exact marginal probabilities.
On graphs with cycles (Loopy BP), the algorithm is not guaranteed to converge or give exact solutions, but it often works very well in practice.
Sum-Product Intuition: The Distributive Law
Why is this algorithm efficient? Because it cleverly uses the distributive law to avoid redundant computations.
Consider calculating the marginal probability \(P(x_1) = \sum_{x_2, x_3, x_4} P(x_1,x_2,x_3,x_4)\).
We push the summations as far inside as possible, summing out the innermost variables first and passing the result outward as a ‘message’. This is the mathematical essence of the sum-product message-passing algorithm.
Local Real-Data Check: Conditioning Is Not Intervention
Use local pre-adjusted daily prices for Jiangsu Hengrui Pharmaceuticals (600276.XSHG) to estimate the empirical probability of a next-day decline after observing today’s return direction and volume state.
Code
from pathlib import Path # Locate the downloaded data fileimport pandas as pd # Read HDF5 and Calculate Discrete Conditional Probability Table# 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")price_columns = ['close', 'volume'] # Only Select Fields Required for This Exercise to Reduce Memoryhengrui_prices = pd.read_hdf(price_path, key='data', where='order_book_id == "600276.XSHG"', columns=price_columns).reset_index() # Select Hengrui Medicine on behalf of the company in the Yangtze River Deltahengrui_prices['date'] = pd.to_datetime(hengrui_prices['date']) # Unifying Dealing Day Typeshengrui_prices = hengrui_prices.query("'2015-01-01' <= date <= '2024-12-31'").sort_values('date') # Fixed Sample Period and Maintained Timingtoday_return = hengrui_prices['close'].pct_change() # Keep first day unavailable gains as missingrolling_volume_median = hengrui_prices['volume'].rolling(20).median() # Retain warm-up window as missing firstnext_return = today_return.shift(-1) # Direct Alignment of next-trading-day return and Retention of End-of-Day Missinghengrui_prices['today_down'] = today_return.lt(0).where(today_return.notna()).astype('Int64') # Discretize only when benefits are availablehengrui_prices['volume_high'] = hengrui_prices['volume'].gt(rolling_volume_median).where(rolling_volume_median.notna()).astype('Int64') # Only Discretize at full 20 day windowhengrui_prices['next_day_down'] = next_return.lt(0).where(next_return.notna()).astype('Int64') # Construct results only when next-day returns are availableobservational_table = hengrui_prices.dropna().groupby(['today_down', 'volume_high'])['next_day_down'].agg(['mean', 'size']) # Calculate Empirical Condition Probability and Sample Sizedisplay(observational_table) # Demonstrate All Condition Combinations without Prefilling Run Values
mean
size
today_down
volume_high
0
0
0.505942
589
1
0.496933
652
1
0
0.465008
643
1
0.472486
527
Interpretation answer:
mean estimates \(P(\text{next down}\mid\text{today state, volume state})\).
It is not \(P(\text{next down}\mid do(\text{volume high}))\), because news, volatility, and liquidity may be common causes that have not been identified.
Executed output: for (today_down, volume_high)=(0,0),(0,1),(1,0),(1,1), next-day downside rates are 0.5059, 0.4969, 0.4650, and 0.4725, with n=589, 652, 643, and 527.
Lesson Review: Answer Before Reveal
In \(A\rightarrow B\rightarrow C\), are A and C d-separated after conditioning on B?
In \(A\rightarrow B\leftarrow C\), what changes before and after observing B?
Reveal and remediation
item 1 is yes; item 2 is separated before observation, while observing B or a descendant opens the path.
If either was wrong, return to the three basic structures and mark collider status path by path.
Apply It to a New Case: Another Yangtze River Delta Firm
Apply it to a new case:
Repeat the table for another Yangtze River Delta non-financial firm.
Data: report the file, key, and date; construct states without looking ahead.
Evidence: show the full conditional table and use d-separation correctly.
Boundary: explain why cross-firm differences cannot be attributed causally to volume.
Code
from pathlib import Path # Locate the downloaded data filetransfer_code ='600104.XSHG'# Choose Shanghai Automobile Group as a non-financial migration company in the Yangtze River Delta# 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")transfer_prices = pd.read_hdf(price_path, key='data', where=f'order_book_id == "{transfer_code}"', columns=price_columns).reset_index() # Select select the same minimum fieldtransfer_prices['date'] = pd.to_datetime(transfer_prices['date']) # Unifying Dealing Day Typestransfer_prices = transfer_prices.query("'2015-01-01' <= date <= '2024-12-31'").sort_values('date') # Fixed Same Sample Period as Demonstrationtransfer_return = transfer_prices['close'].pct_change() # Retain first day unavailable returns as missingtransfer_volume_median = transfer_prices['volume'].rolling(20).median() # Keep warm-up window for missingtransfer_next_return = transfer_return.shift(-1) # Align next-trading-day returns and Preserve End-of-Day Missingtransfer_prices['today_down'] = transfer_return.lt(0).where(transfer_return.notna()).astype('Int64') # Create the daily-return indicator only when the return is observedtransfer_prices['volume_high'] = transfer_prices['volume'].gt(transfer_volume_median).where(transfer_volume_median.notna()).astype('Int64') # Only Discrete Full Scroll Windowtransfer_prices['next_day_down'] = transfer_next_return.lt(0).where(transfer_next_return.notna()).astype('Int64') # Create the next-day indicator only when its return is observedtransfer_table = transfer_prices.dropna().groupby(['today_down', 'volume_high'])['next_day_down'].agg(['mean', 'size']) # Calculate Four Empirical Condition Unitsdisplay(transfer_table.round(4)) # Demonstrate Full Reference Output
mean
size
today_down
volume_high
0
0
0.5044
563
1
0.5046
656
1
0
0.4817
683
1
0.4872
509
Apply It to a New Case: Result and Interpretation
Complete reference output:
for (today_down, volume_high)=(0,0),(0,1),(1,0),(1,1), next-day downside rates are 0.5044, 0.5046, 0.4817, and 0.4872, with n=563, 656, 683, and 509.
High- versus low-volume differences are small.
Even a larger gap would remain observational because news, volatility, and liquidity may affect both volume and next-day returns.
Answer note: If the answer says high volume causes the decline, return to conditioning/intervention; if cell sizes are missing, return to empirical support.
Sources and Further Reading
Koller, D. and Friedman, N. (2009), Probabilistic Graphical Models, MIT Press.
Pearl, J. (2009), Causality, 2nd ed., Cambridge University Press; adjacent support for distinguishing conditioning from intervention.
Lauritzen, S. L. (1996), Graphical Models, Oxford University Press.
Data: local stock_price_pre_adjusted.h5 / data; the empirical table is generated by slide code.
The curse of dimensionality motivates us to find simplified ways to represent joint probability distributions.
Probabilistic Graphical Models exploit conditional independence to factor complex distributions into local functions. D-separation guarantees graph-entailed independence; d-connection alone proves neither statistical nor causal dependence.
Bayesian Networks (Directed) use conditional probabilities to encode a factorization; causal interpretation requires additional structural causal assumptions.
Extension Summary: Undirected Graphs and General Inference
Markov Networks (Undirected) use potential functions, are suitable for modeling symmetric relationships, and their joint probability is given by a product of potentials on maximal cliques (Hammersley-Clifford theorem).
Factor Graphs provide a unifying, more refined representation for both models and are the foundation for general inference algorithms.
Belief Propagation (Sum-Product Algorithm) is the core algorithm for efficient inference on graphical models, whose essence is using the distributive law to avoid redundant calculations.
Key Takeaways
Structure is an Assumption: Every node and every edge (or lack thereof) in a graph is an assumption about how the world works.
Decomposition is Key: The goal is to break down a large, intractable problem into many small, manageable ones.
State the Query Semantics: Ordinary BN inference answers “after observing”; intervention questions require do(·) and causal identification.