KatInterview

Build a Pandas Pipeline for Portfolio Returns and Risk Metrics

SQL & DataModel answer
MediumModel answerSQL & Datapandastime-seriesportfolio-analytics

Last 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.

  1. 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).
  2. Clean. Handle missing values, duplicate dates, invalid prices and optionally outliers. Each choice must be explicit and documented.
  3. Returns. Derive simple and log returns from prices when needed.
  4. Portfolio returns. Produce a daily return series for a portfolio under fixed weights, periodic rebalancing (monthly, quarterly, yearly), or no rebalancing at all.
  5. 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.
  6. 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).
  7. Robustness. Keep the arithmetic numerically stable, keep function boundaries clean, and write unit tests for non-overlapping dates, zero weights and NaNs.
  8. 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.