如何使用python绘制k线图
时间: 2023-07-20 16:17:29 浏览: 162
在 Python 中,可以使用第三方库 `mplfinance` 绘制 K 线图。`mplfinance` 是一个基于 matplotlib 的库,提供了简单易用的 API 来绘制股票交易数据的图表,包括 K 线图、成交量图等。
以下是一个绘制 K 线图的示例代码,假设您已经安装了 `mplfinance` 库:
```python
import pandas as pd
import mplfinance as mpf
# 读取股票交易数据
data = pd.read_csv('your_data.csv', index_col=0, parse_dates=True)
# 绘制 K 线图
mpf.plot(data, type='candle', volume=True, mav=(5, 10, 20), show_nontrading=True)
```
这段代码将从 CSV 文件中读取股票交易数据,并绘制 K 线图。其中 `type='candle'` 表示绘制 K 线图,`volume=True` 表示绘制成交量图,`mav=(5, 10, 20)` 表示计算并绘制 5 日、10 日和 20 日的移动平均线,`show_nontrading=True` 表示显示非交易日的数据。
如果您的数据不是 CSV 格式,可以使用 `pandas` 库将数据转换成 `DataFrame` 对象。例如,假设您的数据是一个 Python 列表,包含了每天的开盘价、最高价、最低价和收盘价,可以使用以下代码将数据转换为 `DataFrame` 对象,并绘制 K 线图:
```python
import pandas as pd
import mplfinance as mpf
# 假设数据是一个列表,包含了每天的开盘价、最高价、最低价和收盘价
data = [
[100, 120, 90, 110], # 第一天的数据
[110, 130, 100, 120], # 第二天的数据
[120, 140, 110, 130], # 第三天的数据
# ...
]
# 将数据转换为 DataFrame 对象
columns = ['Open', 'High', 'Low', 'Close']
index = pd.date_range(start='20210101', periods=len(data), freq='D')
df = pd.DataFrame(data, index=index, columns=columns)
# 绘制 K 线图
mpf.plot(df, type='candle', volume=True, mav=(5, 10, 20), show_nontrading=True)
```
这段代码将把列表数据转换为 `DataFrame` 对象,然后绘制 K 线图。请注意,这里使用了 `pd.date_range()` 函数生成了一个日期索引,以便将数据按日期排序。
阅读全文
相关推荐

















