Foundations#
In this section, we will build the foundations of financial data analysis using pandas:
Creating and manipulating DataFrames
Loading price data and structured metadata
Time-series operations with DatetimeIndex
Calculating returns, correlations, and basic risk metrics
Grouping companies by industry or sector
Merging market data with company fundamentals
Using MultiIndex DataFrames for more complex analyses
Running a full case study using your company_overviews.csv dataset
By the end of this section, you will be comfortable treating pandas DataFrames as the main “data container” for financial datasets and transitioning smoothly between pandas and NumPy for more advanced quantitative calculations.
Installation and Usage#
We can install pandas through pip:
pip install pandas
Then to use pandas, simply import. By convenetion, we use pd to refer to pandas.
import pandas as pd
Pandas Fundamentals#
Pandas builds on NumPy by adding labels and rich data structures designed for tabular and time-indexed data. This section introduces the essential components you will use throughout financial data analysis.
We will work with two main objects:
Series— a one-dimensional labeled arrayDataFrame— a two-dimensional table with labeled rows and columns
Once comfortable with these, you can navigate almost any pandas-based workflow.
Pandas Series#
A Series is like a NumPy array with index labels.
1import pandas as pd
2
3# Example: closing prices of a single stock
4prices = pd.Series(
5 [101.2, 103.5, 102.8, 104.1],
6 index=["2024-01-02", "2024-01-03", "2024-01-04", "2024-01-05"],
7 name="AAPL"
8)
9
10prices
2024-01-02 101.2
2024-01-03 103.5
2024-01-04 102.8
2024-01-05 104.1
Name: AAPL, dtype: float64
Key characteristics:
Each value has an index (here, dates).
.namehelps track the asset represented.Series support vectorized operations just like NumPy.
Example:
1# Daily returns using vectorized arithmetic
2returns = prices.pct_change()
3print(type(returns))
4print(returns)
<class 'pandas.core.series.Series'>
2024-01-02 NaN
2024-01-03 0.022727
2024-01-04 -0.006763
2024-01-05 0.012646
Name: AAPL, dtype: float64
Note that the first value in the series is NaN as their is no corresponding
return for that date in the data.
Pandas DataFrame#
A DataFrame is a table with labeled rows and columns, similar to a spreadsheet.
1data = {
2 "AAPL": [101.2, 103.5, 102.8, 104.1],
3 "MSFT": [245.3, 247.0, 246.2, 249.8]
4}
5
6df = pd.DataFrame(
7 data,
8 index=["2024-01-02", "2024-01-03", "2024-01-04", "2024-01-05"]
9)
10print(type(df))
11print(df)
<class 'pandas.core.frame.DataFrame'>
AAPL MSFT
2024-01-02 101.2 245.3
2024-01-03 103.5 247.0
2024-01-04 102.8 246.2
2024-01-05 104.1 249.8
This DataFrame has:
Rows labeled by date
Columns labeled by ticker
In financial time-series analysis, dates almost always serve as the row index rather than as columns because each row naturally represents the state of the market on a given day. Using dates as the index allows pandas to automatically align data across different assets, handle missing trading days, and perform time-based operations such as resampling, shifting, rolling windows, and merging multiple datasets. Keeping dates in the rows (rather than creating a separate column for each day) also keeps the DataFrame wide by assets and long over time—exactly the orientation most financial models expect.
We’ll reuse our AdjustedCloseMatrix class from the NumPy section, but this
time treating it as a DataFrame.
1from finance import AdjustedCloseMatrix
2matrix = AdjustedCloseMatrix(symbols=["AAPL", "MSFT", "GOOGL", "AMZN", "NVDA"], lookback_days=10)
3matrix.load_from_csv("../StockData/stocks")
4df = matrix.to_dataframe()
5df
| AAPL | MSFT | GOOGL | AMZN | NVDA | |
|---|---|---|---|---|---|
| 2025-11-06 | 269.509923 | 497.10 | 284.75 | 243.04 | 188.08 |
| 2025-11-07 | 268.211176 | 496.82 | 278.83 | 244.41 | 188.15 |
| 2025-11-10 | 269.430000 | 506.00 | 290.10 | 248.40 | 199.05 |
| 2025-11-11 | 275.250000 | 508.68 | 291.31 | 249.10 | 193.16 |
| 2025-11-12 | 273.470000 | 511.14 | 286.71 | 244.20 | 193.80 |
| 2025-11-13 | 272.950000 | 503.29 | 278.57 | 237.58 | 186.86 |
| 2025-11-14 | 272.410000 | 510.18 | 276.41 | 234.69 | 190.17 |
| 2025-11-17 | 267.460000 | 507.49 | 285.02 | 232.87 | 186.60 |
| 2025-11-18 | 267.440000 | 493.79 | 284.28 | 222.55 | 181.36 |
| 2025-11-19 | 268.560000 | 487.12 | 292.81 | 222.69 | 186.52 |
Selecting rows/columns#
Pandas uses two powerful selectors:
loc→ label-basediloc→ position-based
1row = df.loc["2025-11-11"] # row by date label
2column = df["AAPL"] # column by label
3
4df.iloc[0] # first row
5df.iloc[:, 1] # second column
6
7print(f"Row {type(row)}:\n{row}")
8print(f"Column {type(column)}:\n{column}")
Row <class 'pandas.core.series.Series'>:
AAPL 275.25
MSFT 508.68
GOOGL 291.31
AMZN 249.10
NVDA 193.16
Name: 2025-11-11 00:00:00, dtype: float64
Column <class 'pandas.core.series.Series'>:
2025-11-06 269.509923
2025-11-07 268.211176
2025-11-10 269.430000
2025-11-11 275.250000
2025-11-12 273.470000
2025-11-13 272.950000
2025-11-14 272.410000
2025-11-17 267.460000
2025-11-18 267.440000
2025-11-19 268.560000
Name: AAPL, dtype: float64
Filtering and Boolean Selection#
Filtering and Boolean selection let you extract rows or columns that satisfy
specific financial conditions, such as “days when AAPL rose more than 2%” or
“companies with market caps above $10B.” Instead of looping, pandas allows
you to write expressive, vectorized conditions that return a mask of True/False
values, which can then be used to select only the rows meeting your criteria.
This makes it easy to isolate trading signals, screen companies based on fundamentals,
or create rule-based filters across large datasets with just a single line of code.
In this example, we’ll select stocks that closed above $250 on Nov 11th
1# Stocks that closed above $250 on Nov. 11th
2stocks = df.loc["2025-11-11"][df.loc["2025-11-11"] > 250]
3print(type(stocks))
4print(stocks)
<class 'pandas.core.series.Series'>
AAPL 275.25
MSFT 508.68
GOOGL 291.31
Name: 2025-11-11 00:00:00, dtype: float64
We are doing two things in the first line: grabbing a specific day, then filtering that day’s prices.
df.loc["2025-11-11"]Uses
.locto select the row whose index label is"2025-11-11".If
dfis a price DataFrame (rows = dates, columns = tickers), this returns a Series: one price per stock on that date.
df.loc["2025-11-11"] > 250Compares each of those prices to 250.
Returns a Boolean Series (same index), with
Truewhere the price is greater than 250,Falseotherwise.
df.loc["2025-11-11"][df.loc["2025-11-11"] > 250]Uses that Boolean Series as a filter on the first Series.
Result: a Series of stocks whose price on 2025-11-11 is greater than 250.
So, stocks ends up holding only the tickers (as the index) and their prices (as the values) for those that traded above 250 on that specific date.
Summary Statistics#
Pandas automatically understands labeled data and can produce desccriptive statistics on numeric data.
df.describe() # summary statistics per column
df.mean() # mean closing price per stock
df.std() # standard deviation per stock
df.min() # daily minimum per stock
1df.describe()
| AAPL | MSFT | GOOGL | AMZN | NVDA | |
|---|---|---|---|---|---|
| count | 10.000000 | 10.000000 | 10.000000 | 10.000000 | 10.000000 |
| mean | 270.469110 | 502.161000 | 284.879000 | 237.953000 | 189.375000 |
| std | 2.803908 | 8.043495 | 5.611329 | 9.700089 | 4.918663 |
| min | 267.440000 | 487.120000 | 276.410000 | 222.550000 | 181.360000 |
| 25% | 268.298382 | 496.890000 | 280.192500 | 233.325000 | 186.665000 |
| 50% | 269.469961 | 504.645000 | 284.885000 | 240.310000 | 188.115000 |
| 75% | 272.815000 | 508.382500 | 289.252500 | 244.357500 | 192.412500 |
| max | 275.250000 | 511.140000 | 292.810000 | 249.100000 | 199.050000 |
1min_values = df.min()
2print(type(min_values))
3print(min_values)
<class 'pandas.core.series.Series'>
AAPL 267.44
MSFT 487.12
GOOGL 276.41
AMZN 222.55
NVDA 181.36
dtype: float64
By default, pandas computes summary statistics column-wise, meaning each column is treated as a separate series of values. For a price DataFrame where columns represent different stocks, methods such as .mean(), .std(), or .min() will return one statistic per stock as we saw in the above code.
Sometimes we want to compute statistics across rows instead—such as the a
verage price across all stocks on each day, or the daily maximum/minimum across
the portfolio. Pandas lets you control this using the axis parameter:
axis=0→ operate down the rows, producing one value per column (the default)axis=1→ operate across the columns, producing one value per row
1df.mean(axis=1) # average price across all stocks for each day
2df.max(axis=1) # the highest-priced stock each day
3
4print("Mean prices each day:")
5print(df.mean(axis=1))
6print("Max prices each day:")
7print(df.max(axis=1))
Mean prices each day:
2025-11-06 296.495985
2025-11-07 295.284235
2025-11-10 302.596000
2025-11-11 303.500000
2025-11-12 301.864000
2025-11-13 295.850000
2025-11-14 296.772000
2025-11-17 295.888000
2025-11-18 289.884000
2025-11-19 291.540000
dtype: float64
Max prices each day:
2025-11-06 497.10
2025-11-07 496.82
2025-11-10 506.00
2025-11-11 508.68
2025-11-12 511.14
2025-11-13 503.29
2025-11-14 510.18
2025-11-17 507.49
2025-11-18 493.79
2025-11-19 487.12
dtype: float64
This flexibility makes it easy to compute both asset-level and time-level statistics depending on the analysis you need.
Column Operations & Broadcasting#
Pandas automatically aligns columns by their labels and applies operations element-wise, just like NumPy. This behavior—called broadcasting—allows you to combine columns or apply arithmetic to an entire DataFrame without writing loops.
If your DataFrame df contains closing prices for 5 stocks across multiple dates:
df
AAPL MSFT AMZN GOOGL META
2025-01-02 102.5 247.8 150.2 133.0 265.4
2025-01-03 103.3 249.1 151.0 134.5 266.1
...
broadcasting means:
If you subtract one column from another, pandas subtracts row by row.
If you divide a column by a scalar, pandas divides every value in that column.
If you operate on the whole DataFrame with a scalar or a Series, pandas aligns by column name (or index) and broadcasts intelligently.
Spread Between Two Stocks#
1df["AAPL_MSFT_Spread"] = df["AAPL"] - df["MSFT"]
2df
| AAPL | MSFT | GOOGL | AMZN | NVDA | AAPL_MSFT_Spread | |
|---|---|---|---|---|---|---|
| 2025-11-06 | 269.509923 | 497.10 | 284.75 | 243.04 | 188.08 | -227.590077 |
| 2025-11-07 | 268.211176 | 496.82 | 278.83 | 244.41 | 188.15 | -228.608824 |
| 2025-11-10 | 269.430000 | 506.00 | 290.10 | 248.40 | 199.05 | -236.570000 |
| 2025-11-11 | 275.250000 | 508.68 | 291.31 | 249.10 | 193.16 | -233.430000 |
| 2025-11-12 | 273.470000 | 511.14 | 286.71 | 244.20 | 193.80 | -237.670000 |
| 2025-11-13 | 272.950000 | 503.29 | 278.57 | 237.58 | 186.86 | -230.340000 |
| 2025-11-14 | 272.410000 | 510.18 | 276.41 | 234.69 | 190.17 | -237.770000 |
| 2025-11-17 | 267.460000 | 507.49 | 285.02 | 232.87 | 186.60 | -240.030000 |
| 2025-11-18 | 267.440000 | 493.79 | 284.28 | 222.55 | 181.36 | -226.350000 |
| 2025-11-19 | 268.560000 | 487.12 | 292.81 | 222.69 | 186.52 | -218.560000 |
Here pandas subtracts MSFT from AAPL for each date, producing a new Series aligned by the date index,
and adding it to our dataframe
This is broadcasting across rows.
1# Clean up the added column
2df.drop(["AAPL_MSFT_Spread"], axis=1, inplace=True)
3
4# Can also use: del df["AAPL_MSFT_Spread"]
Scaling All Prices by a Factor#
If we divide the entire DataFrame by 100:
1df_scaled = df / 100
2df_scaled
| AAPL | MSFT | GOOGL | AMZN | NVDA | |
|---|---|---|---|---|---|
| 2025-11-06 | 2.695099 | 4.9710 | 2.8475 | 2.4304 | 1.8808 |
| 2025-11-07 | 2.682112 | 4.9682 | 2.7883 | 2.4441 | 1.8815 |
| 2025-11-10 | 2.694300 | 5.0600 | 2.9010 | 2.4840 | 1.9905 |
| 2025-11-11 | 2.752500 | 5.0868 | 2.9131 | 2.4910 | 1.9316 |
| 2025-11-12 | 2.734700 | 5.1114 | 2.8671 | 2.4420 | 1.9380 |
| 2025-11-13 | 2.729500 | 5.0329 | 2.7857 | 2.3758 | 1.8686 |
| 2025-11-14 | 2.724100 | 5.1018 | 2.7641 | 2.3469 | 1.9017 |
| 2025-11-17 | 2.674600 | 5.0749 | 2.8502 | 2.3287 | 1.8660 |
| 2025-11-18 | 2.674400 | 4.9379 | 2.8428 | 2.2255 | 1.8136 |
| 2025-11-19 | 2.685600 | 4.8712 | 2.9281 | 2.2269 | 1.8652 |
Every value in the DataFrame is divided by 100 — pandas broadcasts the scalar across all columns and rows.
This is broadcasting across the entire DataFrame.
Normalize Each Stock Relative to the First Day#
1first_day = df.iloc[0]
2df_normalized = df / first_day
3df_normalized
| AAPL | MSFT | GOOGL | AMZN | NVDA | |
|---|---|---|---|---|---|
| 2025-11-06 | 1.000000 | 1.000000 | 1.000000 | 1.000000 | 1.000000 |
| 2025-11-07 | 0.995181 | 0.999437 | 0.979210 | 1.005637 | 1.000372 |
| 2025-11-10 | 0.999703 | 1.017904 | 1.018788 | 1.022054 | 1.058326 |
| 2025-11-11 | 1.021298 | 1.023295 | 1.023038 | 1.024934 | 1.027010 |
| 2025-11-12 | 1.014694 | 1.028244 | 1.006883 | 1.004773 | 1.030413 |
| 2025-11-13 | 1.012764 | 1.012452 | 0.978297 | 0.977535 | 0.993513 |
| 2025-11-14 | 1.010761 | 1.026313 | 0.970711 | 0.965644 | 1.011112 |
| 2025-11-17 | 0.992394 | 1.020901 | 1.000948 | 0.958155 | 0.992131 |
| 2025-11-18 | 0.992320 | 0.993341 | 0.998349 | 0.915693 | 0.964271 |
| 2025-11-19 | 0.996475 | 0.979924 | 1.028306 | 0.916269 | 0.991706 |
What happens here?
first_dayis a Series with labels["AAPL", "MSFT", ...]When dividing a DataFrame by a Series, pandas aligns by column name
It divides each column of
dfby the corresponding value infirst_day
Result:
df_normalized.loc["2025-11-06"] → all 1.0
df_normalized.loc["2025-11-07"] → each price is relative to day 1
This is powerful: you can scale each stock independently with one line.
Compute Daily Percentage Returns (Elementwise Broadcasting)#
Here we can use one of Panda’s provided methods pct_change
to calculate the daily percentage change (expressed as a decimal).
Under the hood, pandas subtracts each row from its previous row and divides, applying the operation column by column using broadcasting.
1returns = df.pct_change()
2returns
| AAPL | MSFT | GOOGL | AMZN | NVDA | |
|---|---|---|---|---|---|
| 2025-11-06 | NaN | NaN | NaN | NaN | NaN |
| 2025-11-07 | -0.004819 | -0.000563 | -0.020790 | 0.005637 | 0.000372 |
| 2025-11-10 | 0.004544 | 0.018478 | 0.040419 | 0.016325 | 0.057933 |
| 2025-11-11 | 0.021601 | 0.005296 | 0.004171 | 0.002818 | -0.029591 |
| 2025-11-12 | -0.006467 | 0.004836 | -0.015791 | -0.019671 | 0.003313 |
| 2025-11-13 | -0.001901 | -0.015358 | -0.028391 | -0.027109 | -0.035810 |
| 2025-11-14 | -0.001978 | 0.013690 | -0.007754 | -0.012164 | 0.017714 |
| 2025-11-17 | -0.018171 | -0.005273 | 0.031149 | -0.007755 | -0.018773 |
| 2025-11-18 | -0.000075 | -0.026996 | -0.002596 | -0.044317 | -0.028081 |
| 2025-11-19 | 0.004188 | -0.013508 | 0.030006 | 0.000629 | 0.028452 |
Subtract a Market Benchmark From All Stocks#
Suppose you have a benchmark Series:
benchmark = df["AAPL"] # pretend AAPL is the benchmark
Subtract from all columns:
1benchmark = df["AAPL"] # pretend AAPL is the benchmark
2df_relative = df.sub(benchmark, axis=0)
3df_relative
| AAPL | MSFT | GOOGL | AMZN | NVDA | |
|---|---|---|---|---|---|
| 2025-11-06 | 0.0 | 227.590077 | 15.240077 | -26.469923 | -81.429923 |
| 2025-11-07 | 0.0 | 228.608824 | 10.618824 | -23.801176 | -80.061176 |
| 2025-11-10 | 0.0 | 236.570000 | 20.670000 | -21.030000 | -70.380000 |
| 2025-11-11 | 0.0 | 233.430000 | 16.060000 | -26.150000 | -82.090000 |
| 2025-11-12 | 0.0 | 237.670000 | 13.240000 | -29.270000 | -79.670000 |
| 2025-11-13 | 0.0 | 230.340000 | 5.620000 | -35.370000 | -86.090000 |
| 2025-11-14 | 0.0 | 237.770000 | 4.000000 | -37.720000 | -82.240000 |
| 2025-11-17 | 0.0 | 240.030000 | 17.560000 | -34.590000 | -80.860000 |
| 2025-11-18 | 0.0 | 226.350000 | 16.840000 | -44.890000 | -86.080000 |
| 2025-11-19 | 0.0 | 218.560000 | 24.250000 | -45.870000 | -82.040000 |
Explanation:
axis=0means “align by rows”Pandas subtracts the benchmark’s price for each date from every stock’s price on that same date
Your DataFrame now shows how each stock performs relative to the benchmark on each day.
Why Broadcasting Matters in Finance#
Broadcasting lets you:
scale all prices (e.g., convert currency units)
normalize price histories
compare every asset to a benchmark
compute spreads and ratios
apply transformations across entire portfolios
All without writing loops or managing indices manually. Pandas handles alignment and shape matching automatically.
Sorting and Ranking#
Sorting and ranking are essential when exploring financial datasets because they let us answer questions like:
“Which stocks increased the most today?”
“What were the highest closing prices this month?”
“Which companies have the largest market cap?”
Pandas makes it easy to sort data either by row index, by column values, or by multiple columns at once.
Sorting by Column Values#
When your DataFrame contains daily returns for several stocks (one column per ticker), sorting by a single column shows how that stock behaves relative to others on each date:
1# Sort the DataFrame by MSFT's daily returns (ascending)
2df.pct_change().sort_values("MSFT")
| AAPL | MSFT | GOOGL | AMZN | NVDA | |
|---|---|---|---|---|---|
| 2025-11-18 | -0.000075 | -0.026996 | -0.002596 | -0.044317 | -0.028081 |
| 2025-11-13 | -0.001901 | -0.015358 | -0.028391 | -0.027109 | -0.035810 |
| 2025-11-19 | 0.004188 | -0.013508 | 0.030006 | 0.000629 | 0.028452 |
| 2025-11-17 | -0.018171 | -0.005273 | 0.031149 | -0.007755 | -0.018773 |
| 2025-11-07 | -0.004819 | -0.000563 | -0.020790 | 0.005637 | 0.000372 |
| 2025-11-12 | -0.006467 | 0.004836 | -0.015791 | -0.019671 | 0.003313 |
| 2025-11-11 | 0.021601 | 0.005296 | 0.004171 | 0.002818 | -0.029591 |
| 2025-11-14 | -0.001978 | 0.013690 | -0.007754 | -0.012164 | 0.017714 |
| 2025-11-10 | 0.004544 | 0.018478 | 0.040419 | 0.016325 | 0.057933 |
| 2025-11-06 | NaN | NaN | NaN | NaN | NaN |
This reorders all rows (dates) based on MSFT’s daily returns. We can now compare the other stock’s daily returns for those dates.
To sort in descending order, add ascending=False:
1df.pct_change().sort_values("MSFT", ascending=False)
| AAPL | MSFT | GOOGL | AMZN | NVDA | |
|---|---|---|---|---|---|
| 2025-11-10 | 0.004544 | 0.018478 | 0.040419 | 0.016325 | 0.057933 |
| 2025-11-14 | -0.001978 | 0.013690 | -0.007754 | -0.012164 | 0.017714 |
| 2025-11-11 | 0.021601 | 0.005296 | 0.004171 | 0.002818 | -0.029591 |
| 2025-11-12 | -0.006467 | 0.004836 | -0.015791 | -0.019671 | 0.003313 |
| 2025-11-07 | -0.004819 | -0.000563 | -0.020790 | 0.005637 | 0.000372 |
| 2025-11-17 | -0.018171 | -0.005273 | 0.031149 | -0.007755 | -0.018773 |
| 2025-11-19 | 0.004188 | -0.013508 | 0.030006 | 0.000629 | 0.028452 |
| 2025-11-13 | -0.001901 | -0.015358 | -0.028391 | -0.027109 | -0.035810 |
| 2025-11-18 | -0.000075 | -0.026996 | -0.002596 | -0.044317 | -0.028081 |
| 2025-11-06 | NaN | NaN | NaN | NaN | NaN |
Sorting by column values is useful for quickly identifying the highest or lowest prices, returns, or signals.
Sorting by Multiple Columns#
You can also sort by several columns at once:
1df.sort_values(["AAPL", "MSFT"])
| AAPL | MSFT | GOOGL | AMZN | NVDA | |
|---|---|---|---|---|---|
| 2025-11-18 | 267.440000 | 493.79 | 284.28 | 222.55 | 181.36 |
| 2025-11-17 | 267.460000 | 507.49 | 285.02 | 232.87 | 186.60 |
| 2025-11-07 | 268.211176 | 496.82 | 278.83 | 244.41 | 188.15 |
| 2025-11-19 | 268.560000 | 487.12 | 292.81 | 222.69 | 186.52 |
| 2025-11-10 | 269.430000 | 506.00 | 290.10 | 248.40 | 199.05 |
| 2025-11-06 | 269.509923 | 497.10 | 284.75 | 243.04 | 188.08 |
| 2025-11-14 | 272.410000 | 510.18 | 276.41 | 234.69 | 190.17 |
| 2025-11-13 | 272.950000 | 503.29 | 278.57 | 237.58 | 186.86 |
| 2025-11-12 | 273.470000 | 511.14 | 286.71 | 244.20 | 193.80 |
| 2025-11-11 | 275.250000 | 508.68 | 291.31 | 249.10 | 193.16 |
This will:
Sort all rows by AAPL prices,
Break ties by sorting by MSFT’s prices.
This is often used in fundamental datasets—e.g., sort companies by sector, then market cap, then P/E ratio.
Sorting by the Index (Useful for Dates)#
Time-series data should typically be in ascending date order. Pandas ensures this with:
1df.sort_index()
| AAPL | MSFT | GOOGL | AMZN | NVDA | |
|---|---|---|---|---|---|
| 2025-11-06 | 269.509923 | 497.10 | 284.75 | 243.04 | 188.08 |
| 2025-11-07 | 268.211176 | 496.82 | 278.83 | 244.41 | 188.15 |
| 2025-11-10 | 269.430000 | 506.00 | 290.10 | 248.40 | 199.05 |
| 2025-11-11 | 275.250000 | 508.68 | 291.31 | 249.10 | 193.16 |
| 2025-11-12 | 273.470000 | 511.14 | 286.71 | 244.20 | 193.80 |
| 2025-11-13 | 272.950000 | 503.29 | 278.57 | 237.58 | 186.86 |
| 2025-11-14 | 272.410000 | 510.18 | 276.41 | 234.69 | 190.17 |
| 2025-11-17 | 267.460000 | 507.49 | 285.02 | 232.87 | 186.60 |
| 2025-11-18 | 267.440000 | 493.79 | 284.28 | 222.55 | 181.36 |
| 2025-11-19 | 268.560000 | 487.12 | 292.81 | 222.69 | 186.52 |
If your data imports out of order (common when merging sources), sorting by the
index ensures time-based operations such as .pct_change(), .shift(), or
.rolling() behave correctly.
Ranking#
Where sorting reorders rows, ranking assigns each value a numeric rank.
1df.rank()
| AAPL | MSFT | GOOGL | AMZN | NVDA | |
|---|---|---|---|---|---|
| 2025-11-06 | 6.0 | 4.0 | 5.0 | 6.0 | 5.0 |
| 2025-11-07 | 3.0 | 3.0 | 3.0 | 8.0 | 6.0 |
| 2025-11-10 | 5.0 | 6.0 | 8.0 | 9.0 | 10.0 |
| 2025-11-11 | 10.0 | 8.0 | 9.0 | 10.0 | 8.0 |
| 2025-11-12 | 9.0 | 10.0 | 7.0 | 7.0 | 9.0 |
| 2025-11-13 | 8.0 | 5.0 | 2.0 | 5.0 | 4.0 |
| 2025-11-14 | 7.0 | 9.0 | 1.0 | 4.0 | 7.0 |
| 2025-11-17 | 2.0 | 7.0 | 6.0 | 3.0 | 3.0 |
| 2025-11-18 | 1.0 | 2.0 | 4.0 | 1.0 | 1.0 |
| 2025-11-19 | 4.0 | 1.0 | 10.0 | 2.0 | 2.0 |
In the above DataFrame, we can quickly see where each stock had their high and low prices with comparing them to the other stocks.
For columns:
1df["AAPL"].rank()
2025-11-06 6.0
2025-11-07 3.0
2025-11-10 5.0
2025-11-11 10.0
2025-11-12 9.0
2025-11-13 8.0
2025-11-14 7.0
2025-11-17 2.0
2025-11-18 1.0
2025-11-19 4.0
Name: AAPL, dtype: float64
This gives each AAPL closing price a rank from lowest to highest.
Ranking is extremely useful in quant finance—for example:
Ranking stocks by momentum
Ranking companies by market cap
Ranking assets by volatility
Rank-based portfolio weighting strategies
You can also rank across rows (i.e., across stocks on a single day):
1df.rank(axis=1)
| AAPL | MSFT | GOOGL | AMZN | NVDA | |
|---|---|---|---|---|---|
| 2025-11-06 | 3.0 | 5.0 | 4.0 | 2.0 | 1.0 |
| 2025-11-07 | 3.0 | 5.0 | 4.0 | 2.0 | 1.0 |
| 2025-11-10 | 3.0 | 5.0 | 4.0 | 2.0 | 1.0 |
| 2025-11-11 | 3.0 | 5.0 | 4.0 | 2.0 | 1.0 |
| 2025-11-12 | 3.0 | 5.0 | 4.0 | 2.0 | 1.0 |
| 2025-11-13 | 3.0 | 5.0 | 4.0 | 2.0 | 1.0 |
| 2025-11-14 | 3.0 | 5.0 | 4.0 | 2.0 | 1.0 |
| 2025-11-17 | 3.0 | 5.0 | 4.0 | 2.0 | 1.0 |
| 2025-11-18 | 3.0 | 5.0 | 4.0 | 2.0 | 1.0 |
| 2025-11-19 | 3.0 | 5.0 | 4.0 | 2.0 | 1.0 |
This produces a DataFrame where each row shows how each stock’s price ranks relative to the others on that date.
Example use cases:
Identify the daily top performer across a basket of stocks
Build cross-sectional factor signals
Detect pair trading opportunities
Sorting vs Ranking — When to Use Each#
Task |
Use Sorting |
Use Ranking |
|---|---|---|
Find the highest/lowest values |
✓ |
— |
Get ordered tables (top 10 stocks, worst 20 days) |
✓ |
— |
Assign each stock a score from 1 to N |
— |
✓ |
Create factor signals (momentum, size, value) |
— |
✓ |
Visualize distributions based on order |
✓ |
✓ |
Sorting answers “in what order?” Ranking answers “what is the relative position?”
Together, they form the basis for many exploratory and quantitative finance workflows.
Handling Missing Data#
Missing data is extremely common in real world datasets. We’ll briefly introduce some common methods in this section and will go into more depth in a later notebook.
One very simple way to get missing values (NaN) is when we compute
daily returns: the first day has no previous day to compare to, so its return is undefined.
1# df contains daily closing prices for several stocks
2returns = df.pct_change()
3returns.head(3)
| AAPL | MSFT | GOOGL | AMZN | NVDA | |
|---|---|---|---|---|---|
| 2025-11-06 | NaN | NaN | NaN | NaN | NaN |
| 2025-11-07 | -0.004819 | -0.000563 | -0.020790 | 0.005637 | 0.000372 |
| 2025-11-10 | 0.004544 | 0.018478 | 0.040419 | 0.016325 | 0.057933 |
The first row of returns will be NaN for every stock, because pandas can’t
compute a percentage change from a non-existent prior day.
Detecting Missing Values#
We can use isna()
to produce a DataFrame in which the entries are Boolean to indicate whether or
not the corresponding value is NaN.
1na_df = returns.isna() # True where the value is NaN, False otherwise
2print(na_df)
3returns.isna().sum() # count of NaNs per column
AAPL MSFT GOOGL AMZN NVDA
2025-11-06 True True True True True
2025-11-07 False False False False False
2025-11-10 False False False False False
2025-11-11 False False False False False
2025-11-12 False False False False False
2025-11-13 False False False False False
2025-11-14 False False False False False
2025-11-17 False False False False False
2025-11-18 False False False False False
2025-11-19 False False False False False
AAPL 1
MSFT 1
GOOGL 1
AMZN 1
NVDA 1
dtype: int64
.isna()returns a DataFrame of booleans..sum()on booleans counts how manyTruevalues there are (i.e., how many missing values per stock).
Dropping Missing Values#
dropna()removes any row that contains at least oneNaN.For simple return series, this usually just drops the first day (since that’s where the NaNs are).
1returns_clean = returns.dropna()
2print(returns_clean)
AAPL MSFT GOOGL AMZN NVDA
2025-11-07 -0.004819 -0.000563 -0.020790 0.005637 0.000372
2025-11-10 0.004544 0.018478 0.040419 0.016325 0.057933
2025-11-11 0.021601 0.005296 0.004171 0.002818 -0.029591
2025-11-12 -0.006467 0.004836 -0.015791 -0.019671 0.003313
2025-11-13 -0.001901 -0.015358 -0.028391 -0.027109 -0.035810
2025-11-14 -0.001978 0.013690 -0.007754 -0.012164 0.017714
2025-11-17 -0.018171 -0.005273 0.031149 -0.007755 -0.018773
2025-11-18 -0.000075 -0.026996 -0.002596 -0.044317 -0.028081
2025-11-19 0.004188 -0.013508 0.030006 0.000629 0.028452
Filling Missing Values#
Sometimes we want to keep all dates and replace missing values with something sensible:
1returns_filled = returns.fillna(0)
2print(returns_filled)
AAPL MSFT GOOGL AMZN NVDA
2025-11-06 0.000000 0.000000 0.000000 0.000000 0.000000
2025-11-07 -0.004819 -0.000563 -0.020790 0.005637 0.000372
2025-11-10 0.004544 0.018478 0.040419 0.016325 0.057933
2025-11-11 0.021601 0.005296 0.004171 0.002818 -0.029591
2025-11-12 -0.006467 0.004836 -0.015791 -0.019671 0.003313
2025-11-13 -0.001901 -0.015358 -0.028391 -0.027109 -0.035810
2025-11-14 -0.001978 0.013690 -0.007754 -0.012164 0.017714
2025-11-17 -0.018171 -0.005273 0.031149 -0.007755 -0.018773
2025-11-18 -0.000075 -0.026996 -0.002596 -0.044317 -0.028081
2025-11-19 0.004188 -0.013508 0.030006 0.000629 0.028452
This replaces all
NaNvalues with0.For daily returns, this means “assume zero return on the first day.”
For prices or other time-series data, you’ll often see forward-fill or backward-fill:
1prices_ffill = df.ffill() # propagate last valid value forward
2prices_bfill = df.bfill() # propagate next valid value backward
We’ll explore more sophisticated strategies (interpolation, outlier handling, alignment issues) in a dedicated Data Cleaning chapter. For now, it’s enough to recognize that:
Missing values show up as
NaNisna(),dropna(),ffill(), andbfill()are the core tools to quickly inspect and handle them.
Creating DataFrames from NumPy#
Since pandas is built on top of NumPy, it’s very common to start with a NumPy array — especially when you’ve performed numerical work in the previous chapter — and then wrap that array in a DataFrame to gain labeling, easier slicing, and richer time-series tools.
Suppose you have a 2D NumPy array of closing stock prices where:
each row represents a stock,
each column represents a date.
1import numpy as np
2
3price_matrix = np.array([
4 [100, 101, 102],
5 [ 98, 97, 99]
6])
On its own, this array has no information about which stock is which, or which column corresponds to which day. This is where pandas becomes useful: we attach labels to both axes.
1tickers = ["AAPL", "MSFT"]
2dates = pd.date_range("2024-01-02", periods=3)
3
4df = pd.DataFrame(price_matrix, index=tickers, columns=dates)
5df
| 2024-01-02 | 2024-01-03 | 2024-01-04 | |
|---|---|---|---|
| AAPL | 100 | 101 | 102 |
| MSFT | 98 | 97 | 99 |
Why This Matters in Finance#
Attaching labels turns a plain matrix into something immediately useful:
Columns now carry dates, enabling time-based operations such as
.pct_change(),.shift(), or.rolling().Rows carry tickers, allowing easy slicing (
df.loc["AAPL"]) and merging with other datasets (like yourcompany_overviews.csv).You avoid indexing errors common in raw NumPy (e.g., mixing up which row is which stock).
This structure mirrors how most financial datasets are formatted in real platforms (e.g., Bloomberg, WRDS, Refinitiv, Yahoo Finance): assets as columns, dates as rows.
Example: Converting NumPy Returns to a DataFrame#
After computing returns with NumPy in the previous chapter, you can wrap them the same way:
1returns_matrix = np.diff(price_matrix) / price_matrix[:, :-1]
2
3returns_df = pd.DataFrame(
4 returns_matrix,
5 index=tickers,
6 columns=dates[1:] # shifted because returns have one fewer day
7)
8
9returns_df
| 2024-01-03 | 2024-01-04 | |
|---|---|---|
| AAPL | 0.010000 | 0.009901 |
| MSFT | -0.010204 | 0.020619 |
Now your numerical results carry meaningful labels, enabling:
plotting with seaborn,
merging with company metadata,
computing rolling stats,
aligning with benchmark returns,
exporting clean, readable tables.
Why These Basics Matter for Finance#
You will rely on these fundamentals in the rest of the chapter:
Time series operations need mastery of indexing
Grouped analysis (sector, industry, country) relies on filtering, merging, and aggregations
Merging metadata (from your
company_overviews.csv) requires comfort with DataFramesPortfolio construction often uses Series (for weights) aligned to DataFrame columns
Rolling windows, resampling, and joins build on these basics
This section forms the “grammar” of pandas — everything else builds on these patterns.