Skip to content

Instantly share code, notes, and snippets.

@rrguntaka
Created March 21, 2013 03:00
Show Gist options
  • Save rrguntaka/5210373 to your computer and use it in GitHub Desktop.
Save rrguntaka/5210373 to your computer and use it in GitHub Desktop.
Calculate Mean Return and Variance matrix from the csv files downloaded from Yahoo Finance. Download the historical quotes data and update the tickers variable. Currently this program is just looking at last 200 days (one year). That parameter should be changed if analyzing for a different time horizon
package com.test
import scala.io.Source
object meanVarianceFromYahooData {
val root = "/"
def readData(f: String): List[Double] = {
val iter = Source.fromFile(root + f + "csv").getLines().drop(1).map(_.split(","))
def getClose: List[Double] = (iter map (_.last.toDouble)) toList
def ret(a: Double, b: Double): Double = ((a - b) * 100 / b)
def returnize(list: List[Double]): List[Double] = list match {
case Nil => Nil
case x :: Nil => Nil
case x :: xs => ret(x, xs.head) :: returnize(xs)
}
returnize(getClose take 200)
}
def avg(numbers: List[Double]): Double = numbers.reduceLeft(_ + _) / numbers.length
def stdDev(range: List[Double], domain: List[Double]): Double =
if (range.length >= 2) ((range.map(_ - avg(range)) zip domain.map(_- avg(domain))).map { a => a._1 * a._2 }).reduceLeft(_ + _) / (range.length.toDouble - 1) else 0.0
def varMat(lists: Tuple2[List[Double], List[Double]]) = { stdDev(lists._1, lists._2) }
def main(args: Array[String]) {
val tickers = List("DFCEX","VINIX","VBMFX","DODGX")
val returns = for(tick <- tickers) yield readData(tick)
println("+++ Expected Return Matrix ++++")
println (for (a <- returns) yield avg(a))
println("+++++++ Variance Matrix +++++++")
(for (first <- returns; second <- returns) yield varMat((first, second))).grouped(tickers.length).toList foreach println
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment