(1)數據網址獲取
網易財經和新浪財經等網站的數據可以免費獲取,我們可以使用爬蟲方法(通過rvest包)抓取相應網站的表格數據,我們首先以在網易財經中抓取600550在2019年第3季度的數據為例,其網址為:
http://quotes.money.163.com/trade/lsjysj_600550.html?year=2019&season=3,
可以看到不同時間段的網址是有規律的,只需要更改其中的股票代碼和year、season就可以進行多個股票的循環網頁抓取。
(2)網絡表格數據節點獲取
我們需要解析網頁表格數據的節點,除了系統性地掌握網頁設計原理和基本結構,還可以通過FireFox(Firebug插件)、Chrome瀏覽器來對網頁結構進行解析得到相應的分支結構點,這里我們使用Firefox瀏覽器,具體操作為在找到我們需要的表格位置后(關於如何找到表格位置請自行探索),右鍵點擊復制XPath路徑。
表格部分的XPath為/html/body/div[2]/div[4]/table[1]。
(3)抓取單個股票的單個頁面數據
library(rvest) symbol=600550 year=2019 season=3 url=paste0("http://quotes.money.163.com/trade/lsjysj_",symbol,".html?year=",year,"&season=",season) web=read_html(url) xpath="/html/body/div[2]/div[4]/table[1]" web.table=web%>%html_nodes(xpath=xpath)%>%html_table()
此時的web.table就是爬取到的數據
(4)抓取單個股票的多個頁面數據並合並
library(lubridate) symbol=600550 from="2001-05-28" from=as.Date(from) to=Sys.Date() time.index=seq(from=from,to=to,by="quarter")#生成以季度為開始的時間序列 year.id=year(time.index)#獲取年份 quarter.id=quarter(time.index)#獲取季度 price=list() for(t in 1:length(time.index)){ year=year.id[t] season=quarter.id[t] url=paste0("http://quotes.money.163.com/trade/lsjysj_",symbol,".html?year=",year,"&season=",season) web=read_html(url) xpath="/html/body/div[2]/div[4]/table[1]" web.table=web%>%html_nodes(xpath=xpath)%>%html_table() web.table=web.table[[1]][-1,] price[[t]]=web.table }
(5)抓取多個股票的多個頁面數據並合並
get.wangyi.stock=function(symbol,from,to){ from=as.Date(from) to=as.Date(to) if(mday(from==1)){ from=from-1 } time.index=seq(from=from,to=to,by="quarter") year.id=year(time.index) quarter.id=quarter(time.index) prices=list() for(t in 1:length(time.index)){ year=year.id[t] season=quarter.id[t] url=paste0("http://quotes.money.163.com/trade/lsjysj_",symbol,".html?year=",year,"&season=",season) web=read_html(url) xpath="/html/body/div[2]/div[4]/table[1]" web.table=web%>%html_nodes(xpath=xpath)%>%html_table() web.table=web.table[[1]][-1,] prices[[t]]=web.table } } to=Sys.Date() stock.index=matrix(nrow=6,ncol=2) stock.index[,1]=c("600550.ss","600192.ss","600152.ss","600644.ss","600885.ss","600151.ss") stock.index[,2]=c("2017-05-28","2017-05-28","2017-05-28","2017-05-28","2017-05-28","2017-05-28") for(i in nrow(stock.index)){ symbol=stock.index[i,1] from=stock.index[i,2] prices=get.wangyi.stock(symbol,from,to) filenames=paste0("D://dataset//",symbol,".csv") }
(6)讀取所有A股數據
我們還可以將所有的A股代碼整理為一個文件,讀取后即可以實現對所有A股股票數據進行實時更新,可以通過這種方法來建立自己的數據庫進行實時分析。同時通過網絡爬蟲,我們還可以爬取很多有意義的數據,並進行實時更新。