尝试使用 datetime 绘制财务数据但遇到错误 TypeError: string indices must be integers, not str

Posted

技术标签:

【中文标题】尝试使用 datetime 绘制财务数据但遇到错误 TypeError: string indices must be integers, not str【英文标题】:Try to plot finance data with datetime but met error TypeError: string indices must be integers, not str 【发布时间】:2018-03-19 05:19:26 【问题描述】:

我想用日期时间绘制财务数据,如下面的数据示例所示。 但我得到了错误:

TypeError: string indices must be integers, not str

能否请您帮助我知道我遇到此错误的原因以及解决方案?

from datetime import datetime, timedelta
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import date2num

plt.figure(2)
datafile = cbook.get_sample_data(self.minuteListFile, asfileobj=False)
print('loading %s' % datafile)

datafile['minute'] =date2num(pd.to_datetime(datafile['minute']).tolist())
plt.plotfile(datafile, (0, 1, 2, 3), checkrows=0, subplots=False)
plt.show()

数据示例 -

minute,spreadprice,bollup,bollmid,bolldown,buy,short,sell,cover
2014/01/02/09/00,144.0,0,0,1,142,0,0,0
2014/01/02/09/01,143.0,0,0,1,0,0,0,0
2014/01/02/09/02,145.0,0,0,1,0,0,0,0
2014/01/02/09/03,144.0,0,0,1,0,0,0,0
2014/01/02/09/04,142.0,0,0,1,0,0,0,0
2014/01/02/09/05,142.0,0,0,1,0,0,0,0
2014/01/02/09/06,143.0,0,0,1,0,0,0,0
2014/01/02/09/07,143.0,0,0,1,0,0,0,0
2014/01/02/09/08,142.0,0,0,1,0,0,0,0
2014/01/02/09/09,140.0,0,0,1,0,0,0,0
2014/01/02/09/10,140.0,0,0,1,0,0,0,0
2014/01/02/09/11,141.0,0,0,1,0,0,0,0
2014/01/02/09/12,142.0,0,0,1,0,0,0,0
2014/01/02/09/13,142.0,144.0,142.0,141.0,0,0,0,0
2014/01/02/09/14,142.0,144.0,142.0,141.0,0,0,0,0
2014/01/02/09/15,143.0,144.0,142.0,141.0,0,0,0,0
2014/01/02/09/16,142.0,144.0,142.0,141.0,0,0,0,0
2014/01/02/09/17,142.0,144.0,142.0,141.0,0,0,0,0

【问题讨论】:

我想推荐finplot,它是为金融策划而设计的。 【参考方案1】:

以下内容可用于绘制您的数据。要点是您需要指定日期时间("%Y/%m/%d/%H/%M")的(相当不寻常的)格式,以便可以将其转换为日期时间对象。

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("data/minuteData.csv")
df["minute"] = pd.to_datetime(df["minute"], format="%Y/%m/%d/%H/%M")

plt.plot(df["minute"],df["spreadprice"], label="spreadprice" )
plt.plot(df["minute"],df["bollup"], label="bollup" )
plt.legend()
plt.show()

【讨论】:

以上是关于尝试使用 datetime 绘制财务数据但遇到错误 TypeError: string indices must be integers, not str的主要内容,如果未能解决你的问题,请参考以下文章

matplotlib 财务没有正确绘制窗口

使用ggplot绘制时导入库存数据问题

如何在 Seaborn distplot 中绘制 Pandas 日期时间序列?

python字符串到日期时间的错误输出

使用 PyQtGraph 绘制 Datetime 对象

Pandas datetime64 问题(datetime 引入数据峰值)