In this post we are going to discuss how to build a simple Kalman Filter for our swing trading system. Kalman Filter is better than a moving average. In a moving average we are calculating the average over a rolling window. In Kalman Filter there is no rolling window. Before we continue, did you read the post on **GBP CPI Y/Y trade that made 350 pips in 4 hours**? News trading can be highly profitable if you can read the charts correctly.

Kalman Filter is a predictor corrector type estimator that minimizes the estimated error covariance with each new measurement. Kalman Filter is a recursive solution to estimating and then predicting discrete. Discrete data is what we are working with when trading the currency market. When we download the csv file we have the Open, High, Low and Close for a specific time period. The problem is to use this discrete data and predict the next Open, High, Low and Close. In this post we are going to only deal with the closing price. We will build a simple Kalman Filter that we will use in swing trading and see if we get good results. In the coming posts we will build more sophisticated Kalman Filters.

If you want to build more sophisticated Kalman Filters you can **take a look at our Kalman Filters For Traders Course**. In this course we teach you how to make multivariate Kalman Filters as well as the Extended Kalman Filter and the Unscented Kalman Filter.Kalman Filter is a linear state space model. Linear models are good and easy to calculate. Non linear systems are difficult to calculate. The results are also approximate. When we are trading in real time, we need algorithms that make quick calculations. We cannot afford to use algorithms that take many minutes to do the calculation. Kalman Filter is a concept that takes time to grasp due to difficult mathematical jargon that is used in it. But once you grasp the concept, you will be surprised at the simplicity. You will wonder why it is shrouded in so much complex mathematical jargon. Watch the video below that explains Kalman Filter!

### Who Was Rudolf Kalman?

Kalman Filter had been originally developed for tracking rockets in early 1960s. Rudolf Kalman was the person who developed this filter. He has done his bachelors and masters in electrical engineering from MIT. He did his PhD from Columbia in 1957 . This filter had been around for sometime but he was the one who put it in final shape by publishing a research paper on how to use it for estimation. Initially his filtering method was met with skepticism. But in 1960 when Kalman visited NASA Ames Research Center, his presentation was a success. His filter was subsequently used in Apollo Space Mission. After a few decades economists discovered it and started using it in econometrics as well. From there it found its way into quantitative trading. Below is a photo of Kalman receiving presidential medal from US President Obama. So you can well imagine how much important this filtering method had been over the years.

Today Kalman Filters are being widely used in computer graphics and robotics as well as drone tracking. Once you learn how to build it, you will be amazed at its simplicity. Calculations made in the filter are not intensive. This is the beauty of this filter. It is not intensive on computer resources. **Did you read the post on USDJPY trade that made 1000 pips**? Let’s start building our Kalman Filter Trading System. First we need to read the data. We will read GBPUSD M30 data into a numpy array. You should know how to download csv files from MT4. It hardly takes 30 seconds to download data from MT4. Once we download the data csv file we can read it using numpy loadtxt command. Now in the future posts we are going to build a real algorithmic trading system using Dukascopy JForex platform that used java. Java is a powerful language. We can integrate our python and R code into java. Python and R are two powerful machine learning and artificial intelligence languages. Java is a very very powerful system language. Java is at the backbone of your android apps. Don’t worry I will show you how to integrate C++, Python and R with Java. Below is the code for the reading the data.

#import numpy module import numpy as np import matplotlib.pyplot as plt #read the open, high, low and clsoing price from the csv files o, h, l, c=np.loadtxt("E:/MarketData/GBPUSD30.csv", delimiter=',', usecols=(2,3,4,5), unpack=True) #plot the closing prices fig0=plt.figure(0) plt.plot(c) fig0.suptitle('GBPUSD Closing Price', fontsize=20) plt.xlabel('Time', fontsize=18) plt.ylabel('Closing Price', fontsize=16) plt.show() #redraw the data so that we have returns after n period n=20 c1=c[len(c)-110*n:len(c)-1:n,] c1.shape len(c1) #plot the new closing prices fig1=plt.figure(1) plt.plot(c1) fig1.suptitle('GBPUSD Closing Price', fontsize=20) fig1.plt.xlabel('Time', fontsize=18) fig1.plt.ylabel('Closing Price', fontsize=16) plt.show()

We read the GBPUSD M30 data. It comprises of 18000 observations. Take a look at the following chart of the closing price.

After reading the data we rearrange it. We want to predict the price after 10 hours. In the above python code we rearrange the data so that the closing price is 20 bars apart. We choose 50 observations. Kalman Filter is expected to adjust itself in a few observations. The last observations are the important one as it will be used to make the prediction. Below is the plot of the 50 observations that we will use the build the Kalman Filter. After building a Kalman Filter we can use it to improve our Candlestick Trading System.

The aim of our candlestick trading system is to reduce risk as low as possible while maximizing the gain. The problem with candlesticks are they are vague and imprecise. **We need a filter to improve upon our Candlestick Trading System**. We need to know about the trend before we enter into a trade. You can read this post in which I explain in detail **how I made 120 pips with a small 20 pip small stop loss** using my candlestick trading system.

### Random Walk Model Of Price

Random Walk Model is the most popular model for financial time series. It is basically an Autoregressive Model of Order 1. In the random walk model we assume price depends on the previous price plus random noise. So first we build a random walk model. Below is the code for the random walk model.

#import numpy module import numpy as np import matplotlib.pyplot as plt #read the open, high, low and clsoing price from the csv files o, h, l, c=np.loadtxt("E:/MarketData/GBPUSD30.csv", delimiter=',', usecols=(2,3,4,5), unpack=True) #redraw the data so that we have returns after n period n=20 size=50 c1=c[len(c)-size*n:len(c)-1:n,] c1.shape len(c1) #build a random walk model ##build a Kalman Filter for a random walk model from statsmodels.tsa.arima_model import ARMA model1=ARMA(c1, order=(1,0)) resultsmodel1 = model1.fit(disp=-1) resultsmodel1.summary() pred1=resultsmodel1.predict() pred1 ##plot the Autoregressive Model plt.plot(c1, label='Closing Price') plt.plot(pred1, label='AR(1)') plt.legend() plt.title('Random Walk Model', fontweight='bold') plt.xlabel('Time') plt.ylabel('Price') plt.show()

Swing trading is a good strategy. Swing trading is better than day trading. In swing trading, we don’t need to make a lot of trades. We only need a few good swing trades every month to make 1000 pips per month. Many traders fail at swing trading. But those who win win spectacularly. Now we have a model that can predict price after 10 hours. We can change the variable n in the above code and make predictions after whatever time we want. It can be 10 hours, 20 hours, 30 hours, 40 hours. So we are primed for swing trading with this model. Below is the summary for this model as well as the plot of the Autoregressive model.

""" ARMA Model Results ============================================================================== Dep. Variable: y No. Observations: 50 Model: ARMA(1, 0) Log Likelihood 184.293 Method: css-mle S.D. of innovations 0.006 Date: Sun, 12 Feb 2017 AIC -362.585 Time: 16:53:41 BIC -356.849 Sample: 0 HQIC -360.401 ============================================================================== coef std err z P>|z| [95.0% Conf. Int.] ------------------------------------------------------------------------------ const 1.2898 0.036 35.850 0.000 1.219 1.360 ar.L1.y 0.9894 0.014 69.881 0.000 0.962 1.017 Roots ============================================================================= Real Imaginary Modulus Frequency ----------------------------------------------------------------------------- AR.1 1.0107 +0.0000j 1.0107 0.0000 ----------------------------------------------------------------------------- """

Algorithmic trading is the future. If you have been a manual trader, then you should know that algorithmic trading systems have taken over the markets and with the passage of time, it will be difficult for manual traders to compete with these algorithmic trading systems. Did you read this post on **how one 23 years old trader make $700K in 1 year**. As said above, algorithmic trading is becoming more and more popular. You too can become an algorithmic trader. There is no bar now. Algorithmic trading is open source. You just need too master either R or Python and some artificial intelligence and machine learning. **Read this post on how to use random forest algorithmic in your trading**. Random Forest is a robust algorithm that has been used a lot in many fields. Can we use it in algorithmic trading. Read this post and you will discover whether we can use Random Forest in trading or not. **You can also watch this documentary on how high frequency trading is done**. These are the AR(1) model predicted values:

array([ 1.28976929, 1.33268032, 1.32983085, …, 1.27465194,

1.27128798, 1.26470846])

### Kalman Filter For The Random Walk Model

Now we are ready to build the Kalman Filter for the Random Walk Model. First we need to develop the state space equations for the Kalman Filter. From the AR(1) model summary we have the state space equations:

X[k]=0.9894X[k-1]+1.2898+Noise(Gaussian)

From the above equation we have a constant term. This type of model is known as Random Walk Model with Drift. So we have a drift. Drift is an indication of a trend. From the plot of the closing price you can also see visually that there is a downward trend. The other state space equation is:

Price[k]=X[k]+Noise(Gaussian)

So we have successfully build the state space equations before we can build Kalman Filter Model. Below is python code that implements Kalman Filter.

#import numpy module import numpy as np import matplotlib.pyplot as plt #read the open, high, low and clsoing price from the csv files o, h, l, c=np.loadtxt("E:/MarketData/GBPUSD30.csv", delimiter=',', usecols=(2,3,4,5), unpack=True) #redraw the data so that we have returns after n period n=20 size=50 c1=c[len(c)-size*n:len(c)-1:n,] c1.shape len(c1) ##build a Kalman Filter for a random walk model ##initialize the state space arrays xhat=np.zeros(size) xhatminus=np.zeros(size) Noisehatminus=np.zeros(size) Noise=np.zeros(size) KalmanGain=np.zeros(size) R=10 ##initialize the values xhat[0]=0 NoiseHatMinus=1 for k in range(1,size): ##time update or prediction xhatminus[k]=xhat[k-1] Noisehatminus[k]=Noise[k-1] ##measurement update or correction KalmanGain[k]=Noisehatminus[k]/(Noisehatminus[k]+R) xhat[k]=xhatminus[k]+KalmanGain[k]*(c1[k]-xhatminus[k]) Noise[k]=Noisehatminus[k]*(1-KalmanGain[k]) ##plot the Kalman Filter Model plt.plot(c1, label='Closing Price') plt.plot(xhat, label='Kalman Estimate') plt.legend() plt.title('Kalman Filter', fontweight='bold') plt.xlabel('Time') plt.ylabel('Price') plt.show() ##plot the Kalman Filter plt.plot(c1, label='Closing Price') plt.plot(xhatminus, label='Estimate') plt.legend() plt.title('Kalman FIlter', fontweight='bold') plt.xlabel('Time') plt.ylabel('Price') plt.show()

This is the plot of our Kalman Filter.

## 0 Comments