%复刻alpha101-037 (rank(correlation(delay((open - close), 1), close, 200)) + rank((open - close))) factor_name='alpha101_037'; k=size(stock_info,1); alpha101_037=zeros(size(close_hfq,1),size(close_hfq,2)); a_037_1=zeros(size(close_hfq,1),size(close_hfq,2)); a_037_2=zeros(size(close_hfq,1),size(close_hfq,2)); n1=100;n2=44; for i=2:size(daylist_pair2,1) for j=1:k a_037_1(i,j)=open_hfq(i-1,j)-close_hfq(i-1,j); end end for i=200:size(daylist_pair2,1) for j=1:k temp=corrcoef(a_037_1(i-n1:i,j),close_hfq(i-n1:i,j)); a_037_2(i,j)=temp(1,end); alpha101_037(i,j)=open_hfq(i-n2,j)/close_hfq(i,j)+a_037_2(i,j); end end 把这段matlab写的函数改成python
时间: 2023-09-17 07:11:59 浏览: 75
Spearman-s-Rank-Correlation-Coefficient
下面是将该 Matlab 代码改写成 Python 代码的示例:
```python
import numpy as np
from scipy.stats import rankdata
# 计算alpha101_037因子
def alpha101_037(stock_info, open_hfq, close_hfq):
k = stock_info.shape[0]
alpha101_037 = np.zeros(close_hfq.shape)
a_037_1 = np.zeros(close_hfq.shape)
a_037_2 = np.zeros(close_hfq.shape)
n1 = 100
n2 = 44
for i in range(1, len(daylist_pair2)):
for j in range(k):
a_037_1[i, j] = open_hfq[i-1, j] - close_hfq[i-1, j]
for i in range(200, len(daylist_pair2)):
for j in range(k):
temp = np.corrcoef(a_037_1[i-n1:i, j], close_hfq[i-n1:i, j])
a_037_2[i, j] = temp[0, -1]
alpha101_037[i, j] = open_hfq[i-n2, j] / close_hfq[i, j] + a_037_2[i, j]
alpha101_037 = rankdata(alpha101_037) / len(alpha101_037)
return alpha101_037
```
需要注意的是,在 Python 中,没有内置的 `corrcoef` 函数,我们需要使用 `numpy` 库中的 `corrcoef` 函数来计算相关系数。同时,由于 Python 的数组索引从0开始,因此需要将索引的初始值从1改为0。此外,我们使用 `scipy.stats` 库中的 `rankdata` 函数来进行排名操作。
阅读全文