|
1 // Part 2 about Buy-Low-Sell-High using Yahoo Financial Data |
|
2 //=========================================================== |
|
3 |
|
4 |
|
5 // (1) Complete the function that is given a list of floats |
|
6 // and calculuates the indices for when to buy the commodity |
|
7 // and when to sell |
|
8 |
|
9 def trade_times(xs: List[Double]): (Int, Int) = { |
|
10 val low = xs.min |
|
11 val low_index = xs.indexOf(low) |
|
12 val rest = xs.drop(low_index) |
|
13 val high = rest.max |
|
14 val high_index = rest.indexOf(high) |
|
15 (low_index, low_index + high_index) |
|
16 } |
|
17 |
|
18 val prices = List(28.0, 18.0, 20.0, 26.0, 24.0) |
|
19 assert(trade_times(prices) == (1, 3), "the trade_times test fails") |
|
20 |
|
21 |
|
22 // (2) Complete the ``get webpage'' function that takes a |
|
23 // a stock symbol as argument and queries the Yahoo server |
|
24 // at |
|
25 // http://ichart.yahoo.com/table.csv?s=<<insert stock symbol>> |
|
26 // |
|
27 // This servive returns a CSV-list that needs to be separated into |
|
28 // a list of strings. |
|
29 |
|
30 import io.Source |
|
31 import scala.util._ |
|
32 |
|
33 def get_yahoo_page(symbol: String): List[String] = { |
|
34 val url = """http://ichart.yahoo.com/table.csv?s=""" + symbol |
|
35 Try(Source.fromURL(url)("ISO-8859-1").getLines.toList). |
|
36 getOrElse { println(s" Problem with: $url"); List() } |
|
37 } |
|
38 |
|
39 // (3) Complete the function that processes the CSV list |
|
40 // extracting the dates and anjusted close prices. The |
|
41 // prices need to be transformed into Doubles. |
|
42 |
|
43 def process_page(symbol: String): List[(String, Double)] = { |
|
44 get_yahoo_page(symbol).drop(1).map(_.split(",").toList).map((xs) => (xs(0), xs(6).toDouble)) |
|
45 } |
|
46 |
|
47 |
|
48 // (4) Complete the query_company function that obtains the |
|
49 // processed CSV-list for a stock symbol. It should return |
|
50 // the dates for when to buy and sell the stocks of that company. |
|
51 |
|
52 def query_company(symbol: String): (String, String) = { |
|
53 val list = process_page(symbol).reverse |
|
54 val (tbuy, tsell) = trade_times(list.map(_._2)) |
|
55 (list(tbuy)._1, list(tsell)._1) |
|
56 } |
|
57 |
|
58 //query_company("GOOG") |
|
59 |
|
60 |
|
61 val indices = List("GOOG", "AAPL", "MSFT", "IBM", "FB", "YHOO", "AMZN", "BIDU") |
|
62 |
|
63 for (name <- indices) { |
|
64 val times = query_company(name) |
|
65 println(s"Buy ${name} on ${times._1} and sell on ${times._2}") |
|
66 } |
|
67 |
|
68 |
|
69 |
|
70 /* |
|
71 scala trade.scala 2> /dev/null || echo "command1 borked it" |
|
72 |
|
73 command1 |
|
74 if [ $? -ne 0 ]; then |
|
75 echo "command1 borked it" |
|
76 fi |
|
77 */ |
|
78 |
|
79 |