2017年12月25日月曜日

calculate NIKKEI225





getSymbols("^GSPC")
getSymbols("NIKKEI225",src="FRED") # download nikkei 225
getSymbols("YJUSDJPY",src="yahooj")
N225 <- NIKKEI225  
k3 <-  "2007-01-01::2017-11-30"
result <- summary(lm(to.monthly(N225[k3])[,4] ~  to.monthly(GSPC[k3])[,4] + to.monthly(YJUSDJPY[k3])[,4]))
result$coefficients[2]*last(GSPC)[,4]+result$coefficients[3]*last(YJUSDJPY)[,4]+result$coefficients[1]
beep(2)

# or

getFX("USD/JPY")
YJUSDJPY <- USDJPY


> k3 <-  "2007-01-01::2017-11-30"
> result <- summary(lm(to.monthly(N225[k3])[,4] ~  to.monthly(GSPC[k3])[,4] + to.monthly(YJUSDJPY[k3])[,4]))
 警告メッセージ:
 to.period(x, "months", indexAt = indexAt, name = name, ...) で:
  missing values removed from data
>
> result

Call:
lm(formula = to.monthly(N225[k3])[, 4] ~ to.monthly(GSPC[k3])[,
    4] + to.monthly(YJUSDJPY[k3])[, 4])

Residuals:
     Min       1Q   Median       3Q      Max
-1997.11  -433.52    25.52   484.71  2025.68

Coefficients:
                                Estimate Std. Error t value Pr(>|t|) 
(Intercept)                   -9833.6019   476.8960  -20.62   <2e-16 ***
to.monthly(GSPC[k3])[, 4]         4.6365     0.1847   25.11   <2e-16 ***
to.monthly(YJUSDJPY[k3])[, 4]   161.7323     5.9325   27.26   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 755.9 on 128 degrees of freedom
Multiple R-squared:  0.9661, Adjusted R-squared:  0.9656
F-statistic:  1826 on 2 and 128 DF,  p-value: < 2.2e-16

> result$coefficients[2]*last(GSPC)[,4]+result$coefficients[3]*last(YJUSDJPY)[,4]+result$coefficients[1]
           GSPC.Close
2017-12-22   20925.53
>

2017年12月22日金曜日

calculate portfolio historical record after 2017-12-15


# omit getsymbols when data are up-to-dated.
getSymbols('FAS',src="yahoo")
getSymbols('SPXL',src="yahoo")

# built time series for FAS share holding.
l <- seq(as.Date("2014-01-01"),Sys.Date(),by="days")
fas_shares <- (as.xts(rep(3472*4,length(l)),l))

# sold 750 shares at 2016-12-19
l2 <- seq(as.Date("2016-12-19"),Sys.Date(),by="days")
s2 <- c(rep(0,length(l)-length(l2)),rep(750,length(l2)))
# build time series record for materialized cash after 2016-12-19
#
# 41.44 was the price at the end of 2016-12-09
c2 <- c(rep(0,length(l)-length(l2)),rep(750*41.44,length(l2)))

# sold 638 shares at 2017-12-04
l3 <- seq(as.Date("2017-12-04"),Sys.Date(),by="days")
s3 <- c(rep(0,length(l)-length(l3)),rep(638,length(l3)))
# record for materialized cash after 2017-12-04
# 69.3 was the price to be soldl at  2017-12-04.
c3 <- c(rep(0,length(l)-length(l3)),rep(638*69.3,length(l3)))
# special capital gain divident for SPXL $1.6. 10% US income tax for Firstrade
#
l4 <- seq(as.Date("2017-12-15"),Sys.Date(),by="days")
c4 <- c(rep(0,length(l)-length(l4)),rep(23412+9326,length(l4)))
# calculate time series for FAS
#
# take changes of ownership by 2016-12-19 and 2017-12-04 trade
#
fas_shares <- fas_shares - s2
fas_shares <- fas_shares - s3

# calculate time series for SPXL
spxl_shares <- as.xts(rep(21000,length(l)),l)

# candleChart(to.weekly(fas_shares * FAS[,4] +spxl_shares * SPXL[,4]),theme='white')

candleChart(to.weekly(fas_shares * FAS[,4] +spxl_shares * SPXL[,4]+as.xts(c2+c3+c4,index(fas_shares))),theme='white')

# store xts data into weekly_pf

weekly_pf <- to.weekly(fas_shares * FAS[,4] +spxl_shares * SPXL[,4]+as.xts(c2+c3+c4,index(fas_shares)))
colnames(weekly_pf)[1] <- 'open'
colnames(weekly_pf)[2] <- 'high'
colnames(weekly_pf)[3] <- 'low'
colnames(weekly_pf)[4] <- 'close'

Add the horizontal line if you like.

# add the horizontal line
> tmp <- as.xts(rep(2200000,length(index(weekly_pf))),index(weekly_pf))
> addTA(tmp,on=1,legend="tmp")
# add slope.
> length(index(weekly_pf))
[1] 243
> addTA(as.xts(approx(seq(1,2,1),c(600000,1100000),n=243,method="linear")$y,index(weekly_pf)),on=1,name='2100000')
# add the vertical line at "2018-01-05"
> length(weekly_pf[,1][paste(index(weekly_pf[1]),index(weekly_pf["2018"][1]),sep="::")])
> index(weekly_pf)[210]
[1] "2018-01-05"
> plot(addLines(v=210))
# calculate sequence # of the first week of each year.
>  for(i in seq(2014,2018,1)){cat(i);cat(" ");cat(length(weekly_pf[,1][paste(head(index(weekly_pf),n=1),head(index(weekly_pf[as.character(i)]),n=1),sep="::")]));cat("\n")}
2014 1
2015 53
2016 106
2017 158
2018 210 
> plot(addLines(v=c(106,158,210)))
> weekly_pf[,4][c(106,158,210)]
               close
2016-01-08  684234.9
2017-01-06 1189421.8
2018-01-05 1991231.4

2017年12月20日水曜日

to update packages in R

It may require to restart R session in order to detach packages which conflict with updates, but fail to start even after restart.

Vist configuration General -> Restore .RData into worksapce at start up to uncheck. You may have to Save workspace to .RData on exit as "Never" in order to avoid new .RData to be re-written.

2017年12月12日火曜日

Automatic save before quit



.Last <- function() {
  # save.image(file=paste(getwd(),Sys.time(),sep="/"))
  save.image(file=gsub(" ","",paste(getwd(),Sys.time(),sep="/")))
  cat("bye bye...\n")
}
quit("yes")

Backup files are created under the current working directory with the time stamp.



save.image(file=paste(getwd(),format(Sys.time(), "%b%d%X"),sep="/"))

or

save.image(file=gsub(" ","",paste(getwd(),Sys.time(),sep="/"))

Will eliminate unnecessary space in the file names.

> gsub(" ","",paste(getwd(),Sys.time(),sep="/")
+ )
[1] "/Users/honomoto/2017-12-1210:08:23"

Below will improve the readability.

> gsub(" ","",paste(getwd(),gsub(" ","-",Sys.time()),sep="/"))
[1] "/Users/honomoto/R_proj/tmp1/2018-08-14-15:00:34"


format(Sys.time(), "%b%d%X")
[1] "121210時03分53秒"
Sys.setlocale("LC_ALL",'C')
[1] "C/C/C/C/C/ja_JP.UTF-8"
format(Sys.time(), "%b%d%X")
[1] "Dec1210:04:28"

2017年12月9日土曜日

S&P500 forecast after 2017 Nov. jobs report.

> my_sp5(kg,m_GDP,m_PA,m_UC)
[1] "m_m params! apply.quarter - UC w/ nominal GDP"
               [,1]
2018-01-01 2553.472
2018-04-01 2606.021
2018-07-01 2660.625
2018-10-01 2717.719
2019-01-01 2777.573
> head(m_PA,n=6)
               [,1]
2018-01-01 147599.0
2018-04-01 148108.1
2018-07-01 148578.3
2018-10-01 149020.6
2019-01-01 149443.0
2019-04-01 149851.1
> last(UC)
           UNDCONTSA
2017-10-01      1096
> head(m_UC,n=6)
               [,1]
2018-01-01 1119.792
2018-04-01 1138.671
2018-07-01 1153.191
2018-10-01 1164.359
2019-01-01 1172.948
2019-04-01 1179.555

S&P500,GDP,PAYEMS,UNDCONTSA



getSymbols("GDP",src="FRED")
getSymbols("PAYEMS",src="FRED")
getSymbols("UNDCONTSA",src="FRED")
PA <- PAYEMS
UC <- UNDCONTSA
kikan <- "1992-01-01::2017-09-30"
SP5 <- as.xts(read.zoo(read.csv("~/SP5.csv")))
G <- GDP
l <- 120  # # of months to predict
i <- seq(2,l/3,1)  # seq of quarters to predict
d <- as.Date(as.yearqtr(seq(Sys.Date(),as.Date("2100-12-31"),by="quarters")[i])) # pick up the first day of each quarters.
r <- 1.05 # pesumed GDP growth ratekk
m_GDP <- as.xts(as.vector(last(GDP)) * r**(i/4),d)
m_PA <- (as.xts(forecast(auto.arima(PA),h=l)$mean[1:l],as.Date(as.yearmon(seq(mondate(index(last(PA)))+1,by=1,length.out=l))))[(3-month(index(last(PA))) %% 3) + seq(1,l-3,3)])[d]
m_UC <- (as.xts(forecast(auto.arima(UC),h=l)$mean[1:l],as.Date(as.yearmon(seq(mondate(index(last(UC)))+1,by=1,length.out=l))))[(3-month(index(last(UC))) %% 3) + seq(1,l-3,3)])[d]
my_sp5(m_GDP,m_PA,m_UC)
kg <- "1992-01-01::2017-09-30"
my_sp5(kg,m_GDP,m_PA,m_UC)

2017年12月5日火曜日

managing portfolio - building portfolio table. - vol2

x <- as.data.frame(tapply(read.csv("~/f4.csv")$quantity,read.csv("~/f4.csv")$ticker,sum))
colnames(x)[1] <- "shares"
z <- as.data.frame(tapply(read.csv("~/f4.csv")$quantity,read.csv("~/f4.csv")$ticker,sum))
colnames(z)[1] <- "shares"
z2 <- transform(z,ticker=rownames(z))
my_pf <- transform(z2,currency=mapply(function(x) read.csv("~/f4.csv")[grep(x,read.csv("~/f4.csv")$ticker),5][1],my_pf$ticker))
mapply(my_getsymbols,my_pf$currency,my_pf$ticker)
my_pf <- transform(my_pf,total=mapply(function(x,y) x*last(get(as.character(y))[,4]),z2$shares,z2$ticker))
tapply(my_pf$total,my_pf$currency,sum)
getFX("USD/JPY")
tapply(my_pf$total,my_pf$currency,sum)["JPY"] + tapply(my_pf$total,my_pf$currency,sum)["USD"] * last(USDJPY)
beep(2)

calculate portfolio historical record after 2017-12-04



# retrieve price data from gogole
getSymbols('FAS',src="google")
getSymbols('SPXL',src="google")

# built time series for FAS share holding.
l <- seq(as.Date("2014-01-01"),Sys.Date(),by="days")
fas_shares <- (as.xts(rep(3472*4,length(l)),l))

# sold 750 shares at 2016-12-19
l2 <- seq(as.Date("2016-12-19"),Sys.Date(),by="days")
s2 <- c(rep(0,length(l)-length(l2)),rep(750,length(l2)))
# build time series record for materialized cash after 2016-12-19
#
# 41.44 was the price at the end of 2016-12-09
c2 <- c(rep(0,length(l)-length(l2)),rep(750*41.44,length(l2)))

# sold 638 shares at 2017-12-04
l3 <- seq(as.Date("2017-12-04"),Sys.Date(),by="days")
s3 <- c(rep(0,length(l)-length(l3)),rep(638,length(l3)))
# record for materialized cash after 2017-12-04
# 69.3 was the price to be soldl at  2017-12-04.
c3 <- c(rep(0,length(l)-length(l3)),rep(638*69.3,length(l3)))
# calculate time series for FAS
#
# take changes of ownership by 2016-12-19 and 2017-12-04 trade
#
fas_shares <- fas_shares - s2
fas_shares <- fas_shares - s3

# calculate time series for SPXL
spxl_shares <- as.xts(rep(21000,length(l)),l)

candleChart(to.weekly(fas_shares * FAS[,4] +spxl_shares * SPXL[,4]),theme='white')

candleChart(to.weekly(fas_shares * FAS[,4] +spxl_shares * SPXL[,4]+as.xts(c2+c3,index(fas_shares))),theme='white')

fas_shares * apply.monthly(FAS,last)[,4]
spxl_shares * apply.monthly(SPXL,last)[,4]

fas_shares * apply.monthly(FAS,last)[,4] +spxl_shares * apply.monthly(SPXL,last)[,4] #monthly historcal price

# weekly closed price chart
plot(fas_shares * apply.weekly(FAS,last)[,4] +spxl_shares * apply.weekly(SPXL,last)[,4])

# store weekly balance
weekly_pf <- fas_shares * apply.weekly(FAS,last)[,4] +spxl_shares * apply.weekly(SPXL,last)[,4]