#redo analysis with some interactivity
#original post is here
#https://timelyportfolio.blogspot.com/2011/11/after-reading-fine-article-style.html




#use Ken French momentum style indexes for style analysis
#https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/6_Portfolios_ME_Prior_12_2.zip

require(PerformanceAnalytics)
require(FactorAnalytics)
require(quantmod)

my.url="https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/6_Portfolios_ME_Prior_12_2.zip"
my.tempfile<-paste(tempdir(),"\frenchmomentum.zip",sep="")
my.usefile<-paste(tempdir(),"\6_Portfolios_ME_Prior_12_2.txt",sep="")
download.file(my.url, my.tempfile, method="auto", 
quiet = FALSE, mode = "wb",cacheOK = TRUE)
unzip(my.tempfile,exdir=tempdir(),junkpath=TRUE)
#read space delimited text file extracted from zip
french_momentum <- read.table(file=my.usefile,
header = TRUE, sep = "",
as.is = TRUE,
skip = 12, nrows=1038)
colnames(french_momentum) <- c(paste("Small",
colnames(french_momentum)[1:3],sep="."),
paste("Large",colnames(french_momentum)[1:3],sep="."))

#get dates ready for xts index
datestoformat <- rownames(french_momentum)
datestoformat <- paste(substr(datestoformat,1,4),
substr(datestoformat,5,7),"01",sep="-")

#get xts for analysis
french_momentum_xts <- as.xts(french_momentum[,1:6],
order.by=as.Date(datestoformat))

french_momentum_xts <- french_momentum_xts/100

#get price series from monthly returns
french_price<-as.xts(
apply(1+coredata(french_momentum_xts[,1:6]),MARGIN=2,cumprod),
index(french_momentum_xts))
#check data for reasonability
plot.zoo(french_price,log="y")

#for this example lets use Bill Millers fund
getSymbols("LMVTX",from="1896-01-01", to=Sys.Date(), adjust=TRUE)
LMVTX <- to.monthly(LMVTX)
index(LMVTX) <- as.Date(format(as.Date(index(LMVTX)),"%Y-%m-01"))
LMVTX.roc <- ROC(LMVTX[,4],type="discrete",n=1)

perfComp <- na.omit(merge(LMVTX.roc,french_momentum_xts))


fit.time <- fitTimeSeriesFactorModel(
assets.names=colnames(perfComp[,1]),
factors.names=colnames(perfComp[,-1]),
data=perfComp,
fit.method="DLS"
)

betasRolling <- rollapply(perfComp, width = 36, by.column=FALSE, by=1, FUN = function(x){
fit.time <- fitTimeSeriesFactorModel(
assets.names=colnames(x[,1]),
factors.names=colnames(x[,-1]),
data=x,
fit.method="OLS"
)
return(fit.time$beta)
})
colnames(betasRolling) <- colnames(perfComp)[-1]

require(reshape2)
betasRolling.melt <- melt(data.frame(index(betasRolling),betasRolling),id.vars=1)
colnames(betasRolling.melt) <- c("date", "factor", "beta")

nBeta <- nPlot(
beta ~ date,
group = "factor",
data = na.omit(betasRolling.melt),
type = "lineChart"
)
#nBeta$chart(stacked = TRUE)
nBeta$xAxis(tickFormat = 
"#!function(d) {return d3.time.format('%Y-%m-%d')(new Date(d * 24 * 60 * 60 * 1000));}!#"
)
nBeta