參考這一篇:「How to group a time series by interval (OHLC bars) with LINQ」。
我這裡使用 C#.NET 實作,並作了一些小小的修正,使之確實可以執行,並可從期交所所下載的原始 Tick 資料檔,經由前置的解壓縮、轉換為 Tick 物件型態,再透過該實作邏輯,就可以將 Tick 物件依所指定的時間週期 (time-interval),群組為所謂的「分K棒」(其實,正確的稱呼應該為 OHCK Bar)。
這裡也不禁對 LINQ 實作技術感到讚嘆! 它讓中間層 (middleware)的物件結構與資料來源 (data-sources)的存取,變得更為簡單太多了,所以也使得 Tick 轉K棒 的轉換邏輯,可以利用相當簡潔的語法 (類 SQL 語法),而達成該功能的實現。
底下的程式碼並未包含前述所提包括解壓縮、轉換為 Tick 物件等邏輯,只從一群已有 Tick 資料的 Collection 集合 (型態為 IEnumerable),依據所指定的 Interval 時間間隔,轉換為 K棒 (含開、高、收、低、量)的實作邏輯。
Tick 與 OHLC-Bar(K棒) 物件結構為:
public class Tick { public string Symbol { get; set; } //商品代號 public DateTime Timestamp { get; set; } //成交日期時間 public decimal Price { get; set; } //成交價格 public uint volume { get; set; } //成交量 } public class OHLCBar { public string Symbol { get; set; } //商品代號 public decimal OPEN { get;set; } //開盤價 public decimal CLOSE { get; set; } //收盤價 public decimal HIGH { get; set; } //最高價 public decimal LOW { get; set; } //最低價 public uint VOLUME { get; set; } //成交量 public DateTime BeginTime { get; set; } //開始時間 public TimeSpan Interval { get; set; } //時間區間 } |