Session 9 · Workshop

Workshop: the line, with packages

This morning Pavel built the line by hand. Now you get the same numbers in three lines of code, and a picture at every step.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Workshop

Where we are

  • Part 1 (sessions 1–7): plain Python. Loops, lists, dicts, functions, files, errors. This is exactly what internship coding tests check: CodeSignal, HackerRank, the online test before the interview.
  • Part 2 (sessions 9–14): data science. From today, the packages everybody in the field uses.
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Workshop

A package is code someone else wrote

import brings it into your file. On Nuvolos, these are already installed.

Package What it does You write
pandas tables: read, look, compute import pandas as pd
matplotlib pictures import matplotlib.pyplot as plt
scikit-learn models, like the line from sklearn.linear_model import LinearRegression

pd and plt are short names everybody uses.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Workshop

The line exists in several packages

Package Who uses it What you get
scikit-learn the standard of data science and machine learning fit, predict, the same pattern for every model
statsmodels statistics, finance research the full regression table: standard errors, t-stats, p-values
pyfixest economics, econometrics regressions with fixed effects, like Stata's reghdfe

Same least squares underneath: same beta, 1.296. Today we use scikit-learn.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Workshop

pandas: a table, and a first look

prices = pd.read_csv("prices.csv", index_col="Date", parse_dates=True)

prices.head(3)        # the first 3 rows
prices.shape          # (rows, columns): (250, 4)
prices["AAPL"]        # one column
prices.describe()     # mean, std, min, max … of every column
prices.pct_change()   # daily returns: (today − yesterday) / yesterday

Always look at the table before you compute anything.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Workshop

matplotlib: draw, save, open

plt.scatter(returns["VOO"], returns["AAPL"])   # one point per day
plt.savefig(HERE / "step-4.png")                # save the picture as a file
plt.close()

Then open step-4.png in the Explorer on the left.

Pavel's lesson this morning (Anscombe): the same numbers can hide very different pictures. Look first.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Workshop

scikit-learn: always the same three moves

model = LinearRegression()      # 1. make a model
model.fit(X, y)                 # 2. fit it to the data
model.coef_, model.score(X, y)  # 3. read it: the slope, R²
model.predict(...)              #    and use it
  • X is a table: returns[["VOO"]], with two brackets.
  • y is one column: returns["AAPL"].

Same slope as the lecture's cov / var. No magic: the same least squares.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Workshop

Read the documentation

Nobody remembers every function. Professionals look it up, every day.

  • Where: scikit-learn.org, pandas.pydata.org, matplotlib.org. Search "sklearn LinearRegression".
  • One page per function. Read it in this order:
    1. Examples at the bottom: copy one, run it.
    2. Parameters: what you can give it.
    3. Attributes / Returns: what you get back (coef_, intercept_).
  • In VS Code: type model. and wait, the list shows everything the model has. Hover over a name to see its help.
  • Check your version (pip show scikit-learn) against the version on the page: old versions differ.
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Workshop

How today's file works

  1. Open week-09/workshop-s09.py.
  2. Find the first ___ (three underscores) and replace it.
  3. Press ▷. Read the terminal:
✓ Step 1: right, (250, 4)
✗ Step 2: fill the ___ in this step.
  1. Pictures appear as step-N.png next to the file.

Do the steps in order: each one uses the one before.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Workshop

Today's story: does each share follow the market?

  1. Load the prices, take a first look
  2. Daily returns: which share moves the most?
  3. 🖼 The year: all four shares start at 100
  4. 🖼 The cloud: market against Apple. Guess the slope!
  5. The line: fit, the beta, R²
  6. 🖼 The line on the cloud. The market falls 2 %: and Apple?
  7. 🖼 One typo in the file: what happens to the beta?

Part 2, build it yourself (no scikit-learn): 8. the slope by hand · 9. R² by hand · 10. 🖼 gradient descent finds the line

★ Faster? 11: a beta for every share · 12: two halves of the year, two betas · 13: the beta of the whole ledger

Data Science and Advanced Programming · UNIL · 2026