Reader small image

You're reading from  Learning Quantitative Finance with R

Product typeBook
Published inMar 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781786462411
Edition1st Edition
Languages
Right arrow
Authors (2):
Dr. Param Jeet
Dr. Param Jeet
author image
Dr. Param Jeet

Dr. Param Jeet is a Ph.D. in mathematics from one of India's leading technological institute in Madras (IITM), India. Dr. Param Jeet has a couple of mathematical research papers published in various international journals. Dr. Param Jeet has been into the analytics industry for the last few years and has worked with various leading multinational companies as well as consulted few of companies as a data scientist.
Read more about Dr. Param Jeet

PRASHANT VATS
PRASHANT VATS
author image
PRASHANT VATS

Prashant Vats is a masters in mathematics from one of India's leading technological institute, IIT Mumbai. Prashant has been into analytics industry for more than 10 years and has worked with various leading multinational companies as well as consulted few of companies as data scientist across several domain.
Read more about PRASHANT VATS

View More author details
Right arrow

Chapter 5. Algorithmic Trading

Algorithmic trading is defined as the buying and selling of financial instruments using predefined rules called algorithms. Traders use predictive modeling, time series modeling, and machine learning to predict the price, return, or direction of movement of the asset.

Algorithms are developed by quantitative traders or quantitative researchers and tested on historical data. Algorithms go through rigorous testing before they are used for live trading. Technical indicator-based trading can also come under algorithm trading if it is fully automated. However, sometimes quantitative traders also use fundamental data such as market capitalization, cash flow, debt to equity ratio, and so on to define rules for algorithms. People are free to use any technique to define rules for algorithms. Very recently, investment or trading firms have started to dive deep into machine learning methods to predict price, return, or direction movement.

I will be covering machine learning...

Momentum or directional trading


Momentum trading is trading when the instrument is trending up or down or, in other words, continuation in the trend as like historical winners are expected to be winners and historical losers are expected to lose. You bet on the direction of the instrument and you aim for buying at a low price and selling at a high price. I will not cover the pros and cons and what the different types of momentum trading strategies are. It is left to the trader to devise any idea. I will cover how to implement momentum trading rules and backtest using historical data in R. Stock return depends on various factors, and later in this chapter, I will show you how to use the multifactor model which explains stock return.

Let me start with simple technical indicators.

Technical indicators are implemented in the quantmod package so I will be using quantmod for this:

> library('quantmod') 
>getSymbols("^DJI",src="yahoo") 
[1] "DJI" 
> head(DJI) 

We have...

Capital asset pricing model


The capital asset pricing model (CAPM) model helps to gauge risk contributed by security or portfolio to its benchmark and is measured by beta (). Using the CAPM model, we can estimate the expected excess return of an individual security or portfolio which is proportional to its beta:

Here:

  • E(Ri): Expected return of security

  • E(Rm): Expected return of market

  • Ri: Rate of return of security

  • Rf: Risk Free rate of return

  • Rm: Benchmark or market return

  • : Beta of the security

CVX is regressed against DJI using linear model as per equation 5.4.

Here I used zero as risk-free return in the following command:

>rf<- rep(0,length(dji))
>model <- lm((ret_cvx  -rf) ~ (ret_dji -rf) )
> model
Call:
lm(formula = (ret_cvx - rf) ~ (ret_dji - rf))
Coefficients:
(Intercept)  ret_dji
-0.0002013    1.1034521 

You can see the intercept term in the above result is alpha (-0.0002013) and coefficient for ret_dji is beta (1.1034521). However, you can also use the PerformanceAnalytics...

Multi factor model


The multi factor model can be used to decompose returns and calculate risk. The factors are constructed using pricing, fundamental, and analyst estimates data. I will use Systematic Investor Toolbox for this section.

The gzcon() function creates a connection and reads data in compressed format. Once we create a connection, we also have to close the connection.

The following commands explain this:

> con = gzcon(url('http://www.systematicportfolio.com/sit.gz', 'rb'))
>  source(con)
> close(con)

The following function is used to fetch Dow Jones components data from http://money.cnn.com and join() is taken from Systematic Investor Toolbox:

>dow.jones.components<- function(){
url = 'http://money.cnn.com/data/dow30/'
   txt = join(readLines(url))
   temp = gsub(pattern = '">', replacement = '<td>', txt, perl = TRUE)
   temp = gsub(pattern = '</a>', replacement = '</td>', temp, perl = TRUE) 
   temp = extract.table.from.webpage(temp, 'Volume...

Portfolio construction


Investors are interested in reducing risk and maximizing return of their investment and creating a portfolio does this job provided we have constructed it by keeping in mind the investor risk-return profile. I will guide you through creating an efficient frontier that can help you to measure risk with respect to your return expectation. For that, I will start extracting data for four securities. The first line of code creates a new environment to store data; the next few lines are for symbols list, data starting date, and extracting data using getSymbols():

>stockData<- new.env() 
> symbols <- c("MSFT","FB","GOOG","AAPL")
>start_date<- as.Date("2014-01-01")
>getSymbols(symbols, src="yahoo", env=stockData, from=start_date)
> x <- list()

The next for loop stores individual stock data in a list, and calculates the day's gain and a data frame consisting of closing prices of all stocks in portfolio:

>for (i in 1:length(symbols)) {
  x[[i]]...

Questions


  1. How do you import stock data into the R workspace from Yahoo Finance?

  2. How do you generate a momentum strategy using moving average crossover?

  3. Which package helps to calculate the performance metrics of a strategy?

  4. How do you calculate the covariance matrix for a portfolio consisting of five stocks?

  5. Extract MSFT data from Yahoo and test that the closing price series is non-stationary.

  6. Use the distance method to generate trading signals which exit when the spread reverts to mean.

  7. How do you test a pair of stocks for co-integration and write code to test it?

  8. How do you calculate hedge ratio and how does it helps in trading?

  9. How do you calculate portfolio beta? Show it using an example.

  10. How do you use the fundamental factor to create quantiles and quantile spread?

  11. Write code to calculate portfolio expected _return and standard deviation.

  12. How do you calculate the efficient frontier and plot it using the R command?

Summary


In this chapter, I presented different concepts of trading using R. I started with trend following strategy and explained in depth how the trading signals are generated and how various parameters related to its performance are captured. Momentum strategies was followed by pairs trading using three different methods. The first method covered was distance based pairs trading, the second was correlation based, and the third and final method was co-integration based pairs trading. Sometimes, trading in a portfolio is important to control the risk and reward ratio and for that I have covered capital asset pricing, the multi factor model, and portfolio construction. I used Systematic Investor Toolbox for implementing portfolio ideas.

In the next chapter, I will explain trading strategies using machine learning algorithms, which are gaining in popularity. Machine learning algorithms learn automatically from historical market behavior and try to mimic this behavior.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning Quantitative Finance with R
Published in: Mar 2017Publisher: PacktISBN-13: 9781786462411
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Dr. Param Jeet

Dr. Param Jeet is a Ph.D. in mathematics from one of India's leading technological institute in Madras (IITM), India. Dr. Param Jeet has a couple of mathematical research papers published in various international journals. Dr. Param Jeet has been into the analytics industry for the last few years and has worked with various leading multinational companies as well as consulted few of companies as a data scientist.
Read more about Dr. Param Jeet

author image
PRASHANT VATS

Prashant Vats is a masters in mathematics from one of India's leading technological institute, IIT Mumbai. Prashant has been into analytics industry for more than 10 years and has worked with various leading multinational companies as well as consulted few of companies as data scientist across several domain.
Read more about PRASHANT VATS