A key drawback of only checking the model’s output at the final time step (T) is that it completely ignores the intra-horizon dynamics—that is, it does not assess whether the model correctly predicted when (or if) the price crosses a given threshold at any intermediate time steps. This can obscure the model’s ability (or inability) to forecast moves in a timely fashion.
A Better Alternative: Evaluate Across the Horizon
Instead of only looking at the final predicted and actual prices, you can compute the directional (or other performance) metrics at each time step within the prediction horizon. Then, you could aggregate these metrics (e.g., taking an average or looking at the time to threshold crossing) to understand both the timing and magnitude of predicted moves.
Some Ideas:
Time-Resolved Directional Metrics:
Rather than computing a single metric at T, compute directional accuracy (and F1 for instance) at several time steps (or even every time step).
For each sample and each time step, convert the predicted and target moves to directional labels.
Compute per-step accuracy.
Aggregate these per-step metrics (e.g., average them) or analyze them separately to see how performance evolves over time.
First-Hit or Hitting Time Metrics:
Instead of just measuring performance at the horizon’s end, determine the first time step where the predicted/actual move exceeds the threshold:
First-Hit Time: Compare the time step at which the actual move first exceeds the threshold to the time the prediction does.
You can measure metrics such as mean absolute error between these hit times or even a “hit rate” at various time intervals.
This provides insight on the timeliness of the prediction.
Cumulative Metrics Over Time:
Evaluate the cumulative performance within the prediction window:
Compute a cumulative sum (or maximum) of moves at each time step.
Compare how quickly the cumulative metric crosses a threshold for both predictions and targets.
This is particularly useful in settings where the cumulative return (or cumulative move) matters.
Illustrative Code Example
Below is an illustrative rework of the evaluation method that computes directional accuracy at every time step and also considers the first time step where a move exceeds the threshold (if it does):
python
import jax.numpy as jnp
import jax
import matplotlib.pyplot as plt
from pathlib import Path
def to_labels(changes: jnp.ndarray, threshold: float) -> jnp.ndarray:
"""Convert continuous moves to discrete labels based on threshold."""
up = changes > threshold
down = changes < -threshold
return jnp.where(up, 1, jnp.where(down, -1, 0))
def safe_divide(numerator, denominator):
"""Safe division that returns 0 when denominator is 0."""
return jnp.where(denominator > 0, numerator / denominator, 0.0)
def evaluate_intra_horizon_metrics(preds, targets, threshold=20.0, plot_dir="plots_matplotlib/intra_horizon"):
"""
Evaluate directional accuracy and 'first-hit time' metrics at every time step.
Args:
preds: Predictions array of shape (samples, prediction_horizon)
targets: Targets array of shape (samples, prediction_horizon)
threshold: The threshold magnitude for directional moves
plot_dir: Directory to save plots
"""
# Convert to JAX arrays (if not already)
preds = jnp.array(preds)
targets = jnp.array(targets)
num_samples, horizon = preds.shape
# Compute directional labels for each time step
pred_labels = to_labels(preds, threshold) # Shape: (samples, horizon)
target_labels = to_labels(targets, threshold)
# Compute per-step directional accuracy over the horizon
step_accuracy = jnp.mean(pred_labels == target_labels, axis=0)
# Compute average accuracy across all time steps
overall_accuracy = jnp.mean(step_accuracy)
# Compute first-hit time: the first time index at which the move exceeds threshold in absolute value
def first_hit(moves):
# Find indices where move exceeds threshold
hit_indices = jnp.where(jnp.abs(moves) > threshold, size=horizon)[0]
# If no hit is found, we'll designate the hit time as the horizon (or an indicator value)
return jnp.where(hit_indices.size > 0, hit_indices[0], horizon)
# Vectorize over all samples
v_first_hit = jax.vmap(first_hit)
pred_first_hits = v_first_hit(preds)
target_first_hits = v_first_hit(targets)
# Compute error in the first-hit time prediction
first_hit_error = jnp.mean(jnp.abs(pred_first_hits - target_first_hits))
# Visualize accuracy across time steps
Path(plot_dir).mkdir(parents=True, exist_ok=True)
plt.figure(figsize=(8, 4))
plt.plot(jnp.arange(horizon), step_accuracy, marker='o')
plt.xlabel("Time Step")
plt.ylabel("Directional Accuracy")
plt.title("Intra-horizon Directional Accuracy")
plt.grid(True)
plt.savefig(f"{plot_dir}/intra_horizon_accuracy.png")
plt.close()
print(f"Overall intra-horizon directional accuracy: {overall_accuracy:.3f}")
print(f"Average first-hit time error: {first_hit_error:.3f} time steps")
return {
"overall_accuracy": overall_accuracy,
"step_accuracy": step_accuracy,
"first_hit_error": first_hit_error,
"pred_first_hits": pred_first_hits,
"target_first_hits": target_first_hits,
}
# Example usage:
if __name__ == "__main__":
import numpy as np
# Dummy data: 100 samples, 10 time steps
np.random.seed(0)
preds = np.random.randn(100, 10) * 25 # scaled for threshold demonstration
targets = np.random.randn(100, 10) * 25
results = evaluate_intra_horizon_metrics(preds, targets, threshold=20.0)
How This Alternative Helps:
Time-Resolved Evaluation:
By computing metrics at every time step, you get insights into how the predictive performance evolves over the entire horizon rather than focusing solely on T.
First-Hit Time Metric:
The first time step when the move exceeds the threshold is critical for decision-making. Measuring the difference between predicted and actual first-hit times helps assess how well the model predicts not only the magnitude but also the timing of moves.
Comprehensive Insight:
The approach yields both per-time-step accuracy and an aggregated (overall) metric, providing a full picture of the model's performance.
Using this method, you can better gauge your autoregressive model’s ability to predict intra-horizon moves, making the evaluation more informative and aligned with the real-world task requirements.