File size: 2,077 Bytes
cd0e571
8d318ce
cd0e571
8d318ce
cd0e571
8d318ce
cd0e571
 
8d318ce
cd0e571
8d318ce
 
 
 
 
cd0e571
8d318ce
 
 
cd0e571
8d318ce
 
 
cd0e571
8d318ce
 
 
cd0e571
8d318ce
 
 
cd0e571
8d318ce
 
 
 
 
cd0e571
8d318ce
 
 
 
cd0e571
 
 
8d318ce
 
 
 
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
48
49
50
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

def plot_stock_data_with_signals(stock_data):
    """
    Plots the stock data along with SMAs, Bollinger Bands, and buy/sell signals.

    Parameters:
    - stock_data (pd.DataFrame): The stock data with 'Close', 'SMA_21', 'SMA_50', 'BB_Upper', 'BB_Lower', 'Buy_Signal', and 'Sell_Signal' columns.
    """
    # Setting up the plot
    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 signals
    buy_signals = stock_data[stock_data['Buy_Signal']]
    ax.scatter(buy_signals.index, buy_signals['Close'], label='Buy Signal', marker='^', color='green', alpha=1, s=100)

    # Highlighting sell signals
    sell_signals = stock_data[stock_data['Sell_Signal']]
    ax.scatter(sell_signals.index, sell_signals['Close'], label='Sell Signal', marker='v', color='red', alpha=1, s=100)

    # Beautifying the plot
    ax.set_title("Stock Price with Indicators and Signals")
    ax.set_xlabel("Date")
    ax.set_ylabel("Price")
    ax.legend()

    # Formatting the x-axis to show dates nicely
    ax.xaxis.set_major_locator(mdates.WeekdayLocator())
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate() # Rotate date labels to prevent overlap

    plt.show()

if __name__ == "__main__":
    # Example usage:
    # Generate or fetch your stock_data DataFrame with necessary columns before calling this function
    pass