您的位置:首页 > 其它

第11周书面作业

2013-07-08 20:55 218 查看
要求:

下载Apple、Google、微软三家股票数据,计算它们从2008年到2011年每年的总成交量。然后画一堆叠方式的直方图,横坐标上标注股票名,直方图描述每一年成交量占总成交量的百分比,这个百分比要标注在直方图内部,颜色代表不同的年份(用图例说明) 

解答:

##########准备工作,没装的包要先装好

install.packages("quantmod")
library(quantmod)
install.packages("tseries")
library(tseries)
install.packages("zoo")
library(zoo)

##########读取股票数据

aapl<-get.hist.quote(instrument = "aapl", quote = c("Vol"))
goog <- get.hist.quote(instrument = "goog", quote = c("Vol"))
msft <- get.hist.quote(instrument = "msft", quote = c("Vol"))

##########aapl公司的成交量

dt <- index(aapl)
dt <- as.POSIXlt(dt,format="%Y-%m-%d")

yr <- 2008:2011
aapl_vol <- vector(length=0)
for(i in 1:4){
aapl_vol[i] <- sum(as.numeric(aapl[which(dt$year+1900 == yr[i])]))
}
aapl_vol

##########goog公司的成交量

dt <- index(goog)
dt <- as.POSIXlt(dt,format="%Y-%m-%d")

yr <- 2008:2011
goog_vol <- vector(length=0)
for(i in 1:4){
goog_vol[i] <- sum(as.numeric(goog[which(dt$year+1900 == yr[i])]))
}
goog_vol

##########msft公司的成交量

dt <- index(msft)
dt <- as.POSIXlt(dt,format="%Y-%m-%d")

yr <- 2008:2011
msft_vol <- vector(length=0)
for(i in 1:4){
msft_vol[i] <- sum(as.numeric(msft[which(dt$year+1900 == yr[i])]))
}
msft_vol

##########把3个成交量放到一个数据框中

total <- cbind(aapl_vol, goog_vol, msft_vol)
total <- as.data.frame(total)
total$year <- yr
total

##########转成百分比的形式

for(i in 1:3){
total[,i] <- 100*total[,i]/sum(total[,i])
}
total

##########堆叠的直方图
par(mar=c(5,4,4,8),xpd=T)
x <- barplot(as.matrix(total[,1:3]),
col=brewer.pal(4,"Set1"),
border="white",
ylab="Percent (%)",
main="2008年到2011三大公司的股票成交量")

##########图例

legend("right",
legend=total$year,
bty="n",
inset=c(-0.3,0),
fill=brewer.pal(4,"Set1"))

##########在柱子内标注百分比
for(i in 1:3){
text(x[i], cumsum(total[,i])-10, sprintf("%4.2f%s",total[,i],"%"))
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: