Spaces:
Runtime error
Runtime error
| import matplotlib.pyplot as plt | |
| import matplotlib.dates as mdates | |
| def plot_stock_data_with_signals(stock_data): | |
| """ | |
| Creates a plot of stock data along with SMAs, Bollinger Bands, and buy/sell signals, | |
| tailored for display in a Streamlit app. | |
| Parameters: | |
| - stock_data (pd.DataFrame): The stock data with 'Close', 'SMA_21', 'SMA_50', | |
| 'BB_Upper', 'BB_Lower', 'Buy_Signal', and 'Sell_Signal' columns. | |
| """ | |
| fig, ax = plt.subplots(figsize=(14, 7)) | |
| # Plotting the closing prices | |
| ax.plot(stock_data.index, stock_data['Close'], label='Close Price', color='blue', alpha=0.5) | |
| # Plotting the SMAs | |
| ax.plot(stock_data.index, stock_data['SMA_21'], label='21-Period SMA', color='orange', alpha=0.75) | |
| ax.plot(stock_data.index, stock_data['SMA_50'], label='50-Period SMA', color='green', alpha=0.75) | |
| # Plotting the Bollinger Bands | |
| ax.plot(stock_data.index, stock_data['BB_Upper'], label='Upper Bollinger Band', color='red', linestyle='--', alpha=0.5) | |
| ax.plot(stock_data.index, stock_data['BB_Lower'], label='Lower Bollinger Band', color='cyan', linestyle='--', alpha=0.5) | |
| # Highlighting buy and sell signals | |
| buy_signals = stock_data[stock_data['Buy_Signal']] | |
| sell_signals = stock_data[stock_data['Sell_Signal']] | |
| ax.scatter(buy_signals.index, buy_signals['Close'], label='Buy Signal', marker='^', color='green', alpha=1, s=100) | |
| ax.scatter(sell_signals.index, sell_signals['Close'], label='Sell Signal', marker='v', color='red', alpha=1, s=100) | |
| # Setting title and labels | |
| ax.set_title("Stock Price with Indicators and Signals") | |
| ax.set_xlabel("Date") | |
| ax.set_ylabel("Price") | |
| # Formatting date on the x-axis | |
| ax.xaxis.set_major_locator(mdates.WeekdayLocator()) | |
| ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) | |
| fig.autofmt_xdate() | |
| # Adding legend | |
| ax.legend() | |
| # Instead of plt.show(), just return the figure object | |
| return fig | |