As an investor, not only do you want to watch your investment grow, you want it to grow as much as possible. However, being far from a sure thing, an investment carries a certain degree of risk, and while there is a possibility of achieving a great return, there is also the possibility of suffering a substantial loss. There are some investors that are willing to take on a high degree of risk, but I think it’s reasonable that many investors are typically risk-averse. The idea of incurring a large loss is probably an investor’s biggest fear. At the same time, an investor does want to be in a position to earn the highest return he or she can. It’s this dynamic of risk-and-reward that an investor has to weigh, and I think the central questions are what the highest return an investor can earn while not taking an excessive amount of risk, or what is the least amount of risk an investor can take while maximizing his return? Modern Portfolio Theory is an approach that answers these questions.
作为投资者,您不仅希望看到自己的投资增长,还希望它尽可能地增长。 但是,从不确定的事物来看,一项投资会承担一定程度的风险,尽管有可能获得丰厚的回报,但也有遭受重大损失的可能性。 有些投资者愿意承担较高的风险,但我认为许多投资者通常会规避风险是合理的。 造成巨大损失的想法可能是投资者最大的恐惧。 同时,投资者确实希望能够获得他或她可以获得的最高回报。 投资者必须权衡这种风险和回报的动态,我认为核心问题是,在不承担过多风险的情况下,投资者可以获得最高的回报,或者是投资者的最小风险是多少?可以最大限度地提高他的回报? 现代投资组合理论是回答这些问题的一种方法。
解释现代投资组合理论 (Explaining Modern Portfolio Theory)
Modern Portfolio Theory, founded by Harry Markowitz, is a theory that says that an investor can build a portfolio of stocks that maximizes return for a given level of risk. Similarly, for a given level of return, an investor can select a portfolio that minimizes the level of risk. Diversification makes this all possible. Diversification is the idea of building a portfolio of different and negatively correlated assets, so that if one asset were to go down, another asset in the portfolio would go up, helping offset the loss. In effect, this helps reduce “idiosyncratic risk” associated with each particular investment.
由哈里·马克维茨(Harry Markowitz)建立的现代投资组合理论是一种理论,该理论认为投资者可以建立股票投资组合,从而在给定风险水平下获得最大的回报。 类似地,对于给定的回报水平,投资者可以选择使风险水平最小的投资组合。 多样化使这一切成为可能。 多元化是建立由不同且负相关的资产组成的投资组合的想法,这样,如果一项资产下降,投资组合中的另一项资产将上升,从而有助于抵消损失。 实际上,这有助于减少与每个特定投资相关的“特质风险”。
Modern Portfolio Theory uses two inputs, assets’ historical returns and the risk, in this case variance, associated with the assets, to construct a portfolio of assets with an the optimal return, for a given level a risk, or the minimal amount of risk, for a given level of return. For example, say you’re considering building a portfolio consisting of Tesla, Apple, Walmart, and Caterpillar. If you wanted to maximize the return, given a level of risk, Modern Portfolio Theory would allocate a certain level of each stock to the portfolio e.g.40% Apple, 40% Tesla, 10% Walmart, and 10% Caterpillar, based on the historical returns and variance associated with each asset.
现代投资组合理论使用两个输入,即资产的历史收益和与资产相关的风险(在这种情况下为方差)来构建具有最佳收益,对于给定水平的风险或最小风险量的资产投资组合。 ,对于给定的回报水平。 例如,假设您正在考虑建立一个由Tesla,Apple,Walmart和Caterpillar组成的投资组合。 如果您想在一定风险水平下最大化回报,则现代投资组合理论会根据历史回报将一定比例的每只股票分配给投资组合,例如40%苹果,40%特斯拉,10%沃尔玛和10%卡特彼勒与每个资产相关的差异。
用Python实施现代投资组合理论 (Implementing Modern Portfolio Theory with Python)
Let’s now see how to implement Modern Portfolio Theory in practice. (The Modern Portfolio Theory portion of the code is from the book, Python for Finance, by Yves Hilpsich, which I highly recommend. You can access the code in its entirety here: https://github.com/yhilpisch/py4fi2nd/blob/master/code/ch13/13_a_statistics.ipynb). Sticking with our example of Apple, Tesla, Caterpillar, and Walmart, we’ll use the theory to construct the optimal balance of these stocks in order to achieve the highest return, for a given level of risk.
现在让我们看看如何在实践中实施现代投资组合理论。 (代码的现代投资组合理论部分来自Yves Hilpsich撰写的《 Python for Finance 》一书,我极力推荐。您可以在此处完整访问代码: https : //github.com/yhilpisch/py4fi2nd/blob /master/code/ch13/13_a_statistics.ipynb )。 继续以苹果,特斯拉,卡特彼勒和沃尔玛为例,我们将使用该理论构建这些股票的最佳平衡,以在给定风险水平下获得最高回报。
First, we’ll import the packages will be using:
首先,我们将导入将使用的软件包:
import pandas as pd
import ffn
import numpy as np
from pylab import mpl, plt
import scipy.stats as scs
import scipy.optimize as sco
import time
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'
%matplotlib inline
Next we’ll create an input box that accepts a list of stocks a user enters.
接下来,我们将创建一个输入框,该框接受用户输入的股票列表。
symbols = input('Enter a seris of tickers e.g. DOCU AMD NVDA')
symbols = symbols.split()
Then we’ll fetch stock data for Apple, Tesla, Caterpillar and Walmart.
然后,我们将获取苹果,特斯拉,卡特彼勒和沃尔玛的股票数据。
#retrieve stock data
prices = ffn.get(symbols, start='2015-01-01')
noa = len(symbols)
#Calculate Daily Returns
rets = np.log(prices / prices.shift(1))
We’ll then create two functions, one that calculates the annual returns and the other that calculates the volatility associated with our stocks.
然后,我们将创建两个函数,一个函数计算年收益,另一个函数计算与我们的股票相关的波动率。
def port_ret(weights):
return np.sum(rets.mean() * weights) * 252def port_vol(weights):
return np.sqrt(np.dot(weights.T, np.dot(rets.cov() * 252, weights)))
Next we’ll create a function that allows us to assess the strength of our portfolio. A value of 1 or higher is considered good.
接下来,我们将创建一个函数,使我们能够评估投资组合的实力。 1或更高的值被认为是好的。
def min_func_sharpe(weights):
return -port_ret(weights)/port_vol(weights)
Then we’ll essentially create a min-max operation i.e. minimizing volatility and maximizing the return.
然后,我们将本质上创建一个最小-最大操作,即最小化波动率并最大化回报。
cons = ({'type': 'eq', 'fun': lambda x: np.sum(x)-1})
bnds = tuple((0,1) for x in range(noa))
eweights = np.array(noa * [1. / noa,])%%time
opts = sco.minimize(min_func_sharpe, eweights, method='SLSQP', bounds=bnds, constraints=cons)
We’re now ready to see the return, volatility, and how good our portfolio is.
现在,我们准备看到收益,波动性以及我们的投资组合有多好。
print('The return is: {:.2f}'.format(port_ret(opts['x'].round(3))))
print('the volatility is: {:.2f}'.format(port_vol(opts['x'].round(3))))
print("The Sharpe Ratio is: {:.2f}".format(port_ret(opts['x']/port_vol(opts['x']))))
The return is 25%; the volatility is 26%, and the sharpe ratio — a measure of how good our portfolio is — is nearly 1. Overall, it’s an okay portfolio, but we can do better. The difficulty is finding the right combination of stocks or assets that would produce a high return, or a high Sharpe Ratio. It would be pretty cumbersome to keep inputting a group of stocks to get the desired Sharpe Ratio, so let’s see if we could speed that up with a few lines of code.
回报率为25%; 波动率为26%,夏普比率(衡量我们投资组合的良好程度的指标)接近1。总的来说,这是可以的投资组合,但我们可以做得更好。 困难在于找到能够产生高回报或高夏普比率的股票或资产的正确组合。 不断输入一组股票以获得所需的夏普比率会很麻烦,所以让我们看看是否可以通过几行代码来加快速度。
找到较高的夏普比率 (Finding a High Sharpe Ratio)
In order to do this efficiently, we first need to input stock tickers programmatically. To do that, we’ll retrieve all of the tickers from the Nasdaq 100:
为了有效地做到这一点,我们首先需要以编程方式输入股票报价器。 为此,我们将从纳斯达克100检索所有股票代码:
#Get Nasdaq tickers
web_data = requests.get('https://en.wikipedia.org/wiki/NASDAQ-100#Changes_in_2020').text
nasdaq_df = pd.read_html(web_data)
nasdaq_df = nasdaq_df[3]
nasdaq_tickers = list(nasdaq_df['Ticker'])
Secondly, a high Sharpe Ratio depends on stocks with strong historical returns. To identify those, I decided to look for stocks that have gone up by at least 50% this year (I wouldn’t call this the best strategy, and decided to use it more out of curiosity). The first thing this calls for is a function that calculates year-to-date performance for each stock in the Nasdaq 100 and then putting each of those into a data frame. Afterwards, we’ll then filter our data-frame accordingly.
其次,较高的夏普比率取决于具有良好历史收益的股票。 为了识别这些股票,我决定寻找今年至少上涨50%的股票(我不会将其称为最佳策略,而是出于好奇而决定更多地使用它)。 这首先需要一个函数,该函数计算Nasdaq 100中每只股票的年初至今表现,然后将它们放入数据框。 然后,我们将相应地过滤数据帧。
df = pd.DataFrame(columns=['ticker', 'ytd'])
for tick in nasdaq_tickers:
chg = ytd(tick)
row = [tick, chg]
df.loc[len(df)] = rowfiltered_df = df.query("ytd>=50")#convert to a list so that we can plug them into our MPT function
new_list = filtered_df['ticker'].tolist()
Like we did for Apple, Tesla, Caterpillar, and Walmart, we’ll then get historical data for our filtered list and plug them into our MPT functions.
就像我们对Apple,Tesla,Caterpillar和Walmart所做的那样,我们将为过滤后的列表获取历史数据并将其插入MPT功能。
#retreive stock data
prices = ffn.get(new_list, start='2015-01-01')
noa = len(new_list)
#Calculate Daily Returns
rets = np.log(prices / prices.shift(1))
cons = ({'type': 'eq', 'fun': lambda x: np.sum(x)-1})
bnds = tuple((0,1) for x in range(noa))
eweights = np.array(noa * [1. / noa,])
And then:
接着:
%%time
opts = sco.minimize(min_func_sharpe, eweights, method='SLSQP', bounds=bnds, constraints=cons)
And finally:
最后:
print('The return is: {:.2f}'.format(port_ret(opts['x'].round(3))))
print('the volatility is: {:.2f}'.format(port_vol(opts['x'].round(3))))
print("The Sharpe Ratio is: {:.2f}".format(port_ret(opts['x']/port_vol(opts['x']))))
Based on our filtered list, the maximum return, for a given level of risk is 104%, and the Sharpe Ratio is 2.73! A huge improvement over our last selection.
根据我们的过滤列表,对于给定的风险水平,最大回报为104%,夏普比率为2.73! 与我们上一次选择相比有很大的改进。
Finally, let’s see what the composition of our portfolio actually looks like:
最后,让我们看看我们的投资组合的组成实际上是什么样的:
i = 0
for x in opts['x']:
print(new_list[i] + ": " + str(x.round(2)))
i = i + 1
Portfolio Composition 投资组合构成
Zoom is where the portfolio is most concentrated, followed closely by DexCom, DocuSign, Pinduoduo, Tesla, Apple, and Moderna.
Zoom是投资组合最集中的地方,紧随其后的是DexCom,DocuSign,Pinduoduo,Tesla,Apple和Moderna。
现代投资组合理论的缺点 (Drawbacks of Modern Portfolio Theory)
At this point, we’ve made a portfolio that optimizes an expected return based on a given level of risk. Should we now go ahead and construct our portfolio in the way outlined above? Not so fast. The theory’s biggest drawback is mainly using the variance of each asset, and not accounting for downside risk i.e. a material change in market conditions. Moderna is a case and point. That stock is in the running to produce a vaccine for COVID-19, and obviously it could fail to do so, which would probably send the stock tumbling. Our portfolio would take a hit in such a scenario. Moderna’s downside risk is very real, so it might be a good idea to reconsider that allocation.
至此,我们已经建立了一个投资组合,可以根据给定的风险水平优化预期收益。 我们现在应该按照上面概述的方式继续构建我们的投资组合吗? 没那么快。 该理论的最大缺点是主要使用每种资产的方差,而不考虑下行风险,即市场条件的重大变化。 Moderna是一个案例和重点。 该库存正在生产用于COVID-19的疫苗,很显然它可能无法生产,这可能会使库存大跌。 在这种情况下,我们的投资组合将会受到打击。 Moderna的下行风险非常大,因此重新考虑该分配可能是个好主意。
This brings me an important point: I would not consider MPT the be all and end all. It’s best to do some additional research into each stock to get a full understanding of the risks associated with each investment. In a lot of cases, I use Modern Portfolio Theory as a starting point to give me a rough sense of how I should allocate my portfolio.
这给我带来了一个重要的观点:我不会认为MPT是万事通。 最好对每只股票做一些额外的研究,以全面了解与每笔投资相关的风险。 在很多情况下,我以现代投资组合理论为起点,让我对应该如何分配投资组合有一个粗略的认识。
结语 (Wrapping Up)
Putting it all together, we examined Modern Portfolio Theory to see how to select a portfolio with the highest return, given a level of risk, or the least amount of risk, given a level of return. And while there are drawbacks to the theory, I think it’s great to use as a starting point.
综上所述,我们研究了现代投资组合理论,以了解如何在给定风险水平的情况下选择收益最高的投资组合,或者在给定收益水平的情况下选择风险最小的投资组合。 尽管该理论有缺点,但我认为以它为起点非常好。
进一步阅读 (Further Reading)
Python for Finance
Python金融版
Portfolio Selection
投资组合选择
What is Portfolio Theory and Why it is Important
什么是投资组合理论及其重要性
翻译自: https://medium.com/analytics-vidhya/constructing-a-killer-investment-portfolio-with-python-51f4f0d344be