Pages

Saturday, September 2, 2017

R code to do Basic Stock Analysis

library(quantmod)
require(quantmod)

#! to disable warnings
options("getSymbols.yahoo.warning"=FALSE)

#! add list of stocks which you want to review
stocklist <- c("SBIN.NS","ITC.NS","MARUTI.NS")
j=1
RTable= array(c(stocklist,1:10),c(length(stocklist),2))

#! get the data for all the stocks and perform the basic calculations
for (i in stocklist)
{
test<-as.data.frame(getSymbols(Symbols = i,from ='2015-01-01',to = Sys.Date(), env = NULL))
ptest <- test[,6]
RTable[j,2] = as.numeric(ptest[length(ptest)] / ptest[1])
j = j+1
}

#! plot the output
print (RTable)
barplot(type.convert(RTable[,2]),names.arg = RTable[,1])


Sunday, August 27, 2017

Process Command Line Arguments in R


We can further extend the use of R by passing command line arguments to functions the way we do in multiple programming languages.

You will have to create a script in R which uses the arguments to process the data, we will use below script for example-

library(quantmod)
require(quantmod)



#! To Enable Command Line Arguments
args <- commandArgs(TRUE)


#! Using the Argument Value & Processing Data
symbolsHUL<-c(args[1])
getSymbols(symbolsHUL)
startT <- "2016-01-01"
endT <- "2017-01-01"
rangeT <- paste(startT,"::",endT,sep="")



#! We are still using Static Data here which will be fixed in next post
HUL <- HINDUNILVR.NS[,6][rangeT]
plot(HUL) 


  • Save the above script as Stock.R in working directory
  • Run the below command from Command line
Rscript Stock.R HINDUNILVR.NS

There should be HUL plot saved in working directory in the form of PDF.

Saturday, May 6, 2017

Markets on 6th May 2017 - Asset Bubble??


To Reflect my thoughts on stock market today based on few chapters that i read from Intelligent Investor and some other literature. Stock market is at all time high BSE ~30,000 NSE ~ 9300, Is there any chance for this to continue any longer?

Yes, for few more percentage points and then a downfall is imminent and below are the omens-

  1. PE nearing about 22-23 which is almost at the same level as we had in 2007-08. As per Benjamin Graham (BG), at this level of market a conservative investor should reduce the weight-age of equity in the portfolio if there are good fixed income options available. What he meant to say is that downfall is going to happen soon so secure your portfolio.
  2. Fed has started increasing the rates, The asset bubble created since 2008 crisis by keeping the interest rates low and QE, is going to end soon as people will have higher rates (EMIs) to pay. Default will rise & we may witness another 2008 which will spread to the global economy.
  3.  The increase in Fed rate is also going to increase the capital cost for companies which will in-turn hit their bottom line. Increased rate will also make dollar stronger which is the world reserve currency, making it difficult for companies to repay the dollar denominated loans and also hit on their hedging costs (TATA motors recently had incurred huge hedging losses).
Looks like the stock market ups/down are mostly dictated by the Fed Rates, Alan Greenspan has been blamed all along for 2007-08.

If increasing the interest rates is going to cause so much problem then why can't fed keep its interest rate zero all the time?

Because with Zero interest rates, Time value of money will be lost and everybody goes insane on spending and longer this insanity continue, dangerous it is for economy. Below is how it will hurt overall economy -

  • There is no incentive for investors to save money which will lead to increase in artificial demand of goods hence inflation (To contain inflation is main task of Central Banks as Inflation will eat into Buying power of consumer/currency)
  • Bank deposits/Bonds are no more interesting, people will start chasing risky assets and may end up loosing money there or supporting economical nonviable models.
  • Banks have no way of getting deposits or giving loans as there won't be much profit. Overall Banking (deposit/lending business) will start loosing money.
  • Also the built up of unnecessary capacity during low interest regime will take the most hit during the high interest scenario so the near Zero Interest should not continue for long time.
  • Low Interest rates is not a viable business model - see Japan example
https://www.https://www.nytimes.com/2016/09/21/business/international/japan-boj-negative-interest-rates.html?_r=0nytimes.com/2016/09/21/business/international/japan-boj-negative-interest-rates.html?_r=0 



Sunday, January 22, 2017

Plot Stock Graph using quantmod & functions in R


In next few blogs, we will use quantmod and explore its uses for indian markets, test some strategies and try to build some new one.

One of the basic tool in any programming language is functions and same is the case with R Language, we will use this concept to create function which can help us to plot graphs easily.

Save the below code in text editor with name - example.R

PlotGraph <- function(StockSymbol) {

  # Ensure that you have quantmod installed
require("quantmod")

  # Choose date from Where you want to Plot Graph
startT <- "2016-01-01"

  # Retrieve data
NSExts <- getSymbols(StockSymbol, from=startT, auto.assign=FALSE)

chartSeries(NSExts,name = StockSymbol)
}


Run the function using below code, You can open this in RStudio by double clicking the text file.

source('example.R')

Print the graph by passing name of the stock as argument and below is the result


PlotGraph("SBIN.NS") 

Saturday, January 14, 2017

Pair Trading using Quantmod - HUL & ITC


In my earlier post, I have explained that very first step for stat Arb Strategies is to find out the relation between two stocks. To analyze the whole data and run the relations could be very time consuming if done using downloading data and running calculations separately.

In this blog we will discuss Quantmod which is a package in R language and can help us to get it done easily. It helps to download the data from Yahoo finance and run quick calculations since the data gets downloaded in the form of vectors.

This blog will be using example of Indian Market's stock prices to understand basic use of quantmod.

TO INSTALL PACKAGE

>install.packages("quantmod")
>library(quantmod)
>require(quantmod)

TO RETRIEVE DATA

> symbolsHUL<-c("HINDUNILVR.NS")
> getSymbols(symbolsHUL)
[1] "HINDUNILVR.NS"
> startT <- "2016-01-01"
> endT <- "2017-01-01"
> rangeT <- paste(startT,"::",endT,sep="")
> HUL <- HINDUNILVR.NS[,6][rangeT]
> symbolsITC<-c("ITC.NS")
> getSymbols(symbolsITC)
[1] "ITC.NS"
> HUL <- HINDUNILVR.NS[,6][rangeT]
> ITC <- ITC.NS[,6][rangeT]

ANALYZE DATA & RUNNING REGRESSION

> pdtHUL <- diff(HUL)[-1]
> pdtITC <- diff(ITC)[-1]
> model <- lm(pdtHUL ~ pdtITC -1)
> hr <- as.numeric(model$coefficients)
 [1] 0.1332138

PLOTTING DATA

> plot(ITC)



Saturday, January 7, 2017

Stat Arb India - SBI & YES BANK


Currently going through the book ' The Quants' by Scott Patterson and it has some wonderful strategies used by Quants on the Wall Street and how it almost broke the entire financial system. There are some good strategies if used with caution can help generate some returns.

In this blog we will try to study the relation between SBI & YESBANK to understand if the price anomalies between these stocks can be used to drive some meaningful trades.

Data set is from 1st Jan 2012 till 31st Dec 2012. Co-relation between both the stocks is +0.65 and as you can see from the graph below the relation is positive.


Positive co-relation of 0.65 means that any wide anomolies in the stock returns of both the companies can be exploited by shorting the stock of one and buying the stock of another. Over the time the market will stick to the long term relations.

Make sure you have enough liquidity to stay for time till the market settles to historic relations and also conduct some additional research before getting into these kind of trades since they need huge leverage and can wipe out the entire capital if not executed correctly.

statistical arbitrage india