Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Portfolio Theory

Python Portfolio Theory

Everyone says "don't put all your eggs in one basket", but how to choose the baskets and how to split the eggs has rigorous mathematics behind it.

This article uses three real A-shares (Kweichow Moutai, ICBC, CATL) to walk through Markowitz portfolio theory completely: random portfolio scatter, maximum Sharpe portfolio, CAPM Beta, and risk parity.


The mathematical essence of diversification

First look at the 2019-2024 annualized return and volatility of the three stocks (computed from daily returns):

Example

import

yfinance

as

yf

import

pandas

as

pd

import

numpy

as

np

Three A-shares from different industries: consumer, banking, new energy

symbols

=

[

"600519.SS"

,

"601398.SS"

,

"300750.SZ"

]

names

=

[

"Kweichow Moutai"

,

"ICBC"

,

"CATL"

]

prices

=

yf.

download

(

symbols

,

start

=

"2019-01-01"

,

end

=

"2024-12-31"

,

                     progress

=

False

,

multi_level_index

=

False

)

[

"Close"

]

daily_ret

=

prices.

pct_change

(

)

.

dropna

(

)

Annualized return (geometric compounding) and annualized volatility

mu_ann

=

(

1

)

.

prod

(

)

**

(

252

/

len

(

daily_ret

)

)

1

vol_ann

=

daily_ret.

std

(

)

sqrt

(

252

)

print

(

pd.

DataFrame

(

{

"Annualized return"

: mu_ann

,

"Annualized volatility"

: vol_ann

}

,

                   index

=

names

)

.

round

(

4

)

.

to_string

(

)

)

The output is shown below:



          年化收益    年化波动

贵州茅台   0.2012   0.2964

工商银行   0.1127   0.1605

宁德时代   0.3944   0.4611

The three stocks have very different risk-return profiles: CATL has the highest return and also the largest volatility; ICBC has the lowest return but is the most stable.

The magic of diversification hides in the covariance matrix: a portfolio's volatility depends not only on each asset's volatility, but even more on their correlations.

Example

Annualized covariance matrix: the raw material for computing portfolio volatility

cov_ann

=

daily_ret.

cov

(

)

252

print

(

cov_ann.

round

(

4

)

.

to_string

(

)

)

The output is shown below:



          600519.SS  601398.SS  300750.SZ

600519.SS     0.0878     0.0094     0.0498

601398.SS     0.0094     0.0258     0.0013

300750.SZ     0.0498     0.0013     0.2126

Note that the off-diagonal elements (covariances) are far smaller than the diagonal elements (variances) - the three stocks are not highly correlated pairwise. In the portfolio volatility formula these "cross terms" are partly cancelled out; this is the source of diversification's risk reduction.


Efficient frontier: 5000 random portfolios

Given a set of weights w, the portfolio's annualized return and volatility can be computed directly. Use 5000 sets of random weights to scan the "risk-return" plane:

Example

rng

=

np.

random

.

default_rng

(

42

)

weights

=

rng.

dirichlet

(

np.

ones

(

3

)

,

5000

)

     

5000 sets of random weights, each summing to 1

Portfolio return: weights dotted with each asset's return

port_ret

=

weights

@

mu_ann.

values

Portfolio volatility: square root of w^T x covariance x w

port_vol

=

np.

sqrt

(

np.

einsum

(

"ij,jk,ik->i"

,

weights

,

cov_ann.

values

,

weights

)

)

sharpe

=

(

port_ret -

0.03

)

/ port_vol          

Risk-free rate set to 3%

best

=

sharpe.

argmax

(

)

print

(

f

"Max Sharpe among random portfolios: {sharpe[best]:.3f}"

)

print

(

"Max Sharpe portfolio weights:"

)

print

(

pd.

Series

(

weights

[

best

]

,

index

=

names

)

.

round

(

4

)

.

to_string

(

)

)

The output is shown below:



随机组合中最大夏普: 0.960

Max Sharpe ratio portfolio weights:

贵州茅台    0.1539

工商银行    0.5546

宁德时代    0.2915

Plot the 5000 points and you get the textbook "bullet" shape:

Example

import

matplotlib.

pyplot

as

plt

fig

,

ax

=

plt.

subplots

(

figsize

=

(

12

,

7

)

)

sc

=

ax.

scatter

(

port_vol

,

port_ret

,

c

=

sharpe

,

cmap

=

"viridis"

,

                s

=

6

,

alpha

=

0.6

)

plt.

colorbar

(

sc

,

ax

=

ax

,

label

=

"Sharpe Ratio"

)

ax.

scatter

(

port_vol

[

best

]

,

port_ret

[

best

]

,

marker

=

"*"

,

s

=

420

,

           color

=

"#c0563f"

,

zorder

=

3

,

label

=

"Max Sharpe Portfolio"

)

for

i

,

name

in

enumerate

(

names

)

:

    ax.

scatter

(

vol_ann.

iloc

[

i

]

,

mu_ann.

iloc

[

i

]

,

marker

=

"o"

,

               s

=

90

,

color

=

"#1f2933"

,

zorder

=

3

)

    ax.

annotate

(

name

,

(

vol_ann.

iloc

[

i

]

,

mu_ann.

iloc

[

i

]

)

,

                xytext

=

(

8

,

6

)

,

textcoords

=

"offset points"

,

fontsize

=

11

)

ax.

set_title

(

"5000 Random Portfolios: Risk vs Return (2019-2024)"

)

ax.

set_xlabel

(

"Annualized Volatility"

)

ax.

set_ylabel

(

"Annualized Return"

)

ax.

legend

(

)

ax.

grid

(

alpha

=

0.25

)

plt.

show

(

)

Run the code above and the output chart is as follows:

Random Portfolio Risk-Return Scatter Plot and Efficient Frontier

The chart reveals three important facts:

Observation Meaning
All scatter points lie to the left of the individual assets Portfolios can achieve lower volatility than any constituent stock - diversification works
The scatter forms the left boundary of the "bullet" This boundary is the efficient frontier, the set of portfolios with the highest return for a given risk
Max Sharpe portfolio Sharpe 0.960 Higher than any single asset (Moutai 0.578, ICBC 0.515, CATL 0.790)

The max Sharpe portfolio holds only 15% Moutai and 55% ICBC - the highest-return CATL is just 29%. Because ICBC's correlation with the other two is extremely low (covariances 0.0094 and 0.0013), it is the best "diversifier".

Note: random search only demonstrates the principle; in engineering use scipy.optimize to minimize the negative Sharpe. Also historical covariance is unstable, the efficient frontier moves over time - don't treat it as a permanent map.


CAPM: scoring a stock's "market sensitivity"

The Capital Asset Pricing Model (CAPM) splits asset returns into two parts: Beta that follows the market and Alpha that is the excess.

Beta is estimated as the regression slope of a stock's returns on market returns. Use an ETF tracking the CSI 300 (510300.SS) as the market proxy:

Example

CSI 300 ETF as the market benchmark proxy

bench

=

yf.

download

(

"510300.SS"

,

start

=

"2019-01-01"

,

end

=

"2024-12-31"

,

                    progress

=

False

,

multi_level_index

=

False

)

[

"Close"

]

mkt_ret

=

bench.

pct_change

(

)

.

dropna

(

)

for

sym

,

name

in

zip

(

symbols

,

names

)

:

    r

=

daily_ret

[

sym

]

    common

=

r.

index

.

intersection

(

mkt_ret.

index

)

    beta

=

np.

polyfit

(

mkt_ret.

loc

[

common

]

,

r.

loc

[

common

]

,

1

)

[

0

]

   

print

(

f

"{name}: Beta = {beta:.3f}"

)

The output is shown below:



贵州茅台: Beta = 1.008

工商银行: Beta = 0.302

宁德时代: Beta = 1.301

Beta range Meaning
Beta = 1 Moves in sync with the market
Beta > 1 When the market rises 10% it rises more, aggressive
Beta < 1 Less volatile than the market, defensive
Beta < 0 Moves opposite to the market, rare

ICBC's Beta is only 0.302 - when the broad market falls 10% it falls only 3% on average, which is exactly why it is an excellent diversifier, mutually confirming the efficient-frontier finding.


Risk parity: let each asset contribute the same risk

An equal-weight portfolio looks fair, but in fact high-volatility assets contribute most of the risk. Risk Parity allocates weights by the inverse of volatility, making each asset's risk contribution similar:

Example

Inverse-volatility weighting: the higher the volatility the smaller the weight (a simplified version of risk parity)

inv_vol

=

1

/ vol_ann

rp_weights

=

inv_vol / inv_vol.

sum

(

)

print

(

pd.

Series

(

rp_weights.

values

,

index

=

names

)

.

round

(

4

)

.

to_string

(

)

)

The output is shown below:



贵州茅台    0.2866

工商银行    0.5292

宁德时代    0.1842

CATL has the largest volatility, its weight is pushed down to the lowest 18%; ICBC is the most stable, at 53%.

Solution Weighting logic Who It's For
Equal weight 1/3 each Simplest, but risk is dominated by high-volatility assets
Market-cap weighting Allocate by market cap The approach of index funds
Inverse volatility Reciprocal of volatility Pursue balanced risk contribution
Maximum Sharpe Optimization solution Return-oriented, but sensitive to parameters

Note: all of the above is based on 2019-2024 historical data. Returns and correlations both drift; the historically optimal portfolio is not the future optimal portfolio - this topic is systematically covered in the parameter optimization article.