graphics.off(); objects(); remove(list=objects()); # MAIN PROGRAM myData <- read.table("xom.dat", header=TRUE); x <- as.matrix(myData); k <- ncol(x); nobs <- nrow(x); print(k); print(nobs); ## extract month mn <- floor( x[,2]/100 ) - floor( x[,2]/10000 )*100; #print( mn ); ## Open file and write header write.table("date ret RV RCOV" ,"rv.txt",sep=" ",row.names=FALSE,col.names = FALSE); ## convert to cont. compounded returns rstock <- log( 1.+x[,4] ); rindex <- log( 1.+x[,5] ); rv=rindex[1]^2; rmonth=rindex[1]; rcov=rindex[1]*rstock[1]; i=2; while( i <= nobs ){ if( mn[i] == mn[i-1] && i != nobs){ rv = rv + rindex[i]^2; rmonth = rmonth + rindex[i]; rcov = rcov + rindex[i]*rstock[i]; }else{ ## end of month -- save results and restart sums write.table(cbind(x[i,2],rmonth,rv,rcov) ,"rv.txt",sep=" ",row.names=FALSE,col.names = FALSE,append=TRUE); rv = rindex[i]^2; rmonth = rindex[i]; rcov=rindex[i]*rstock[i]; } i=i+1; } sink(file = NULL);