1

我是 scala 的新手,所以不知道如何解决这个问题?基本上,我正在尝试为一系列报价找到移动平均线交叉点。我不确定如何获取以前的值以将它们与当前值进行比较?

if ( fastMovingAverage(n-1) > slowMovingAverage(n-1) && fastMovingAverage(n) < slowMovingAverage(n) )
then do some action



package com.example.csv

import scala.io.Source


object FileParser {
  val TIMESTAMP_LOCATION = 3
  val BID_LOCATION = 4
  val OFFER_LOCATION = 5
  val FAST_WINDOW_SIZE = 5
  val SLOW_WINDOW_SIZE = 10

  def main(args: Array[String]) = {
    val records = Source.fromFile("Sample.csv")
    .getLines()
    .drop(1)
    .map(_.split(","))
    .takeWhile( _ != null)
    .sliding(SLOW_WINDOW_SIZE , 1)
    .foreach(x => movingAverage(x))
  }

  def movingAverage(numbers: Seq[Array[String]]) = {
    val listOfBids = numbers.map(x => x(BID_LOCATION).toDouble)
    val slowAverage = listOfBids.reduceLeft(_ + _)/numbers.length
    val fastListOfBids = listOfBids.takeRight(FAST_WINDOW_SIZE)
    val fastAverage = fastListOfBids.reduceLeft(_ + _)/fastListOfBids.length
    println("Slow Average " + slowAverage + " Fast Average " + fastAverage)
  }

}
4

1 回答 1

5

简短的回答是使用zip操作slowAveragefastAverage组合列表,然后找到压缩元素的差异。当差值从负值变为正值时,这表明快速平均值已超过(更大)慢速平均值。

这是我使用的数据和更长的示例:

Price      Fast Average(2)  Slow Average(4) Diff
9           
8           8.5     
7           7.5     
6           6.5             7.5              -1
5           5.5             6.5              -1
5           5               5.75             -0.75
6           5.5             5.5               0
7           6.5             5.75              0.75
8           7.5             6.5               1
9           8.5             7.5               1

移动平均线交叉示例

谷歌文档链接:https ://docs.google.com/spreadsheet/ccc?key=0Alfb-wgy-zTddHdwU2stS0U5ZUxtN2cwdWFoeWNPZFE&usp=sharing

最近的价格是最后的。

让我们在 Scala 中看看它:

scala> val prices = List(9,8,7,6,5,5,6,7,8,9)
prices: List[Int] = List(9, 8, 7, 6, 5, 5, 6, 7, 8, 9)

scala> val fastAverage = prices.sliding(2).toList.map(xs => xs.sum / 2.0)
fastAverage: List[Double] = List(8.5, 7.5, 6.5, 5.5, 5.0, 5.5, 6.5, 7.5, 8.5)

scala> val slowAverage = prices.sliding(4).toList.map(xs => xs.sum / 4.0)
slowAverage: List[Double] = List(7.5, 6.5, 5.75, 5.5, 5.75, 6.5, 7.5)

拉链在一起fastAverageslowAverage但由于它们的尺寸不同,我们采用最后七个fastAveragewith takeRight

scala> val zipped = fastAverage.takeRight(7) zip slowAverage
zipped: List[(Double, Double)] = List((6.5,7.5), (5.5,6.5), (5.0,5.75), (5.5,5.5), (6.5,5.75), (7.5,6.5), (8.5,7.5))

取压缩平均值的差值。从负到正(>=0)的变化表明快速平均线大于慢速平均线,即看涨移动平均线交叉。

scala> zipped.map(x => x._1 - x._2)
res44: List[Double] = List(-1.0, -1.0, -0.75, 0.0, 0.75, 1.0, 1.0)
于 2013-04-20T05:55:34.187 回答