Forecast future price trends (with projections)

November 11, 2023
Facebook logo.
Twitter logo.
LinkedIn logo.

Forecast future price trends (with projections)

In a previous newsletter, we used VectorBT PRO (VBT) to detect price patterns. VBT can also forecast these price segments into the future!

Having a high-confidence estimate of where the price of an asset may move in the future can help with risk management and real-time analysis.

Are you ready to learn how?

Let’s go!

Forecast future price trends (with projections)

Imports and set up

Given the self-contained design of VBT, a single import is enough for the analysis.

1import vectorbtpro as vbt
2vbt.settings.set_theme("dark")

Let's define a set of variables for our analysis and grab data from Yahoo Finance.

1SYMBOL = "BTC-USD"
2TIMEFRAME = "1 hour"
3START = "one year ago"
4
5LAST_N_BARS = 66
6PRED_N_BARS = 12
7
8GIF_FNAME = "projections.gif"
9GIF_N_BARS = 72
10GIF_FPS = 4
11GIF_PAD = 0.01
12
13data = vbt.YFData.pull(SYMBOL, timeframe=TIMEFRAME, start=START)

Find and plot projections

Let's write a function that analyzes the most recent price trend and employs it as a pattern to identify similar price movements in historical data

1def find_patterns(data):
2    price = data.hlc3
3    pattern = price.values[-LAST_N_BARS:]
4    pattern_ranges = price.vbt.find_pattern(
5        pattern=pattern,
6        rescale_mode="rebase",
7        overlap_mode="allow",
8        wrapper_kwargs=dict(freq=TIMEFRAME)
9    )
10    pattern_ranges = pattern_ranges.status_closed
11    return pattern_ranges
12
13pattern_ranges = find_patterns(data)

This pattern recognition function will focus exclusively on segments of price history having a comparable percentage change from their respective starting points.

We identified 14 price segments that closely resemble the latest price trend.

1def plot_projections(data, pattern_ranges, **kwargs):
2    projection_ranges = pattern_ranges.with_delta(
3        PRED_N_BARS,
4        open=data.open,
5        high=data.high,
6        low=data.low,
7        close=data.close,
8    )
9    projection_ranges = projection_ranges.status_closed
10    return projection_ranges.plot_projections(
11        plot_past_period=LAST_N_BARS, 
12        **kwargs,
13    )
14
15plot_projections(data, pattern_ranges, plot_bands=True).show_png()

The function that extracts the price data immediately after each segment and plots these as extensions of the price trend. The result is a series of price projections.

Forecast future price trends (with projections). VBT can also forecast these price segments into the future!

As we can see, similar price movements have historically branched into many paths.

For a statistically robust forecast, we display the confidence bands around the projections, with 60% of these projections falling between the upper and lower bands

Generate an animated GIF

Lastly, we will generate an animated GIF that iterates through a specified range of bars, applying the procedure to each bar within that range.

1def plot_frame(frame_index, **kwargs):
2    sub_data = data.loc[:frame_index[-1]]
3    pattern_ranges = find_patterns(sub_data)
4    if pattern_ranges.count() < 3:
5        return None
6    return plot_projections(sub_data, pattern_ranges, **kwargs)
7
8vbt.save_animation(
9    GIF_FNAME,
10    data.index[-GIF_N_BARS:],
11    plot_frame,
12    plot_projections=False,
13    delta=1,
14    fps=GIF_FPS,
15    writer_kwargs=dict(loop=0),
16    yaxis_range=[
17        data.low.iloc[-GIF_N_BARS:].min() * (1 - GIF_PAD), 
18        data.high.iloc[-GIF_N_BARS:].max() * (1 + GIF_PAD)
19    ],
20)

The result is an illustrated depiction of the real time price forecasts.

Forecast future price trends (with projections). VBT can also forecast these price segments into the future!
Forecast future price trends (with projections). VBT can also forecast these price segments into the future!

Next steps

There are two action items you can follow to take advantage of this powerful forecasting feature. First, is use it to set limit orders and stop losses during live trading.

The second is to generate a backtest using these price predictions in your strategy.

Man with glasses and a wristwatch, wearing a white shirt, looking thoughtfully at a laptop with a data screen in the background.