CML资本市场线 Python 画(Python构建资本市场线)

CML(Capital Market Line)资本市场线是为衡量收益与风险之间的平衡而生的。Python 作为世界上最流行的编程语言之一,其强大的数据分析和可视化工具支持使其在金融分析领域受到广泛关注。在本篇文章中,我们将介绍如何使用 Python 画 CML 资本市场线。

一、准备材料

在开始绘制 CML 资本市场线之前,需要准备以下材料:市场指数数据、风险无风险利率、不同投资组合的收益率与风险。

二、绘制资本市场线

首先,我们需要导入以下库文件:

    import matplotlib.pyplot as plt
    import numpy as np

接着,我们需要定义市场风险溢价公式,以及投资组合的风险、收益率数据。

    def market_risk_premium(rm, rf):
        return rm - rf

    def investment_return(weight, returns):
        return np.dot(weight.T, returns)

    def investment_risk(weight, cov_matrix):
        return np.dot(np.dot(weight.T, cov_matrix), weight)

    weight = np.array([0.3, 0.4, 0.3])
    returns = np.array([0.15, 0.10, 0.12])
    cov_matrix = np.matrix([[0.06, 0.03, 0.01], [0.03, 0.07, 0.03], [0.01, 0.03, 0.05]])
    rm = 0.10
    rf = 0.05

接下来,我们可以通过以下公式计算投资组合的风险和收益率。

    portfolio_returns = []
    portfolio_risks = []

    for i in range(1000):
        w = np.random.random(3)
        w /= sum(w)
        portfolio_returns.append(investment_return(w, returns))
        portfolio_risks.append(np.sqrt(investment_risk(w, cov_matrix)))

    portfolio_returns = np.array(portfolio_returns)
    portfolio_risks = np.array(portfolio_risks)

我们可以通过以下语句来绘制散点图。

    plt.scatter(portfolio_risks, portfolio_returns, c=(portfolio_returns - rf) / portfolio_risks)
    plt.xlabel('Risk')
    plt.ylabel('Return')

最后,我们可以使用以下代码来添加资本市场线。

    plt.plot([0, portfolio_risks.max()], [rf, rm], 'k-', lw=2)
    plt.xlim([0, portfolio_risks.max()])

三、效果图展示

通过以上代码的执行,我们得到了 CML 资本市场线,如下图所示:

四、总结

本篇文章介绍了如何使用 Python 画 CML 资本市场线,通过上述步骤的实现,我们能够更加直观地了解收益和风险之间的关系,并评估投资组合的风险和收益率。

Published by

风君子

独自遨游何稽首 揭天掀地慰生平