.chapter26<-function(i=0){ " i Chapter 26: Two dozen R packages for finance - ------------------------------------- 1 Please read chapter 31:Intro to R package 2 One example: quantmod 3 Getting the annual balance-sheets 4 Getting historical data 5 Method I: finding out finance related packages 6 Getting manual (pdf file) related to fImport 7 Several data sets (fImport) 8 Obs from amexListing, nyseListing, oandaListing 9 Introduction to pdfetch 10 A list of functions for fOptions 11 .getDailyPriceBatchGetSymbols function 12 A list of R packages related to finance 13 What is a task view? 14 How to find the location of various task views? 15 A list of task views 16 Links for the task view for finance 17 3 line to install task views called Finance 18 A list of R packages for the task view of Finance 19 Error message 20 Links Example #1:>.c26 # see the above list Example #2:>.c26() # the same as the above Example #3:>.c26(1) # see the first explanation ";.zchapter26(i)} .n26chapter<-20 .zchapter26<-function(i){ if(i==0){ print(.c26) }else{ .printEachQ(26,i,.n26chapter) } } .c26<-.chapter26 .C26EXPLAIN1<-"Please read chapter 31:Intro to R package //////////////////////////////// R packages are written by a group of people or individual who usually have expertise around a specific area to serve a specific purpose. Just type .c31 to view the contents /////////////////////////////// " .C26EXPLAIN2<-"One example:quantmod //////////////////////////////// > library(quantmod) Loading required package: xts Loading required package: zoo Attaching package: 'zoo' The following object is masked from 'package:timeSeries': time<- The following objects are masked from package:base : as.Date, as.Date.numeric Loading required package: TTR Version 0.4-0 included new data defaults. See ?getSymbols. Learn from a quantmod author: https://www.datacamp.com/courses/importing-and-managing-financial-data-in-r /////////////////////////////// " .C26EXPLAIN3<-"Get annual balance-sheets //////////////////////////////// > x<-.getBSannual('ibm') > head(x) Period Ending 12/31/2017 12/31/2016 12/31/2015 12/31/2014 1 Current Assets - - - - 2 Cash And Cash Equivalents 11,972,000 7,826,000 7,686,000 8,476,000 3 Short Term Investments 608,000 701,000 508,000 - 4 Net Receivables 9,909,000 10,239,000 9,534,000 11,996,000 5 Inventory 1,583,000 1,553,000 1,551,000 2,103,000 6 Other Current Assets 184,000 532,000 293,000 746,000 > tail(x) Period Ending 12/31/2017 12/31/2016 12/31/2015 12/31/2014 32 Retained Earnings 153,126,000 152,759,000 146,124,000 137,793,000 33 Treasury Stock -190,098,000 -188,448,000 -185,124,000 -178,591,000 34 Capital Surplus - - - - 35 Other Stockholder Equity -26,591,000 -29,398,000 -29,606,000 -27,876,000 36 Total Stockholder Equity 17,594,000 18,246,000 14,262,000 11,868,000 37 Net Tangible Assets -22,936,000 -22,641,000 -21,246,000 -21,792,000 /////////////////////////////// " .C26EXPLAIN4<-"Getting historical price data //////////////////////////////// intall.packages(\"BatchGetSymbols\") ibrary(BatchGetSymbols) first.date <- Sys.Date() - 60 last.date <- Sys.Date() freq.data <- 'daily' tickers <- c('C','WMT') x<- BatchGetSymbols(tickers = tickers,first.date = first.date, last.date = last.date,freq.data = freq.data, cache.folder = file.path(tempdir(),'BGS_Cache') ) /////////////////////////////// " .C26EXPLAIN5<-"Method I: finding out finance packages //////////////////////////////// Step 1: to go r-project.org Step 2; click \"CRAN\" Step 3: choose a mirror server Step 4: Click \"R packages\" Step 5: choose one list, see a few lines below Step 6: Ctrl-f and use keyword search /////////////////////////////// " .C26EXPLAIN6<-"get pdf related to fImport //////////////////////////////// Step 1: go to http://r-project.org Step 2: click \"CRAN\" Step 3: choose a mirror server Step 4: choose \"R packages\" Step 5: choose one list Step 6: using keywords \"fImport\" Step 7: choose the pdf file /////////////////////////////// " .C26EXPLAIN7<-"Data sets for R package fImport //////////////////////////////// Name Description ------------- --------- amexListing 1,553 stocks listed on the AMEX nyseListing 3,387 stocks listed on the NYSE oandaListing 191 data items from OANDA stoxxListing 2,328 stocks for European stocks swxListing 2,085 stocks /////////////////////////////// " .C26EXPLAIN8<-"A few obs fro amexListing //////////////////////////////// > library(fImport) > data(amexListing) > dim(amexListing) [1] 1553 4 > head(amexListing) Symbol Name MarketCap Exchange 1 AA-P Alcoa Inc. $43.6 AMEX 2 AAC Ableauctions.Com Inc $4.3 AMEX 3 AAU Almaden Minerals, Ltd. $89.4 AMEX 4 ABL American Biltrite Inc. $19.1 AMEX 5 ABP Abraxas Petroleum Corporation $219.0 AMEX 6 ACU Acme United Corporation. $46.9 AMEX /////////////////////////////// " .C26EXPLAIN9<-"Introduction to pdfetch //////////////////////////////// Functions Description --------- -------------------------------- pdfetch_BLS Fetch data from US Bureau of Labor Statistics pdfetch_BOE Fetch data from the Bank of England Statistical Interactive Database pdfetch_ECB Fetch data from European Central Bank's Statistical Data Warehouse pdfetch_EIA Fetch data from the US Energy Information Administration pdfetch_EUROSTAT Fetch data from Eurostat pdfetch_EUROSTAT_DSD Fetch description for a Eurostat data set pdfetch_FRED Fetch data from St Louis Fed's FRED database pdfetch_INSEE Fetch data from the French National Institute of Statistics and Economic Studies (INSEE) pdfetch_ONS Fetch data from the UK Office for National Statistics pdfetch_WB Fetch data from the World Bank pdfetch_YAHOO Fetch data from Yahoo Finance Example: > library(pdfetch) > x<-pdfetch_BLS(c(\"EIUIR\",\"EIUIR100\"), 2005, 2014) > head(x) EIUIR EIUIR100 2005-01-31 104.6 141.2 2005-02-28 105.5 148.4 2005-03-31 107.8 168.3 2005-04-30 108.8 174.4 2005-05-31 107.9 166.7 2005-06-30 109.2 181.5 > dim(x) [1] 120 2 /////////////////////////////// " .C26EXPLAIN10<-"functions for the package fOptions //////////////////////////////// Function Description -------- --------------------- GBSOption Black-Scholes-Merton option model for European options BSAmericanApproxOption Bjerksund and Stensland approximation for an American option CRRBinomialTreeOption CRR Binomial Tree Option, JRBinomialTreeOption JR Binomial Tree Option TIANBinomialTreeOption TIAN Binomial Tree Option BinomialTreeOption Binomial Tree Option BinomialTreePlot Binomial Tree Plot HNGOption Heston-Nandi GARCH(1,1) option price HNGGreeks Heston-Nandi GARCH(1,1) option sensitivities HNGCharacteristics option prices and sensitivities MonteCarloOption Monte Carlo Simulator for options. BlackScholesOption a synonyme for the GBSOption Black76Option options on Futures MiltersenSchwartzOption options on commodity futures NDF, CND, CBND distribution functions, unif.sobol Sobol sequence BAWAmericanApproxOption Barone-Adesi and Whaley Approximation BSAmericanApproxOption Bjerksund and Stensland Approximation RollGeskeWhaleyOption Roll, Geske and Whaley Approximation * BAWAmericanApproxOption Barone-Adesi and Whaley Approximation BSAmericanApproxOption Bjerksund and Stensland Approximation. /////////////////////////////// " .C26EXPLAIN11<-".getDailyPriceBatchGetSymbols //////////////////////////////// .getDailyPriceBatchGetSymbols<-function(ticker,nDays=60){ library(BatchGetSymbols) first.date <- Sys.Date() -nDays last.date <- Sys.Date() freq.data <- 'daily' tickers <-ticker x<- BatchGetSymbols(tickers = tickers,first.date = first.date, last.date = last.date,freq.data = freq.data, cache.folder = file.path(tempdir(),'BGS_Cache') ) y<-as.matrix(x[2][1]) z<-data.frame(y[1][[1]]) z2<-data.frame(z$ticker,z$ref.date,z$price.open, z$price.high,z$price.low,z$price.close,z$volume, z$price.adjusted,z$ret.adjusted.prices,z$ret.closing.prices) names<-colnames(z2) names2<-gsub('z.','',names) # colnames(z2)<-topper(names2) colnames(z2)<-names2 return(z2) } /////////////////////////////// " .C26EXPLAIN12<-" //////////////////////////////// Table 16.1 A list of packages discussed briefly in this Chapter --------------------------------- Package Description ------ ------------------------------ CreditMetrics Credit migration, credit VaR fAsianOptions Path dependent Asian options fAssets Related to assets selection and modeling fBasics Markets and Basic Statistics fBonds Two functions: Nelson-Siegel,and Svensson (Nelson-Siegel-Svensson) Term Structure fExoticOptions Exotic options fImport Retrieve financial data fOptions Basic options, such as Black-Scholes-Merton model MASS Functions/datasets to support Modern Applied Statistics with S metafolio Portfolio construction pdfetch Retrieve public data PerformanceAnalystics Econometric tools for performance and risk analysis quantmod Quantitative finance modeling framework RQuantLib Quantitative finance, options, fixed income and calendar functions stockPorftolio Portfolio Termstruc Term structure of interest rate timeDate Calendar functions: timeDate(), dayOfWeek(), dayOfYear() timeSeries Time series tseries Time series (for computational finance) TTR Technical Trading Rule ttrTest Backtest for technical Trading Rules XML Read and analyses various web pages YieldCurve Yield curve construction Zoo Regular and irregular time series /////////////////////////////// " .C26EXPLAIN13<-"What is a task view? //////////////////////////////// CRAN Task Views ------------------- CRAN task views aim to provide some guidance which packages on CRAN are relevant for tasks related to a certain topic. They give a brief overview of the included packages and can be automatically installed using the ctv package. The views are intended to have a sharp focus so that it is sufficiently clear which packages should be included (or excluded) - and they are not meant to endorse the \"best\" packages for a given task. /////////////////////////////// " .C26EXPLAIN15<-"A list of task veiws? //////////////////////////////// Topics Description ---------- --------------------- Bayesian Bayesian Inference ChemPhys Chemometrics and Computational Physics ClinicalTrials Clinical Trial Design, Monitoring, and Analysis Cluster Cluster Analysis & Finite Mixture Models Databases Databases with R DifferentialEquations Differential Equations Distributions Probability Distributions Econometrics Econometrics Environmetrics Analysis of Ecological and Environmental Data ExperimentalDesign Design of Experiments (DoE) & Analysis of Experimental Data ExtremeValue Extreme Value Analysis Finance Empirical Finance FunctionalData Functional Data Analysis Genetics Statistical Genetics Graphics Graphic Displays & Dynamic Graphics & Graphic Devices & Visualization HighPerformanceComputing High-Performance and Parallel Computing with R MachineLearning Machine Learning & Statistical Learning MedicalImaging Medical Image Analysis MetaAnalysis Meta-Analysis MissingData Missing Data ModelDeployment Model Deployment with R Multivariate Multivariate Statistics NaturalLanguageProcessing Natural Language Processing NumericalMathematics Numerical Mathematics OfficialStatistics Official Statistics & Survey Methodology Optimization Optimization and Mathematical Programming Pharmacokinetics Analysis of Pharmacokinetic Data Phylogenetics Phylogenetics, Especially Comparative Methods Psychometrics Psychometric Models and Methods ReproducibleResearch Reproducible Research Robust Robust Statistical Methods SocialSciences Statistics for the Social Sciences Spatial Analysis of Spatial Data SpatioTemporal Handling and Analyzing Spatio-Temporal Data Survival Survival Analysis TimeSeries Time Series Analysis WebTechnologies Web Technologies and Services gR gRaphical Models in R /////////////////////////////// " .C26EXPLAIN16<-"View for Finance (empirical finance) //////////////////////////////// Link #1: https://cran.r-project.org/web/views/Finance.html or link #2: http://canisius.edu/~yany/webs/taskViewFinance.html /////////////////////////////// " .C26EXPLAIN17<-"3 line to install task views called Finance //////////////////////////////// install.packages(\"ctv\") library(ctv) install.views(\"Finance\") /////////////////////////////// " .C26EXPLAIN18<-"A list of R packages installed //////////////////////////////// Issue the following three lines install.packages(\"ctv\") library(ctv) install.views(\"Finance\") we can install 302 R packages related to finance, see the installed R packages. http://canisius.edu/~yany/doc/listTaskViewFinance.txt /////////////////////////////// " .C26EXPLAIN19<-"Error messages //////////////////////////////// Since Yahoo!Finance and Google finance have changed their data structures, many functions would not work properly > library(quantmod) > x<-viewFin(getFin(\"ibm\",auto.assign=FALSE),\"BS\",\"A\") Error: 'getFinancials.google' is defunct. Google Finance stopped providing data in March, 2018. You could try some of the data sources via Quandl instead. See help(\"Defunct\") and help(\"quantmod-defunct\") /////////////////////////////// " .C26EXPLAIN20<-"Links //////////////////////////////// Dancho,Matt, Introduction to tidyquant https://cran.r-project.org/web/packages/tidyquant/vignettes/TQ00-introduction-to-tidyquant.html Task view for finance https://cran.r-project.org/web/views/Finance.html http://canisius.edu/~yany/doc/viewFinance.html (11/13/2017) Perlin,Marcelo, Using BatchGetSymbols to download financial data for several tickers https://cran.r-project.org/web/packages/BatchGetSymbols/vignettes/BatchGetSymbols-vignette.html https://amzn.to/2I5FFnE /////////////////////////////// " " not working Download data for S&P500 library(BatchGetSymbols) first.date <- Sys.Date()-365 last.date <- Sys.Date() df.SP500 <- GetSP500Stocks() tickers <- df.SP500$tickers x <- BatchGetSymbols(tickers = tickers, first.date = first.date,last.date = last.date) print(x.out$df.control) print(x.out$df.tickers) Package ;Description fImport ;Retrieve financial data pdfetch ;Retrieve public data quantmod ;Quantitative finance modeling framework CreditMetrics ;Credit migration, credit VaR metafolio ;Portfolio construction stockPorftolio ;Portfolio PerformanceAnalystics ;Econometric tools for performance and risk analysis Termstruc ;Term structure of interest rate YieldCurve ;Yield curve construction fBonds ;Two functions: Nelson-Siegel,and Svensson (Nelson-Siegel-Svensson) Term Structure tseries ;Time series (for computational finance) fOptions ;Basic options, such as Black-Scholes-Merton model fAsianOptions ;Path dependent Asian options fExoticOptions ;Exotic options timeDate ;Calendar functions: timeDate(), dayOfWeek(), dayOfYear() timeSeries ;Time series fBasics ;Markets and Basic Statistics fAssets ;Related to assets selection and modeling MASS ;Functions/datasets to support 'Modern Applied Statistics with S' RQuantLib ;Quantitative finance, options, fixed income and calendar functions TTR ;Technical Trading Rule ttrTest ;Backtest for technical Trading Rules XML ;Read and analyses various web pages Zoo ;Regular and irregular time series x<-read.table('clipboard',header=T,sep=';') y<-x[order(x[,1]),] write.table(y,'clipboard',row.names=F,quote=F) "