import yfinance as yf import matplotlib.pyplot as plt import pandas as pd Define the…
- User
import yfinance as yf import matplotlib.pyplot as plt import pandas as pd
Define the stock ticker symbol
ticker_symbol = '^IBEX' # Replace with your desired stock ticker symbol
Download the daily close values for the stock
stock_data = yf.download(ticker_symbol, start='2020-01-01', end='2024-10-16')['Close']
Calculate the moving averages
short_window = 20 long_window = 50
Calculate the short-term and long-term moving averages
short_ma = stock_data.rolling(window=short_window).mean() long_ma = stock_data.rolling(window=long_window).mean()
Calculate the Relative Strength Index (RSI)
window_length = 14 delta = stock_data.diff(1) up, down = delta.copy(), delta.copy() up[up<0] = 0 down[down>0] = 0 roll_up = up.rolling(window=window_length).mean() roll_down = down.rolling(window=window_length).mean().abs() RS = roll_up / roll_down RSI = 100.0 - (100.0 / (1.0 + RS))
Calculate the Bollinger Bands
window = 20 no_of_std = 2 rolling_mean = stock_data.rolling(window).mean() rolling_std = stock_data.rolling(window).std() upper_band = rolling_mean + (rolling_std * no_of_std) lower_band = rolling_mean - (rolling_std * no_of_std)
Plot the daily close values, moving averages, RSI, and Bollinger Bands
fig, ax = plt.subplots(2, 1, figsize=(12, 8))
Plot the daily close values
ax[0].plot(stock_data, label='Daily Close') ax[0].plot(short_ma, label=f'Short-term MA ({short_window})', color='g') ax[0].plot(long_ma, label=f'Long-term MA ({long_window})', color='r') ax[0].set_title('Daily Close Values and Moving Averages') ax[0].set_xlabel('Date') ax[0].set_ylabel('Price ($)') ax[0].legend(loc='upper left')
Plot the RSI and Bollinger Bands
ax[1].plot(RSI, label='RSI', color='b') ax[1].axhline(y=70, color='r', linestyle='--', label='Overbought') ax[1].axhline(y=30, color='g', linestyle='--', label='Oversold') ax[1].plot(upper_band, label='Upper Bollinger Band', color='r') ax[1].plot(lower_band, label='Lower Bollinger Band', color='g') ax[1].set_title('RSI and Bollinger Bands') ax[1].set_xlabel('Date') ax[1].set_ylabel('Value') ax[1].legend(loc='upper left')
plt.tight_layout() plt.show()
At "# Plot the RSI and Bollinger Bands", RSI, Overbought and Oversold are in a very different scale that upper and lower Bollinger bands... so the plot is not functional. Can you put Bolling Bands referenced to one y-axis and RSI, Overbought and Oversold referenced to other y-axis?
- Assistant
You're right—plotting the Relative Strength Index (RSI) alongside Bollinger Bands on the same y-axis can lead to a confusing and non-functional visualization due to their differing scales. To resolve this, you can utilize Matplotlib's
twinx()function to create a secondary y-axis for one of the datasets in the second subplot. This way, RSI and Bollinger Bands will each have their own y-axis, making the plot more readable and meaningful.Here's how you can modify your code to achieve this:
import yfinance as yf import matplotlib.pyplot as plt import pandas as pd # Define the stock ticker symbol ticker_symbol = '^IBEX' # Replace with your desired stock ticker symbol # Download the daily close values for the stock stock_data = yf.download(ticker_symbol, start='2020-01-01', end='2024-10-16')['Close'] # Calculate the moving averages short_window = 20 long_window = 50 # Calculate the short-term and long-term moving averages short_ma = stock_data.rolling(window=short_window).mean() long_ma = stock_data.rolling(window=long_window).mean() # Calculate the Relative Strength Index (RSI) window_length = 14 delta = stock_data.diff(1) up, down = delta.copy(), delta.copy() up[up < 0] = 0 down[down > 0] = 0 roll_up = up.rolling(window=window_length).mean() roll_down = down.rolling(window=window_length).mean().abs() RS = roll_up / roll_down RSI = 100.0 - (100.0 / (1.0 + RS)) # Calculate the Bollinger Bands window = 20 no_of_std = 2 rolling_mean = stock_data.rolling(window).mean() rolling_std = stock_data.rolling(window).std() upper_band = rolling_mean + (rolling_std * no_of_std) lower_band = rolling_mean - (rolling_std * no_of_std) # Plot the daily close values, moving averages, RSI, and Bollinger Bands fig, ax = plt.subplots(2, 1, figsize=(14, 10), sharex=True) # Plot the daily close values and moving averages ax[0].plot(stock_data, label='Daily Close', color='blue') ax[0].plot(short_ma, label=f'Short-term MA ({short_window})', color='green') ax[0].plot(long_ma, label=f'Long-term MA ({long_window})', color='red') ax[0].set_title('Daily Close Values and Moving Averages') ax[0].set_ylabel('Price ($)') ax[0].legend(loc='upper left') ax[0].grid(True) # Create a twin y-axis for RSI and Bollinger Bands ax_rsi = ax[1] ax_boll = ax[1].twinx() # Plot RSI and Overbought/Oversold lines ax_rsi.plot(RSI, label='RSI', color='purple') ax_rsi.axhline(y=70, color='red', linestyle='--', label='Overbought (70)') ax_rsi.axhline(y=30, color='green', linestyle='--', label='Oversold (30)') ax_rsi.set_ylabel('RSI') ax_rsi.set_ylim(0, 100) # Plot Bollinger Bands ax_boll.plot(upper_band, label='Upper Bollinger Band', color='orange') ax_boll.plot(lower_band, label='Lower Bollinger Band', color='cyan') ax_boll.set_ylabel('Bollinger Bands ($)') ax_boll.grid(False) # Optional: Disable grid for secondary y-axis # Combine legends from both y-axes lines_rsi, labels_rsi = ax_rsi.get_legend_handles_labels() lines_boll, labels_boll = ax_boll.get_legend_handles_labels() ax_rsi.legend(lines_rsi + lines_boll, labels_rsi + labels_boll, loc='upper left') ax[1].set_title('RSI and Bollinger Bands') ax[1].set_xlabel('Date') plt.tight_layout() plt.show()Explanation of Changes
-
Creating a Twin Y-Axis:
ax_rsi = ax[1]: This is the primary y-axis for RSI.ax_boll = ax[1].twinx(): This creates a secondary y-axis sharing the same x-axis.
-
Plotting RSI and Overbought/Oversold Levels:
- RSI is plotted on
ax_rsi. - Horizontal lines are added at RSI levels 70 (Overbought) and 30 (Oversold).
- RSI is plotted on
-
Plotting Bollinger Bands:
- Upper and lower Bollinger Bands are plotted on
ax_boll.
- Upper and lower Bollinger Bands are plotted on
-
Setting Labels and Limits:
- Each y-axis has its own label and appropriate limits.
- RSI is limited between 0 and 100 for better visualization.
-
Combining Legends:
- Legends from both y-axes are combined to provide a comprehensive legend.
-
Enhancements:
- Grid Lines: Enabled for the first subplot and optional for the second.
- Figure Size: Increased to
(14, 10)for better clarity. - Shared X-axis: Using
sharex=Trueto align the x-axes of both subplots.
Visualization Result
The updated plot will have two subplots:
- Top Subplot: Shows the daily close prices along with short-term and long-term moving averages.
- Bottom Subplot:
- Left Y-Axis: Displays RSI with Overbought and Oversold indicators.
- Right Y-Axis: Shows Bollinger Bands.
This separation ensures that each indicator is clearly visible and interpretable without scale conflicts.
Sample Output
[image: Sample Plot] open (Replace with actual plot image if available)
Additional Tips
- Customization: Feel free to adjust colors, line styles, and other aesthetics to match your preferences or to differentiate between the plots more clearly.
- Interactivity: Consider using interactive plotting libraries like Plotly for more dynamic visualizations, especially if you're analyzing multiple stocks or timeframes.
- Annotations: Adding annotations for significant events or threshold breaches can provide deeper insights.
By implementing these changes, your plot will effectively display both RSI and Bollinger Bands without scale-related issues, enhancing your ability to analyze the stock's performance.
-