How to replicate your favorite investment portfolio

April 6, 2024
Facebook logo.
Twitter logo.
LinkedIn logo.
Get this code in Google Colab

How to replicate your favorite investment portfolio

Market indices are vital in finance, offering investors a quick look at the overall performance of a specific market or sector.

They act as benchmarks for assessing the performance of different investment portfolios.

Investors can copy the performance of an index for exposure to securities without the need to buy each one.

This process is called index replication.

In this newsletter, we'll make a portfolio that replicates the S&P500.

How to replicate your favorite investment portfolio

Index replication is a strategy that lets investors mimic the performance of market indices. All without holding each asset in the index. These indices comprise various securities that reflect a particular market segment.

For investors following market indices, many make investments in the individual assets to replicate it.

However, this method can prove expensive, particularly for individual investors. So to replicate an index, we can weight a smaller portfolio to mimic index returns. That's where Riskfolio-Lib comes in.

We’ll use Riskfolio-Lib to optimize a portfolio's returns while minimizing its expected loss. We'll do this while keep a low tracking error relative to the S&P 500.

This constraint is the key for achieving index replication.

Let's see how it works.

Imports and set up

We’ll use Riskfolio-Lib to create our portfolio and yFinance for historical data.

1import riskfolio as rp
2import pandas as pd
3import yfinance as yf
4import warnings
5warnings.filterwarnings("ignore")

Next, we’ll download price data for the portfolio we want to weight. The weights will be those that minimize the tracking error between the portfolio and the index.

1assets = [
2    "JCI",
3    "TGT",
4    "CMCSA",
5    "CPB",
6    "MO",
7    "APA",
8    "MMC",
9    "JPM",
10    "ZION",
11    "PSA",
12    "BAX",
13    "BMY",
14    "LUV",
15    "PCAR",
16    "TXT",
17    "TMO",
18    "DE",
19    "MSFT",
20    "HPQ",
21    "SEE",
22    "VZ",
23    "CNP",
24    "NI",
25    "T",
26    "BA",
27    "^GSPC",
28]
29
30data = yf.download(assets, start="2016-01-01", end="2019-12-30")
31data = data.loc[:, ("Adj Close", slice(None))]
32data.columns = assets

The last step is to compute the portfolio and index returns.

1returns = data.pct_change().dropna()
2bench_returns = returns.pop("^GSPC").to_frame()

Build the portfolio

We’ll build the Riskfolio-Lib portfolio to estimate expected returns and the covariance matrix based on historical data. Then, we’ll set the portfolio attributes to get ready to optimize.

1port = rp.Portfolio(returns=returns)
2port.assets_stats(method_mu="hist", method_cov="hist", d=0.94)
3port.kindbench = False
4port.benchindex = bench_returns
5port.allowTE = True
6port.TE = 0.008

This code creates the portfolio object using historical returns data. It estimates the expected asset returns and covariance matrix based on historical data. Then it configures the portfolio to use an index with specified returns.

It also sets the tracking error constraint to a maximum limit relative to the benchmark returns.

Tracking error measures the deviation of a portfolio's returns from a benchmark index. By optimizing our portfolio with a maximum tracking error constraint, we can weight the portfolio so the returns closely match the index returns.

Run the optimization

Now that our portfolio is set up, we can run the optimization.

1model = "Classic"
2rm = "CVaR"
3obj = "Sharpe"
4hist = True
5rf = 0
6l = 0
7w = port.optimization(
8    model=model,
9    rm=rm,
10    obj=obj,
11    rf=rf,
12    l=l,
13    hist=hist
14)

This code calculates the optimal portfolio such that the weights maximize the risk adjusted return and minimize the conditional value at risk (otherwise known as CVaR or expected loss).

Riskfolio-Lib does this with the tracking error constraint. This means that while the portfolio is optimized, the tracking error does not exceed 0.008.

We can plot the optimal weights.

1ax = rp.plot_pie(
2    w=w,
3    title="Sharpe Mean CVaR",
4    others=0.05,
5    nrow=25,
6    cmap="tab20",
7    height=6,
8    width=10,
9    ax=None,
10)

The result is a donut plot that shows the weights of the top portfolio assets.

How to replicate your favorite investment portfolio. Market indices are vital the overall performance of a specific market or sector.

We can also create an efficient frontier. The Efficient Frontier represents a set of optimal portfolios that offer the highest expected return for a given level of risk or the lowest risk for a given level of expected return.

1frontier = port.efficient_frontier(
2    model=model, 
3    rm=rm, 
4    points=50, 
5    rf=rf, 
6    hist=hist
7)
8ax = rp.plot_frontier(
9    w_frontier=frontier,
10    mu=port.mu,
11    cov=port.cov,
12    returns=port.returns,
13    rm=rm,
14    rf=rf,
15    cmap="viridis",
16    w=w,
17    label="Max Risk Adjusted Return Portfolio",
18    marker="*",
19)

The result is our Efficient Frontier.

How to replicate your favorite investment portfolio. Market indices are vital the overall performance of a specific market or sector.

Next steps

With Riskfolio-Lib, you can use several different portfolio models including Black-Litterman and factor models to estimate returns. You can also use many different risk measures to optimize. As a next step, try building your own portfolio and experiment with the different expected return and risk models.

Man with glasses and a wristwatch, wearing a white shirt, looking thoughtfully at a laptop with a data screen in the background.