Skip to content

Commit ccab516

Browse files
committed
analysis of stock market through Google Finance
1 parent 6e8e77f commit ccab516

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

ideas/stockmarket/GoogleFinance.R

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#
2+
# ANALYSIS of STOCK TIME SERIES
3+
#
4+
5+
# LIBRARIES and SETTINGS
6+
library(lattice)
7+
8+
# FUNCTIONS
9+
stockAnalysis <- function(symbol, from) {
10+
11+
# set locale to make Date readable
12+
lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C")
13+
14+
# gather data
15+
url <- paste0("https://www.google.com/finance/historical?q=",
16+
symbol, "&startdate=", from, "&output=csv")
17+
idata <- read.csv(url, stringsAsFactors = FALSE)
18+
names(idata)[1] <- "Date"
19+
20+
# organize data
21+
idata$Date <- as.Date(idata$Date,'%d-%B-%y')
22+
idata$Year <- as.factor(format(idata$Date, "%Y"))
23+
idata$Day <- as.Date(format(idata$Date, "%d-%m"), "%d-%m")
24+
25+
# select data
26+
pdata <- idata[idata$Date >= "1990-01-01" &
27+
idata$Date < "2016-01-01",]
28+
29+
# base plot data
30+
# plot(pdata$Date, pdata$Close, type = "l")
31+
32+
# lattice plot data
33+
plot <-
34+
xyplot(Close ~ Day | Year, data = pdata, main = symbol,
35+
panel = function(x, y, ...) {
36+
c <- lm(y ~ x)$coefficient[2]
37+
if(c > 0) { panel.fill(col = "lightgreen") }
38+
if(c <= 0) { panel.fill(col = "coral") }
39+
## First call default panel function
40+
panel.xyplot(x, y, ...)
41+
## Overlay a simple linear regression line
42+
panel.lmline(x, y, col = 2, lwd = 2)
43+
})
44+
45+
# reset locale
46+
Sys.setlocale("LC_TIME", lct)
47+
48+
# output
49+
plot
50+
}
51+
52+
# MAIN
53+
## DJIA ETF
54+
symbol <- 'NYSEARCA:DIA'
55+
from <- '1990-01-01'
56+
png(file = "DJIA.png")
57+
stockAnalysis(symbol, from)
58+
dev.off()
59+
60+
## S&P 500 ETF
61+
symbol <- 'NYSEARCA:SPY'
62+
from <- '1990-01-01'
63+
png(file = "SP500.png")
64+
stockAnalysis(symbol, from)
65+
dev.off()
66+
67+
## EURO STOXX 50 ETF
68+
symbol <- 'NYSEARCA:FEZ'
69+
from <- '1990-01-01'
70+
png(file = "ES50.png")
71+
stockAnalysis(symbol, from)
72+
dev.off()
73+
74+
## GOLD ETF
75+
symbol <- 'NYSEARCA:GLD'
76+
from <- '1990-01-01'
77+
png(file = "Gold.png")
78+
stockAnalysis(symbol, from)
79+
dev.off()

0 commit comments

Comments
 (0)