Hi to all who play with the financial charts. I'd like the legend on the chart to be updated on mouse move over the time-series on the chart. I have an example of how to do it for 1 time-series (one symbol). But when I have two symbols on the chart for comparison, I have no experience editing simple methods properly. I'm sure the problem I couldn't manage is in method
def update_legend_text(x, y):
Here is an example
from pandas_datareader import get_data_yahoo
import finplot as fplt
symbol1, symbol2 = 'GOOG', 'BA'
df1 = get_data_yahoo(symbol1, start='2022-10-01', end='2022-10-30')
df1.rename(str.lower, axis='columns', inplace=True)
df2 = get_data_yahoo(symbol2, start='2022-10-01', end='2022-10-30')
df2.rename(str.lower, axis='columns', inplace=True)
ax = fplt.create_plot(f'{symbol1} - {symbol2} analysis', maximize=True)
fplt.candlestick_ochl(datasrc=df1[['open', 'close', 'high', 'low']], ax=ax)
pb = fplt.candlestick_ochl(datasrc=df2[['open', 'close', 'high', 'low']], ax=ax)
pb.colors['bull_body'], pb.colors['bear_body'] = '#0f0', '#630'
fplt.legend_fill_color = '#f2f2f2'
fplt.legend_text_color = '#070707'
df1['dates'] = df1.index.astype('int64') # this is needed for finplot library
hover_label = fplt.add_legend('', ax=ax)
def update_legend_text(x, y):
row1 = df1.loc[df.dates == x]
row2 = df2.loc[df.dates == x]
fmt1 = '<span style="color:#%s">%%.6f</span>' % ('004a00' if (row1.open < row1.close).all() else 'a00')
fmt2 = '<span style="color:#%s">%%.6f</span>' % ('004a00' if (row2.open < row2.close).all() else 'a00')
rawtxt = '<span style="font-size:13px">%%s %%s</span> O:%s C:%s H:%s L:%s ||| <span style="font-size:13px">%%s %%s</span> O:%s C:%s H:%s L:%s' % (fmt1, fmt1, fmt1, fmt1, fmt2, fmt2, fmt2, fmt2)
hover_label.setText(rawtxt % (symbol1, 'D', row1.open, row1.close, row1.high, row1.low, symbol2, 'D', row2.open, row2.close, row2.high, row2.low))
def update_crosshair_text(x, y, xtext, ytext):
ytext = '%s C: %s (close%+.2f)' % (ytext, df1.iloc[x].close, (y - df1.iloc[x].close))
return xtext, ytext
fplt.set_time_inspector(update_legend_text, ax=ax, when='hover')
fplt.add_crosshair_info(update_crosshair_text, ax=ax)
fplt.autoviewrestore()
fplt.show()
The legend at the top right corner should display data for each symbol, but it doesn't show anything :(
If you use
import yfinance as yf
df1 = yf.download(symbol1, start='2022-12-01', end='2022-12-30')
instead, and you then modify your update to
def update_legend_text(x, y):
x = pd.to_datetime(x, unit='ns')
row1 = df1.loc[df1.index == x]
row2 = df2.loc[df2.index == x]
...
you should be able to see something like this: