【发布时间】:2019-07-24 14:12:24
【问题描述】:
这是我的数据:
Last
Date
2019-02-19 277.850006
2019-02-20 278.410004
2019-02-21 277.420013
2019-02-22 279.140015
2019-02-25 279.940002
我正在将此功能用于日常数据,效果很好。
def corr_window (data, cdw, dyf, corr_level):
'''
data = historical data
cdw = corralation days window
dyf = number of days forward
corr_level = desirable correlation level
'''
mylabels = ['Dax', str(dyf)+' days forward']
s=[]
data2= data[-cdw:]
data[-cdw:].plot(title='Dax last {} trading Days'.format(str(cdw)))
for i in range(len(data)-cdw*2):
if (pearsonr(data[i:i+cdw],data2)[0]) > corr_level:
s.append((data.iloc[i+cdw+dyf]['Last']/data.iloc[i+cdw]['Last'])-1)
fig, ax = plt.subplots(1, 1)
data[i:i+cdw+dyf].plot(title="Correlation:"+str(pearsonr(data[i:i+cdw],data2)[0]),ax=ax)
data[i+cdw:i+cdw+dyf].plot(color = 'red',label='Days forward', ax=ax)
ax.legend(labels=mylabels, loc=0)
plt.tight_layout();
return print(f'Average Return after {dyf} days is {round(np.mean(s)*100,2)}% \nfor {len(s)} occurrences\
----> {np.round(sum(1 for x in s if x>0)/len(s)*100,1)}% positive returns\n')
当尝试将数据移动到分辨率时,我使用:
data.index = pd.to_datetime(data.Date + ' ' + data.Time)
data['Date'] = pd.to_datetime(data.Date)
data['Time'] = pd.to_datetime(data['Time'], format=' %H:%M:%S.%f').dt.time
我的数据如下所示:
Date Time Last
2019-03-01 20:51:00 2019-03-01 20:51:00.0 11628.5
2019-03-01 20:54:00 2019-03-01 20:54:00.0 11627.5
2019-03-01 20:57:00 2019-03-01 20:57:00.0 11633.5
2019-03-01 21:00:00 2019-03-01 21:00:00.0 11633.0
2019-03-01 21:03:00 2019-03-01 21:03:00.0 11629.5
在我的分钟数据上运行上述函数时,我收到此错误:
ValueError: view limit minimum -24654.425000000003 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units.
【问题讨论】:
-
您能提供错误日志的完整堆栈跟踪吗?哪一行代码会产生错误?是
plt.tight_layout()吗? -
1) 您应该将时间转换为
timedelta:pd.to_timedelta(df['Time'])。 2) 之后做索引:df.index = df['Date'] + df['Time']. -
data[i+cdw:i+cdw+dyf]有效吗?还是应该是data.iloc[i+cdw:i+cdw+dyf]? -
事实上我敢打赌你的错误发生得更早,这里是
data2= data[-cdw:]。您将负数作为索引传递,但data数据框有一个日期时间索引。如果您想索引 pandas 中最后的cdw行,则需要使用iloc除非您的索引包含连续整数,而您的索引不包含日期,因为它包含日期。所以你需要data2= data.iloc[-cdw:, :]然后在下一行再次使用它而不是重新计算它。 -
与您的问题没有直接关系,但
return print(...)并没有任何意义。打印到输出,然后返回None。此外,我怀疑您可以通过将其缩减为 minimal example 来让您自己和/或其他人更轻松地找出问题所在。
标签: python pandas datetime matplotlib