Advertisement
Guest User

HKEX

a guest
Oct 29th, 2012
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 2.14 KB | None | 0 0
  1.  
  2. new.env()
  3. library(XML)
  4. library(quantmod)
  5.  
  6. Sys.setenv(TZ="Asia/Hong Kong")
  7.  
  8. #******************************************************************************
  9. # hkex function to get all Hongkong StockExchange Mainboard listed companies  
  10. # usage : mc=hkex()
  11.  
  12. hkex <-function(){
  13.   rawCODE <- readHTMLTable('http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdeqty_pf.htm')
  14.   n.rows <- unlist(lapply(rawCODE, function(t) dim(t)[1]))
  15.   mcr=rawCODE[[which.min(n.rows-1)]]
  16.   # now remove colname line of table
  17.   mcr <- mcr[-c(1), ]
  18.   # change the colnames to what we actually want
  19.   colnames(mcr)=c('SYMBOL','NAME','LOT','R1','R2','R3','R4')
  20.   # this should be the actual stockcode count
  21.   maxrows=n.rows[which.min(n.rows-1)]-1  
  22.   rownames(mcr)=1:maxrows
  23.   # show head/tails of what we got
  24.   mc=tail(mcr,maxrows) # mc is where everything resides now
  25.   # for quantmod we need to massage the Symbols into form xxxx.HK
  26.   # first add the.HK
  27.   mc[,1]=paste(mc[,1],'.HK',sep="")
  28.   #now remove the first 0
  29.   mc[,1]=substring(mc[,1], 2, 9)
  30.   # see the magic
  31.   print(head(mc))
  32.   print(tail(mc))
  33.   # just to see if we actually fetched something
  34.   if (mc[,1][1] == "0001.HK"){  
  35.     print(paste('STOCKS in LIST : ',maxrows))
  36.     } else print("An Error occured stocks not fetched correctly")
  37.  
  38.   # All stocks listed in HKEX mainboard are in vector mc
  39.   return(mc)
  40. }
  41. #*******************************************************************************
  42. #testing hkex
  43.  
  44. mc=hkex()
  45. maxrows=NROW(mc)
  46. show(mc)
  47. writeLines(paste("Currently Listed Stocks on Hongkong Stock Exchange MainBoard :",maxrows))
  48.  
  49. # Create 5 random portfolios with 5 stocks each and display the latest quotes
  50.  
  51. runs=5
  52. for (k in 1:runs){
  53.   s=sample(maxrows,runs,replace=FALSE,prob=runif(maxrows)) # this generates random stockcodes
  54.   codes=mc[,1][s]
  55.   pfnames=as.character(mc[,2][s])
  56.   writeLines(paste("\n================ PORTFOLIO : ",k,"==================="))
  57.   show(paste(codes,pfnames))
  58.   writeLines(paste("\n================ Quotes ==========================="))
  59.   show(getQuote(codes))
  60.  
  61. }
  62.  
  63. #*******************************END*********************************************
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement