我正在尝试计算股票投资组合的一阶和二阶矩(即预期回报和标准差)。
expected_returns_annual
Out[54]:
ticker
adj_close CNP 0.091859
F -0.007358
GE 0.095399
TSLA 0.204873
WMT -0.000943
dtype: float64
type(expected_returns_annual)
Out[55]: pandas.core.series.Series
weights = np.random.random(num_assets)
weights /= np.sum(weights)
returns = np.dot(expected_returns_annual, weights)
Run Code Online (Sandbox Code Playgroud)
所以通常预期回报计算为
(x1,...,xn' * (R1,...,Rn)
x1,...,xn 是具有约束的权重,所有权重必须加起来为 1,' 表示向量已转置。
现在我有点想知道 numpy dot 函数,因为
returns = np.dot(expected_returns_annual, weights)
Run Code Online (Sandbox Code Playgroud)
和
returns = np.dot(expected_returns_annual, weights.T)
Run Code Online (Sandbox Code Playgroud)
给出相同的结果。
我还测试了 weights.T 和 weights 的形状。
weights.shape
Out[58]: (5,)
weights.T.shape
Out[59]: (5,)
Run Code Online (Sandbox Code Playgroud)
weights.T 的形状应该是 (,5) 而不是 (5,),但 numpy 将它们显示为相等(我也尝试过 np.transpose,但结果相同)
有人知道为什么 numpy 会这样吗?在我看来, np.dot 乘积会自动塑造向量正确的原因,以便向量乘积运行良好。那是对的吗?
最好的问候汤姆
我也在进行简单的交易,并且需要一些帮助将数据帧连接在一起。直到现在,我的方法都行不通。
我的代码如下:
连接到量子API
quandl.ApiConfig.api_key = 'xxxxxxxxxxxxxxx'
Run Code Online (Sandbox Code Playgroud)
股票代号
ticker = ['FSE/ZO1_X',"FSE/WAC_X"]
Run Code Online (Sandbox Code Playgroud)
创建一个带有熊猫引号的面板对象->创建一个熊猫DataFrame
df = quandl.get(ticker, start_date='2017-01-01', end_date='2017-11-03')
Run Code Online (Sandbox Code Playgroud)
从面板数据集中切出每只股票的收盘价
close1 = df['FSE/ZO1_X - Close']
close2 = df['FSE/WAC_X - Close']
Run Code Online (Sandbox Code Playgroud)
将两个数据帧连接在一起-此步骤无效
close = pd.concat(close1,close2)
Run Code Online (Sandbox Code Playgroud)
close1和close 2的类型是pandas.core.series.Series。
如何将close1和close2放在一起,这样索引就是日期,并且我还有另外两个列,分别包含股票1(close1)和股票2(close2)的收盘价-类似于普通的Excel工作表。