Stock Index Estimation with Hidden Markov Model

Author Xinyi Wu Email xinyiwu2019@u.northwestern.edu EECS349 Machine Learning Northwestern University

This project is maintained by XinyiLeo

Headder Xinyi Wu

Email: xinyiwu2019@u.northwestern.edu

Course: [EECS349] Machine Learning

College: Northwestern University

Introduction

I finally finish one of my dream this year to play with some codes in stock indexes estimation. In January to Martch I made some literature research for a wide-used hidden markov - stochastic volatility models, see Literature Research. Later in Machine learning course, I used software like Weka to give some baseline predictions and finally understood and revised some codes in HMM stock prediction. This is my first ML project in finance. Regard it as prototype, because it is far from mature to put in to reality algo trading.

Background

I myself firmly believe that algorithms is the core backbone of trading strategy, despite that human operations like legal policies and government regulation can push the stock up and down some time. The essence and charisma of machine learning algorithms will apparently stand out in high frequency trading (HFT). HFT aims to do quantitative trading by designing algorithm to buy or sell a product in a very transient time period that mostly cannot be realized by human beings. The profit of a buy/sell is very little, but we do millions of trading within a day. So the profit summed up is observable.

I used python3 to implemet codes and visualize data. I revised some codes in HMM. Those codes are for education purpose, but I revised them in my financial projects. My revised codes are here My codes.

The process of my work is similiar to this flow chart. First, I analysed some significant feaures in stock estimation. For example, log return and moving averages. Second, I used some popular regression methods to make simple estimations and serve the results as baseline method. It’s noted that the baseline method performs similarly except the basic Gaussian Method. Last I followed the tutorial of GaussianHMM package to simulate the Baum-Welch training, and calculate the hidden layes of the stock indexes. I simplified the validation process. Instead of using MAP(Maximum a posteriori estimation), I simply compared the result of HMM with those baseline results from Weka.

Flow chart

Visualization for historical data

Those are visualization of three close values: Apple Inc. (NASDAQ:AAPL), Microsoft (NASDAQ:MSFT) and Google (NASDAQ:GOOG), from 2016 January to 2018 June. Apple Close Value

I extracted data from Morningstar Investment management company, because it has high compatibility with pandas in python. The current inputs are extracted from historical financial time series data, which includes:

  1. Daily Open: the price of the stock at the beginning of the trading day (it need not be the closing price of the previous trading day).
  2. Daily High: the highest price of the stock on that trading day.
  3. Daily Low: the lowest price of the stock on that trading day, and close the price of the stock at closing time.
  4. Adjusted close: the closing price of the stock that adjusts the price of the stock for corporate actions.

A good way to visualize all data is by Candlestick Chart. In this chart. If the daily open value is lower than the close value, the bar is black (reported a gain). If the daily close value is higher than the open value, the bar is red (reported a loss). The wicks on the top and lower part of the bar means the high value and low value of a day.
Candle Stick

In finance, we concerned about the relative change of an asset rather than its absolute price. That’s because when we trade, we concern more about the volatility of a stock price.

Return

Log return is a much more useful plot. We can now see how profitable each stock was since the beginning of the period. Furthermore, we see that these stocks are highly correlated; they generally move in the same direction, a fact that was difficult to see in the other charts.

Log Return

Another possible feature for stock estimation is Moving Average,

Moving averages smooth a series and helps identify trends, and help identify trends from “noise”.

MA

Here, the 200-day moving average shows that the stock is trending downward over ina general view. Also the crossing of moving average lines indicate changes in trend, which can be used as trading signals, or indications that a financial security is changing direction and a profitable trade might be made.

MA for all

Weka Baseline Estimation

First I installed package Time Series Forecasting. The Regression Techniques I used:

Data Collection: Used python to generate two csv files: Weka automaticlaly generate statistics (take Google (NASDAQ: GOOG) close value from 2016 Jan. 1st, to 2018 May 25th as an example):

GOOGstatbar GOOGstat

I used those methods above to forecast the result of GOOG stock index 10 days after:

  1. Simple Gaussian Process Predictor (not fit) Gaussian

  2. Linear Regression (Intuitive Method)

LR LR

  1. Multilayer Perception

LR LR

  1. SMOreg

LR

  1. HoltWinters (I don’t what that is, but fancy enough to try):

LR LR LR

Except Gaussian method, all the other perform tolerable results.

Hmmlearn Package

For those who have problem installing hmmlearn, I provide the wheel executable here HMMwheel. It does not appears on official website and it takes a while to find this.

The reason of using HMM is that based on observations, we predict that the hidden states are some Gaussian Distrbutions with different parameters. We don’t know the exact number of hidden states, so I assume 4 states (simplified model).

Model Description

My code for this part is here: HMM

where A is the transition matrix, B is the matrix of observation, where

Baum-Welch

Baum-Welch is mased on Estimation-Maximum Procesure. First use EM to estimate the model, then collect expected number of trasitions from a state_i, and make statistics of expected number of transitions from S_i to S_j.

The M step is estimating the posterior of transition matrix, new observations and probability matrixes. I haven’t give real predictions for Hidden Markov Model, but based on the baseline method, the HMM looks well. I posted a graph that use similiar methods with me:

Baum-Welch

Ref: Gupta, Aditya, and Bhuwan Dhingra. “Stock market prediction using hidden markov models.” Engineering and Systems (SCES), 2012 Students Conference on. IEEE, 2012.

Improvement

Can probabily implement HMM on my own in the future(Implment Forward algorithm, backward algorithm, GetGamma, GetXi, Viterbi).

Besides HMM, other famous machine learning methods includes Artificial Neural Netowrks(ANN), Fuzzy Logic(FL), and Support Vector Machines(SVM). Can learn them in the future.