A sliding window implementation of AR(1) model for financial time series

Below is working c++ equivalent code snippet I am sharing for curious readers, the auto-correlation regression, also known as AR model are popular and classic method for analysis and forecasting time series such as stock prices. AR models comes with many varieties of which AR(1), the single lag is simplest and easier to implement by programming ordinary least square (OLS), understanding this will form basis for developing your own higher order AR models. correlation coefficient obtain using this method can be readily used for Unit root test, to find out whether our time series is stationary.

Without further ado, sharing a sliding window based ( aka moving window ) implementation which are must for all kinds of performance oriented algos, please read code comments, they are there for some explanation.

#include <iostream>
#include <stdio.h>


/****
	Author: randomticks.com
	Subject: AR(1) model examplde code
*/

int main() {

	int n = 10000;// entire price array length
	int pds = 10; // moving window period
	
	///// this is a virtual stock closing price, 
	///// in reality it will be obtained from your charting software
	double* close = new double[n]();
	close[0] = 1000; // starting price
	for(int i=1; i < n; ++i) { 
                if(std::rand()%10 > 5) {
			close[i] = close[i-1] + 1;
		} else {
			close[i] = close[i-1] - 1;
		}

	}

	double* input = new double[n](); // prepare an empty time series input - 0 filled
	double* array = new double[n](); // array to hold predicated values
	
	// below allocating 0 filled arrays in heap 
	double* _sumx = new double[n](); 
	double* _sumy = new double[n]();
	double* _sumx2 = new double[n]();
	double* _sumxy = new double[n]();

	for(int i=1; i < n; ++i ) { // starting the loop from 1 
                input[i] = close[i] - close[i-1];  // this is for 1st order differencing 
                                                                        // one can also use close[i] 
                double y = input[i]; // return 
                double x = input[i-1]; // lag-1 value for return 
                _sumx[i] = _sumx[i-1] + x; 
                _sumy[i] = _sumy[i-1] + y; 
                _sumx2[i] = _sumx2[i-1] + x*x; 
                _sumxy[i] = _sumxy[i-1] + x*y; 
                if( i > pds - 1 ) {
		
			double y_old = input[i-pds];
			double x_old = input[i-pds-1];
	
			_sumx[i] -= x_old;
			_sumy[i] -= y_old;
			_sumx2[i] -= x_old * x_old;
			_sumxy[i] -= x_old * y_old; 
	
			double var = pds*_sumx2[i] - _sumx[i]*_sumx[i];
			double cor = (pds*_sumxy[i] - _sumx[i]*_sumy[i])/var; // correlation coefficient can be 
			double fix = (_sumy[i]*_sumx2[i] - _sumx[i]*_sumxy[i])/var;
			array[i] = fix + cor * input[i-1] + close[i-1];  // predict current closing using lag-1
			
			printf("i=%d	actual= %.2f		forcast= %.2f\n", i, close[i], array[i]);
	
		} 
	}
}

Now comppile it with
g++ -std=c++11 ar1.cpp

Leave a Reply