Thursday, December 11, 2014

Out of Nowhere–Explore Text on a Path

I had not really stopped to think of this until I listened to this The Web Ahead podcast with Sara Soueidan.  What is really interesting about the tech world is how experts can seemingly pop up out of nowhere and become the authority on a topic.  In the podcast, this was the case with the interviewee Sara Soueidan.  We can find a similar example in Joni "Bologna" Trythall with SVG.

I find it even more fun when I can incorporate these experts’ content into R.  Let’s animate some text on a path as Joni does in her article "Animating SVG text On A Path", but instead of an arbitrary path, let’s use a line in a plot.

some text on a path

I’ll copy the code below.  Let me know if a tutorial would be helpful.

library(SVGAnnotation)
library(pipeR)
library(htmltools)

# make as basic a line plot as I know how in R
svg = svgPlot(plot(sin(seq(0,pi*3,0.2)),type="l")) %>>%
# extract the XML and use htmlParse
# to overcome namespace confusion and difficulty
saveXML %>>% htmlParse

# with base R plots, we get clues with clip-path attributes
# in this case we know with some inspection
# there will be one g with a clip-path attribute
# and that g will contain our plotted line
getNodeSet(svg,"//g[contains(@clip-path,'url')]//path")[[1]] %>>%
# let's add an id so we can reference this later
( addAttributes( node=., id = "ourline" ) )

# first step in adding text to a path
# make a new text node
textOnPath = newXMLNode("text")
# now the critical part to join the text to the path
addChildren(
textOnPath
, newXMLNode(
"textPath"
,attrs=c( "xlink:href" = "#ourline" ) #our id given above
,"some text on a path" #some very creative saying
)
)

# add our text node to the svg plot
addChildren(
getNodeSet(svg,"//svg")[[1]]
,kids = list(textOnPath)
)
# see if it works by sending to our viewer/browser
getNodeSet(svg,"//svg")[[1]] %>>%
saveXML %>>% HTML %>>% html_print

# let's continue our journey by exploring the startOffset attribute
# startOffset says where on the path to start our text
# what happens if we add startOffset = 30%
getNodeSet(svg, "//textPath")[[1]] %>>%
( addAttributes( node = . , startOffset = "30%" ) )
# find out the effect of startOffset by browsing
getNodeSet(svg,"//svg")[[1]] %>>%
saveXML %>>% HTML %>>% html_print

# for our grand finale we can animate the text
# note: this might not work in your browser, so use Chrome
# add a child animate node with the same attributes as Joni's tutorial
getNodeSet(svg, "//textPath")[[1]] %>>%
(
addChildren(
node = .
, newXMLNode(
"animate"
,attrs = c(
attributeName="startOffset"
,values = "0;0.7;1"
,dur = "8s"
,repeatCount = "indefinite"
,keyTimes = "0;0.2;1"
)
)
)
)
# see the animated text
getNodeSet(svg,"//svg")[[1]] %>>%
saveXML %>>% HTML %>>% html_print(viewer=utils::browseURL)

Thursday, December 4, 2014

No Reason to Read, Just Need an Outlet

Don’t intend for this to be a bitch and moan post, and I’m not sure there is really any real objective other than I feel like I need an outlet.  This happens to be my only one,.

For those out there not engaged in money management, it can be pleasantly simple and maybe even entertaining to poke fun  at those of us who foolishly choose to call ourselves portfolio managers.  However, this business can be excrutiating, depressing, and frustrating.  Generally, our biggest benefit to our clients is insulating themselves from their own stupidity, but often this task becomes impossible, usually at the time when client stupidity results in the most amount of damage to themselves.

While distracting myself with my insatiable curiosity through academic research, technology, and data visualization (just look at the last couple of years of posts) helps, I cannot forget that I get paid to manage money, which generally just ain’t no fun as failing is the norm, and the brief moments of “success” go unnoticed and disappear with no lasting memory or permanent effect. 

Most would naively say go do something else, but I still feel this delusional quest really can help those few clients who trust and endure.

Tuesday, December 2, 2014

Much Better Animated Paths | Christmas SVG

Just after I made my really ugly animated turkey sketch (see post), I saw this much better set of Christmas icons in the Smashing Magazine Article Freebie Christmas Icon Set from Manuela Langella.  While I still remember how to do this, I thought I would use the same techniques in R using rvest + XML + htmltools to animate the paths with vivus.js.  In the iframe below is the result on the Santa icon.

Code: http://gist.github.com/39394d6e37a7fd878cab#file-code-R

Wednesday, November 26, 2014

Happy Thanksgiving | More Examples of XML + rvest with SVG

I did not intend for this little experiment to become a post, but I think the code builds nicely on the XML + rvest combination (also see yesterday’s post) for working with XML/HTML/SVG documents in R.

It all started when I was playing on my iPhone in the Sketchbook app and drew a really bad turkey.  Even though, the turkey was bad, I thought it would be fun to combine with vivus.js.  However, Sketchbook does not export SVG, so I exported as PDF and imported into Inkscape.  The end result was a still very messy SVG file, so I thought it would be a great test / application of my new skills with rvest + XML. The code opens the SVG, grabs all the path nodes, assembles those into a svg tag with id = "turkey", and then adds a script to use the addDependency for vivus.js.

Happy Thanksgiving to all the US readers out there.

Slightly Advanced rvest with Help from htmltools + XML + pipeR

Hadley Wickham’s post “rvest: easy web scraping with R” introduces the fine new package rvest very well.  For those now yearning a slightly more advanced example with a little help from pipeR + htmltools + XML, I thought this might fill your yearn.  The code grabs css information running the fancy new site cssstats.com on my blog site.  With the background colors, it makes and labels some swatches and outputs them to the RStudio viewer--if installed--or your browser if not.

library(pipeR)
library(htmltools)
library(rvest)
library(XML)

# some slightly more advanced exercises
# using rvest, XML, and htmltools

# this one takes all the svg nodes in the section
# with id unique-background-colors from the
# site cssstats.com run on timelyportfolio.blogspot.com
# 1) removes attributes
# 2) sizes them at 85px x 64px
# 3) add new text node with fill value
# 4) combines them into a single div
# 5) with some meta information
"http://cssstats.com/stats?url=http%3A%2F%2Ftimelyportfolio.blogspot.com" %>>%
html %>>%
html_nodes( "#unique-background-colors svg" ) %>>%
xmlApply( function(x){
removeAttributes(x)
addAttributes(x,style="display:inline-block;height:85px;width:64px")
fillNode = newXMLNode(
"text"
,html_attr(html_node(x,"rect"),"fill")
,attrs=c(x=0,y=75,style="font-size:70%")
)
addChildren(x,fillNode)
saveXML(x) %>>% HTML
} ) %>>%
(tags$div(
style="display:inline-block;height:100%;width:100%"
,list(
tags$h3(
"Colors of TimelyPortfolio from "
,tags$a(href="http://cssstats.com","cssstats")
)
,.
)
)) %>>%
tagList %>>%
html_print

I just copied the div output below in Windows Live Writer (notably from JJ Allaire and Joe Cheng of RStudio).



Colors of TimelyPortfolio from cssstats

transparent #fff #ffffff #fcfcfc #eeeeee #fcf8e3 #f2dede #dff0d8 #d9edf7 #f5f5f5 #a9dba9 #f9f9f9 #d0e9c6 #ebcccc #faf2cc #c4e3f3 #e5e5e5 #0081c2 #e6e6e6 #cccccc \9 #006dcc #0044cc #003399 \9 #faa732 #f89406 #c67605 \9 #da4f49 #bd362f #942a25 \9 #5bb75b #51a351 #408140 \9 #49afcd #2f96b4 #24748c \9 #363636 #222222 #080808 \9 #0088cc #999999 #fafafa #ededed #1b1b1b #111111 #515151 #0e0e0e #040404 #000000 \9 #000000 #f7f7f7 #b94a48 #953b39 #c67605 #468847 #356635 #3a87ad #2d6987 #333333 #1a1a1a #0e90d2 #149bdf #dd514c #ee5f5b #5eb95e #62c462 #4bb1cf #5bc0de #fbb450 #ccc rgba(255, 255, 255, 0.25) #2288bb #ffff00

Monday, November 24, 2014

Secret to Making Things Appear in RStudio Viewer

I am by no means an authoritative source on this, but I think I found out the secret behind htmltools html_print that chooses the RStudio Viewer browser rather than your default browser like utils::browseURL. Here is a quick code snippet that hopefully explains what is happening. It appears you just need a temp directory with the pattern starting with viewhtml*.

library(htmltools)
library(pipeR)

# htmltools from RStudio very nicely
# makes things appear in the Viewer Window
"<h3>Hello in RStudio Viewer</h3>" %>>%
HTML %>>%
html_print


# there is a little secret to doing the same
# without htmltools
"<h3>Hello in RStudio Viewer</h3>" %>>%
HTML %>>%
# and the secret is to place in a temp directory
# with the pattern viewhtml
(
ht ~
tempfile("viewhtml") %>>%
(~ dir.create(.) ) %>>%
(~ save_html(ht, file = file.path(.,"index.html")) ) %>>%
( getOption("viewer")(file.path(.,"index.html")) )
)

# to see it in action look at the code change
# in this project
utils::browseURL("https://github.com/bryanhanson/exCon/pull/1/files")
The only reason I mention it is that I much prefer to stay in the RStudio environment instead of switching contexts to a browser.  I still firmly recommend using tags from htmltools as the best method to make all this work seamlessly and as intended by the experts at RStudio. 

Pipeline to Plot Annual % Change

image

(thanks tradeblotter for pointing out error in code in first release)

Pipes in R make my life incredibly easy, and I think my code easier to read.   Note, there are a couple different flavors of pipes (see magrittr and pipeR).  For now, I choose pipeR.

library(quantmod)
library(pipeR)
library(ggplot2)

getSymbols("^GSPC",from="1900-01-01",auto.assign=F) %>>% #get S&P 500 from Yahoo!Finance
( .[endpoints(.,"years"),4] ) %>>% #get end of year
ROC( type="discrete", n=1 ) %>>% #get one year rate of change
na.fill(0) %>>% #fill first year with 0
( #make data.frame
data.frame(
date = as.Date(format(index(.),"%Y-01-01"))
,.
)
) %>>%
structure( #hard way to do colnames()
names = c("date","change")
) %>>%
ggplot( #start our plot pipe
aes( y= change, x= date)
) %>>%
+ geom_bar( stat="identity" ) %>>% #choose bar
+ labs( title = "Annual Change of the S&P 500" ) #give plot a title

Or if we wanted to use the new pipeline syntax for the plot portion.

library(quantmod)
library(pipeR)
library(ggplot2)

getSymbols("^GSPC",from="1900-01-01",auto.assign=F) %>>% #get S&P 500 from Yahoo!Finance
( .[endpoints(.,"years"),4] ) %>>% #get end of year
ROC( type="discrete", n=1 ) %>>% #get one year rate of change
na.fill(0) %>>% #fill first year with 0
( #make data.frame
data.frame(
date = as.Date(format(index(.),"%Y-01-01"))
,.
)
) %>>%
structure( #hard way to do colnames()
names = c("date","change")
) %>>%
(
pipeline({
ggplot(., aes( y= change, x= date) )
+ geom_bar( stat="identity" )
+ labs( title = "Annual Change of the S&P 500 (source: Yahoo! Finance)" )
})
)

Wednesday, November 5, 2014

Update on JGBs versus USTs

Given the recent selloff in the Yen, I thought now would be a good time to update my favorite chart from Intended or Unintended Consequences.

image

For a true currency death spiral, rates need to move up rather than down.  It appears we are long way from that.

Long-time readers will know that I have been keenly interested in the Yen for the entire history of this blog http://timelyportfolio.blogspot.com/search?q=yen.

Code for this post: https://gist.github.com/timelyportfolio/5665790

Wednesday, October 22, 2014

Postive Feedback in R with a Little Javascript

Let’s face it, sometimes the struggle in R can become frustrating, depressing, daunting, or just monotonous.  For those moments when you need a little positive feedback, some encouragement, or a pat on the back, I thought this might help.  Maybe I should make this into a package.

I found this from Sweet Alert for Bootstrap forked from Tristan Edwards non-bootstrap SweetAlert.  This builds on the technique used in my previous post SVG + a little extra (d3.js) in RStudio Browser | No Pipes This Time.

 

positive_feedback_sweetalert_r

# give yourself some positive feedback in R
# as you toil away on some difficult, but worthwhile task
# uses javascript sweet-alert https://github.com/t4t5/sweetalert

library(htmltools)
library(pipeR)

tagList(
tags$script(
'
document.addEventListener("DOMContentLoaded", function(event) {
swal("Good job! Brilliant!", "You\'re doing worthwhile things.", "success")
});
'

)
) %>>%
attachDependencies(
htmlDependency(
name="sweet-alert"
,version="0.2.1"
,src=c("href"=
"http://timelyportfolio.github.io/sweetalert/lib"
)
,script = "sweet-alert.min.js"
,style = "sweet-alert.css"
)
) %>>%
html_print

Friday, October 10, 2014

SVG + Javascript Ekholm Decomposition in RStudio Browser

Our topics this week seem unrelated, but in an effort to bridge the two

another random project – make website in R for these SVGs of Portland Vector Bridges
result: Portland Bridges in SVG
code: R to make simple site

Ekholm decomposition

SelectionShare & TimingShare | Masterfully Written by Delightfully Responsive Author
Popular Mutual Funds Decomposed With Ekholm (2014)

Responsive SVG in the browser

Responsive SVG in Your RStudio Browser
SVG + a little extra (d3.js) in RStudio Browser | No Pipes This Time

let’s build a website in R with htmltools to calculate the Ekholm decomposition in Javascript using this nifty simple-statistics.js from the brilliant Tom Macwright.  The result will not be beautiful and I’ll leave out a fancy interactive chart, but that is intentional to reduce the amount of code and dependencies.

r_ekholm_js

I wonder what I’ll get into next week.

Github Repo

library(htmltools)
library(pipeR)
library(jsonlite)
library(Quandl)
library(xts)

# use Quandl Kenneth French Fama/French factors
# http://www.quandl.com/KFRENCH/FACTORS_D
#f <- Quandl("KFRENCH/FACTORS_D",type = "xts", start_date="2010-12-31") / 100

tagList(
#pull in the bridge to span all the week's topics
#Portland Vector Bridges http://timelyportfolio.github.io/portland_vector_bridges
tags$div( style = "height:15%;width:100%"
,readLines(
"http://timelyportfolio.github.io/portland_vector_bridges/Burnside Bridge.svg"
) %>>% HTML
)
,tags$h1( "Sparsest Test in Javascript of Ekholm")
, tags$div( style = "width:100%"
,tags$div( style = "background-color:red;"
,"Note: Date range currently limited to one year, but there is a fairly easy workaround
for the next version."
)
,tags$div(
style = "display:inline-block; width: 25%;float:left;"
,"Mutual Fund Symbol", tags$input( id = "mfsymbol" )
,tags$br()
,"Start Date "
, tags$span( style="font-size:75%;fill:lightgray", "(2013-08-29)" )
, tags$input( type = "date", id = "stdate" )
,tags$br()
,"End Date"
,tags$span( style="font-size:75%;fill:lightgray", "(2014-08-29)" )
, tags$input( type = "date", id= "enddate" )
,tags$br()
,tags$input(
type="submit", id = "calc", value = "Calculate"
)
,tags$br()
)
, tags$div(style = "display:inline-block;height:100%;width:60%;margin-left:30px"
, tags$textarea(id = "results", style="width:100%; height:150px")
)
)
,tags$script(sprintf(
'

var french = %s;
'
, toJSON(data.frame("Date"=index(f),f)) %>>% HTML
))
,tags$script(
'

function calculateEkholm( data ) { // data in form of x,y or fund-rf, mkt-rf
/* get an error with regression.js
var myReg = regression(
"linear",
data
)
*/

// so use the great simple-statistics library
var myReg = ss.linear_regression().data(data);

//get residuals
var resid = data.map(function(p){return myReg.line()(p[0]) - p[1]});

//regress residuals^2 on (mkt-rf)^2
var myReg2 = ss.linear_regression().data(
data.map(function(d,i){
return [ Math.pow(d[0],2), Math.pow(resid[i],2) ]
})
)
//coefficients ^ 1/2 will give us ActiveAlpha and ActiveBeta
var activeAlpha = Math.pow( myReg2.b(), 0.5 );
var activeBeta = Math.pow( myReg2.m(), 0.5 );

//now do the next step to get ActiveShare and SelectionShare
var selectionShare = Math.pow(activeAlpha, 2 ) / ( ss.variance(data.map(function(d){return d[1]})) * (data.length - 1) / data.length )
var timingShare = Math.pow(activeBeta, 2 ) * ss.mean( data.map(function(d){return Math.pow(d[0],2)}) ) / ( ss.variance(data.map(function(d){return d[1]})) * (data.length - 1) / data.length )

//pass correlation result also
var correlation = ss.sample_correlation(data.map(function(d){return d[0]}),data.map(function(d){return d[1]}));

return {
regression: myReg,
correlation: correlation,
activeAlpha: activeAlpha,
activeBeta: activeBeta,
selectionShare: selectionShare,
timingShare: timingShare
}
}


// thanks https://gist.github.com/fincluster/6145995
function getStock(opts, type, complete) {
var defs = {
desc: false,
baseURL: "http://query.yahooapis.com/v1/public/yql?q=",
query: {
quotes: \'select * from yahoo.finance.quotes where symbol = \"{stock}\" | sort(field=\"{sortBy}\", descending=\"{desc}\")\',
historicaldata: \'select * from yahoo.finance.historicaldata where symbol = \"{stock}\" and startDate = \"{startDate}\" and endDate = \"{endDate}\"\'
},
suffixURL: {
quotes: "&env=store://datatables.org/alltableswithkeys&format=json&callback=?",
historicaldata: "&env=store://datatables.org/alltableswithkeys&format=json"
}
};

opts = opts || {};

if (!opts.stock) {
complete("No stock defined");
return;
}

var query = defs.query[type]
.replace("{stock}", opts.stock)
.replace("{sortBy}", defs.sortBy)
.replace("{desc}", defs.desc)
.replace("{startDate}", opts.startDate)
.replace("{endDate}", opts.endDate)

var url = defs.baseURL + query + (defs.suffixURL[type] || "");

return url;
}


d3.select("#calc").on("click",function(){
calculateFund(
d3.select("#mfsymbol")[0][0].value,
d3.select("#stdate")[0][0].value,
d3.select("#enddate")[0][0].value
)
})

function calculateFund( symbol, startdate, enddate ) {

d3.json(getStock({stock:symbol.toUpperCase(),startDate:startdate,endDate:enddate},"historicaldata"), function(e1,fund){


if( e1 || !fund.query.results ) {
updateResults ( {e1:e1, e2:e2, queryresults: "query problems"} );
} else {
var fund_factor = [];

//manipulate data to join fund with factors
//would be nice to have a xts merge in javascript


// query.results.quote will have the data stripped of meta
// also we will sort date ascending
fund = fund.query.results.quote
.sort(function(a,b){
return d3.ascending(
d3.time.format("%Y-%m-%d").parse(a.Date),
d3.time.format("%Y-%m-%d").parse(b.Date)
)
} );




// now lets go period by period with fund.map
fund.map( function(per, i){
if( i > 0 ) {
var frenchThisPer = french.filter(function(d){return d.Date == per.Date})[0];
fund_factor.push([
//Date: per.Date,
//FundPrice:
per.Adj_Close / fund[ i - 1 ].Adj_Close - 1 - frenchThisPer["RF"],
//Rm_Rf:
+frenchThisPer["Mkt.RF"],
//Rf: +frenchThisPer["RF"]/100
])
}
})

updateResults( calculateEkholm( fund_factor ) );
}

})
}

function updateResults( ekholmCalc ){
var ekhArr = [];
Object.keys(ekholmCalc).map(function(k){
ekhArr.push( [ k,": ", ekholmCalc[k] ].join("") )
})
d3.select("#results").text(ekhArr.join("\\n"))
}
'
%>>% HTML )
) %>>%
attachDependencies(
list(
htmlDependency(
name="d3"
,version="3.4"
,src=c("href"="http://d3js.org/")
,script="d3.v3.min.js"
)
,htmlDependency(
name="simple_statistics"
,version="0.1"
,src=c("href"=
"http://timelyportfolio.github.io/rCharts_factor_analytics/js"
)
,script = "simple_statistics.js"
)
)
) %>>% html_print