1. 程式人生 > >R語言 : 讀取csv 檔案, 畫基金淨值線

R語言 : 讀取csv 檔案, 畫基金淨值線

資料檔案 66001.txt 內容格式:

date1,jz0,jz1,jz2,jz3,jz4,jz5

2017-09-01,1.0202,1.6531,2.4647,1.1081,NA,2.9068
2017-09-04,1.0134,1.6621,2.4576,1.1083,NA,2.8983
2017-09-05,1.0168,1.6637,2.4616,1.1085,NA,2.9010

 ... ...

xts 是基於 zoo 的時間序列

xts_funds.R 程式碼:

library(zoo)
setwd("D:/test")
data <- read.csv("66001.txt", header=TRUE, sep=",")
class(data)
head(data)
dates <- as.Date(data$date1, "%Y-%m-%d")
attach(data)
plot(dates,jz0, type="l", lwd=1, main="基金淨值圖", xlab="日期",ylab="淨值",ylim=c(0.5,4.0));
lines(dates,jz1, type="l", lwd=1, col="blue")
lines(dates,jz2, type="l", lwd=1, col="green")
lines(dates,jz3, type="l", lwd=1, col="yellow")
lines(dates,jz4, type="l", lwd=1, col="red")
lines(dates,jz5, type="l", lwd=1, col="purple")
grid()
detach(data)
jjdm <- c("660010","660011","660012","660013","660014","660015")
color <- c("black","blue","green","yellow","red","purple")
legend("topleft", jjdm, pch=c(0,0,0,0,0,0), col=color, cex=0.6); # 圖例

參考書: [ R in Action 第2版 ] 第3章 圖形初階 : 3.5 圖形的組合

xts_fund6.R 程式碼:

library(xts)
setwd("D:/test")
data <- read.csv("66001.txt", header=TRUE, sep=",")
class(data)
dates <- as.Date(data$date1, "%Y-%m-%d")
attach(data)
opar <- par(no.readonly=TRUE)
par(mfrow= c(2,3), oma= c(0,0, 3,0)) # 2行3列
plot(dates, jz0, type="l", lwd=1,  main="660010", xlab="date", ylab="value", col="black")
text(x=200, y=200, labels="fund net value")
grid()
plot(dates, jz1, type="l", lwd=1,  main="660011", xlab="date", ylab="value", col="blue")
grid()
plot(dates, jz2, type="l", lwd=1,  main="660012", xlab="date", ylab="value", col="green")
grid()
plot(dates, jz3, type="l", lwd=1,  main="660013", xlab="date", ylab="value", col="yellow")
grid()
plot(dates, jz4, type="l", lwd=1,  main="660014", xlab="date", ylab="value", col="red")
grid()
plot(dates, jz5, type="l", lwd=1,  main="660015", xlab="date", ylab="value", col="purple")
grid()
mtext("6個基金淨值圖", side=3, line=0, outer=T) # 總的標題
par(opar)
detach(data)