progs/trade.scala
changeset 11 417869f65585
parent 8 ab77f6006f1f
child 18 87e55eb309ed
--- a/progs/trade.scala	Sat Nov 05 18:15:38 2016 +0000
+++ b/progs/trade.scala	Sun Nov 06 18:28:47 2016 +0000
@@ -1,7 +1,7 @@
-
+// Part 2
 
-val trades = List(28.0, 18.0, 20.0, 26.0, 24.0)
-
+// (1) the function that 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)
@@ -12,46 +12,47 @@
 }
 
 
-trade_times(trades)
+val prices = List(28.0, 18.0, 20.0, 26.0, 24.0)
 
-assert(trade_times(List(10.0, 8.0, 7.0, 6.0)) == (3, 3), "the first test fails")
-
+trade_times(prices)
+assert(trade_times(prices) == (1, 3), "the first test fails")
 
 
 import io.Source
 import scala.util._
 
+// (2) the function that queries the Yahoo financial data
+// servive and returns a comma-separated-value list
 def get_page(url: String): List[String] = {
   Try(Source.fromURL(url)("ISO-8859-1").getLines.toList).
     getOrElse { println(s"  Problem with: $url"); List() }
 }
 
+// (3) the function that processes the comma-separated-value list
+// extracting the dates and anjusted close prices
 def process_page(url: String): List[(String, Double)] = {
   get_page(url).drop(1).map(_.split(",").toList).map((xs) => (xs(0), xs(6).toDouble))
 }
 
-def query_comp(name: String): (Int, Int) = {
-  val list = process_page("""http://ichart.yahoo.com/table.csv?s=""" + name)
-  trade_times(list.reverse.map(_._2))
+// (4) the function that generates the query for a stock
+// market symbol and returns the dates for when to buy and
+// sell
+def query_comp(name: String): (String, String) = {
+  val list = process_page("""http://ichart.yahoo.com/table.csv?s=""" + name).reverse
+  val (tbuy, tsell) = trade_times(list.map(_._2))
+  (list(tbuy)._1, list(tsell)._1)
 }
 
+//query_comp("GOOG")
+
 
 val indices = List("GOOG", "AAPL", "MSFT", "IBM", "FB", "YHOO", "AMZN", "BIDU")
 
-indices.map(query_comp(_))
-
-val appl_page = get_page("""http://ichart.yahoo.com/table.csv?s=GOOG""")
-val goog_page = get_page("""http://ichart.yahoo.com/table.csv?s=GOOG""")
-goog_page.length
+for (name <- indices) {
+  val times = query_comp(name)
+  println(s"Buy ${name} on ${times._1} and sell on ${times._2}")
+}
 
-val pairs = goog_page.drop(1).map(_.split(",").toList).map((xs:List[String]) => (xs(0), xs(6).toDouble))
-
-pairs.map(_._2)
-
-trade_times(pairs.reverse.map(_._2))
-
-pairs(3067)
-pairs(11)
 
 
 /*