PoorRican / tradr-rs

0 stars 0 forks source link

Graph multiple bollinger bands #28

Open PoorRican opened 1 month ago

PoorRican commented 1 month ago

In order to better understand ts tendencies and plan a better strategy, figure out a way to graph multiple (ie: different intraday data)

Using Streamlit might be the best strategy

Here is a streamlit component which aims to make plotly plots interactive

https://github.com/null-jones/streamlit-plotly-events

There should be a way to control the time range using a double ended slider which shows the time range.

PoorRican commented 1 month ago

Using this output from Claude might be helpful.

Chat is called "Visualizing Stock Prices with Bollinger Bands"

Certainly, I can help you create a function to plot candle close prices along with multiple Bollinger Band indicators using matplotlib and pandas. This kind of visualization can be very useful for analyzing stock price movements and comparing different Bollinger Band settings.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates

def plot_price_with_bollinger_bands(df, bollinger_bands_dict):
    """
    Plot candle close price with multiple Bollinger Band indicators.

    :param df: pandas DataFrame with 'Date' and 'Close' columns
    :param bollinger_bands_dict: dict of Bollinger Bands, where key is the label and value is a tuple of (lower, middle, upper)
    """
    # Create the plot
    fig, ax = plt.subplots(figsize=(12, 6))

    # Plot close price
    ax.plot(df['Date'], df['Close'], label='Close Price', color='black', linewidth=1)

    # Plot Bollinger Bands
    colors = plt.cm.rainbow(np.linspace(0, 1, len(bollinger_bands_dict)))
    for (label, (lower, middle, upper)), color in zip(bollinger_bands_dict.items(), colors):
        ax.plot(df['Date'], upper, label=f'{label} Upper', color=color, linestyle='--', alpha=0.7)
        ax.plot(df['Date'], middle, label=f'{label} Middle', color=color, linestyle='-', alpha=0.7)
        ax.plot(df['Date'], lower, label=f'{label} Lower', color=color, linestyle='--', alpha=0.7)
        ax.fill_between(df['Date'], lower, upper, alpha=0.1, color=color)

    # Customize the plot
    ax.set_title('Stock Price with Multiple Bollinger Bands')
    ax.set_xlabel('Date')
    ax.set_ylabel('Price')
    ax.legend(loc='upper left', bbox_to_anchor=(1, 1))
    ax.grid(True, linestyle='--', alpha=0.5)

    # Format x-axis
    ax.xaxis.set_major_formatter(DateFormatter("%Y-%m-%d"))
    ax.xaxis.set_major_locator(mdates.AutoDateLocator())
    fig.autofmt_xdate()  # Rotate and align the tick labels

    plt.tight_layout()
    plt.show()

# Example usage:
# Assuming you have a DataFrame 'df' with 'Date' and 'Close' columns
# and multiple Bollinger Band calculations

# bollinger_bands = {
#     'BB(20, 2)': (df['lower_20_2'], df['middle_20_2'], df['upper_20_2']),
#     'BB(50, 2.5)': (df['lower_50_2.5'], df['middle_50_2.5'], df['upper_50_2.5']),
#     'BB(100, 3)': (df['lower_100_3'], df['middle_100_3'], df['upper_100_3'])
# }

# plot_price_with_bollinger_bands(df, bollinger_bands)

This function, plot_price_with_bollinger_bands, takes two parameters:

  1. df: A pandas DataFrame containing at least 'Date' and 'Close' columns for the stock price data.
  2. bollinger_bands_dict: A dictionary where each key is a label for a set of Bollinger Bands, and each value is a tuple of (lower, middle, upper) bands.

The function creates a plot with the following features:

To use this function, you would first need to calculate your Bollinger Bands using your preferred method (e.g., using pandas rolling functions or ta-lib). Then, you would create a dictionary with your Bollinger Bands and pass it to the function along with your DataFrame.

Here's a quick example of how you might calculate Bollinger Bands and use this function:

import pandas as pd
import numpy as np

# Assume df is your DataFrame with 'Date' and 'Close' columns

def calculate_bollinger_bands(df, window, num_std):
    rolling_mean = df['Close'].rolling(window=window).mean()
    rolling_std = df['Close'].rolling(window=window).std()
    upper_band = rolling_mean + (rolling_std * num_std)
    lower_band = rolling_mean - (rolling_std * num_std)
    return lower_band, rolling_mean, upper_band

# Calculate different Bollinger Bands
bb_20_2 = calculate_bollinger_bands(df, 20, 2)
bb_50_2_5 = calculate_bollinger_bands(df, 50, 2.5)
bb_100_3 = calculate_bollinger_bands(df, 100, 3)

# Create the dictionary for the Bollinger Bands
bollinger_bands = {
    'BB(20, 2)': bb_20_2,
    'BB(50, 2.5)': bb_50_2_5,
    'BB(100, 3)': bb_100_3
}

# Plot the chart
plot_price_with_bollinger_bands(df, bollinger_bands)

This will create a chart with the stock's closing price and three different Bollinger Band indicators, each in a different color. You can easily add or remove Bollinger Bands by modifying the bollinger_bands dictionary.

Would you like me to explain any part of this code in more detail?​​​​​​​​​​​​​​​​