main_marking1/drumb.scala
author Christian Urban <christian.urban@kcl.ac.uk>
Thu, 06 Jun 2024 22:18:15 +0100
changeset 490 4778fefecd0c
parent 463 0315d9983cd0
permissions -rw-r--r--
updated

// Main Part 1 about a really dumb investment strategy
//===================================================

object M1 {

//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", "HCP") 

import io.Source
import scala.util._

// ADD YOUR CODE BELOW
//======================


// (1) 
def get_january_data(symbol: String, year: Int) : List[String] = {
  Try(Source.fromFile(s"${symbol}.csv").getLines.toList.filter(_.startsWith(year.toString))).getOrElse(Nil)
}
// (2) 
def get_first_price(symbol: String, year: Int) : Option[Double] = {
  val list = get_january_data(symbol, year)
  if (list == Nil) None else {
    Some(list.head.split(",").toList(1).toDouble)
  }
}


// (3) 
def get_prices(portfolio: List[String], years: Range) : List[List[Option[Double]]] = {
  for (n <- years.toList) yield{
    for (m <- portfolio) yield{
      get_first_price(m, n)
    }
  }
}



// (4) 
def get_delta(price_old: Option[Double], price_new: Option[Double]) : Option[Double] = {
  if (price_old != None && price_new != None) Some((price_new.get - price_old.get) / price_old.get) else None
}



// (5) 
def get_deltas(data: List[List[Option[Double]]]) :  List[List[Option[Double]]] = {
  for (n <- data.tail) yield{
    for (m <- n) yield{
      get_delta(data(data.tail.indexOf(n))(n.indexOf(m)),m)
    }
  }
}

// (6) 
def yearly_yield(data: List[List[Option[Double]]], balance: Long, index: Int) : Long = {
  if(data.length == 0) balance else{
    val equal = balance / data(index).flatten.length
    val list = for(n <- data(index).flatten) yield n * equal
    (balance + list.sum).toLong
  }
}

// (7) 
def compound_yield(data: List[List[Option[Double]]], balance: Long, index: Int) : Long = {
  val deltas = get_deltas(data)
  if (deltas.length == 0) balance else{
      if(deltas.length - 1 == index) yearly_yield(deltas, balance, index) else compound_yield(data, yearly_yield(deltas, balance, index), index + 1)
  }
}

def investment(portfolio: List[String], years: Range, start_balance: Long) : Long = {
  val list = get_prices(portfolio, years)
  compound_yield(list, start_balance, 0)
}




//Test cases for the two portfolios given above

//println("Real data: " + investment(rstate_portfolio, 1978 to 2019, 100))
//println("Blue data: " + investment(blchip_portfolio, 1978 to 2019, 100))


}




// This template code is subject to copyright 
// by King's College London, 2022. Do not 
// make the template code public in any shape 
// or form, and do not exchange it with other 
// students under any circumstance.