Thank you very much Paul. I shall incorporate the changes based on your
suggestion.

 

Regards

Ravi

 

 

From: Paul Teetor [mailto:paulteetor@yahoo.com] 
Sent: Thursday, February 03, 2011 7:25 PM
To: Ravi S. Shankar; r-sig-finance@r-project.org
Subject: Re: [R-SIG-Finance] Help in generalizing code

 

Ravi,

First, install the "xts" and "zoo" packages, and use xts objects to
represent your time series data. The function called read.zoo() can read
your OHLC data, creating a zoo object; convert that to xts by using the
as.xts() function.

Second, use the "apply.monthly" and "first" functions of xts;
specifically, use apply.monthly to apply the "first" function to each
month of data, extracting the first day of data. Something like this:

   apply.monthly(dat, first)

You should be able to replace your entire code block (below) with a few
calls to xts and zoo functions.

As for extracting the last observation of the month, try apply.monthly
function with "last" function, instead. For the 15th of the month,
define a function that extracts the 15th row of a time series:

   fifteenth <- function(ts) ts[15,]

Then apply that to every month by using apply.monthly:

   apply.monthly(dat, fifteenth)

HTH,

Paul

 

Paul Teetor, Elgin, IL USA
http://quanttrader.info/public

 

 

________________________________

From: Ravi S. Shankar <ravis@ambaresearch.com>
To: r-sig-finance@r-project.org
Sent: Thu, February 3, 2011 4:34:37 AM
Subject: [R-SIG-Finance] Help in generalizing code

Hi R,



I have a code below that looks at the first trading day of every month.
Any help towards improving this is welcome. However my question is how
do I generalize to look at every trading day of the every month like the
last or 15th  trading day of every month?



dat=read.csv("z:/ S&P-OHLC.csv")

dat[,1]=as.Date(dat[,1],"%m/%d/%Y")

dat=dat[,-(3:4)]

names(dat)[1]="Date"

yy=unique(format(dat[,1],"%Y"))



for(i in 1:
length(yy))dat[which(format(dat[,1],"%Y")==yy[i]),4]=months(dat[which(fo
rmat(dat[,1],"%Y")==yy[i]),1])

for(i in 1: (nrow(dat)-1))dat[i,5]=ifelse(dat[i,4]==dat[i+1,4],1,0)

new_dat=dat[(which(dat[,5]==0)+1),]



Thanks in advance for the help.

Ravi



This e-mail may contain confidential and/or privileged
i...{{dropped:13}}

_______________________________________________
R-SIG-Finance@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-sig-finance
-- Subscriber-posting only. If you want to post, subscribe first.
-- Also note that this is not the r-help list where general R questions
should go.

This e-mail may contain confidential and/or privileged i...{{dropped:13}}

