"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;
Showing posts with label Timeseries. Show all posts
Showing posts with label Timeseries. Show all posts

November 21, 2023

Forecasting - nixtla

A ton of Algo's consolidated and released - nixtla

There's an ever-growing forest of related projects out there, including:

  • TimeGPT does zero-shot inference
  • Allows forecasting of multiple time series.
  • TimeGPT leverages the Transformer for forecasting tasks.
Ref - Link








Temporian is a library for safe, simple and efficient preprocessing and feature engineering of temporal data in Python.


Keep Exploring!!!

June 05, 2023

Cashflow forecasting

Paper - Empowering cash managers to achieve cost savings by improving predictive accuracy

  • Cash management is concerned with optimizing the short-term funding requirements of a company

Time Series Forecasting with Transformer Models and Application to Asset Management

  • Sequence prediction - we often predict the next value of the sequence itself
  • Sequence generation - convert sequences from one domain into sequences from another domain, such as machine translation, text summarization, chatbots
  • Iterated multi-step forecasting
  • Direct multi-step forecasting



Self-attention is designed to capture the dependencies in the sequence, such as the relationship between each word with each other word in a senten

For a given query, we compare it with all keys K and get different weights for different values

Self-attention and multi-head attention are permutation-equivariant with respect to its inputs

In our experiment, we consider three different portfolio allocation methods:

  • Single-period MVO portfolio with monthly rebalancing
  • Risk parity portfolio with monthly rebalancing
  • Multi-period MVO portfolio with weekly rebalancing as described by Problem

How to Build a Cash Flow Forecast

  • Determine Your Forecasting Objective(s)
  • Short-term liquidity planning
  • Interest and debt reduction
  • Liquidity risk management
  • Growth planning

Cash payments and receipts. - Short-period forecasts: Short-term forecasts typically look two to four weeks into the future and contain a daily breakdown of cash payments and receipts.

The most common medium-term forecast is the rolling 13-week cash flow forecast.

Long-period forecasts: Longer-term forecasts typically look 6–12 months into the future and are often the starting point for annual budgeting processes

Mixed-period forecasts: Mixed-period forecasts use a mix of the three periods above and are commonly used for liquidity risk management.

Cash flow forecasting

  • Forecast your income or sales
  • Estimate cash inflows
  • Estimate cash outflows and expenses
  • Review your estimated cash flows against the actual

Preparing a cash flow forecast: Simple steps for vital insight

  • Decide how far out you want to plan for
  • List all your income
  • List all your outgoings

Empirical analysis of daily cash flow time series and its implications for forecasting

Cash management is concerned with the efficient use of a company’s cash and short-term investments such as marketable securities.

From these and other works, we observe that common assumptions on the statistical properties of cash flow time-series include:

  • Normality: cash flows follow a Gaussian distribution with observations symmetrically centered around the mean, and with finite variance.
  • Absence of correlation: the occurrence of past cash flows does not affect the probability of occurrence of the next ones.
  • Stationarity: the probability distribution of cash flows does not change over time and, consequently, its statistical properties such as the mean and variance remain stable.
  • Linearity: cash flows are proportional either to another (external) explanatory variable or to a combination of (external) explanatory variables.

Empowering cash managers to achieve cost savings by improving predictive accuracy

Kurtosis is a measure of the tailedness of a distribution. Tailedness is how often outliers occur

Transforming Financial Forecasting with Data Science and Machine Learning at Uber

  • Strategic planning
  • Operations
  • Insights


Modeling strategic investments as an optimization problem

  • Minimize spending
  • Maximize number of drivers or riders
  • Maximize number of first trips or total trips
  • Maximize gross bookings

With each optimization problem, we can also specify constraints, such as:

  • Maximum budget, overall or specific to certain channels (such as marketing versus rider promotion)
  • Minimum number of first trips or trips
  • Minimum month-to-month gross booking growth

Short-term use cases: Short-term use cases for cashflow forecasting include budgeting, forecasting sales, and managing cash flow. It can also be used to identify potential areas of overspending and to plan for future investments

Long-term use cases: Cashflow forecasting can be used to plan for long-term investments, such as capital expenditures and acquisitions. It can also be used to develop strategies for managing cash flow over the long-term, such as budgeting and debt management




  • Receivables forecast
  • Payable forecast
Ref - Link


Keep Exploring!!!

February 01, 2023

Research paper Read - Are Transformers Effective for Time Series Forecasting?

 Are Transformers Effective for Time Series Forecasting?

  • Time series are ubiquitous in today’s data-driven world.
  • Given historical data, time series forecasting (TSF) is a long-standing task that has a wide range of applications
  • Long-term time series forecasting (LTSF)
  • Simple one-layer linear models named LTSF-Linear for comparison
  • The main working power of Transformers is from its multi-head self-attention mechanism
  • Extensive experiments on nine widely-used benchmark datasets that cover various real-life applications: traffic, energy, economics, weather, and disease predictions.
  • LTSF-Linear outperforms existing complex Transformerbased models in all cases, and often by a large margin (20% - 50%).

  • The difference between the original sequence and the trend component is regarded as the seasonal component

  • Transformer-based methods: FEDformer [31], Autoformer [28], Informer [30], Pyraformer [18], and LogTrans [16].
  • FEDformer in most cases by 20% ∼ 50% improvements on the multivariate forecasting
  • FEDformer employs classical time series analysis techniques such as frequency processing, which brings in time series inductive bias and benefits the ability of temporal feature extraction

  • Recurrent neural networks (RNNs) based methods (e.g., [21]) summarize the past information compactly in internal memory states and recursively update themselves for forecasting.
  • Convolutional neural networks (CNNs) based methods (e.g., [3]), wherein convolutional filters are used to capture local temporal features.

Keep Exploring!!!

January 15, 2023

Time Series Notes - Features Evaluation - Anamoly Detection

Time Series Features

  • Date time features -  hour, month, and day of week for each observation. Daylight savings or not, Public holiday or not, Quarter of the year, Hour of day, Season of the year. 
  • Lag features and window features - Business day, Quarter start, Weekly frequency
  • Rolling window statistics - moving average
  • Expanding window statistics - minimum, mean, and maximum values
  • Domain-specific features - additional research into each feature and find out domain-specific information beyond what is provided in the dataset description
  • Additional factors, such as trends, seasonality, holidays, and external economic variables.

Introduction to feature engineering for time series forecasting

Top 4 Time Series Feature Engineering Lessons From Kaggle

Time Series as Features

Ref - Link



An observation that deviates so much from other observations as to arouse suspicions that it was generated by a different mechanism



  • Python Outlier Detection (PyOD)
  • Python Streaming Anomaly Detection (PySAD)
  • Python Graph Outlier Detection (PyGOD)



Ref - Link


Keep Exploring!!!

October 03, 2022

Financial Time Series Forecasting

Financial Time Series Forecasting

Usecases

  • Stock price forecasting
  • Index prediction
  • Forex price prediction
  • Commodity (oil, gold, etc) price prediction
  • Bond price forecasting
  • Volatility forecasting
  • Cryptocurrency price forecasting

Patterns

  • Price prediction and price movement (trend) prediction
  • Researchers consider trend prediction
  • Trend prediction becomes a classification problem - only up or down movements are taken into consideration. whereas up, down or neutral movements (3-class problem) also exist.

Time Aspects

  • Period refers to the time period for training and testing
  • Lag has the time length of the input vector (e.g. 30d means the input vector has a 30 day window)
  • Horizon shows how far out into the future is predicted

Features

  • Lagged stock returns
  • Price data
  • Turnover and number of trades.
  • Daily closing prices
  • Monthly and daily log-returns
  • Price time series and emotional data from text posts for predicting the stock opening price of the next day
  • Detecting the buy-sell pressure of movements
  • GDP, Unemployment rate, Inventories, etc.
  • Financial news
  • Stock market data
  • Volatility
  • Technical indicators, Price data, News
  • Twitter sentiment and stock prices
  • Social media news, Index data
  • Limit order book state
  • Trades
  • Buy/sell orders
  • Order deletions
  • Selected words in a news
  • Weather conditions and various macroeconomic indicators
  • Specific customer shipment patterns or the current competitive market situation
  • A further example is the transformation of categorical variables into several binary values via so-called one-hot encoding trends or seasonal components 
  • When classifying the competitive market situation as “highly competitive”, “moderately competitive”, “not competitive” and the like
  • When a particular weather situation coincides with a peak shipment date, nullifying or exacerbating the effect of the peak shipment date

Challenges

  • Price disruptions, high volatility, bid-ask spread variations cause arbitrage opportunities across different platforms

What is the future direction for DL research for financial time series forecasting ?

  • Response: NLP, semantics and text mining-based hybrid models ensembled with timeseries data might be more common in the near future.

Expert Aggregation for Financial Forecasting

  • Aggregation with expert advice has the advantage of considering several forecasters instead of one, keeping the knowledge of each expert across time
  • By weighting dynamically portfolios the mixture decreases the mean mixture excess risk, ensuring that on average the aggregation forecasting loss is close or better than the one of the best expert
  • Stocks are then sorted according to their expert’s prediction, allowing to build two portfolios (stocks to be invested or shorted) for each expert. 
  • In a second step, the expert portfolios are aggregated based on the strategy returns, building an adaptive convex combination of the family of portfolios.

MACHINE LEARNING FOR FINANCIAL FORECASTING, PLANNING AND ANALYSIS: RECENT DEVELOPMENTS AND PITFALLS

  • Fraud detection and financial forecasting. Planning and resource allocation
  • Investments in research and development (R&D) 
  • Expansion of production capacity
  • Financial obligations to debt holders or equity investors and tax authorities
  • The time horizons considered for financial forecasts and plans usually range from one month to several years
  • A practical example is to predict the sales of a product using input variables such as time of the year, price level, advertising expenditures and availability of competitor products.

Real-time Forecasting of Time Series in Financial Markets Using Sequentially Trained Many-to-one LSTMs

  • LSTM is also suitable for complex data sequences such as stock time series extracted from financial markets because it has internal memory, has capability of customization, and is free from gradient-related issues
  • Since we make predictions only for one time step ahead at a time for an input time series, the LSTM architecture implemented here is the many-to-one type

Time series workshop



  • Dynamic Time Wrapping
  • Common Periodicity Detection Algorithms
  • Time domain: autocorrelation function
  • Freq domain: Fisher’s test by Periodogram

  • Short-term forecasting: predict the near future
  • Long-term forecasting: predict the future with an extended period
  • Extreme value forecasting: predict the extreme values
  • Point or Probabilistic forecasting: predict point value or interval/probability distribution

Nbeats

DeepAR


TFT


Autoformer: Transformer with auto-correlation mechanism

FEDformer: frequency enhanced decomposed Transformer

Quatformer: Transformer with quaternions for periodic time series

Time-Series Works and Conferences

Transformers in Time Series

Dynamic Time Warping (DTW) variations

  • FastDTW
  • RobustDTW

Kstacked LSTM

Ref link 

Deep Time

  • DeepTime: Using Deep Time-Index Meta-Learning to Improve Non-Stationary Time-Series Forecasting
  • A time-series is a series of data measurements over time – a sequential collection of numerical data
  • Non-Stationarity: When Time Series Changes Over Time
  • Stationarity refers to time series data values that stay within a range, as well as regularity in the time series statistical patterns
  • Meta-learning is a technique that aims to achieve the kind of quick learning exhibited by humans
  • The inner learning loop learns very quickly from a small set of examples, called the support set.
  • The outer learning loop ensures that the inner loop can perform this fast adaptation on new support sets. This is done by being trained on a query set - a set containing similar but distinct examples from the initial support set.
  • Single-shot: Make the predictions all at once.
  • Autoregressive: Make one prediction at a time and feed the output back to the model.
The main features of the input windows are:
  • The width (number of time steps) of the input and label windows.
  • The time offset between them.
  • Which features are used as inputs, labels, or both.
Generates windows 24 hours of consecutive inputs and labels at a time
input_width=24, label_width=24, shift=1

Forecasting Notes

Ref Link 

  • RNNs/CNNs are able to extract the most relevant features without manual engineering
  • Forecasting applications (e.g. retail demand, electricity load, weather, finance, etc.)
  • Bregman Volatility allows us to compute the optimal volatility of a sequence of forecasts

MQTransformer: Multi-Horizon Forecasts with Context-Dependent and Feedback-Aware Attention


Time series forecasting the key fundamental questions

Time series forecasting is a statistical technique used to predict future values of a variable based on historical data. It is widely used in various fields, such as finance, economics, and weather forecasting. When working with time series forecasting, there are several key fundamental questions to consider:

What is the objective of the forecast? Clearly define the purpose of the forecast, such as predicting sales, stock prices, or weather conditions. This will help guide the selection of appropriate forecasting methods and evaluation metrics.

What is the frequency and length of the time series data? The frequency (e.g., daily, monthly, yearly) and length of the historical data will influence the choice of forecasting models and techniques. Longer and more frequent data can provide more accurate forecasts but may also require more complex models.

Is the time series stationary or non-stationary? Stationary time series have constant mean and variance over time, while non-stationary time series exhibit trends or seasonality. Different forecasting methods are suitable for stationary and non-stationary data, so it is essential to identify the nature of the time series.

Are there any seasonal patterns or trends in the data? Identifying and accounting for seasonality and trends can improve the accuracy of forecasts. Techniques such as decomposition, differencing, or using seasonal models like SARIMA can help address these patterns.

Are there any external factors or events that may influence the time series? Consider any external factors, such as economic conditions, holidays, or promotions, that may impact the variable being forecasted. Incorporating these factors into the forecasting model can improve its accuracy.

Which forecasting model(s) should be used? There are various time series forecasting models, such as ARIMA, Exponential Smoothing, and Neural Networks. Selecting the appropriate model(s) depends on the characteristics of the data and the forecasting objective.

How to evaluate the accuracy of the forecasts? Use appropriate evaluation metrics, such as Mean Absolute Error (MAE), Mean Squared Error (MSE), or Mean Absolute Percentage Error (MAPE), to assess the accuracy of the forecasts and compare different models.

How to handle uncertainty and confidence intervals? Forecasting is inherently uncertain, so it is essential to provide confidence intervals or prediction intervals to quantify the uncertainty associated with the forecasts.

How often should the forecasts be updated? Determine the frequency of updating the forecasts based on the needs of the decision-making process and the availability of new data.

How to communicate the forecasts and their uncertainty to stakeholders? Effectively communicate the forecasts, their accuracy, and associated uncertainties to stakeholders to support informed decision-making.

Addressing these fundamental questions will help ensure a robust and accurate time series forecasting process that meets the needs of the decision-makers and stakeholders.

Global models in time series forecasting refer to models that capture the overall structure and patterns in the entire time series data. These models consider the entire dataset as a single entity and attempt to identify and model the underlying patterns, trends, and seasonality that are consistent across the entire time series. Global models are in contrast to local models, which focus on capturing patterns and relationships within smaller segments or windows of the time series data.

Some common global models used in time series forecasting include:

Autoregressive Integrated Moving Average (ARIMA): ARIMA is a linear model that combines autoregressive (AR) and moving average (MA) components, along with differencing to make the time series stationary. It is a widely used global model for forecasting stationary time series data.

Exponential Smoothing State Space Model (ETS): ETS is a family of forecasting models that includes Simple Exponential Smoothing, Holt's Linear Trend, and Holt-Winters Seasonal models. These models use exponential smoothing to capture the level, trend, and seasonality components in the time series data.

Seasonal Decomposition of Time Series (STL): STL is a technique used to decompose a time series into its trend, seasonal, and residual components. The decomposed components can then be modeled separately and combined to generate forecasts.

Vector Autoregression (VAR): VAR is a multivariate extension of the ARIMA model, used for forecasting multiple interrelated time series simultaneously. It captures the linear dependencies between the variables in the system and can be used for global forecasting in a multivariate setting.

Prophet: Developed by Facebook, Prophet is a global forecasting model that combines additive regression with seasonal and holiday components. It is designed to handle time series data with strong seasonality and multiple seasonality patterns.

Global models are generally more straightforward to implement and interpret compared to local models, as they focus on capturing the overall structure of the time series data. However, they may not be as effective in capturing short-term fluctuations or non-linear patterns in the data. In such cases, local models or a combination of global and local models may be more appropriate for forecasting.

Keep Exploring!!!

August 11, 2022

Forecasting - Timeseries

Key Notes

  • ML for forecasting
  • M5 dataset hierarchical information
  • A large number of correlated time series 30K


  • Sparsity of data
  • Weekly / Seasonal patterns
  • LightGBM performed better
  • Baseline exponential smoothing was better
  • Benchmark with simple methods

  • Table of features
  • Features with info from past
  • Feature / Lag1 / Lag2
  • Know past/feature values
  • Advertising spend of future


  • Use weather forecast for future
  • Create a naive forecast from the previous value
  • Use lag futures

  • Metadata static features

  • Multi-step forecasting
  • Direct forecasting
  • Recursive forecasting

  • Models to build one step, two steps ahead
  • Recursive forecasting
  • Fit once and recursively use the model with one step ahead forecast
  • Append to training data
  • Recreate features
  • Plug that back into the model


  • Independent models have issues
  • Recursive is less complicated
  • Correlated but errors may propagate
  • Split data by time to replicate the actual forecasting process
  • Split by time horizon
  • Split & Forecast Horizon

  • Differences for time series
  • Split by time

  • Feature Engineering
  • Data Imputation
  • Encode Categorical variable
  • Temporal aspects - Time
  • Future data (Marketing info / Promos)
  • Do not allow data leak of future in past


  • Weekly Seasonality
  • Exogeneous features - Advertising spend
  • Effect distributed in time
  • Spend on a daily basis (Distributed lags)

  • lag selection

  • Seasonal trends - Festivals / Seasons

  • Create a bunch of lags

  • Window features (Function over a window of time)

  • Rolling standard deviation
  • Rolling mean
  • Month trend
  • biweekly trend
  • Weekendtrend
  • Festive trend
  • Nested window features
  • Model learns seasonality

  • Future values are discarded while featuring computation
  • Use value before the timestamp
  • Expanding window of mean
  • Useful libraries


Ref Slides

Exogenous Variables - having an external cause or origin

  • Agriculture - Crop-eating pests, weather, crop diseases
  • Supply chain - Economy, consumer attitudes changes
  • Retail - Economy indicator, Weather, Unemployment rates, Inflation

Keep Forecasting!!!!