路径:“E:\自定义时间周期\csv\1”中存放了,csv文件类型的股票K线图数据,将股票数据生成K线图要怎么做?给出完整代码
时间: 2024-02-13 07:00:27 浏览: 144
好的,以下是完整代码,可以将指定路径下的所有csv文件转换成K线图并显示:
```python
import os
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
from mpl_finance import candlestick_ohlc
# 设置日期显示格式
date_fmt = '%Y-%m-%d'
date_converter = mdates.strpdate2num(date_fmt)
# 遍历文件夹中的所有csv文件
folder = 'E:/自定义时间周期/csv/1'
for filename in os.listdir(folder):
if filename.endswith('.csv'):
# 读取数据
filepath = os.path.join(folder, filename)
df = pd.read_csv(filepath)
# 将日期转换为数字
df['Date'] = df['Date'].apply(date_converter)
# 准备绘图数据
ohlc = df[['Date', 'Open', 'High', 'Low', 'Close']].values
# 创建子图
fig, ax = plt.subplots()
# 绘制K线图
candlestick_ohlc(ax, ohlc, width=0.6, colorup='green', colordown='red')
# 设置x轴标签格式
ax.xaxis.set_major_formatter(mdates.DateFormatter(date_fmt))
# 自动旋转x轴标签
plt.xticks(rotation=30)
# 设置标题和保存图片
plt.title(os.path.splitext(filename)[0])
plt.savefig(os.path.splitext(filepath)[0] + '.png')
# 显示图形
plt.show()
```
请将`folder`变量设置为你存放csv文件的文件夹路径。这个代码将遍历指定文件夹下的所有csv文件,并将它们转换成K线图并保存为同名的png文件。同时,程序也会显示出每个K线图。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![xlsm](https://img-home.csdnimg.cn/images/20250102104920.png)