R语言 股价分析
首先判斷股價的分布是不是正態分布:
#獲取3m公司收盤價
mmmdata = read.csv("E:\\kuaipan\\A Introduction to Analysis of Financial Data with R\\chapter 1\\ch1data\\d-mmm-0111.txt",header = T)
mmmprice = as.numeric(sapply(mmmdata, function(l){substring(l,15)}))#繪制頻度直方圖
hist(mmmprice, nclass = 35)#繪制密度圖,并和同方差同均值的正態分布做比較
mmmprice.density=density(mmmprice)
x=seq(-.1,.1,.001) # Create a sequence of x with increment 0.001.
y1=dnorm(x,mean(mmmprice),sd(mmmprice))
plot(mmmprice.density$x,mmmprice.density$y,xlab='rtn',ylab='density',type='l')
lines(x, y1, lty=2)
legend(0.06,32,c('price','Norm'),lty = c(1,2))#使用流行的qq圖來與正態分布做比較
qqnorm(mmmprice)
qqline(mmmprice)#ohlc analysis
#ohlc means open highest lowest and close price
library(quantmod)
getSymbols("AAPL",from="2015-01-03",to="2015-09-30")
chartSeries(AAPL)#the left protuberance means open price, the right one means close price
barChart(AAPL,theme='white.mono',bar.type='ohlc')#最近n個price的均值的變化趨勢——移動平均曲線
"ma" <- function(pri,n,plot=TRUE){# pri: price series of an asset (univariate)# n: window size#nob=length(pri)ma1=prirange=max(pri)-min(pri)if(nob > n){psum=sum(pri[1:(n-1)])ma1[1:n]=psum/(n-1)for (i in n:nob){psum=psum+pri[i]ma1[i]=psum/npsum=psum-pri[i-n+1]}}if(plot){par(mfcol=c(1,1))plot(pri,type='l',xlab="time index")lines(ma1,lty=2)loc=max(pri)-range/3legend(n/2,loc,c(paste("n = ",c(n))),lty=2)title(main='Moving average plot')}ma <- list(ma=ma1)
}
ma(as.numeric(AAPL$AAPL.Close)) 下面這段代碼可以用來對二元正態假設進行判斷, 代碼中對IBM 和 SP 的股價收益率進行了分析
分析手段1: 協方差矩陣
分析手段2: 用rmnorm函數生成了2元正態分布的變量, 對比了兩個plot, 來得出ibm和sp的股價收益率不符合二元正態假設!
da = read.table("E:\\kuaipan\\A Introduction to Analysis of Financial Data with R\\chapter 1\\ch1data\\m-ibmsp-2611.txt", header = T)
ibm=log(da$ibm+1) # Transform to log returns
sp=log(da$sp+1)
tdx=c(1:nrow(da))/12+1926 # Create time index
par(mfcol=c(2,1))
plot(tdx,ibm,xlab='year',ylab='lrtn',type='l')
title(main='(a) IBM returns')
plot(tdx,sp,xlab='year',ylab='lrtn',type='l') # X-axis first.
title(main='(b) SP index')
cor(ibm,sp) # Obtain sample correlation
m1=lm(ibm~sp) # Fit the Market Model (linear model)
summary(m1)
plot(sp,ibm,cex=0.8) # Obtain scatter plot
ablines(0.008,.807) # Add the linear regression lineda = read.table("E:\\kuaipan\\A Introduction to Analysis of Financial Data with R\\chapter 1\\ch1data\\m-ibmsp-2611.txt", header = T)
ibm = log(da$ibm + 1)
sp = log(da$sp + 1)
rt=cbind(ibm, sp)
m1=apply(rt,2,mean)
v1= cov(rt) #協方差, 判斷兩個維度的相關度
library(mnormt)
x=rmnorm(1029,mean=m1,varcov=v1)#隨機二元正態分布生成
plot(x[,2],x[,1],xlab='sim-sp',ylab='sim-ibm',cex=.8)轉載于:https://www.cnblogs.com/rav009/p/5131071.html
總結
- 上一篇: 做鼻息肉手术要多少钱
- 下一篇: 雷凌汽车多少钱?