Bokeh

在Bokeh中如何构建一个实时股票市场仪表板

小樊
83
2024-05-21 09:41:16
栏目: 编程语言

要在Bokeh中构建一个实时股票市场仪表板,您可以按照以下步骤进行操作:

1、导入必要的库和模块:

```python

from bokeh.io import curdoc

from bokeh.layouts import column

from bokeh.models import ColumnDataSource

from bokeh.plotting import figure

from bokeh.models import DatetimeTickFormatter

from bokeh.models.widgets import Div

from bokeh.models import HoverTool

from bokeh.models import Range1d

from bokeh.models import LinearAxis

import pandas as pd

import random

import time

```

2、创建一个实时数据源:

```python

source = ColumnDataSource(data=dict(

time=[], price=[]

))

```

3、创建一个绘图函数来绘制股票价格走势图:

```python

def create_figure():

p = figure(plot_width=800, plot_height=400, title="Real-time Stock Market Dashboard",

x_axis_label='Time', y_axis_label='Price', x_axis_type='datetime')

p.line(x='time', y='price', source=source, line_width=2, line_color="blue")

p.xaxis.formatter=DatetimeTickFormatter(

hours=["%H:%M"],

days=["%m/%d"],

months=["%m/%Y"],

years=["%Y"],

)

p.extra_y_ranges = {"volume": Range1d(start=0, end=max(volume))}

p.add_layout(LinearAxis(y_range_name="volume", axis_label="Volume"), 'left')

p.add_tools(HoverTool(

tooltips=[

("Time", "@time{%F %T}"),

("Price", "@price{$0.2f}")

],

formatters={

'@time': 'datetime',

}

))

return p

```

4、创建一个更新数据函数来更新数据源中的数据:

```python

def update_data():

new_data = dict(

time=[pd.Timestamp.now()],

price=[random.uniform(50, 150)]

)

source.stream(new_data, rollover=100)

```

5、创建一个回调函数来定时更新数据:

```python

def update():

update_data()

# 每隔1秒更新一次数据

curdoc().add_periodic_callback(update, 1000)

```

6、将绘图函数和数据源添加到文档中:

```python

plot = create_figure()

curdoc().add_root(column(plot))

```

7、运行应用程序:

在终端中运行以下命令来启动Bokeh服务器

```

bokeh serve --show your_script.py

```

替换`your_script.py`为包含以上代码的Python脚本文件名。您将在浏览器中看到一个实时股票市场仪表板,显示股票价格的实时走势图。

0
看了该问题的人还看了