使用mplfinance绘制1分钟K线图遇AttributeError错误求助
解决mplfinance绘制K线图的AttributeError问题
错误原因
你用resample().agg()生成的OHLC数据是多级列索引,列名是类似('price', 'first')的元组(tuple)。而mplfinance在处理数据时,会尝试对列名调用strip()方法(字符串专属方法),但元组没有该方法,因此触发AttributeError: 'tuple' object has no attribute 'strip'。
修正方案
方案1:重命名已生成的OHLC列
直接修改ohlc的列名,将多级索引转为mplfinance要求的单级列名(需为Open、High、Low、Close,大小写不敏感,建议规范命名):
prices = df['price'] time = pd.to_datetime(df['ts_event']) sample_df = pd.DataFrame({'time': time, 'price': prices}) # 生成OHLC数据 ohlc = sample_df.set_index('time').resample('min').agg({'price': ['first', 'max', 'min', 'last']}) # 关键:重命名列,去除多级索引 ohlc.columns = ['Open', 'High', 'Low', 'Close'] # 绘制K线图 import mplfinance as mplf mplf.plot(ohlc, type='candle') mplf.show()
方案2:聚合时直接指定列名(更简洁)
在agg()中直接定义列名,避免生成多级索引:
prices = df['price'] time = pd.to_datetime(df['ts_event']) sample_df = pd.DataFrame({'time': time, 'price': prices}) # 聚合时直接指定列名,生成单级索引的DataFrame ohlc = sample_df.set_index('time').resample('min').agg( Open=('price', 'first'), High=('price', 'max'), Low=('price', 'min'), Close=('price', 'last') ) # 绘制K线图 import mplfinance as mplf mplf.plot(ohlc, type='candle') mplf.show()
验证说明
修改后,ohlc的列名会变成Open、High、Low、Close的单级索引,mplfinance可以正常识别并处理数据,不会再触发元组相关的错误。
内容的提问来源于stack exchange,提问作者DylanMediaTV
相关产品推荐
相关产品推荐

