diff -r 9b5165b8a762 -r 0587ef444547 progs/drumb_sol.scala --- a/progs/drumb_sol.scala Sat Mar 11 23:12:49 2023 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,88 +0,0 @@ -// Advanvced Part 3 about a really dumb investment strategy -//========================================================== - -object CW6c { - - -//two test portfolios - -val blchip_portfolio = List("GOOG", "AAPL", "MSFT", "IBM", "FB", "AMZN", "BIDU") -val rstate_portfolio = List("PLD", "PSA", "AMT", "AIV", "AVB", "BXP", "CCI", - "DLR", "EQIX", "EQR", "ESS", "EXR", "FRT", "GGP", "HCP") - -import io.Source -import scala.util._ - -def get_january_data(symbol: String, year: Int) : List[String] = - Source.fromFile(symbol ++ ".csv")("ISO-8859-1").getLines.toList.filter(_.startsWith(year.toString)) - - -def get_first_price(symbol: String, year: Int) : Option[Double] = { - val data = Try(Some(get_january_data(symbol, year).head)) getOrElse None - data.map(_.split(",").toList(1).toDouble) -} - -get_first_price("GOOG", 1980) -get_first_price("GOOG", 2010) -get_first_price("FB", 2014) - - -def get_prices(portfolio: List[String], years: Range): List[List[Option[Double]]] = - for (year <- years.toList) yield - for (symbol <- portfolio) yield get_first_price(symbol, year) - - -// test case -val p_fb = get_prices(List("FB"), 2012 to 2014) -val p = get_prices(List("GOOG", "AAPL"), 2010 to 2012) - -val tt = get_prices(List("BIDU"), 2004 to 2008) - - -def get_delta(price_old: Option[Double], price_new: Option[Double]) : Option[Double] = { - (price_old, price_new) match { - case (Some(x), Some(y)) => Some((y - x) / x) - case _ => None - } -} - -def get_deltas(data: List[List[Option[Double]]]): List[List[Option[Double]]] = - for (i <- (0 until (data.length - 1)).toList) yield - for (j <- (0 until (data(0).length)).toList) yield get_delta(data(i)(j), data(i + 1)(j)) - - -// test case using the prices calculated above -val d = get_deltas(p) -val ttd = get_deltas(tt) - - -def yearly_yield(data: List[List[Option[Double]]], balance: Long, year: Int): Long = { - val somes = data(year).flatten - val somes_length = somes.length - if (somes_length == 0) balance - else { - val portion: Double = balance.toDouble / somes_length.toDouble - balance + (for (x <- somes) yield (x * portion)).sum.toLong - } -} - -def compound_yield(data: List[List[Option[Double]]], balance: Long, year: Int): Long = { - if (year >= data.length) balance else { - val new_balance = yearly_yield(data, balance, year) - compound_yield(data, new_balance, year + 1) - } -} - -def investment(portfolio: List[String], years: Range, start_balance: Long): Long = { - compound_yield(get_deltas(get_prices(portfolio, years)), start_balance, 0) -} - - - -//test cases for the two portfolios given above - -println("Real data: " + investment(rstate_portfolio, 1978 to 2017, 100)) -println("Blue data: " + investment(blchip_portfolio, 1978 to 2017, 100)) - - -}