如何在FSharp.Data中select一个时间段?

How to select a time period in the in FSharp.Data?

我写了这个脚本来绘制历史财务数据:

open FSharp.Data
#load "C:\Users\Nick\Documents\Visual Studio 2013\Projects\TryFsharp\packages\FSharp.Charting.0.90.9\FSharp.Charting.fsx"
open FSharp.Charting
open System

let plotprice nasdaqcode =
    let url = "http://ichart.finance.yahoo.com/table.csv?s="+nasdaqcode
    let company = CsvFile.Load(url)
    let companyPrices = [ for r in company.Rows -> r.GetColumn "Date", r.GetColumn "Close" ]
    (companyPrices 
        |> List.sort 
        |> Chart.Line).WithTitle(nasdaqcode, InsideArea=false)

plotprice "MSFT"
plotprice "ORCL"
plotprice "GOOG"
plotprice "NTES"

这很好用。

问题:

  1. 有些数据是从1986年开始的,有些是从2000年开始的,我想把2000年到2015年的数据画出来,这个时间段怎么select?

  2. 鼠标悬停在图表上是否可以显示时间?

1) GetColumn 获取一个字符串。您需要先将其转换为 DateTime 并简单地进行比较。即

let plotprice nasdaqcode =
    let url = "http://ichart.finance.yahoo.com/table.csv?s="+nasdaqcode
    let company = CsvFile.Load(url)
    let companyPrices = [ for r in company.Rows -> DateTime.Parse(r.GetColumn "Date"), r.GetColumn "Close" ]
    (companyPrices 
        |> List.filter (fun (date, _) -> date > DateTime(2000, 1, 1))
        |> List.sort 
        |> Chart.Line).WithTitle(nasdaqcode, InsideArea=false)

2) 您可以尝试添加标签(虽然不确定如何在悬停时做...)

let plotprice nasdaqcode =
    let url = "http://ichart.finance.yahoo.com/table.csv?s="+nasdaqcode
    let company = CsvFile.Load(url)
    let companyPrices = [ for r in company.Rows -> DateTime.Parse(r.GetColumn "Date"), r.GetColumn "Close" ]
    (companyPrices 
        |> List.filter (fun (date, _) -> date > DateTime(2000, 1, 1))
        |> List.sort 
        |> fun data -> Chart.Line(data, Labels=(Seq.map (fst >> string) data))).WithTitle(nasdaqcode, InsideArea=false)

如果您正在访问 Yahoo 数据,那么最好使用 CsvProvider 而不是使用 F# Data 中的 CsvFile。您可以找到有关 the type provider here 的更多信息。遗憾的是,标准 F# 数据库中的命名和 TryFSharp.org 上的命名不同,所以这有点令人困惑。

CSV 类型提供程序将自动推断类型:

open FSharp.Data
open FSharp.Charting
open System

// Generate type based on a sample
type Stocks = CsvProvider<"http://ichart.finance.yahoo.com/table.csv?s=FB">

let plotprice nasdaqcode =
    let url = "http://ichart.finance.yahoo.com/table.csv?s=" + nasdaqcode
    let company = Stocks.Load(url)
    // Now you can access the columns in a statically-typed way
    // and the types of the columns are inferred from the sample
    let companyPrices = [ for r in company.Rows -> r.Date, r.Close ]

    // If you want to do filtering, you can now use the `r.Date` property
    let companyPrices = 
      [ for r in company.Rows do
          if r.Date > DateTime(2010, 1, 1) && r.Date < DateTime(2011, 1, 1) then
            yield r.Date, r.Close ]

    // Charting as before
    companyPrices |> (...)

我不确定 F# Charting 库是否有一种方法可以根据鼠标指针位置显示价格 - 它基于标准 .NET Windows Forms 图表控件,所以您可以看看at the documentation for the underlying library.