R语言--股票数据分析
(本实验是以股票数据作为分析背景,股票数据如何从雅虎财经板块上获取,观察股票每日价格和成交量数据开始,接着计算某一支股票数据中比较重要的日度收益率。然后通过各种股票线图进行技术分析,最后在一支股票的基础上同时分析多支股票的成交量,涨幅时间点,最后得出它们之间的相关性等数据特征。)
#Quantitative Financial Modelling Framework
> library(quantmod)#S3 Infrastructure for Regular and Irregular Time Series
> library(zoo)
#eXtensible Time Series
> library(xts)
#Technical Trading Rules
> library(TTR)
#Time Series Analysis and Computational Finance
> library(tseries)
#Econometric tools for performance and risk analysis
> library(PerformanceAnalytics)
#Procedures for Psychological, Psychometric, and Personality Research
> library(psych)
#Visualization of a Correlation Matrix
> library(corrplot)
#调用quantmod包中 getSymbols 函数获取苹果公司的股票数据
> getSymbols("AAPL",from = "2017-01-01",to = Sys.Date(),src = "yahoo")
> head(AAPL)
#调用tseries包中 get.hist.quote 函数获取谷歌公司的股票数据
> goog<-get.hist.quote(instrument = "GOOG", start="2017-01-01", end="2017-08-08",quote = "AdjClose")
> head(goog)
#绘制股票图:chartSeries(K线图)
> chartSeries(AAPL,up.col='red', dn.col='green',theme="white")
> chartSeries(AAPL,name = "AAPLBARCHART",subset="2017-01-01::2017-08-07",type="bars")
> chartSeries(AAPL,name = "AAPLLINECHART",subset="2017-01-01::2017-08-07",type="line")
> chartSeries(AAPL,name = "AAPLCANDCHART",subset="2017-01-01::2017-07-17",type="candlesticks")
#技术函数:addBBands()求出股价的标准差及信赖区间;addADX()趋势衡量指标;addMACD()指数平滑异同移动平均线;addCCI()测量股价是否超出常态分布范围;addVo()测量成交量……
> chartSeries(AAPL,up.col='red',dn.col='green',theme="white")
> addBBands(n=14,sd=2,draw='bands')
> addADX()
> addMACD()
#收益率:简单收益率
> close <- AAPL[,4]
> close1 <- lag(close,1)
> head(close1)
> calclose <- merge(close,close1)
> simplerate <- (close-close1)/close1
> names(simplerate)="simplerate"
> calrate=merge(calclose,simplerate)
> head(calrate)
#收益率:对数收益率
> rate=periodReturn(close,period="daily",type="log")
> head(rate)
#抓取四家公司的全部股票行情数据并查看抓取的全量数据情况
> new.environment <- new.env()
> getSymbols(c("AAPL", "ORCL", "MSFT", "GOOG"), src = "yahoo", env = new.environment)
> str(get("AAPL", env = new.environment))
> str(get("ORCL", env = new.environment))
> str(get("MSFT", env = new.environment))
> str(get("GOOG", env = new.environment))
#计算出Apple公司股票总成交量使用情况
> summary(AAPL)
> sum(Vo(AAPL))
#查看各公司涨跌幅超过 2% 的情况
> AAPL <- Delt(Cl(get("AAPL", env = new.environment)))
> length(AAPL[which(AAPL > 0.02), ])
> plot(AAPL[which(AAPL > 0.02), ])
#调整数据
> m <- cbind(Ad(get("AAPL", env = new.environment)), Ad(get("ORCL", env = new.environment)), Ad(get("MSFT", env = new.environment)), Ad(get("GOOG", env = new.environment)))
#分析判断相关性并绘图
> corr.test(as.data.frame(m))
> corrplot.mixed(cor(m), lower = "ellipse", upper = "circle")