書名: Scala Programming Projects作者名: Mikael Valot Nicolas Jorand本章字數: 160字更新時間: 2021-07-23 16:25:22
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
}
推薦閱讀
- 物聯網網絡安全及應用
- 網絡故障現場處理實踐(第4版)
- WordPress 5 Complete
- 局域網組建、管理與維護項目教程(Windows Server 2003)
- Bonita Open Solution 5.x Essentials
- 物聯網場景設計與開發(初級)
- 紅藍攻防:構建實戰化網絡安全防御體系
- Getting Started with nopCommerce
- 云計算技術與標準化
- TCP/IP基礎(第2版)
- Building RESTful Web Services with .NET Core
- React Design Patterns and Best Practices(Second Edition)
- ElasticSearch Server
- 網絡分析技術揭秘:原理、實踐與WinPcap深入解析
- 云計算、網絡安全和網絡盜竊:網絡世界防盜初學指南