8.8 KiB
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.
import vectorbtpro as vbt vbt.settings.set_theme("dark")
Configure the settings to set global defaults for Plotly figures.
# 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.
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.
data = vbt.YFData.pull(SYMBOL, timeframe=TIMEFRAME, start=START)
Analyze the most recent price trend and identify similar historical price segments.
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.
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.
plot_projections(data, pattern_ranges, plot_bands=True).show_png()
Generate a GIF animation that iterates through a specified range of bars.
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.
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.

