定义一个函数,1.输入分时图data和昨日收盘价preclose,2.用pyecharts画分时图,分时图左侧显示价格,右侧显示涨跌幅度百分比,3.以昨日收盘价为基准
时间: 2024-05-09 19:21:19 浏览: 98
,计算出每个时间点的涨跌幅度百分比,并将其作为图例显示在分时图右侧。
```python
from typing import List
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Line
def draw_kline(data: pd.DataFrame, preclose: float) -> Line:
"""
用pyecharts画分时图,并显示价格和涨跌幅度百分比
:param data: 分时图数据,包含时间、价格、成交量等信息
:param preclose: 昨日收盘价
:return: Line对象,可以调用render方法生成html文件或在jupyter notebook中显示
"""
x_data = data['time'].tolist()
y_data = data['price'].tolist()
# 计算涨跌幅度百分比
change_percent = [(price - preclose) / preclose * 100 for price in y_data]
line = (Line()
.add_xaxis(xaxis_data=x_data)
.add_yaxis(series_name="价格", y_axis=y_data)
.extend_axis(
yaxis=opts.AxisOpts(
name="涨跌幅",
type_="value",
min_=-10,
max_=10,
position="right",
axislabel_opts=opts.LabelOpts(formatter="{value}%")
)
)
.add_yaxis(
series_name="涨跌幅",
y_axis=change_percent,
yaxis_index=1,
label_opts=opts.LabelOpts(is_show=True)
)
.set_global_opts(
xaxis_opts=opts.AxisOpts(
type_="category",
is_scale=True,
boundary_gap=False,
axisline_opts=opts.AxisLineOpts(is_on_zero=False),
splitline_opts=opts.SplitLineOpts(is_show=False),
split_number=20,
min_interval=1,
max_interval=240
),
yaxis_opts=opts.AxisOpts(
name="价格",
type_="value",
is_scale=True,
axislabel_opts=opts.LabelOpts(formatter="{value}")
),
tooltip_opts=opts.TooltipOpts(
trigger="axis",
axis_pointer_type="cross",
background_color="rgba(245, 245, 245, 0.8)",
border_width=1,
border_color="#ccc",
textstyle_opts=opts.TextStyleOpts(color="#000")
),
datazoom_opts=[opts.DataZoomOpts()],
title_opts=opts.TitleOpts(title="分时图")
)
)
return line
```
使用示例:
```python
import pandas as pd
import tushare as ts
# 获取分时数据
df = ts.get_realtime_quotes('000001')
df = df[['time', 'price', 'volume']]
df['time'] = pd.to_datetime(df['time'])
df['price'] = df['price'].astype(float)
# 获取昨日收盘价
preclose = ts.get_k_data('000001', '2021-08-12', '2021-08-12')['close'][0]
# 画分时图
line = draw_kline(df, preclose)
line.render("分时图.html")
```
阅读全文