diff -r ecf83084e41d -r 87e55eb309ed progs/trade_sol.scala --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/progs/trade_sol.scala Wed Nov 09 00:52:08 2016 +0000 @@ -0,0 +1,79 @@ +// Part 2 about Buy-Low-Sell-High using Yahoo Financial Data +//=========================================================== + + +// (1) Complete the function that is given a list of floats +// and calculuates the indices for when to buy the commodity +// and when to sell + +def trade_times(xs: List[Double]): (Int, Int) = { + val low = xs.min + val low_index = xs.indexOf(low) + val rest = xs.drop(low_index) + val high = rest.max + val high_index = rest.indexOf(high) + (low_index, low_index + high_index) +} + +val prices = List(28.0, 18.0, 20.0, 26.0, 24.0) +assert(trade_times(prices) == (1, 3), "the trade_times test fails") + + +// (2) Complete the ``get webpage'' function that takes a +// a stock symbol as argument and queries the Yahoo server +// at +// http://ichart.yahoo.com/table.csv?s=<> +// +// This servive returns a CSV-list that needs to be separated into +// a list of strings. + +import io.Source +import scala.util._ + +def get_yahoo_page(symbol: String): List[String] = { + val url = """http://ichart.yahoo.com/table.csv?s=""" + symbol + Try(Source.fromURL(url)("ISO-8859-1").getLines.toList). + getOrElse { println(s" Problem with: $url"); List() } +} + +// (3) Complete the function that processes the CSV list +// extracting the dates and anjusted close prices. The +// prices need to be transformed into Doubles. + +def process_page(symbol: String): List[(String, Double)] = { + get_yahoo_page(symbol).drop(1).map(_.split(",").toList).map((xs) => (xs(0), xs(6).toDouble)) +} + + +// (4) Complete the query_company function that obtains the +// processed CSV-list for a stock symbol. It should return +// the dates for when to buy and sell the stocks of that company. + +def query_company(symbol: String): (String, String) = { + val list = process_page(symbol).reverse + val (tbuy, tsell) = trade_times(list.map(_._2)) + (list(tbuy)._1, list(tsell)._1) +} + +//query_company("GOOG") + + +val indices = List("GOOG", "AAPL", "MSFT", "IBM", "FB", "YHOO", "AMZN", "BIDU") + +for (name <- indices) { + val times = query_company(name) + println(s"Buy ${name} on ${times._1} and sell on ${times._2}") +} + + + +/* +scala trade.scala 2> /dev/null || echo "command1 borked it" + +command1 +if [ $? -ne 0 ]; then + echo "command1 borked it" +fi +*/ + +