一个小区产生的各种名称错误
在此代码中,我有一个单元格产生了三个不同的名称错误。首先是name error:名称'np'未定义
,第二个是name eRror:name'stroge_portfolio'未定义
。我摆脱了这两个。
第三个名称错误是name error:name'variance_matrix'未定义
。如您所见,它们肯定是定义的。什么事?我也可以通过再次定义vriance_matrix
来摆脱这一点,但是名称错误只是移动到单元格中的另一个变量。
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import matplotlib.pyplot as plt
import scipy.optimize as sco
stocks = ['corp1','corp2','corp3','corp4']
pf_data = pd.DataFrame()
for stock in stocks:
pf_data[stock] = web.DataReader(stock, data_source = 'yahoo', start = '2008-1-1')['Adj Close']
num_stocks = len(stocks)
pf_data
portfolio = pf_data
returns_portfolio = portfolio.pct_change()
weight_portfolio = [0.2, 0.4, 0.3, 0.1]
portfolio_return = returns_portfolio.dot(weight_portfolio)
variance_matrix = returns_portfolio.cov()*252
然后是包含错误的单元格。我对装饰器的使用知之甚少,但是我想 @ sign与错误有关。
#computing porfolio variance
portfolio_variance = np.transpose(weight_portfolio)@variance_matrix@weight_portfolio
#computing portfolio volatility i.e. risk
portfolio_volatility = np.sqrt(portfolio_variance)
print("Portfolio variance is", portfolio_variance)
print("Portfolio volatility is", portfolio_volatility)
In this code I have a cell that has produced three different name errors. First was NameError: name 'np' is not defined
, the second was NameError: name 'weight_portfolio' is not defined
. I got rid of these two.
The third name error is NameError: name 'variance_matrix' is not defined
. As you can see they sure are all defined. What is the matter? I can get rid of this as well by defining variance_matrix
again, but then name error just moves to another variable in the cell.
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import matplotlib.pyplot as plt
import scipy.optimize as sco
stocks = ['corp1','corp2','corp3','corp4']
pf_data = pd.DataFrame()
for stock in stocks:
pf_data[stock] = web.DataReader(stock, data_source = 'yahoo', start = '2008-1-1')['Adj Close']
num_stocks = len(stocks)
pf_data
portfolio = pf_data
returns_portfolio = portfolio.pct_change()
weight_portfolio = [0.2, 0.4, 0.3, 0.1]
portfolio_return = returns_portfolio.dot(weight_portfolio)
variance_matrix = returns_portfolio.cov()*252
Then comes the cell that contains the error. I know very little about the usage of decorators, but I guess the @ sign has something to do with the error.
#computing porfolio variance
portfolio_variance = np.transpose(weight_portfolio)@variance_matrix@weight_portfolio
#computing portfolio volatility i.e. risk
portfolio_volatility = np.sqrt(portfolio_variance)
print("Portfolio variance is", portfolio_variance)
print("Portfolio volatility is", portfolio_volatility)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试以这种方式导入numpy:从numpy import *或无别名导入numpy(在您的情况下NP)。
Try to import numpy in this way: from numpy import * or import numpy without an alias (np in your case).