Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b0294db

Browse files
stackoverflow 76486448 hover prices annotation
1 parent b35ac8c commit b0294db

File tree

1 file changed

+113
-0
lines changed

1 file changed

+113
-0
lines changed
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import yfinance as yf
2+
import mplfinance as mpf
3+
import matplotlib.pyplot as plt
4+
import matplotlib.patches as mpatches
5+
import pandas as pd
6+
import numpy as np
7+
8+
# Dates to get stock data
9+
start_date = "2020年01月01日"
10+
end_date = "2023年06月15日"
11+
12+
# Fetch Tesla stock data
13+
tesla_data = yf.download("TSLA", start=start_date, end=end_date)
14+
tesla_weekly_data = tesla_data.resample("W").agg(
15+
{"Open": "first", "High": "max", "Low": "min", "Close": "last", "Volume": "sum"}
16+
).dropna()
17+
18+
# Get the latest closing price
19+
latest_price = tesla_weekly_data['Close'][-1]
20+
21+
# Create additional plot
22+
close_price = tesla_weekly_data['Close']
23+
apd = mpf.make_addplot(close_price, color='cyan', width=2)
24+
25+
# Plot the candlestick chart
26+
fig, axes = mpf.plot(tesla_weekly_data,
27+
type='candle',
28+
addplot=apd,
29+
style='yahoo',
30+
title='Tesla Stock Prices',
31+
ylabel='Price',
32+
xlabel='Date',
33+
volume=True,
34+
ylabel_lower='Volume',
35+
volume_panel=1,
36+
figsize=(16, 8),
37+
returnfig=True
38+
)
39+
40+
# Move the y-axis labels to the left side
41+
axes[0].yaxis.tick_left()
42+
axes[1].yaxis.tick_left()
43+
44+
# Adjust the position of the y-axis label for price
45+
axes[0].yaxis.set_label_coords(-0.08, 0.5)
46+
47+
# Adjust the position of the y-axis label for volume
48+
axes[1].yaxis.set_label_coords(-0.08, 0.5)
49+
50+
# Set y-axis label for price and volume
51+
axes[0].set_ylabel('Price', rotation=0, labelpad=20)
52+
axes[1].set_ylabel('Volume', rotation=0, labelpad=20)
53+
54+
# Make the legend box
55+
handles = axes[0].get_legend_handles_labels()[0]
56+
red_patch = mpatches.Patch(color='red')
57+
green_patch = mpatches.Patch(color='green')
58+
cyan_patch = mpatches.Patch(color='cyan')
59+
handles = handles[:2] + [red_patch, green_patch, cyan_patch]
60+
labels = ["Price Up", "Price Down", "Closing Price"]
61+
axes[0].legend(handles=handles, labels=labels)
62+
63+
# Add a box to display the current price
64+
latest_price_text = f"Current Price: ${latest_price:.2f}"
65+
box_props = dict(boxstyle='round', facecolor='white', edgecolor='black', alpha=0.8)
66+
axes[0].text(0.02, 0.95, latest_price_text, transform=axes[0].transAxes,
67+
fontsize=12, verticalalignment='top', bbox=box_props)
68+
69+
# Function to create hover annotations
70+
def hover_annotations(data):
71+
72+
annot_visible = False
73+
annot = axes[0].text(0, 0, '', visible=False, ha='left', va='top')
74+
75+
def onmove(event):
76+
nonlocal annot_visible
77+
nonlocal annot
78+
79+
if event.inaxes == axes[0]:
80+
index = int(event.xdata)
81+
if index >= len(data.index):
82+
index = -1
83+
elif index < 0:
84+
index = 0
85+
values = data.iloc[index]
86+
mytext = (f"{values.name.date().strftime('%m/%d/%Y'):}\n"+
87+
f"O: {values['Open']:.2f}\n"+
88+
f"H: {values['High']:.2f}\n"+
89+
f"L: {values['Low']:.2f}\n"+
90+
f"C: {values['Close']:.2f}\n"+
91+
f"V: {values['Volume']:.0f}"
92+
)
93+
94+
annot_visible = True
95+
else:
96+
mytext = ''
97+
annot_visible = False
98+
99+
annot.set_position((event.xdata,event.ydata))
100+
annot.set_text(mytext)
101+
annot.set_visible(annot_visible)
102+
fig.canvas.draw_idle()
103+
104+
fig.canvas.mpl_connect('motion_notify_event', onmove)
105+
106+
return annot
107+
108+
109+
# Attach hover annotations to the plot
110+
annotations = hover_annotations(tesla_weekly_data)
111+
112+
# Display the chart
113+
plt.show()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /