Build a Pandas Pipeline for Portfolio Returns and Risk Metrics
SQL & DataModel answerLast updated
Design a pandas workflow that cleans price CSVs, builds portfolio returns under several rebalancing rules, and reports return, risk, Sharpe and drawdown metrics for multiple portfolios.
You receive one or more CSV files of daily asset prices (or returns), plus a set of portfolio definitions, each a mapping from asset to weight. Write Python with pandas that does the following.
- Load and align. Read every file, parse dates, and merge them into one date-indexed table. Accept both wide files (one column per asset) and long files (
date, asset, price). - Clean. Handle missing values, duplicate dates, invalid prices and optionally outliers. Each choice must be explicit and documented.
- Returns. Derive simple and log returns from prices when needed.
- Portfolio returns. Produce a daily return series for a portfolio under fixed weights, periodic rebalancing (monthly, quarterly, yearly), or no rebalancing at all.
- Metrics. Compute cumulative return, annualized return, annualized volatility, Sharpe ratio (given an annual risk-free rate), maximum drawdown, and rolling-window versions of the main metrics.
- Multiple portfolios. Output a tidy summary table (one row per portfolio), a CSV of the metrics, and a plot-ready time series (date, portfolio, return, wealth, drawdown).
- Robustness. Keep the arithmetic numerically stable, keep function boundaries clean, and write unit tests for non-overlapping dates, zero weights and NaNs.
- Analysis. State the time and space complexity and justify your design decisions.
Explain your reasoning as well as writing code. A good answer names the conventions it picks (annualization factor, treatment of leftover weight, rebalancing semantics) and says why.
Hints
Hint 1
Structure the work as a chain of small, single-purpose functions: load, clean, compute returns, build the portfolio series, compute metrics, export. Each one should be testable alone.
Hint 2
Never back-fill missing prices, since that leaks future information. Forward-fill only for a bounded number of days, and align dates per portfolio using only the assets that carry non-zero weight.
Hint 3
With daily rebalancing, portfolio return is just the weighted sum of asset returns. For periodic or no rebalancing, compound each asset's growth inside the holding period, sum the weighted growth into a NAV, and take the day-over-day change of that NAV.
Hint 4
Compound in log space (log1p, cumsum, exp/expm1) and guard the divisions: Sharpe should be NaN when volatility is essentially zero, and the drawdown peak should start at 1.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Build a linear pipeline of small functions:
load -> clean -> returns -> (optional outlier clip) -> portfolio returns -> metrics / series -> export
The correctness concerns are alignment without look-ahead bias, correct rebalancing math, and stable compounding.
Documented design choices
| Concern | Choice | Reason |
|---|---|---|
| Duplicate dates | Keep the last row | Later rows are usually corrections |
| Prices <= 0 | Set to NaN | Bad ticks, and log returns would be undefined |
| Missing prices | Forward-fill up to ffill_limit days, never back-fill | Back-filling uses future data. Longer gaps stay NaN and drop out at alignment |
| Alignment | Per portfolio, only assets with non-zero weight, then intersect dates | A zero-weight asset with bad data should not shrink the sample |
| Outliers | Optional clip at median +/- k * MAD, off by default | Real crashes are not errors, so clipping must be an explicit, logged decision |
| Weights | Fractions of NAV, not normalized. The residual 1 - sum(w) is cash earning 0 | Supports long/short and dollar-neutral books |
| Rebalancing | "D" constant mix, "M"/"Q"/"Y" reset at period start, None buy-and-hold | Covers fixed and periodic schemes |
| Annualization | 252 days. Daily rf = (1+rf)^(1/252) - 1 | Standard geometric convention |
Rebalancing math
- Constant mix (daily reset): r_p,t = sum_i w_i * r_i,t, so it is a single matrix-vector product.
- Periodic or no rebalancing: inside a holding period each asset's value is w_i * G_i,t, where G is its cumulative growth since the period start. The NAV is V_t = sum_i w_i G_i,t + cash, with V = 1 at the period start. The daily return is V_t / V_{t-1} - 1. This reproduces weight drift exactly without a Python loop over days.
Metrics
- Cumulative return:
expm1(sum(log1p(r))) - Annualized return:
expm1(mean(log1p(r)) * 252) - Annualized volatility:
std(r, ddof=1) * sqrt(252) - Sharpe:
mean(excess) / std(excess) * sqrt(252), NaN if the std is about 0 - Max drawdown:
min(W / running_peak - 1), where the peak starts at 1 so a day-one loss counts
Code
import numpy as np
import pandas as pd
TD = 252
def load_prices(paths, date_col="date"):
frames = []
for p in paths:
df = pd.read_csv(p)
df[date_col] = pd.to_datetime(df[date_col], errors="coerce")
df = df.dropna(subset=[date_col])
if {"asset", "price"} <= set(df.columns): # long format
df = df.pivot_table(index=date_col, columns="asset",
values="price", aggfunc="last")
else: # wide format
df = df.set_index(date_col)
df = df[~df.index.duplicated(keep="last")]
frames.append(df.apply(pd.to_numeric, errors="coerce"))
out = pd.concat(frames, axis=1, join="outer").sort_index()
return out.loc[:, ~out.columns.duplicated(keep="last")]
def clean_prices(prices, ffill_limit=3):
return prices.where(prices > 0).ffill(limit=ffill_limit)
def clip_outliers(rets, k=None):
if k is None:
return rets
med = rets.median()
mad = (rets - med).abs().median() * 1.4826
return rets.clip(med - k * mad, med + k * mad, axis=1)
def compute_returns(prices, kind="simple"):
if kind == "simple":
r = prices.pct_change(fill_method=None)
elif kind == "log":
r = np.log(prices).diff()
else:
raise ValueError("kind must be 'simple' or 'log'")
return r.iloc[1:]
def portfolio_returns(rets, weights, rebalance="D"):
w = pd.Series(weights, dtype=float)
cash = 1.0 - w.sum()
w = w[w != 0]
if w.empty: # all cash
return pd.Series(0.0, index=rets.index, name="ret")
missing = set(w.index) - set(rets.columns)
if missing:
raise KeyError(f"no data for {missing}")
R = rets[w.index].dropna(how="any")
if R.empty:
raise ValueError("no overlapping dates")
if rebalance == "D":
return (R @ w).rename("ret")
keys = (pd.Series(0, index=R.index) if rebalance is None
else pd.Series(R.index.to_period(rebalance), index=R.index))
G = (1 + R).groupby(keys).cumprod()
V = G.mul(w, axis=1).sum(axis=1) + cash
prev = V.groupby(keys).shift(1).fillna(1.0)
return (V / prev - 1).rename("ret")
def metrics(r, rf=0.0):
if len(r) < 2:
raise ValueError("need at least 2 observations")
lr = np.log1p(r.clip(lower=-1.0))
wealth = np.exp(lr.cumsum())
peak = np.maximum(wealth.cummax(), 1.0)
rf_d = (1 + rf) ** (1 / TD) - 1
ex = r - rf_d
sd = ex.std(ddof=1)
return {
"cum_return": np.expm1(lr.sum()),
"ann_return": np.expm1(lr.mean() * TD),
"ann_vol": r.std(ddof=1) * np.sqrt(TD),
"sharpe": np.nan if sd < 1e-12 else ex.mean() / sd * np.sqrt(TD),
"max_drawdown": (wealth / peak - 1).min(),
}
def rolling_metrics(r, window=63):
lr = np.log1p(r.clip(lower=-1.0))
return pd.DataFrame({
"roll_return": np.expm1(lr.rolling(window).sum()),
"roll_vol": r.rolling(window).std() * np.sqrt(TD),
})
def run(prices, portfolios, rf=0.0, rebalance="M", out_csv="metrics.csv"):
rets = compute_returns(clean_prices(prices))
rows, series = [], []
for name, w in portfolios.items():
r = portfolio_returns(rets, w, rebalance)
rows.append({"portfolio": name, **metrics(r, rf)})
wealth = (1 + r).cumprod()
series.append(pd.DataFrame({
"date": r.index, "portfolio": name, "ret": r.values,
"wealth": wealth.values,
"drawdown": (wealth / np.maximum(wealth.cummax(), 1) - 1).values}))
summary = pd.DataFrame(rows).set_index("portfolio")
summary.to_csv(out_csv)
return summary, pd.concat(series, ignore_index=True)
Edge cases and tests
- Non-overlapping dates: the intersection is empty, so raise
ValueErrorrather than return empty metrics. - Zero weights: drop them before alignment. An all-zero book is all cash with 0 returns.
- NaNs: gaps up to the limit are forward-filled, and leading NaNs stay NaN.
- Fewer than 2 observations: raise an error.
- Zero volatility: Sharpe is NaN, not inf.
- Return <= -100%: wealth hits 0 and max drawdown is -1, which is why returns are clipped at -1 before
log1p.
Useful unit tests:
- A single asset with weight 1 reproduces its own returns.
- Daily rebalancing and buy-and-hold agree for a single asset.
- Monthly rebalancing differs from buy-and-hold for two assets with diverging returns, and matches a hand-computed NAV.
- A constant return series gives NaN Sharpe and 0 drawdown.
- A day-one loss gives a negative drawdown.
- Disjoint date ranges raise
ValueError. - A zero-weight asset full of NaNs does not change the result.
Complexity
Let R be the total input rows, T dates, N assets and P portfolios.
- Loading and pivoting is O(R log R), plus O(T*N) space.
- Cleaning and returns are O(T*N).
- Portfolio returns are O(T*N) per portfolio, since the groupby cumulative product is vectorized.
- Metrics and rolling windows are O(T) per portfolio.
- Overall time is O(R log R + PTN) and space is O(TN + PT).
Common mistakes
- Back-filling prices, which introduces look-ahead bias.
- Treating daily-rebalanced math as if it applied to buy-and-hold.
- Normalizing weights silently, which breaks long/short and cash books.
- Multiplying thousands of (1+r) terms directly, or dividing by a near-zero standard deviation.
- Starting the drawdown peak at the first wealth value instead of 1.
- Dropping all rows with any NaN across every asset, rather than only the assets in each portfolio.