# HG changeset patch # User Christian Urban # Date 1478741445 0 # Node ID bb8c3dd8c75cd654747ff07818b604fd83534782 # Parent fde9223a530109e8d3d143921320cf64354d877b# Parent a81271342ff6c7f44281d3411eb12b775d068ddc updated diff -r fde9223a5301 -r bb8c3dd8c75c cws/cw01.pdf diff -r fde9223a5301 -r bb8c3dd8c75c cws/cw01.tex --- a/cws/cw01.tex Thu Nov 10 01:30:15 2016 +0000 +++ b/cws/cw01.tex Thu Nov 10 01:30:45 2016 +0000 @@ -83,7 +83,7 @@ \item[(2)] Write a second function that takes an upper bound as argument and calculates the steps for all numbers in the range from 1 up to this bound. It returns the maximum number of steps and the - corresponding number that needs that many steps. More precisely + corresponding number that needs that many steps. More precisely, it returns a pair where the first component is the number of steps and the second is the corresponding number. \hfill\mbox{[1 Mark]} @@ -125,7 +125,7 @@ to buy and when to sell this commodity. In the example above it should return the pair $\texttt{(1, 3)}$ because at index $1$ the price is lowest and then at index $3$ the price is highest. Note the prices are given as -lists of \texttt{Float}s.\newline \mbox{} \hfill[1 Mark] +lists of \texttt{Double}s.\newline \mbox{} \hfill[1 Mark] \item[(2)] Write a function that requests a comma-separated value (CSV) list from the Yahoo websevice that provides historical data for stock @@ -186,13 +186,13 @@ \subsection*{Advanced Part 3 (3 Marks)} -A purely fictional character named Mr T.~Drump inherited in 1978 -approximately 200 Million Dollar from his father. Mr Drump prides +A purely fictional character named Mr T.~Drumb inherited in 1978 +approximately 200 Million Dollar from his father. Mr Drumb prides himself to be a brilliant business man because nowadays it is estimated he is 3 Billion Dollar worth (one is not sure, of course, -because Mr Drump refuses to make his tax records public). +because Mr Drumb refuses to make his tax records public). -Since the question about Mr Drump's business acumen remains, let's do a +Since the question about Mr Drumb's business acumen remains open, let's do a quick back-of-the-envelope calculation in Scala whether his claim has any merit. Let's suppose we are given \$100 in 1978 and we follow a really dump investment strategy, namely: @@ -215,7 +215,7 @@ \end{itemize}\medskip \noindent -\textbf{Tasks (file drump.scala):} +\textbf{Tasks (file drumb.scala):} \begin{itemize} \item[(1.a)] Write a function that queries the Yahoo financial data @@ -313,7 +313,7 @@ turn out to be a blue chip company. Also, since the portfolios are chosen from the current S\&P 500, they do not include the myriad of companies that went bust or were de-listed over the years. -So where does this leave our fictional character Mr T.~Drump? Well, given +So where does this leave our fictional character Mr T.~Drumb? Well, given his inheritance, a really dumb investment strategy would have done equally well, if not much better. \end{document} diff -r fde9223a5301 -r bb8c3dd8c75c progs/drumb.scala --- a/progs/drumb.scala Thu Nov 10 01:30:15 2016 +0000 +++ b/progs/drumb.scala Thu Nov 10 01:30:45 2016 +0000 @@ -1,5 +1,5 @@ -// Advanvced Part 3 about Mr T. Drumb investing into stocks -//========================================================== +// Advanvced Part 3 about really dump investing strategy +//======================================================= //two test portfolios @@ -8,34 +8,55 @@ "DLR", "EQIX", "EQR", "ESS", "EXR", "FRT", "GGP", "HCP") -def get_yahoo_page(url: String): Option[List[String]] = ... +// (1) The function below should obtain the first trading price +// for a stock symbol by using the query +// +// http://ichart.yahoo.com/table.csv?s=<>&a=0&b=1&c=<>&d=1&e=1&f=<> +// +// and extracting the first January Adjusted Close price in a year. def get_first_price(symbol: String, year: Int): Option[Double] = ... +// Complete the function below that obtains all first prices +// for the stock symbols from a portfolio for the given +// range of years + def get_prices(portfolio: List[String], years: Range): List[List[Option[Double]]] = ... +// test case +//val p = get_prices(List("GOOG", "AAPL"), 2010 to 2012) + -//val p = get_prices(List("GOOG", "AAPL"), 2010 to 2012) - +// (2) The first function below calculates the change factor (delta) between +// a price in year n and a price in year n+1. The second function calculates +// all change factors for all prices (from a portfolio). def get_delta(price_old: Option[Double], price_new: Option[Double]): Option[Double] = ... def get_deltas(data: List[List[Option[Double]]]): List[List[Option[Double]]] = ... +// test case using the prices calculated above //val d = get_deltas(p) +// (3) Write a function that given change factors, a starting balance and a year +// calculates the yearly yield, i.e. new balanace, according to our dump investment +// strategy. Another function calculates given the same data calculates the +// compound yield up to a given year. Finally a function combines all +// calculations by taking a portfolio, a range of years and a start balance +// as arguments. def yearly_yield(data: List[List[Option[Double]]], balance: Long, year: Int): Long = ... +//test case //yearly_yield(d, 100, 0) def compound_yield(data: List[List[Option[Double]]], balance: Long, year: Int): Long = ... - def investment(portfolio: List[String], years: Range, start_balance: Long): Long = ... +//test cases for the two portfolios given above //investment(rstate_portfolio, 1978 to 2016, 100) //investment(blchip_portfolio, 1978 to 2016, 100) diff -r fde9223a5301 -r bb8c3dd8c75c progs/drumb_sol.scala --- a/progs/drumb_sol.scala Thu Nov 10 01:30:15 2016 +0000 +++ b/progs/drumb_sol.scala Thu Nov 10 01:30:45 2016 +0000 @@ -1,5 +1,5 @@ -// Advanvced Part 3 about Mr T. Drumb investing into stocks -//========================================================== +// Advanvced Part 3 about really dump investing strategy +//======================================================= //two test portfolios @@ -7,6 +7,12 @@ val rstate_portfolio = List("PLD", "PSA", "AMT", "AIV", "AVB", "BXP", "CBG", "CCI", "DLR", "EQIX", "EQR", "ESS", "EXR", "FRT", "GGP", "HCP") +// (1) The function below should obtain the first trading price +// for a stock symbol by using the query +// +// http://ichart.yahoo.com/table.csv?s=<>&a=0&b=1&c=<>&d=1&e=1&f=<> +// +// and extracting the first January Adjusted Close price in a year. import io.Source import scala.util._ @@ -25,13 +31,24 @@ data.map(_.last.split(",").toList(6).toDouble) } + +// Complete the function below that obtains all first prices +// for the stock symbols from a portfolio for the given +// range of years + def get_prices(portfolio: List[String], years: Range): List[List[Option[Double]]] = for (year <- years.toList) yield for (symbol <- portfolio) yield get_first_price(symbol, year) -get_prices(List("GOOG", "AAPL"), 2010 to 2012) + +// test case +//val p = get_prices(List("GOOG", "AAPL"), 2010 to 2012) +// (2) The first function below calculates the change factor (delta) between +// a price in year n and a price in year n+1. The second function calculates +// all change factors for all prices (from a portfolio). + def get_delta(price_old: Option[Double], price_new: Option[Double]): Option[Double] = { (price_old, price_new) match { case (Some(x), Some(y)) => Some((y - x) / x) @@ -43,6 +60,19 @@ for (i <- (0 until (data.length - 1)).toList) yield for (j <- (0 until (data(0).length)).toList) yield get_delta(data(i)(j), data(i + 1)(j)) + +// test case using the prices calculated above +//val d = get_deltas(p) + + +// (3) Write a function that given change factors, a starting balance and a year +// calculates the yearly yield, i.e. new balanace, according to our dump investment +// strategy. Another function calculates given the same data calculates the +// compound yield up to a given year. Finally a function combines all +// calculations by taking a portfolio, a range of years and a start balance +// as arguments. + + def yearly_yield(data: List[List[Option[Double]]], balance: Long, year: Int): Long = { val somes = data(year).flatten val somes_length = somes.length @@ -53,6 +83,9 @@ } } +//test case +//yearly_yield(d, 100, 0) + def compound_yield(data: List[List[Option[Double]]], balance: Long, year: Int): Long = { if (year >= data.length) balance else { val new_balance = yearly_yield(data, balance, year) @@ -60,15 +93,13 @@ } } -val p = get_prices(List("GOOG", "AAPL"), 2010 to 2012) -val d = get_deltas(p) -yearly_yield(d, 100, 0) - def investment(portfolio: List[String], years: Range, start_balance: Long): Long = { compound_yield(get_deltas(get_prices(portfolio, years)), start_balance, 0) } +//test cases for the two portfolios given above + println("Real data: " + investment(rstate_portfolio, 1978 to 2016, 100)) println("Blue data: " + investment(blchip_portfolio, 1978 to 2016, 100)) diff -r fde9223a5301 -r bb8c3dd8c75c progs/lecture1.scala --- a/progs/lecture1.scala Thu Nov 10 01:30:15 2016 +0000 +++ b/progs/lecture1.scala Thu Nov 10 01:30:45 2016 +0000 @@ -1,16 +1,16 @@ // Lecture 1 -//========== +//=========== -//**Assignments (values)** -//(variable names should be lower case) -//===================================== +// Value assignments +// (variable names should be lower case) +//====================================== val x = 42 val y = 3 + 4 -//**Collections** -//=============== +// Collections +//============= List(1,2,3,1) Set(1,2,3,1) @@ -26,13 +26,13 @@ 1::2::3::Nil List(1, 2, 3) ::: List(4, 5, 6) -//**Printing/Strings** -//==================== +// Printing/Strings +//================== println("test") -val tst = "This is a " + "test" +val tst = "This is a " ++ "test\n" println(tst) val lst = List(1,2,3,1) @@ -43,26 +43,39 @@ // some methods take more than one argument println(lst.mkString("[", ",", "]")) -//**Conversion methods** -//====================== +// Conversion methods +//==================== List(1,2,3,1).toString List(1,2,3,1).toSet "hello".toList 1.toDouble -//**Types** -//========= + +List(1,2,3,4).reverse + +// Types +//======= + +/* Scala is a strongly typed language + + * Base types -// Int, Long, BigInt, Float, Double -// String, Char -// List[Int], Set[Double] -// Pairs: (Int, String) -// List[(BigInt, String)] + Int, Long, BigInt, Float, Double + String, Char + Boolean + + * Compound types + List[Int], + Set[Double] + Pairs: (Int, String) + List[(BigInt, String)] +*/ -//**Smart Strings** -//================= +// Smart Strings +//=============== + println(">\n<") println(""">\n<""") @@ -81,8 +94,8 @@ println(lyrics) -//**Pairs/Tuples** -//================ +// Pairs/Tuples +//============== val p = (1, "one") p._1 @@ -91,52 +104,100 @@ val t = (4,1,2,3) t._4 -//**Function Definitions** -//======================== +// Hello World +//============= + +// show an example of a stand-alone scala file +// remind that in the course work you are asked a +// plain scala "work-sheet" + + + +// Function Definitions +//====================== def square(x: Int): Int = x * x - +square(6) -//**Ifs control structures** -//========================== +// If control structure +//====================== def fact(n: Int): Int = if (n == 0) 1 else n * fact(n - 1) - - +/* boolean operators + + == equals + ! not + && || and, or +*/ def fact2(n: BigInt): BigInt = if (n == 0) 1 else n * fact2(n - 1) +fact2(150) + + def fib(n: Int): Int = if (n == 0) 1 else - if (n == 1) 1 else fib(n - 1) + f(n - 2) + if (n == 1) 1 else fib(n - 1) + fib(n - 2) + + +//gcd - Euclid's algorithm + +def gcd(a: Int, b: Int): Int = + if (b == 0) a else gcd(b, a % b) + +gcd(48, 18) -//a recursive function -def gcd(x: Int, y: Int): Int = 2 //??? +// String Interpolations +//======================= -//**String Interpolations** -//========================= +val n = 3 +println("The square of " + n + " is " + square(n) + ".") + +println(s"The square of ${n} is ${square(n)}.") + -//**Assert/Testing** -==================== +def gcd_db(a: Int, b: Int): Int = { + println(s"Function called with ${a} and ${b}.") + if (b == 0) a else gcd_db(b, a % b) +} + +gcd_db(48, 18) -//**For-Maps (not For-Loops)** -//============================ + +// Assert/Testing +//================ + +// For-Comprehensions (not For-Loops) +//==================================== for (n <- (1 to 10).toList) yield square(n) -for (n <- (1 to 10).toList; m <- (1 to 10).toList) yield m * n +for (n <- (1 to 10).toList; + m <- (1 to 10).toList) yield m * n + -val mtable = for (n <- (1 to 10).toList; m <- (1 to 10).toList) yield m * n +val mult_table = + for (n <- (1 to 10).toList; + m <- (1 to 10).toList) yield m * n -mtable.sliding(10,10).toList.mkString( +mult_table.sliding(10,10).mkString("\n") -// webpages +// with patterns + +for ((m, n) <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield m + n + +for (p <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield p._1 + p._2 + + + +// Webpages +//========== diff -r fde9223a5301 -r bb8c3dd8c75c slides/slides01.pdf Binary file slides/slides01.pdf has changed diff -r fde9223a5301 -r bb8c3dd8c75c slides/slides01.tex --- a/slides/slides01.tex Thu Nov 10 01:30:15 2016 +0000 +++ b/slides/slides01.tex Thu Nov 10 01:30:45 2016 +0000 @@ -100,7 +100,8 @@ \textcolor{codegreen}{\texttt{Float}}, \textcolor{codegreen}{\texttt{Double}}\\ \textcolor{codegreen}{\texttt{String}}, - \textcolor{codegreen}{\texttt{Char}} + \textcolor{codegreen}{\texttt{Char}}\\ + \textcolor{codegreen}{\texttt{Boolean}} \end{tabular} \end{center} @@ -114,7 +115,7 @@ \textcolor{codegreen}{\texttt{List[(BigInt, String)]}} & lists of BigInt-String\\ & pairs\\ - \textcolor{codegreen}{\texttt{List[List[Int]]}} \\ + \textcolor{codegreen}{\texttt{List[List[Int]]}} & list of lists of Int's\\ \end{tabular} \end{center} diff -r fde9223a5301 -r bb8c3dd8c75c style.sty --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/style.sty Thu Nov 10 01:30:45 2016 +0000 @@ -0,0 +1,23 @@ +\usepackage{xcolor} +\usepackage[sc]{mathpazo} +\usepackage{fontspec} +\setmainfont[Ligatures=TeX]{Palatino Linotype} +\usepackage{amssymb} +\usepackage{amsmath} +\usepackage{menukeys} +\definecolor{darkblue}{rgb}{0,0,0.6} +\usepackage[colorlinks=true,urlcolor=darkblue,linkcolor=darkblue]{hyperref} + +%%% for trees +%% http://anorien.csc.warwick.ac.uk/mirrors/CTAN/graphics/pgf/contrib/forest/forest.pdf + +\newcommand{\dn}{\stackrel{\mbox{\scriptsize def}}{=}} +\newcommand{\defn}[1]{\textit{\textbf{#1}}} +\newcommand{\dq}[1]{\mbox{\tt{"}}#1\mbox{\tt{"}}} + +\definecolor{codegray}{gray}{0.9} + +\makeatletter +\def\fnote{\gdef\@thefnmark{}\@footnotetext} +\makeatother +