如何让 Bokeh hovertool 用于烛台图表?
How to get Bokeh hovertool working for candlesticks chart?
我的目标是让我的鼠标悬停在烛台上并在我这样做时显示数据。我能够使 Bokeh 悬停工具正常工作,但是我无法提取和显示数据。我能够显示 (x,y) 数据,但不能显示其余数据。这是我目前所拥有的:
#Importing Libraries
import requests
import pandas as pd
import datetime
from bokeh.plotting import ColumnDataSource, figure, output_file, show
from math import pi
#Request ticker symbol
API_KEY = 'YOUR API KEY'
symbol = input('Enter ticker symbol: ')
r = requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=' + symbol + '&apikey=' + API_KEY)
print(r.status_code)
result = r.json()
dataForAllDays = result['Time Series (Daily)']
#convert to dataframe
df = pd.DataFrame.from_dict(dataForAllDays, orient='index')
df = df.reset_index()
#rename columns
df = df.rename(index=str, columns={"index": "date", "1. open": "open", "2. high": "high", "3. low": "low", "4. close": "close","5. volume":"volume"})
#Changing to datetime
df['date'] = pd.to_datetime(df['date'])
#Sort according to date
df = df.sort_values(by=['date'])
#Changing the datatype
df.open = df.open.astype(float)
df.close = df.close.astype(float)
df.high = df.high.astype(float)
df.low = df.low.astype(float)
df.volume = df.volume.astype(int)
#check the data
df.head()
#Hovertool Tooltips
source = ColumnDataSource(data=dict(date=df['date'], open=df.open, close=df.close))
TOOLTIPS = [
("(x,y)", "($x, $y)"),
("date", "@date"),
("open", "df.open"),
("open", "@open"),
("close", "df.close"),
("close", "@close"),
("percent","@changepercent"),
]
#Check the datatype
df.info()
inc = df.close > df.open
dec = df.open > df.close
w = 12*60*60*1000 # half day in ms
TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
title = symbol + ' Chart'
p = figure(x_axis_type="datetime", tools=TOOLS, tooltips=TOOLTIPS, plot_width=1000, title = title)
p.xaxis.major_label_orientation = pi/4
p.grid.grid_line_alpha=0.3
p.segment(df.date, df.high, df.date, df.low, color="black")
p.vbar(df.date[inc], w, df.open[inc], df.close[inc], fill_color="#a30e15", line_color="black")
p.vbar(df.date[dec], w, df.open[dec], df.close[dec], fill_color="#53680c", line_color="black")
#Store as a HTML file
output_file("stock_information.html", title="candlestick.py")
# Display in browser
show(p)
工具提示规范中唯一有意义的值是:
- 预定义 "special variables" 以
$
开头表示
- 对 ColumnDataSource 中列的引用,以
@
开头表示
所以像 "df.open"
这样的东西在这种情况下是没有意义的。使悬停工具在浏览器中执行的实际代码在 javascript 中,其中 Python 和 Pandas 以及您的 DataFrame df
不存在。如果您希望数据显示在 HoverTool
中,那么您必须在 CDS 中放置一个包含该数据的列,并使用 @column_name
语法在悬停工具规范中引用它。
您可以参考文档了解更多信息:
https://docs.bokeh.org/en/latest/docs/user_guide/tools.html#hovertool
这是一个完整的一分钟烛台示例,其中包含悬停工具提示和 bband。
source = ColumnDataSource(data=df)
hover = HoverTool(
tooltips=[
('d', '@timestamp{%H:%M}'),
('o', '@open{0}'),
('h', '@high{0}'),
('l', '@low{0}'),
('c', '@close{0}'),
('v', '@volume{0}'),
],
formatters={
'@timestamp': 'datetime'
},
mode='mouse'
)
inc_b = source.data['close'] > source.data['open']
inc = CDSView(source=source, filters=[BooleanFilter(inc_b)])
dec_b = source.data['open'] > source.data['close']
dec = CDSView(source=source, filters=[BooleanFilter(dec_b)])
w = 60000
p = figure(x_axis_type="datetime", sizing_mode="stretch_width", height=400)
p.segment(source=source, x0='timestamp', x1='timestamp', y0='high', y1='low', color="black")
p.vbar(source=source, view=inc, x='timestamp', width=w, top='open', bottom='close', fill_color="green", line_color="green")
p.vbar(source=source, view=dec, x='timestamp', width=w, top='open', bottom='close', fill_color="red", line_color="red")
p.line(source=source, x='timestamp', y='bband_up', line_width=1, alpha=0.8, legend_label='bband_up', color='green')
p.line(source=source, x='timestamp', y='bband_mid', line_width=1, alpha=0.8, legend_label='bband_mid', color='blue')
p.line(source=source, x='timestamp', y='bband_low', line_width=1, alpha=0.8, legend_label='bband_low', color='red')
p.add_tools(hover)
p.legend.location = "top_left"
p.legend.click_policy = "hide"
show(p)
我的目标是让我的鼠标悬停在烛台上并在我这样做时显示数据。我能够使 Bokeh 悬停工具正常工作,但是我无法提取和显示数据。我能够显示 (x,y) 数据,但不能显示其余数据。这是我目前所拥有的:
#Importing Libraries
import requests
import pandas as pd
import datetime
from bokeh.plotting import ColumnDataSource, figure, output_file, show
from math import pi
#Request ticker symbol
API_KEY = 'YOUR API KEY'
symbol = input('Enter ticker symbol: ')
r = requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=' + symbol + '&apikey=' + API_KEY)
print(r.status_code)
result = r.json()
dataForAllDays = result['Time Series (Daily)']
#convert to dataframe
df = pd.DataFrame.from_dict(dataForAllDays, orient='index')
df = df.reset_index()
#rename columns
df = df.rename(index=str, columns={"index": "date", "1. open": "open", "2. high": "high", "3. low": "low", "4. close": "close","5. volume":"volume"})
#Changing to datetime
df['date'] = pd.to_datetime(df['date'])
#Sort according to date
df = df.sort_values(by=['date'])
#Changing the datatype
df.open = df.open.astype(float)
df.close = df.close.astype(float)
df.high = df.high.astype(float)
df.low = df.low.astype(float)
df.volume = df.volume.astype(int)
#check the data
df.head()
#Hovertool Tooltips
source = ColumnDataSource(data=dict(date=df['date'], open=df.open, close=df.close))
TOOLTIPS = [
("(x,y)", "($x, $y)"),
("date", "@date"),
("open", "df.open"),
("open", "@open"),
("close", "df.close"),
("close", "@close"),
("percent","@changepercent"),
]
#Check the datatype
df.info()
inc = df.close > df.open
dec = df.open > df.close
w = 12*60*60*1000 # half day in ms
TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
title = symbol + ' Chart'
p = figure(x_axis_type="datetime", tools=TOOLS, tooltips=TOOLTIPS, plot_width=1000, title = title)
p.xaxis.major_label_orientation = pi/4
p.grid.grid_line_alpha=0.3
p.segment(df.date, df.high, df.date, df.low, color="black")
p.vbar(df.date[inc], w, df.open[inc], df.close[inc], fill_color="#a30e15", line_color="black")
p.vbar(df.date[dec], w, df.open[dec], df.close[dec], fill_color="#53680c", line_color="black")
#Store as a HTML file
output_file("stock_information.html", title="candlestick.py")
# Display in browser
show(p)
工具提示规范中唯一有意义的值是:
- 预定义 "special variables" 以
$
开头表示
- 对 ColumnDataSource 中列的引用,以
@
开头表示
所以像 "df.open"
这样的东西在这种情况下是没有意义的。使悬停工具在浏览器中执行的实际代码在 javascript 中,其中 Python 和 Pandas 以及您的 DataFrame df
不存在。如果您希望数据显示在 HoverTool
中,那么您必须在 CDS 中放置一个包含该数据的列,并使用 @column_name
语法在悬停工具规范中引用它。
您可以参考文档了解更多信息:
https://docs.bokeh.org/en/latest/docs/user_guide/tools.html#hovertool
这是一个完整的一分钟烛台示例,其中包含悬停工具提示和 bband。
source = ColumnDataSource(data=df)
hover = HoverTool(
tooltips=[
('d', '@timestamp{%H:%M}'),
('o', '@open{0}'),
('h', '@high{0}'),
('l', '@low{0}'),
('c', '@close{0}'),
('v', '@volume{0}'),
],
formatters={
'@timestamp': 'datetime'
},
mode='mouse'
)
inc_b = source.data['close'] > source.data['open']
inc = CDSView(source=source, filters=[BooleanFilter(inc_b)])
dec_b = source.data['open'] > source.data['close']
dec = CDSView(source=source, filters=[BooleanFilter(dec_b)])
w = 60000
p = figure(x_axis_type="datetime", sizing_mode="stretch_width", height=400)
p.segment(source=source, x0='timestamp', x1='timestamp', y0='high', y1='low', color="black")
p.vbar(source=source, view=inc, x='timestamp', width=w, top='open', bottom='close', fill_color="green", line_color="green")
p.vbar(source=source, view=dec, x='timestamp', width=w, top='open', bottom='close', fill_color="red", line_color="red")
p.line(source=source, x='timestamp', y='bband_up', line_width=1, alpha=0.8, legend_label='bband_up', color='green')
p.line(source=source, x='timestamp', y='bband_mid', line_width=1, alpha=0.8, legend_label='bband_mid', color='blue')
p.line(source=source, x='timestamp', y='bband_low', line_width=1, alpha=0.8, legend_label='bband_low', color='red')
p.add_tools(hover)
p.legend.location = "top_left"
p.legend.click_policy = "hide"
show(p)