|      1 // Advanvced Part 3 about a really dumb investment strategy |      1 // Advanced Part 3 about a really dumb investment strategy | 
|      2 //========================================================== |      2 //========================================================== | 
|      3  |      3  | 
|      4 object CW6c { |      4 object CW6c { | 
|      5  |      5  | 
|      6  |      6  | 
|      7 //two test portfolios |      7 //two test portfolios | 
|      8  |      8  | 
|      9 val blchip_portfolio = List("GOOG", "AAPL", "MSFT", "IBM", "FB", "AMZN", "BIDU") |      9 val blchip_portfolio = List("GOOG", "AAPL", "MSFT", "IBM", "FB", "AMZN", "BIDU") | 
|     10 val rstate_portfolio = List("PLD", "PSA", "AMT", "AIV", "AVB", "BXP", "CCI",  |     10 val rstate_portfolio = List("PLD", "PSA", "AMT", "AIV", "AVB", "BXP", "CCI","DLR", "EQIX", "EQR", "ESS", "EXR", "FRT", "GGP", "HCP")  | 
|     11                             "DLR", "EQIX", "EQR", "ESS", "EXR", "FRT", "GGP", "HCP")  |         | 
|     12  |     11  | 
|     13 // (1) The function below should obtain the first trading price |     12 // (1.a) The function below takes a stock symbol and a year as arguments. | 
|     14 // for a stock symbol by using the query |     13 //       It should read the corresponding CSV-file and read the January  | 
|     15 // |     14 //       data from the given year. The data should be collected in a list of | 
|     16 //    http://ichart.yahoo.com/table.csv?s=<<symbol>>&a=0&b=1&c=<<year>>&d=1&e=1&f=<<year>>  |     15 //       strings for each line in the CSV-file. | 
|     17 //  |         | 
|     18 // and extracting the first January Adjusted Close price in a year. |         | 
|     19  |         | 
|     20  |     16  | 
|     21 import io.Source |     17 import io.Source | 
|     22 import scala.util._ |     18 import scala.util._ | 
|     23  |     19  | 
|     24 def get_january_data(symbol: String, year: Int) : List[String] =  |     20 def get_january_data(symbol: String, year: Int) : List[String] = { | 
|     25   Source.fromFile(symbol ++ ".csv")("ISO-8859-1").getLines.toList.filter(_.startsWith(year.toString)) |     21 	val file = symbol + ".csv" | 
|         |     22 	val list = scala.io.Source.fromFile(file).mkString.split("\n").toList | 
|         |     23 	val rx = (year.toString + ".*") | 
|         |     24 	(for(n <- 1 to list.length -1 if(list(n) matches rx)) yield list(n)).toList | 
|         |     25 } | 
|         |     26  | 
|         |     27  | 
|         |     28 // (1.b) From the output of the get_january_data function, the next function  | 
|         |     29 //       should extract the first line (if it exists) and the corresponding | 
|         |     30 //       first trading price in that year as Option[Double]. If no line is  | 
|         |     31 //       generated by get_january_data then the result is None | 
|     26  |     32  | 
|     27  |     33  | 
|     28 def get_first_price(symbol: String, year: Int) : Option[Double] = { |     34 def get_first_price(symbol: String, year: Int) : Option[Double] = { | 
|     29   val data = Try(Some(get_january_data(symbol, year).head)) getOrElse None  |     35 	val first_line = get_january_data(symbol, year) | 
|     30   data.map(_.split(",").toList(1).toDouble) |     36  | 
|         |     37 	if(first_line.length == 0 ){ | 
|         |     38 		None | 
|         |     39 	} else { | 
|         |     40 	Option((first_line(0).split(",")(1)).toDouble) | 
|         |     41 	} | 
|     31 } |     42 } | 
|     32  |     43  | 
|     33 get_first_price("GOOG", 1980) |     44  | 
|     34 get_first_price("GOOG", 2010) |     45 // (1.c) Complete the function below that obtains all first prices | 
|     35 get_first_price("FB", 2014) |     46 //       for the stock symbols from a portfolio (list of strings) and  | 
|         |     47 //       for the given range of years. The inner lists are for the | 
|         |     48 //       stock symbols and the outer list for the years. | 
|     36  |     49  | 
|     37  |     50  | 
|     38 // Complete the function below that obtains all first prices |     51 def get_prices(portfolio: List[String], years: Range) : List[List[Option[Double]]] ={ | 
|     39 // for the stock symbols from a portfolio for the given |     52 	(for(y <- years) yield (for(n <- 0 to portfolio.length-1) yield get_first_price(portfolio(n), y)).toList).toList | 
|     40 // range of years |     53 } | 
|     41  |         | 
|     42 def get_prices(portfolio: List[String], years: Range): List[List[Option[Double]]] =  |         | 
|     43   for (year <- years.toList) yield |         | 
|     44     for (symbol <- portfolio) yield get_first_price(symbol, year) |         | 
|     45  |     54  | 
|     46  |     55  | 
|     47 // test case |         | 
|     48 val p_fb = get_prices(List("FB"), 2012 to 2014) |         | 
|     49 val p = get_prices(List("GOOG", "AAPL"), 2010 to 2012) |         | 
|     50  |     56  | 
|     51 val tt = get_prices(List("BIDU"), 2004 to 2008) |     57 // (2) The first function below calculates the change factor (dta) between | 
|     52  |     58 //     a price in year n and a price in year n + 1. The second function calculates | 
|     53 // (2) The first function below calculates the change factor (delta) between |     59 //     all change factors for all prices (from a portfolio). The input to this | 
|     54 // a price in year n and a price in year n+1. The second function calculates |     60 //     function are the nested lists created by get_prices above. | 
|     55 // all change factors for all prices (from a portfolio). |         | 
|     56  |     61  | 
|     57 def get_delta(price_old: Option[Double], price_new: Option[Double]) : Option[Double] = { |     62 def get_delta(price_old: Option[Double], price_new: Option[Double]) : Option[Double] = { | 
|     58   (price_old, price_new) match { |     63 	for( x <- price_old; y <- price_new) yield (y-x)/x | 
|     59     case (Some(x), Some(y)) => Some((y - x) / x) |         | 
|     60     case _ => None |         | 
|     61   } |         | 
|     62 } |     64 } | 
|     63  |     65  | 
|     64 def get_deltas(data: List[List[Option[Double]]]):  List[List[Option[Double]]] = |     66 def get_deltas(data: List[List[Option[Double]]]) :  List[List[Option[Double]]] = { | 
|     65   for (i <- (0 until (data.length - 1)).toList) yield  |     67 	(for( n <- 1 to data.length-1) yield (for(i <- 0 to data(n).length-1) yield  get_delta(data(n-1)(i), data(n)(i))).toList).toList | 
|     66     for (j <- (0 until (data(0).length)).toList) yield get_delta(data(i)(j), data(i + 1)(j)) |     68 } | 
|     67  |     69  | 
|     68  |     70  | 
|     69 // test case using the prices calculated above |         | 
|     70 val d = get_deltas(p) |         | 
|     71 val ttd = get_deltas(tt) |         | 
|     72  |     71  | 
|     73 // (3) Write a function that given change factors, a starting balance and a year |     72 // (3) Write a function that given change factors, a starting balance and a year | 
|     74 // calculates the yearly yield, i.e. new balanace, according to our dump investment  |     73 //     calculates the yearly yield, i.e. new balance, according to our dump investment  | 
|     75 // strategy. Another function calculates given the same data calculates the |     74 //     strategy. Another function calculates given the same data calculates the | 
|     76 // compound yield up to a given year. Finally a function combines all  |     75 //     compound yield up to a given year. Finally a function combines all  | 
|     77 // calculations by taking a portfolio, a range of years and a start balance |     76 //     calculations by taking a portfolio, a range of years and a start balance | 
|     78 // as arguments. |     77 //     as arguments. | 
|     79  |     78  | 
|     80  |     79  | 
|     81 def yearly_yield(data: List[List[Option[Double]]], balance: Long, year: Int): Long = { |     80 def yearly_yield(data: List[List[Option[Double]]], balance: Long, year: Int) : Long = { | 
|     82   val somes = data(year).flatten |     81 	val increments = (for(n <- 0 to data(year).length-1 if(!(data(year)(n) == None))) yield (data(year)(n).getOrElse(0.0))).toList | 
|     83   val somes_length = somes.length |     82 	val sumi = (increments.sum).toDouble | 
|     84   if (somes_length == 0) balance |     83 	if(increments.length == 0){ | 
|     85   else { |     84 		balance | 
|     86     val portion: Double = balance.toDouble / somes_length.toDouble |     85 	}else{ | 
|     87     balance + (for (x <- somes) yield (x * portion)).sum.toLong |     86 		val il = (increments.length).toDouble | 
|     88   } |     87 		val averag = sumi/il | 
|         |     88 		val i = (balance + (balance*averag)) | 
|         |     89 		i.toLong | 
|         |     90 	} | 
|     89 } |     91 } | 
|     90  |     92  | 
|     91 def compound_yield(data: List[List[Option[Double]]], balance: Long, year: Int): Long = { |     93 def compound_yield(data: List[List[Option[Double]]], balance: Long, ye: Int) : Long = {//if(year == 0) yearly_yield(data, balance, 0) else compound_yield(data, yearly_yield(data, balance, year), year-1) | 
|     92   if (year >= data.length) balance else { |     94 	val increments_py = (for(year <- 0 to ye) yield { | 
|     93     val new_balance = yearly_yield(data, balance, year) |     95 		val increments = (for(n <- 0 to data(year).length-1 if(!(data(year)(n) == None))) yield (data(year)(n).getOrElse(0.0))).toList | 
|     94     compound_yield(data, new_balance, year + 1) |     96 		val sum_of = (increments.sum).toDouble | 
|     95   } |     97 		val number_of = (increments.length).toDouble | 
|         |     98 		sum_of/number_of + 1.0 | 
|         |     99 	}).toList | 
|         |    100 	val mul_factor = increments_py.reduceLeft(_*_) | 
|         |    101 	(balance*mul_factor).toLong | 
|         |    102 } | 
|         |    103 def investment(portfolio: List[String], years: Range, start_balance: Long) : Long = { | 
|         |    104 	val p = get_prices(portfolio, years) | 
|         |    105 	val d = get_deltas(p) | 
|         |    106 	compound_yield(d, start_balance, d.length-1) | 
|     96 } |    107 } | 
|     97  |    108  | 
|     98 //yearly_yield(d, 100, 0) |         | 
|     99 //compound_yield(d.take(6), 100, 0) |         | 
|    100  |    109  | 
|    101 //test case |         | 
|    102 //yearly_yield(d, 100, 0) |         | 
|    103 //yearly_yield(d, 225, 1) |         | 
|    104 //yearly_yield(d, 246, 2) |         | 
|    105 //yearly_yield(d, 466, 3) |         | 
|    106 //yearly_yield(d, 218, 4) |         | 
|    107  |         | 
|    108 //yearly_yield(d, 100, 0) |         | 
|    109 //yearly_yield(d, 125, 1) |         | 
|    110  |         | 
|    111 def investment(portfolio: List[String], years: Range, start_balance: Long): Long = { |         | 
|    112   compound_yield(get_deltas(get_prices(portfolio, years)), start_balance, 0) |         | 
|    113 } |         | 
|    114  |         | 
|    115 val one = get_deltas(get_prices(rstate_portfolio, 1978 to 1984)) |         | 
|    116 val two = get_deltas(get_prices(blchip_portfolio, 1978 to 1984)) |         | 
|    117  |         | 
|    118 val one_full = get_deltas(get_prices(rstate_portfolio, 1978 to 2017)) |         | 
|    119 val two_full = get_deltas(get_prices(blchip_portfolio, 1978 to 2017)) |         | 
|    120  |         | 
|    121 one_full.map(_.flatten).map(_.sum).sum |         | 
|    122 two_full.map(_.flatten).map(_.sum).sum |         | 
|    123  |    110  | 
|    124 //test cases for the two portfolios given above |    111 //test cases for the two portfolios given above | 
|    125  |    112  | 
|    126 //println("Real data: " + investment(rstate_portfolio, 1978 to 1981, 100)) |    113 investment(rstate_portfolio, 1978 to 2017, 100) | 
|    127 //println("Blue data: " + investment(blchip_portfolio, 1978 to 1981, 100)) |    114 investment(blchip_portfolio, 1978 to 2017, 100) | 
|    128  |    115  | 
|    129 //for (i <- 1978 to 2017) { |         | 
|    130 //  println("Year " + i) |         | 
|    131 //  println("Real data: " + investment(rstate_portfolio, 1978 to i, 100)) |         | 
|    132 //  println("Blue data: " + investment(blchip_portfolio, 1978 to i, 100)) |         | 
|    133 //} |         | 
|    134  |         | 
|    135 //1984 |         | 
|    136 //1992 |         | 
|    137 } |    116 } |