File size: 1,957 Bytes
cd0e571
8d318ce
cd0e571
8d318ce
cd0e571
68580f7
 
cd0e571
 
68580f7
 
cd0e571
8d318ce
 
 
 
cd0e571
8d318ce
 
 
cd0e571
8d318ce
 
 
cd0e571
68580f7
8d318ce
 
68580f7
8d318ce
cd0e571
68580f7
8d318ce
 
 
cd0e571
68580f7
8d318ce
 
68580f7
cd0e571
68580f7
 
cd0e571
68580f7
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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