progs/trade.scala
changeset 8 ab77f6006f1f
child 11 417869f65585
equal deleted inserted replaced
7:7a5a29a32568 8:ab77f6006f1f
       
     1 
       
     2 
       
     3 val trades = List(28.0, 18.0, 20.0, 26.0, 24.0)
       
     4 
       
     5 def trade_times(xs: List[Double]): (Int, Int) = {
       
     6   val low = xs.min
       
     7   val low_index = xs.indexOf(low)
       
     8   val rest = xs.drop(low_index)
       
     9   val high = rest.max
       
    10   val high_index = rest.indexOf(high)
       
    11   (low_index, low_index + high_index)
       
    12 }
       
    13 
       
    14 
       
    15 trade_times(trades)
       
    16 
       
    17 assert(trade_times(List(10.0, 8.0, 7.0, 6.0)) == (3, 3), "the first test fails")
       
    18 
       
    19 
       
    20 
       
    21 import io.Source
       
    22 import scala.util._
       
    23 
       
    24 def get_page(url: String): List[String] = {
       
    25   Try(Source.fromURL(url)("ISO-8859-1").getLines.toList).
       
    26     getOrElse { println(s"  Problem with: $url"); List() }
       
    27 }
       
    28 
       
    29 def process_page(url: String): List[(String, Double)] = {
       
    30   get_page(url).drop(1).map(_.split(",").toList).map((xs) => (xs(0), xs(6).toDouble))
       
    31 }
       
    32 
       
    33 def query_comp(name: String): (Int, Int) = {
       
    34   val list = process_page("""http://ichart.yahoo.com/table.csv?s=""" + name)
       
    35   trade_times(list.reverse.map(_._2))
       
    36 }
       
    37 
       
    38 
       
    39 val indices = List("GOOG", "AAPL", "MSFT", "IBM", "FB", "YHOO", "AMZN", "BIDU")
       
    40 
       
    41 indices.map(query_comp(_))
       
    42 
       
    43 val appl_page = get_page("""http://ichart.yahoo.com/table.csv?s=GOOG""")
       
    44 val goog_page = get_page("""http://ichart.yahoo.com/table.csv?s=GOOG""")
       
    45 goog_page.length
       
    46 
       
    47 val pairs = goog_page.drop(1).map(_.split(",").toList).map((xs:List[String]) => (xs(0), xs(6).toDouble))
       
    48 
       
    49 pairs.map(_._2)
       
    50 
       
    51 trade_times(pairs.reverse.map(_._2))
       
    52 
       
    53 pairs(3067)
       
    54 pairs(11)
       
    55 
       
    56 
       
    57 /*
       
    58 scala trade.scala 2> /dev/null || echo "command1 borked it"
       
    59 
       
    60 command1
       
    61 if [ $? -ne 0 ]; then
       
    62     echo "command1 borked it"
       
    63 fi
       
    64 */
       
    65 
       
    66