вторник, 29 декември 2015 г.

R Script: Yahoo Finance API for CSV

One of our clients has a strategy, based on the consensus estimates of 1-year target prices of US equities. We were hired for backtesting his investment strategy. For the needs of the backtest we needed a script for downloading data from Yahoo. The post of Kelly Elias on Yahoo Finance API for CSV motivated us to write a function for our in-house use. 
We post a simple script that downloads the 1-year target prices of a list of US companies in a csv file in the working directory. Please note, that not all companies in Yahoo Finance have analyst coverage.


########## Start####################
# Create "temp"  directory with "blog" subdirectory in C and set it as wd. 
# If it exists, then set it as a working directory.
mainDir <- "C:\\temp\\blog"

if(dir.exists(file.path(mainDir))==FALSE){
       dir.create(file.path(mainDir)) 
       setwd(mainDir)
} else
       setwd(mainDir)


# Specify the tickers, tags, and labels of the tags
tickers<- c("AAPL","AXP","BA","CAT","CSCO","CVX","DD","DIS","GE","GS","HD","IBM","INTC","JNJ","JPM","KO","MCD","MMM","MRK","MSFT","NKE","PFE","PG","TRV","UNH","UTX","VZ","WMT","XOM")
tags<-c("sd1t8")
label<-c("Symbol","Date","Target")

# Base url       
base<-"http://download.finance.yahoo.com/d/quotes.csv?s="
url<-paste(base,paste(tickers, collapse="+"),"&f=",tags,"&e=.csv",sep="")

# Export data in a csv file in the working  directory
download.file(url, destfile ="targets.csv", method = "libcurl")

# Read the data from csv file in a data frame format
url.data <-read.csv(file="targets.csv",sep=",",header=FALSE,stringsAsFactors=FALSE)
df <- data.frame(matrix(unlist(url.data), nrow=length(tickers), byrow=F),stringsAsFactors=FALSE)

# Name the data frame and convert dates in a Date format
names(df)<-label
df$Date <- as.Date(df$Date, "%m/%d/%Y")

# View the data in a spreadsheet-style
View(df)

######### The End ##############




Yahoo Tags are as follows:

       a       Ask 
       a2 Average Daily Volume
       a5 Ask Size
       b Bid
       b2 Ask (Real-time)
       b3 Bid (Real-time)
       b4 Book Value
       b6 Bid Size
       c Change & Percent Change
       c1 Change
       c3 Commission
       c4 Currency
       c6 Change (Real-time)
       c8 After Hours Change (Real-time)
       d Dividend/Share
       d1 Last Trade Date
       d2 Trade Date
       e Earnings/Share
       e1 Error Indication (returned for symbol changed / invalid)
       e7 EPS Estimate Current Year
       e8 EPS Estimate Next Year
       e9 EPS Estimate Next Quarter
       f0 Trade Links Additional
       f6 Float Shares
       g Day's Low
       g1 Holdings Gain Percent
       g3 Annualized Gain
       g4 Holdings Gain
       g5 Holdings Gain Percent (Real-time)
       g6 Holdings Gain (Real-time)
       h Day's High
       i       More Info
       i5 Order Book (Real-time)
       j 52-week Low
       j1 Market Capitalization
       j2 Shares Outstanding
       j3 Market Cap (Real-time)
       j4 EBITDA
       j5 Change From 52-week Low
       j6 Percent Change From 52-week Low
       k 52-week High
       k1 Last Trade (Real-time) With Time
       k2 Change Percent (Real-time)
       k3 Last Trade Size
       k4 Change From 52-week High
       k5 Percent Change From 52-week High
       l Last Trade (With Time)
       l1 Last Trade (Price Only)
       l2 High Limit
       l3 Low Limit
       m Day's Range
       m2 Day's Range (Real-time)
       m3 50-day Moving Average
       m4 200-day Moving Average
       m5 Change From 200-day Moving Average
       m6 Percent Change From 200-day Moving Average
       m7 Change From 50-day Moving Average
       m8 Percent Change From 50-day Moving Average
       n       Name
       n4 Notes
       o Open
       p Previous Close
       p1 Price Paid
       p2 Change in Percent
       p5 Price/Sales
       p6 Price/Book
       q Ex-Dividend Date
       r P/E Ratio
       r1 Dividend Pay Date
       r2 P/E Ratio (Real-time)
       r5 PEG Ratio
       r6 Price/EPS Estimate Current Year
       r7 Price/EPS Estimate Next Year
       s Symbol
       s1 Shares Owned
       s6 Revenue
       s7 Short Ratio
       t1 Last Trade Time
       t6 Trade Links
       t7 Ticker Trend
       t8 1 yr Target Price
       v Volume
       v1 Holdings Value
       v7 Holdings Value (Real-time)
       w 52-week Range
       w1 Day's Value Change
       w4 Day's Value Change (Real-time)
       x Stock Exchange
       y Dividend Yield

петък, 25 декември 2015 г.

R Function: Jorion’s Bayes-Stein estimators


Recently we have examined the paper of Avramov and Zhou (2009). They review the literature on Bayesian portfolio analysis. One of the methods for mean and covariance estimation, based on Bayesian theory, is the one of Jorion (1986). He argues that portfolios obtained from Bayes-Stein estimates dominate those obtained from historic estimates.
We present a function in R, which estimates Jorion’s Bayes-Stein estimators of mean vector and covariance matrix. The function has one input – the return series of the assets of the portfolio analysis. Moreover, one could use the code of our previous post in order to download price series of a list of assets in his/her portfolio and calculate the return series. Then he/she should put it into the proposed function and will get a list of mean vector and variance-covariance estimates of Jorion.

 jorion.bs<-function(returns){

# Avramov, Doron and Guofu Zhou, Bayesian Portfolio Analysis, 2009, apps.olin.wustl.edu/faculty/zhou/AZ.pdf
#
############## Control of the Input #######################
# number of assets
N<-ncol(returns)
       
# number of observations
T<-length(returns[,1])

#Is the number of observations grater than the number of assets?
if(T<N){
       stop("The number of assets should be less than the number of observations. The sample VCM does not have an inverse.")
}

# Historical sample mean
mu.h<-apply(returns,2,mean)

# Sample Variance-Covariance Matrix (VCM)
vcm<-var(returns)

# Identity vector
i<-rep(1,N)

# Adjusted Sample VCM. Avramov & Zhou (2009) equation 31
V<-T*vcm/(T-N-2)

# Global Minimum Variance return.Avramov & Zhou (2009) equation 32
mu.gmv<-(t(i)%*%solve(V)%*%mu.h)/as.numeric(t(i)%*%solve(V)%*%i)

# nu. Avramov & Zhou (2009) equation 29
nu<-(N+2)/((N+2)+T*as.numeric(t((mu.h-i%*%mu.gmv))%*%solve(V)%*%(mu.h-i%*%mu.gmv)))

# lambda.Avramov & Zhou (2009) equation 30
lambda<-(N+2)/(as.numeric(t((mu.h-i%*%mu.gmv))%*%solve(V)%*%(mu.h-i%*%mu.gmv)))

# Variance - covariance matrix shrinkage estimator. Avramov & Zhou (2009) equation 28
V.j<-(1+1/(T+lambda))*V+(lambda/(T*(T+1+lambda)))*as.numeric((t(i)%*%i)/(t(i)%*%solve(V)%*%(i)))

# Expected returns verctor shrinkage estimator. Avramov & Zhou (2009) equation 27
mu.j<-(1-nu)*mu.h+nu*as.numeric(mu.gmv%*%i)

# Both estimators are presented in a list
jorion.bs<-list("mu.pj"=mu.j,"v.pj"=V.j)
}

References:
Jorion, P., "International Portfolio Diversification with Estimation Error," Journal of Business, 58, 3 (July 1985), pp 259-278.
Jorion, P., "Bayes-Stein Estimation for Portfolio Analysis," Journal of Financial and Quantitative Analysis, 21, 3 (September, 1986), pp 279-292.

вторник, 8 декември 2015 г.

R Script: Get Prices of a List of Companies from Yahoo.

There are numerous codes for getting data from finance yahoo. We share a code, which downloads price data from yahoo for a list of companies, specified in a txt file. The symbols in the  tickers.txt must be presented in a column, as you may see in the picture.



# UPDATE 2015-12-08
# The script imports in a zoo data frame adjusted close prices of a list of companies. 
# Companies tickers are stored in a txt file in the working directory. The list could be
# extended depending on the portfolio under consideration
# finance.yahoo.com is the source of information.
# The user should specify:
# (1) the companies, whose data will be downloaded. The list of tickers is saved as a txt file;
# (2) start date;
# (3) end date;
# (4) frequency (compression) = d for daily, w for weekly, and m for monthly
# (5) quote ("Open", "High", "Low", "Close", "AdjClose", "Volume")
# (6) provider - yahoo for stocks, oanda for fx
# (7) origin - "1970-01-01"
# (8) retclass zoo, 

              #---------------------------------START-----------------------------------

# set working directory. One should make a folder temp first and then to set it as a working directory.
setwd("C:\\temp")

# load packages
suppressPackageStartupMessages(require(tseries))
suppressPackageStartupMessages(require(zoo))

# get the list with tickers from ticker.txt. The txt file is saved in the working directory
      ticker<-read.table("ticker.txt", header=FALSE, stringsAsFactors=FALSE, colClasses="character")

# specify the input parameters. Dates are in a yyyy-mm-dd format
       start.date<-"2007-01-01"
       end.date<-Sys.Date()
              
# add or delete quotes you need in c("Open", "High", "Low", "Close","AdjClose","Volume").
# For example, if one need only adjusted close price data he should delete
# "Open", "High", "Low", "Close","Volume". Thus....
       quotes<-c("AdjClose")

# frequency "d"aily, "w"eekly, or "m"onthly.
       frequency<-c("m")

# get data with the tseries function get.hist.quote. The retclass is set to "zoo".
# create an empty zoo data frame
       price.data <- zoo()

# first specify the date format
       index(price.data) <- as.Date(format(time(price.data)),tz="")

# count the number of the tickers that will be called
       n<-nrow(ticker)
              
# loop through the tickers, get quotes and merge each zoo data frame together in price.data
       for (i in 1:n) {
       tick<-ticker[i,]
       
       ticker.prices<- try(get.hist.quote(instrument=ticker[i,], start=start.date, quote=quotes, provider="yahoo", origin="1970-01-01", compression=frequency, retclass="zoo",quiet=FALSE), silent=FALSE)
          
       colnames(ticker.prices) <- ticker[i,]
       price.data <- try(merge(price.data,ticker.prices))       
       }
# Save the data in a csv file named djia.csv in the specified folder.

       file.folder<-"C:\\temp\\djia.csv"
              
       write.zoo(price.data,file=file.folder ,sep=",",row.names=FALSE)

Introduction

This is the blog of SI Risk Innovations Ltd. The company was established in 2012 as a response to the trends in the last decade of intensive implementation of software solutions for risk assessment in the European banking and non-banking financial institutions. SI Risk SaaS is a home-made cloud solution for risk assessment in UCITS type funds. The SI Risk Engine, which is in the core of SI Risk SaaS, is built in the R Environment.


The main purpose of this blog is to present some useful tricks for financial data analysis in R. Please note that our R codes should not be treated as a guaranteed return on any investment.