text
stringlengths
1
93.6k
fontsize=8,
alpha=0.7,
visible=False,
)
annotations.append(ann)
ax1.set_title(f"{symbol} Stock Price Prediction")
ax1.set_xlabel("Date")
ax1.set_ylabel("Price")
ax1.legend()
# Add hover annotation
hover_annot = ax1.annotate(
"",
xy=(0, 0),
xytext=(10, 10),
textcoords="offset points",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"),
)
hover_annot.set_visible(False)
def update_hover_annot(event):
vis = hover_annot.get_visible()
if event.inaxes == ax1:
x, y = event.xdata, event.ydata
date = num2date(x).strftime("%Y-%m-%d")
hover_annot.xy = (x, y)
hover_annot.set_text(f"Date: {date}\nPrice: ${y:.2f}")
hover_annot.set_visible(True)
fig.canvas.draw_idle()
elif vis:
hover_annot.set_visible(False)
fig.canvas.draw_idle()
# Connect the hover event
fig.canvas.mpl_connect("motion_notify_event", update_hover_annot)
# Add zoom event handler
def on_zoom(event):
ax1 = event.inaxes
if ax1 is None:
return
xlim = ax1.get_xlim()
ylim = ax1.get_ylim()
# Calculate the zoom level based on the x-axis range
zoom_level = (plot_data.index[-1] - plot_data.index[0]).days / (
xlim[1] - xlim[0]
).days
# Adjust annotation visibility based on zoom level
for ann in annotations:
ann.set_visible(
zoom_level > 5
) # Show annotations when zoomed in more than 5x
fig.canvas.draw_idle()
# Connect the zoom event handler
fig.canvas.mpl_connect("motion_notify_event", on_zoom)
# Model performance summary table
ax2.axis("off")
table = ax2.table(
cellText=stats_df.values,
colLabels=stats_df.columns,
cellLoc="center",
loc="center",
)
table.auto_set_font_size(False)
table.set_fontsize(9)
table.scale(1, 1.5)
# Lower the title and add more space between plot and table
ax2.set_title("Model Performance Summary", pad=60)
# Implement trading strategy
strategy_returns = implement_trading_strategy(
plot_data["Close"].values, ensemble_predictions.flatten()
)
strategy_sharpe_ratio = (
np.mean(strategy_returns) / np.std(strategy_returns) * np.sqrt(252)
)
print(f"Trading Strategy Sharpe Ratio: {strategy_sharpe_ratio:.4f}")
# Calculate cumulative returns of the trading strategy
cumulative_returns = (1 + strategy_returns).cumprod() - 1
# Add new subplot for trading strategy performance
ax3.plot(
plot_data.index[-len(cumulative_returns) :],
cumulative_returns,
label="Strategy Cumulative Returns",
color="purple",
)
ax3.set_title(f"{symbol} Trading Strategy Performance")
ax3.set_xlabel("Date")
ax3.set_ylabel("Cumulative Returns")
ax3.legend()