File size: 2,361 Bytes
1400cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
# utils/plotting.py

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

def plot_stock_data_with_signals(data):
    """
    Plots stock data, indicators, and buy/sell signals.

    Parameters:
    - data (DataFrame): DataFrame containing stock 'Close' prices, indicator values, and signals.
    """
    # Create a new figure and set the size.
    plt.figure(figsize=(14, 10))

    # Plot closing prices and EMAs
    ax1 = plt.subplot(311)  # 3 rows, 1 column, 1st subplot
    data['Close'].plot(ax=ax1, color='black', lw=2., legend=True)
    if 'EMA_Short' in data.columns and 'EMA_Long' in data.columns:
        data[['EMA_Short', 'EMA_Long']].plot(ax=ax1, lw=1.5, legend=True)
    ax1.set_title('Stock Price, EMAs, and Bollinger Bands')
    ax1.fill_between(data.index, data['BB_Lower'], data['BB_Upper'], color='grey', alpha=0.3)
    
    # Highlight buy/sell signals
    buy_signals = data[data['Combined_Signal'] == 'buy']
    sell_signals = data[data['Combined_Signal'] == 'sell']
    ax1.plot(buy_signals.index, data.loc[buy_signals.index]['Close'], '^', markersize=10, color='g', lw=0, label='Buy Signal')
    ax1.plot(sell_signals.index, data.loc[sell_signals.index]['Close'], 'v', markersize=10, color='r', lw=0, label='Sell Signal')
    ax1.legend()

    # Plot MACD and Signal Line
    ax2 = plt.subplot(312, sharex=ax1)  # Share x-axis with ax1
    data['MACD'].plot(ax=ax2, color='blue', label='MACD', legend=True)
    data['MACD_Signal_Line'].plot(ax=ax2, color='red', label='Signal Line', legend=True)
    ax2.fill_between(data.index, data['MACD'] - data['MACD_Signal_Line'], color='grey', alpha=0.3)
    ax2.set_title('MACD')

    # Plot RSI
    ax3 = plt.subplot(313, sharex=ax1)  # Share x-axis with ax1
    data['RSI'].plot(ax=ax3, color='purple', legend=True)
    ax3.axhline(70, linestyle='--', alpha=0.5, color='red')
    ax3.axhline(30, linestyle='--', alpha=0.5, color='green')
    ax3.set_title('RSI')

    # Improve layout and x-axis date format
    plt.tight_layout()
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    plt.gca().xaxis.set_major_locator(mdates.DayLocator())
    plt.xticks(rotation=45)

    plt.show()

# Note: This is a basic example for visualization. You may need to adjust it based on your actual 'data' DataFrame structure and the specific indicators you are plotting.