Skip to content

Instantly share code, notes, and snippets.

@krishnanraman
Created December 5, 2012 00:01
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save krishnanraman/4210467 to your computer and use it in GitHub Desktop.
Save krishnanraman/4210467 to your computer and use it in GitHub Desktop.
Portfolio Mgmt using Scalding
import com.twitter.scalding._
import cern.colt.matrix.{DoubleFactory2D, DoubleFactory1D }
import cern.colt.matrix.linalg.Algebra
import java.util.StringTokenizer
class Portfolios(args : Args) extends Job(args) {
val cash = 1000.0 // money at hand
val error = 1 // its ok if we cannot invest the last dollar
val (kr,abt,dltr,mnst) = (27.0,64.0,41.0,52.0) // share prices
val stocks = IndexedSeq( kr,abt,dltr,mnst)
weightedSum( stocks, cash,error).write( Tsv("invest.txt"))
// define the correlation matrix
val data = Array(Array(0.448, 0.177, 0.0, 0.017), Array(0.177, 0.393, 0.177, 0.237), Array(0.0, 0.177, 0.237, 0.06), Array(0.017, 0.237, 0.06, 0.19))
val corr = DoubleFactory2D.dense.make(data)
val alg = Algebra.DEFAULT
// read the file into memory
val file = scala.io.Source.fromFile("invest.txt").getLines.toList
// convert the tab-delimited weights in the file to a row vector
def getWeights(s:String) = {
val weights = s.split("\t").map( x=> x.toDouble)
DoubleFactory1D.dense.make(weights)
}
// compute risks per tuple and sort by risk
file.map(line=> {
val w = getWeights(line)
( line, alg.mult( alg.mult(corr,w), w))
}).sortBy(x=>x._2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment