Spaces:
Running
Running
import matplotlib.pyplot as plt | |
import matplotlib.dates as mdates | |
import pandas as pd | |
from pandas.plotting import register_matplotlib_converters | |
register_matplotlib_converters() | |
def plot_stock_data_with_signals(data): | |
# First, ensure the DataFrame's index is in datetime format. | |
data.index = pd.to_datetime(data.index, errors='coerce') | |
# Create a new figure and set the size. | |
plt.figure(figsize=(14, 7)) | |
# Plotting stock 'Close' prices | |
plt.plot(data.index, data['Close'], label='Close Price', color='black', lw=2) | |
# Check and plot EMAs if they exist | |
if 'EMA_20' in data.columns and 'EMA_50' in data.columns: | |
plt.plot(data.index, data['EMA_20'], label='EMA 20', color='blue', lw=1.5) | |
plt.plot(data.index, data['EMA_50'], label='EMA 50', color='red', lw=1.5) | |
# Check and plot Bollinger Bands if they exist | |
if 'BB_Upper' in data.columns and 'BB_Lower' in data.columns: | |
plt.fill_between(data.index, data['BB_Lower'], data['BB_Upper'], color='grey', alpha=0.1, label='Bollinger Bands') | |
# Highlight buy/sell signals if they exist | |
if 'Combined_Signal' in data.columns: | |
buy_signals = data[data['Combined_Signal'] == 'buy'] | |
sell_signals = data[data['Combined_Signal'] == 'sell'] | |
plt.scatter(buy_signals.index, buy_signals['Close'], label='Buy Signal', marker='^', color='green', alpha=1) | |
plt.scatter(sell_signals.index, sell_signals['Close'], label='Sell Signal', marker='v', color='red', alpha=1) | |
plt.title('Stock Price with Buy/Sell Signals') | |
plt.xlabel('Date') | |
plt.ylabel('Price') | |
plt.legend() | |
# Improve the x-axis date format | |
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) | |
plt.gca().xaxis.set_major_locator(mdates.MonthLocator()) | |
plt.gcf().autofmt_xdate() # Rotation | |
plt.show() |