Files
strategy-lab/to_explore/pyquantnews/68_VectorbtProjections.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

8.8 KiB

No description has been provided for this image

This code utilizes the VectorBT PRO library to detect historical price patterns and project them into the future. It identifies segments of price history similar to the latest price trend and extrapolates these patterns for statistical analysis. The code retrieves price data, finds similar historical patterns, and generates projections to visualize potential future price movements. Additionally, it creates an animated GIF to demonstrate how these projections evolve over time. This is useful for market analysis, forecasting, and real-time decision-making.

In [ ]:
import vectorbtpro as vbt
vbt.settings.set_theme("dark")

Configure the settings to set global defaults for Plotly figures.

In [ ]:
# vbt.settings.plotting.layout["width"] = 900
# vbt.settings.plotting.layout["height"] = 450
# vbt.settings.plotting.layout["images"] = [dict(
#     source="https://vectorbt.pro/assets/logo/logo.svg",
#     xref="paper", yref="paper",
#     x=0, y=0.95,
#     sizex=0.15, sizey=0.15,
#     xanchor="center", yanchor="bottom"
# )]

Define variables for the analysis including symbol, timeframe, and other parameters.

In [ ]:
SYMBOL = "BTC-USD"
TIMEFRAME = "1 hour"
START = "one year ago"

LAST_N_BARS = 66
PRED_N_BARS = 12

GIF_FNAME = "projections.gif"
GIF_N_BARS = 72
GIF_FPS = 4
GIF_PAD = 0.01

Retrieve price data from Yahoo Finance based on the defined parameters.

In [ ]:
data = vbt.YFData.pull(SYMBOL, timeframe=TIMEFRAME, start=START)

Analyze the most recent price trend and identify similar historical price segments.

In [ ]:
def find_patterns(data):
    """Identify historical price segments similar to the latest trend.
    
    This function finds price patterns in historical data that match the most recent price trend.
    
    Parameters
    ----------
    data : vbt.YFData
        The data containing historical price information.
    
    Returns
    -------
    pattern_ranges : vbt.PatternRanges
        The identified historical price segments similar to the latest trend.
    """
    price = data.hlc3
    pattern = price.values[-LAST_N_BARS:]
    pattern_ranges = price.vbt.find_pattern(
        pattern=pattern,
        rescale_mode="rebase",
        overlap_mode="allow",
        wrapper_kwargs=dict(freq=TIMEFRAME)
    )
    pattern_ranges = pattern_ranges.status_closed
    return pattern_ranges

pattern_ranges = find_patterns(data)
print(pattern_ranges.count())

Identify and plot projections from the identified price segments.

In [ ]:
def plot_projections(data, pattern_ranges, **kwargs):
    """Plot projections of historical price segments.
    
    This function extracts and plots the price data following each identified segment.
    
    Parameters
    ----------
    data : vbt.YFData
        The data containing historical price information.
    pattern_ranges : vbt.PatternRanges
        The identified historical price segments.
    
    Returns
    -------
    plot : vbt.Figure
        The plot of projections.
    """
    projection_ranges = pattern_ranges.with_delta(
        PRED_N_BARS,
        open=data.open,
        high=data.high,
        low=data.low,
        close=data.close,
    )
    projection_ranges = projection_ranges.status_closed
    return projection_ranges.plot_projections(
        plot_past_period=LAST_N_BARS, 
        **kwargs,
    )

plot_projections(data, pattern_ranges, plot_bands=False).show_png()

Display confidence bands for a visually compelling and statistically robust forecast.

In [ ]:
plot_projections(data, pattern_ranges, plot_bands=True).show_png()

Generate a GIF animation that iterates through a specified range of bars.

In [ ]:
def plot_frame(frame_index, **kwargs):
    """Plot a single frame for the GIF animation.
    
    This function applies the pattern recognition procedure to each bar within the specified range.
    
    Parameters
    ----------
    frame_index : pd.Index
        Index of the data frame.
    
    Returns
    -------
    plot : vbt.Figure or None
        The plot of projections or None if conditions are not met.
    """
    sub_data = data.loc[:frame_index[-1]]
    pattern_ranges = find_patterns(sub_data)
    if pattern_ranges.count() < 3:
        return None
    return plot_projections(sub_data, pattern_ranges, **kwargs)

vbt.save_animation(
    GIF_FNAME,
    data.index[-GIF_N_BARS:],
    plot_frame,
    plot_projections=False,
    delta=1,
    fps=GIF_FPS,
    writer_kwargs=dict(loop=0),
    yaxis_range=[
        data.low.iloc[-GIF_N_BARS:].min() * (1 - GIF_PAD), 
        data.high.iloc[-GIF_N_BARS:].max() * (1 + GIF_PAD)
    ],
)

Display the generated GIF animation to visualize the projections over time.

projections.gif

Confidence bands describe past performance but are not guarantees of future results.

PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.