上QQ阅读APP看书,第一时间看更新
Loading inflation data
Now that we can load some equity data, we need to load inflation data so that we're able to compute inflation-adjusted returns. It is very similar to the loading of equity data.
First, copy cpi_2017.tsv from https://github.com/PacktPublishing/Scala-Programming-Projects/blob/master/Chapter02/retirement-calculator/src/main/resources/cpi.tsv to src/test/resources. Then, create a new unit test called InflationDataSpec in the retcalc package:
package retcalc
import org.scalatest.{Matchers, WordSpec}
class InflationDataSpec extends WordSpec with Matchers {
"InflationData.fromResource" should {
"load CPI data from a tsv file" in {
val data = InflationData.fromResource("cpi_2017.tsv")
data should ===(Vector(
InflationData("2016.09", 241.428),
InflationData("2016.10", 241.729),
InflationData("2016.11", 241.353),
InflationData("2016.12", 241.432),
InflationData("2017.01", 242.839),
InflationData("2017.02", 243.603),
InflationData("2017.03", 243.801),
InflationData("2017.04", 244.524),
InflationData("2017.05", 244.733),
InflationData("2017.06", 244.955),
InflationData("2017.07", 244.786),
InflationData("2017.08", 245.519),
InflationData("2017.09", 246.819)
))
}
}
}
Then, create the corresponding InflationData class and companion object:
package retcalc
import scala.io.Source
case class InflationData(monthId: String, value: Double)
object InflationData {
def fromResource(resource: String): Vector[InflationData] =
Source.fromResource(resource).getLines().drop(1).map { line =>
val fields = line.split("\t")
InflationData(monthId = fields(0), value = fields(1).toDouble)
}.toVector
}