import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
prices = pd.read_csv('../Data/stock_prices_daily.csv',
parse_dates=['date'], index_col='date')
returns = prices.pct_change(fill_method=None).dropna()
train = 100 * returns.loc[:'2022-12-31']
market_inputs = train[['SP500']]
apple_pp = train['AAPL']
market_model = LinearRegression()
market_model.fit(market_inputs, apple_pp)
a = market_model.intercept_
b = market_model.coef_[0]
market_grid = np.linspace(market_inputs['SP500'].min(), market_inputs['SP500'].max(), 100)
plt.plot(market_inputs['SP500'], apple_pp, '.', label='Observed days')
plt.plot(market_grid, a + b * market_grid, label='Fitted line')
plt.xlabel('S&P 500 daily return (%)')
plt.ylabel('Apple daily return (%)')
plt.legend()
plt.show()Lecture 2: Introduction to Machine Learning
RSM338: Applications of Machine Learning in Finance Winter 2027
1 Introduction
In Lecture 1 we used covariance to describe how stocks move together. Suppose we’re writing a risk report on Apple. We want something more specific. If the market rises by 1%, how much would we expect Apple to move? Put the two returns on a scatterplot and draw a line. Its slope, Apple’s beta, tells us how much the fitted Apple return changes for a one-percentage-point move in the market.
The dots scatter around any line we draw. How should we judge one line against another? We’ll look at what the line gets right and where it misses, starting with one Tuesday in February. Then we’ll use those misses to work out how a computer can search for better coefficients. The search gives us an example of what it means to learn a rule from data. Once we have the rule, we can see how well it holds up on a year the computer hasn’t used to fit it.
2 Fit a Line to Apple and the Market
2.1 What does the slope tell us?
We need Apple’s return and the market return on the same day. Both are in the price file we used in Lecture 1. Apply pct_change to get simple returns, using the S&P 500 price index for the market. Each date gives a pair. We use the 1,258 pairs through the end of 2022 to fit the line and set aside the 250 pairs from 2023. That gives us later observations to judge the line once we’ve chosen it.
The horizontal coordinate \(x_t\) is the market return on date \(t\), and the vertical coordinate \(y_t\) is Apple’s return that day. We multiply the decimal returns by 100, so a coordinate of 1 means a 1% return. LinearRegression fits a line from those pairs. The double brackets in train[['SP500']] keep the input as a one-column table. fit reads one row per date and the matching Apple outcome. To draw the line, np.linspace gives us evenly spaced market returns across the range of the data. We use the fitted intercept and slope to calculate the line’s height at each one.
The line crosses the vertical axis at \(a\approx0.068\). That’s the fitted Apple return on a flat market day. The slope of \(b\approx1.228\) means a one-percentage-point rise in the market return goes with a 1.228-percentage-point rise in the fitted Apple return. Beta is unitless because both changes use the same units. We use raw returns on the supplied series here. In a CAPM regression we’d subtract the risk-free rate on each side, so the intercept there has a different interpretation.
The upward line shows a relationship, and the spread around it shows how much can happen on a particular day. Two days with nearly the same market return can have quite different Apple returns. That spread matters when you use beta in a risk report.
2.2 Read the vertical gaps
Can we see what the slope adds? Let’s compare the fitted line with a flat line. Keep the intercept the same so we can see what changing just the slope does. The two panels show the same five dates, February 5–9, 2018. Find Tuesday’s dot in each panel. Hold its market return fixed and travel vertically from the line to the observation. That’s the difference we want to measure.
On Tuesday the S&P 500 gained about 1.74%, and Apple gained about 4.18%. The flat line gives about 0.07%, so its Tuesday gap is about 4.11 percentage points. The tilted line puts the fitted return at 2.21%, much closer to the dot. We can reproduce that height using the same row-by-column calculation as for the portfolio.
\[ \widehat y_t= \begin{bmatrix}1 & x_t\end{bmatrix} \begin{bmatrix}a\\ b\end{bmatrix} =1\times a+x_t\times b. \]
The hat (read \(\widehat y_t\) as “\(y\) hat”) marks a fitted value. The 1 brings in the intercept on every date. The market return multiplies the slope. On Tuesday, using the unrounded coefficients, \(\widehat y_t\) is approximately \(0.068+1.228(1.744)=2.21\%\). The signed gap \(e_t=y_t-\widehat y_t\) is the residual. Tuesday’s is \(4.18-2.21=+1.97\) percentage points. A downward trip from the line to the dot gives a negative residual.
tuesday = train.loc['2018-02-06']
input_row = np.array([1, tuesday['SP500']]).reshape(1, 2)
coefficients = np.array([a, b]).reshape(2, 1)
tuesday_fitted = (input_row @ coefficients)[0, 0]
tuesday_gap = tuesday['AAPL'] - tuesday_fitted
print(f'Fitted Apple return: {tuesday_fitted:.2f}%')
print(f'Observed minus fitted: {tuesday_gap:+.2f} percentage points')Fitted Apple return: 2.21%
Observed minus fitted: +1.97 percentage points
2.3 Which line gives the smallest errors?
The tilted line got closer on Tuesday. To decide which line works better overall, we need to count its misses on the other dates too. If we add signed gaps, a miss above the line can cancel one below. Squaring makes both count. It also makes a large miss count more. A four-percentage-point miss costs \(4^2=16\) squared percentage points, four times the cost of a two-point miss. For Tuesday alone the fitted line contributes about \(1.97^2=3.88\) squared percentage points.
We need one score for the whole line. For a candidate intercept \(a\) and beta \(b\), calculate a squared residual for each date and average the squares. This is mean squared error (MSE).
\[ \mathcal L(a,b)=\frac{1}{N}\sum_{t=1}^{N} \underbrace{(y_t-a-bx_t)^2}_{\text{squared vertical gap on date }t}. \]
The sum runs through all \(N=1{,}258\) dates in the fitting sample. Ordinary least squares (OLS) chooses the intercept and beta that minimize the sum of squared residuals. Dividing that sum by the same \(N\) for every line preserves the winning pair.
The next graph holds \(a\) at its fitted value and varies \(b\). Each point on the curve stands for a whole candidate line in the return scatterplot. Beta zero gives the flat line and an MSE of about \(4.45\,\mathrm{pp}^2\). Beta 1.228 gives the fitted line and an MSE of about \(1.59\,\mathrm{pp}^2\). Past that beta the line tilts too far and the loss rises again.
We can write a function for the score. It takes a pair of trial coefficients and returns one number, the MSE of that line. The loop holds the intercept fixed, substitutes each trial beta and saves its score for the plot.
x = market_inputs['SP500'].to_numpy()
y = apple_pp.to_numpy()
def mean_squared_gap(parameters):
trial_a, trial_b = parameters
gaps = y - (trial_a + trial_b * x)
return np.mean(gaps ** 2)
beta_grid = np.linspace(-0.5, 2.75, 131)
loss_grid = []
for trial_beta in beta_grid:
loss_grid.append(mean_squared_gap([a, trial_beta]))
plt.plot(beta_grid, loss_grid)
plt.plot(0, mean_squared_gap([a, 0]), 's', label='Flat line')
plt.plot(b, mean_squared_gap([a, b]), 'D', label='OLS line')
plt.xlabel('Slope of the Apple line (β)')
plt.ylabel('Mean squared error (pp²)')
plt.legend()
plt.show()2.4 What came from the examples?
Recall the portfolio we calculated in Lecture 1. Once you give me the weights and the ten realized returns, a rule we wrote tells the computer exactly how to calculate the portfolio return. In the Apple problem we supplied the examples and chose a family of rules to try. Each example gives a past market return and Apple’s observed return that day. The fitting procedure learns the numbers that specify the rule.
The learned rule can answer the analyst’s question. At \(x=+1.0\), it gives \(0.068+1.228(1)\approx+1.30\%\). That’s the line’s value for the scenario. The residuals show the scope for an actual day’s return to differ from that number.
We can write an unknown average relationship as \(f(x)\) and an observed return as
\[y_t=f(x_t)+\varepsilon_t.\]
The Greek letter \(\varepsilon_t\) (epsilon) represents the day-specific variation around the average relationship. Our fitted rule \(\widehat f(x)=a+bx\) is an approximation to \(f\). A curve might capture a response that is different on down days and up days. A more flexible form gives the computer more ways to fit the examples, including more ways to follow chance fluctuations. We’ll come back to that when we try the fitted line on later dates.
3 Slopes on a Hill
3.1 The surface and one slice
A computer can measure the loss for any candidate line. If it can see which way the loss slopes from its current guess, it has a reason to move one way or the other. With beta alone the loss is a curve. Once we can change the intercept too, the loss is a surface over the two coefficients. Let’s see how to read slopes on a surface where we can already find the top by eye. The hill below has height
\[h(x_1,x_2)=-x_1^2-x_2^2.\]
The subscripts distinguish the two coordinates on the floor. At the origin the height is zero, the top of the hill. Our marked point \(P\) has floor coordinates \((1,0.5)\) and height \(-1.25\). The orange path holds the second coordinate at \(0.5\). Its highest point is at \(x_1=0\), where the height is \(-0.25\).
From the side, the orange path is the one-variable curve \(h(x_1,0.5)=-x_1^2-0.25\). Find \(P\) on the whole curve, then in the enlarged view. Moving from \(x_1=1\) to \(1.1\) changes the height from \(-1.25\) to \(-1.46\). The average slope over that small interval is rise over run, \(-0.21/0.10=-2.1\).
Shrink the step and that slope approaches \(-2\), the slope of the dashed tangent at \(P\). The tangent is the straight line the curve looks like when you zoom in on that point. The slope there is the derivative. Since we held \(x_2\) fixed, we call this the partial derivative with respect to \(x_1\) and write it as \(\partial h/\partial x_1\). Along this path the \(-x_2^2\) term stays constant and the derivative of \(-x_1^2\) is \(-2x_1\).
Hold \(x_1=1\) instead and take a step along \(x_2\). The height along that path is \(-1-x_2^2\), with slope \(-2x_2\). At \(P\) that slope is \(-1\). Now we have two numbers, each describing one way to move from the same point.
3.2 Put the slopes in a column
Look down on the hill. A contour joins floor points at the same height. The orange path and \(P\) are still visible. Walking toward smaller \(x_1\) helps, and so does walking toward smaller \(x_2\). The arrow combines those moves. It points twice as far along the first axis as along the second.
The gradient is the column of partial derivatives. The symbol \(\nabla\) (nabla) tells us to collect them in coordinate order.
\[ \nabla h(P) =\begin{bmatrix}\partial h/\partial x_1\\[2pt]\partial h/\partial x_2\end{bmatrix}_{P} =\begin{bmatrix}-2\\-1\end{bmatrix}. \]
The gradient points in the direction of steepest increase. The drawing shortens the arrow to fit the map. Its direction still leads toward higher contours. At the summit the partial slopes are both zero, so the gradient is zero. Such a point is called stationary. For this hill the surrounding heights are lower, so the origin is a maximum. At a smooth interior minimum the gradient is also zero, and the surrounding heights are at least as high. For Apple’s loss we want to go downhill.
4 Finding the Apple Fit
4.1 A numerical search and an OLS fit
On the hill, one coordinate changed at a time when we measured its slope. For Apple’s line the coordinates are the intercept \(a\), which raises or lowers the line, and beta \(b\), which tilts it. The height we want to bring down is the MSE. We already know which coefficients OLS chose. Can a search that begins with both coefficients at zero use the same squared gaps to find that pair? Pass the scoring function and the starting pair to minimize. search.x gives the coefficients it found and search.fun gives their score.
from scipy.optimize import minimize
search = minimize(mean_squared_gap, x0=[0.0, 0.0])
print(f'Intercept: {search.x[0]:.3f} pp, beta: {search.x[1]:.3f}')
print(f'Training MSE: {search.fun:.3f} pp²')Intercept: 0.068 pp, beta: 1.228
Training MSE: 1.586 pp²
Both methods give \(a\approx0.068\) and \(b\approx1.228\). The independent search could move both parameters. The picture shows its answer against the OLS loss slice with the intercept fixed at its fitted value.
4.2 One step from the flat line
Let’s work out an update ourselves. Hold \(a\) fixed at the fitted intercept so we have just one direction to search. Start with \(b=0\). If we raise beta by 0.10, Tuesday’s fitted Apple return increases by about \(1.74(0.10)=0.17\) percentage points. Its upward gap shrinks. On a negative market day, raising beta moves the fitted Apple return down. Add up the effects across all days to decide which way to move.
The gap on date \(t\) is \(e_t(b)=y_t-a-bx_t\). It changes at rate \(-x_t\) with respect to \(b\). Squaring the gap gives slope \(2e_t\) with respect to that gap. Multiply the two rates to get the effect of beta on the squared gap for one day. Averaging these effects gives the derivative of the loss along this slice.
\[\mathcal L'(b)=-\frac{2}{N}\sum_{t=1}^{N}x_t e_t(b).\]
At zero beta the derivative is about \(-4.66\). The negative sign says loss falls as beta rises locally. Gradient descent moves a fraction of the way in the opposite direction to the derivative. We use a learning rate \(\eta=0.1\), where \(\eta\) is the Greek letter eta.
\[b_{\rm next}=b-\eta\mathcal L'(b)\approx 0-0.1(-4.66)=0.47.\]
On this plot, a horizontal difference measures a change in beta. A vertical difference measures a change in fitting error, in squared percentage points. The first move improves both the line’s fit and our estimate of where the minimum lies.
4.3 Why do we measure the slope again?
The first update shrank some of the gaps, so the slope we measured at the flat line describes a line we’ve already left. How do we choose the next move? Work out the new gaps and use them to measure the slope again. The loop starts at the flat line and records each new beta and its loss. We can look up how far we’ve gone after any number of updates.
trial_b = 0.0
learning_rate = 0.1
beta_path = [trial_b]
loss_path = [mean_squared_gap([a, trial_b])]
for step in range(24):
gaps = y - (a + trial_b * x)
slope = -2 * np.mean(x * gaps)
trial_b = trial_b - learning_rate * slope
beta_path.append(trial_b)
loss_path.append(mean_squared_gap([a, trial_b]))The first entry in each list is the starting point, and entry 4 comes after four updates. The left panel below shows the same February observations and two lines. The right panel scores the orange line against all fitting dates. The line is already close to OLS after four moves. As the loss curve flattens, the same learning rate produces smaller changes.
history = pd.DataFrame({'Beta': beta_path, 'Training MSE (pp²)': loss_path})
history.loc[[0, 1, 4, 24]].rename_axis('Updates').round(3)| Beta | Training MSE (pp²) | |
|---|---|---|
| Updates | ||
| 0 | 0.000 | 4.448 |
| 1 | 0.466 | 2.688 |
| 4 | 1.046 | 1.649 |
| 24 | 1.228 | 1.586 |
On this quadratic loss, the slope guides us toward the minimum. A step that’s too large can overshoot. On a more complicated surface we may stop in a valley even when another valley is lower. Try starting to the right of 1.228. Predict the sign of the slope and the direction of the first step. If you use a coding assistant, ask it to change just the starting beta and report the loss before and after the first step. Read its edit and check whether the result agrees with your prediction.
5 The ML Formalism
5.1 The model, the loss and the learning algorithm
At each step the replay drew one whole line. We gave it Tuesday’s market return to get one fitted value and all 1,258 market returns to judge the whole line. The same distinction helps us describe other learning problems. For one day, we know what went into the rule and what actually happened. That’s one labeled example \((\mathbf x_i,y_i)\). The vector \(\mathbf x_i\) contains the inputs, or features, for observation \(i\). Here it contains one market return. The number \(y_i\) is the observed target, Apple’s same-day return. We collect the \(N\) labeled examples into the training set \(\mathcal D\).
The three ingredients of supervised learning answer different questions.
- The model. What rules should we consider? Write \(f_{\boldsymbol\theta}\) for a rule selected by the parameters \(\boldsymbol\theta\) (theta). For Apple, \(\boldsymbol\theta=(a,b)\) and \(f_{\boldsymbol\theta}(x_i)=a+bx_i\). Changing the parameters gives another line. Changing the model family lets us try other shapes.
- The loss. What does a bad prediction cost? Write \(L(y_i,\widehat y_i)\) for the cost on one example. We used \((y_i-\widehat y_i)^2\). If we used the absolute gap \(|y_i-\widehat y_i|\), doubling a miss would double its cost. With squared loss the cost quadruples, so the two objectives can favour different parameters.
- The learning algorithm. What procedure finds parameters that score well? We used a least-squares fit and a numerical search for the pair. The descent loop illustrates a search guided by the slope.
5.2 One score for the training set
The loss tells us how the line did on Tuesday. We need one score to choose between entire rules. The training objective, also called empirical risk, averages the losses across the examples.
\[ \mathcal L(\boldsymbol\theta;\mathcal D)=\frac{1}{N} \sum_{i=1}^{N}L\!\left(y_i,\, f_{\boldsymbol\theta}(\mathbf x_i)\right). \]
Read this from the inside out. First the rule produces a fitted value. Then \(L\) compares it with the observed outcome. Finally the sum and the division by \(N\) give the candidate rule one score. Training means choosing the parameters that minimize that score.
\[ \boldsymbol\theta^\star =\operatorname*{arg\,min}_{\boldsymbol\theta}\mathcal L(\boldsymbol\theta;\mathcal D), \qquad \widehat f=f_{\boldsymbol\theta^\star}. \]
The argmin returns the input that achieves the smallest score, here the intercept and beta. The minimum returns the score achieved there, about \(1.59\,\mathrm{pp}^2\). If you want a new Apple fitted return, use the winning pair in \(\widehat f\).
5.3 A direct solution and an iterative solution
Stack the date rows \([1,x_i]\) in a matrix \(X\) and the realized Apple returns in a column \(\mathbf y\). The OLS coefficients have a formula when the columns of \(X\) are linearly independent. Here that means the market return varies across the dates, so the market column and the column of ones supply different information.
\[\widehat{\boldsymbol\beta}=(X^\top X)^{-1}X^\top\mathbf y.\]
The two entries of \(\widehat{\boldsymbol\beta}\) are the intercept and market slope. The transpose \(\top\) interchanges rows and columns, and the inverse \(^{-1}\) undoes multiplication by \(X^\top X\). LinearRegression.fit solves the least-squares problem numerically. The coefficient system belongs in the Problem Set 1 preparation material.
For an iterative solution with several parameters, collect the slopes in the gradient, as we did on the hill. Start with a vector of parameters. At update \(k\), compute the gradient at the current vector and subtract a step in its direction. Repeat until the changes are small or the iteration budget is reached.
\[ \boldsymbol\theta^{(k+1)} =\boldsymbol\theta^{(k)} -\eta\,\nabla_{\boldsymbol\theta}\mathcal L(\boldsymbol\theta^{(k)};\mathcal D). \]
The gradient has one entry per parameter. The subscript on \(\nabla\) specifies what we change while keeping the training observations fixed. In the Apple loop we changed beta alone. When we let both parameters move, we also need a slope for changing the intercept. This is the same idea used to update many coefficients in a neural network.
Raising \(a\) by one unit lowers every gap by one unit. Using the same calculation as for beta, \(\partial\mathcal L/\partial a=-2\sum_t e_t/N\). At a least-squares minimum with an intercept, this slope is zero, so the training residuals average to zero. The beta slope is zero too, so the average product of the market return and the residual is zero. These conditions describe the bottom of the squared-error surface.
6 Does the Rule Carry Over?
6.1 Apply the same line to 2023
The fitting score told us which line to choose. How do we tell whether the line is useful on its own? Once we’ve fitted it through 2022, freeze it and apply it to the S&P 500 returns from 2023. Also give the analyst a simpler choice. Use Apple’s training average as the fitted return on every day. The two rules now face the same 2023 dates, so the constant shows how much knowing the market move helps.
Use root mean squared error (RMSE) on each set. Taking the square root of MSE puts the score back in percentage points. A root mean squared error of 0.89 percentage points describes the size of the errors under this measure, which puts more weight on the big misses.
test = 100 * returns.loc['2023-01-01':]
test_fit = market_model.predict(test[['SP500']])
train_average = apple_pp.mean()
train_market_rmse = np.sqrt(mean_squared_gap([a, b]))
market_rmse = np.sqrt(np.mean((test['AAPL'] - test_fit) ** 2))
train_mean_rmse = np.sqrt(np.mean((apple_pp - train_average) ** 2))
baseline_rmse = np.sqrt(np.mean((test['AAPL'] - train_average) ** 2))
pd.DataFrame({
'Market line RMSE (pp)': [train_market_rmse, market_rmse],
'Training mean RMSE (pp)': [train_mean_rmse, baseline_rmse],
}, index=['2018–22 fitting sample', '2023 holdout']).round(2)| Market line RMSE (pp) | Training mean RMSE (pp) | |
|---|---|---|
| 2018–22 fitting sample | 1.26 | 2.11 |
| 2023 holdout | 0.89 | 1.28 |
The market line improves the 2023 score by about 0.39 percentage points relative to the constant. This tells us the market feature helped explain Apple’s same-day moves in that year. Before markets open, the day’s S&P 500 return is still unknown. For an advance forecast we’d need an input available at the forecast time. The fitted line can already answer a conditional question such as what Apple’s return might be if the market rose 1%.
6.2 How precise is an average return?
The baseline puts a lot of responsibility on one number, Apple’s average return. If we used a different sample of the same length, how much might that average move? Volatility describes the spread of the individual days. The standard error of the mean describes the spread we would expect across estimates of the mean from repeated samples of the same size.
With a stable mean and variance and independent days, the variance of the average of \(T\) returns is the variance of one return divided by \(T\). Taking the square root and estimating the daily spread by the sample standard deviation \(s\) gives
\[\widehat{\operatorname{SE}}(\bar R)=\frac{s}{\sqrt{T}}.\]
We can see the scale of this uncertainty by using the full history for a descriptive calculation. The baseline in the 2023 check keeps its earlier training mean.
apple_returns = returns['AAPL']
t_days = len(apple_returns)
daily_mean = apple_returns.mean()
daily_volatility = apple_returns.std()
mean_se = daily_volatility / np.sqrt(t_days)
print(f'Mean daily return {100 * daily_mean:.3f}%')
print(f'Daily volatility {100 * daily_volatility:.3f} pp')
print(f'Standard error of the mean {100 * mean_se:.3f} pp')Mean daily return 0.123%
Daily volatility 1.995 pp
Standard error of the mean 0.051 pp
Apple’s estimate is \(1.995/\sqrt{1{,}508}\approx0.051\) percentage points. Even an average based on six years of daily data has appreciable uncertainty relative to the size of the mean. Under these assumptions, halving the standard error requires four times as many observations. Dependence across returns or changing conditions can alter the calculation.
6.3 Underfitting and overfitting
An average can move because the sample changed. The same issue comes up when we let a fitted rule bend. Which bends would we expect to see again on other dates? In the illustration, the three panels start with the same noisy observations. The straight line misses the broad bend in the underlying relationship. This is underfitting. The very flexible curve bends to meet individual observations, including their accidental variation. This is overfitting. The middle curve follows more of the overall shape.
In market data the underlying curve is unknown. A train/test comparison gives you evidence about generalization. Both Apple scores fell in 2023, including the constant’s score. A quieter period can give smaller errors even if the rule stays fixed. To see what the market feature adds, compare the two models within the same held-out period.
If you need to choose between several models or settings, use training data and a validation procedure for those choices. Keep a final test period for evaluating the resulting rule. An earlier-to-later split reflects when return data arrive. If an economic relationship changes across market regimes, later performance can change even when the original fit was sensible. We’ll return to model flexibility and evaluation with regression. James et al., An Introduction to Statistical Learning
7 Supervised and Unsupervised Learning
7.1 Supervised learning
For every day in our training set, we had the market return and Apple’s observed return on the same date. That observed outcome is what makes the problem supervised. We can judge a rule by comparing its fitted values with the targets. What kind of rule we need depends on what the target records.
7.1.1 Regression
Use regression when the target is a number. Apple’s return can take many numerical values, and we want the rule to estimate how much it moved in response to the market. The fitted value and the residual are both in return units.
7.1.2 Classification
A credit team has a different target. Given the latest payment and billing information for an account, will it default next month? “Default” and “no default” are categories, so this is classification. A classifier can estimate a probability of default. The team can then choose a level above which it flags the account for review.
Start with a rule the team could write itself. If the most recent recorded repayment delay is two months or longer, flag the account. The frozen UCI data cover 30,000 Taiwanese credit-card accounts. Each row is one account. PAY_0 is the September 2005 repayment status. LIMIT_BAL, BILL_AMT1 and PAY_AMT1 record the credit limit, latest bill and latest payment in New Taiwan dollars. default records the next month’s outcome, with 1 for default and 0 otherwise. pd.crosstab counts the combinations of the flag and the later outcome. Its True row contains the accounts flagged by the rule.
credit = pd.read_csv('../Data/credit_default.csv')
review_flag = credit['PAY_0'] >= 2
pd.crosstab(review_flag, credit['default'])| default | 0 | 1 |
|---|---|---|
| PAY_0 | ||
| False | 22411 | 4459 |
| True | 953 | 2177 |
The team flags 3,130 accounts, including 2,177 that later default. The upper-right entry is the 4,459 defaults the rule missed. The lower-left entry is the 953 flagged accounts that didn’t default. A higher delay threshold flags a subset of the same accounts. Try it and compare the loss of coverage with the reduction in reviews. Two accounts with the same delay can have very different bills and payment histories. Labeled examples containing those fields and the later outcomes would let us learn a rule that uses them together.
The dataset is I-Cheng Yeh’s Default of Credit Card Clients, distributed by the UCI Machine Learning Repository under CC BY 4.0. Data and field definitions
7.2 Unsupervised learning
What if we have measurements but no target? An investment team might have corruption, peace, property-rights and GDP growth indicators for each country. Country names identify the rows. The table gives us no observed peer group to predict. Unsupervised learning looks for structure in the features themselves.
country_risk = pd.read_csv('../Data/countryriskdata.csv')
country_risk[['Country', 'Corruption', 'Peace', 'Legal', 'GDP Growth']].head()| Country | Corruption | Peace | Legal | GDP Growth | |
|---|---|---|---|---|---|
| 0 | Albania | 39 | 1.867 | 3.822 | 5.000 |
| 1 | Algeria | 34 | 2.213 | 4.160 | 4.202 |
| 2 | Argentina | 36 | 1.957 | 4.568 | -2.298 |
| 3 | Armenia | 33 | 2.218 | 4.126 | 0.208 |
| 4 | Australia | 79 | 1.465 | 8.244 | 2.471 |
- Clustering groups similar rows. A risk team might use it to suggest countries with similar profiles for a peer comparison.
- Dimensionality reduction summarizes several features with fewer features. If two indicators tend to tell us much the same thing, we might use a shared measure to summarize them.
- Anomaly detection can flag rows with unusual combinations of features for a closer look when we have no examples already labelled unusual.
We’ll start with clustering in Lecture 3. To give the country team useful peers, we’ll have to decide what makes two rows similar.
8 Summary
We supplied Apple and market returns, a family of straight lines and a way to score each one. OLS found the coefficients that minimized squared error. Gradient descent showed how the same objective can guide a search. Each update uses the slope of the loss at the current parameters.
The model, loss and learning algorithm answer separate questions. A score on later dates answers a fourth question about whether the learned rule carries over. In 2023 the market line beat the training-mean baseline, conditional on observing the same-day market move. For credit classification an observed outcome can play the same role as Apple’s realized return. The country-risk table gives us a new problem. In Lecture 3 we’ll have measurements for each country and a reason to look for peers.










