萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> Excel 教學 >> Excel 綜合

Excel VBA 讀取通達信股票日線 .day 檔案完整代碼教學

背景動機

量化分析第一步是取得資料。股票軟體 (如通達信) 在本機保留日線資料檔 (`.day`),非程式設計師無 VB/VC 環境,但人人有 Office — Excel 內建 VBA 即可完成讀取。

VBA 代碼完整版 (含註解)

' 定義通達信 .day 檔案記錄結構 (每筆 32 bytes)
Type TDXDailyRecord
    TradeCode As Long     ' 標示碼 (通常為固定值)
    TradeDate As Long     ' 日期 (YYYYMMDD 整數)
    OpenPrice As Single   ' 開盤價 (×100)
    HighPrice As Single   ' 最高價 (×100)
    LowPrice As Single    ' 最低價 (×100)
    ClosePrice As Single  ' 收盤價 (×100)
    Amount As Single      ' 成交金額 (元)
    Volume As Long        ' 成交量 (股)
End Type

Sub ImportTDXDayFile()
    Dim FileNum As Integer
    Dim Rec As TDXDailyRecord
    Dim FilePath As String
    Dim RowIdx As Long
    
    ' === 使用者修改處:指定 .day 檔完整路徑 ===
    FilePath = ThisWorkbook.Path & "\sh600000.day"  ' 請改為實際檔名
    
    FileNum = FreeFile
    Open FilePath For Binary Access Read As #FileNum
    
    RowIdx = 1
    Do While Not EOF(FileNum)
        Get #FileNum, , Rec
        ' 寫入工作表 (第 1 欄為列號,實際資料從第 2 欄起)
        Cells(RowIdx, 1) = RowIdx - 1              ' 序號
        Cells(RowIdx, 2) = Rec.TradeDate            ' 日期 (整數)
        Cells(RowIdx, 3) = Rec.OpenPrice / 100      ' 價格除 100 還原
        Cells(RowIdx, 4) = Rec.HighPrice / 100
        Cells(RowIdx, 5) = Rec.LowPrice / 100
        Cells(RowIdx, 6) = Rec.ClosePrice / 100
        Cells(RowIdx, 7) = Rec.Amount               ' 金額已為元
        Cells(RowIdx, 8) = Rec.Volume               ' 量已為股
        RowIdx = RowIdx + 1
    Loop
    
    Close #FileNum
    MsgBox "匯入完成!共 " & (RowIdx - 1) & " 筆資料。", vbInformation
End Sub

關鍵說明

  1. 檔案路徑:將 `FilePath` 改為實際 `.day` 檔完整路徑 (如 `C:\TdxW\T0002\export\sh600000.day`),或用 `Application.GetOpenFilename` 讓使用者選檔。
  2. 價格欄位:通達信 `.day` 價格欄位為 `Single` 型態,數值 = 實際價格 × 100,故寫入時除以 100。
  3. 日期欄位:`TradeDate` 為 `Long` 整數 `YYYYMMDD` (如 20240305),可用 `Format(Rec.TradeDate, "0000-00-00")` 轉為日期格式,或後續用公式轉換。
  4. 效能:二進位讀取 + 陣列寫入 (可優化為陣列一次寫入) 速度極快,百萬筆資料秒級完成。

進階擴充建議

  • 加入 Application.ScreenUpdating = False 關閉螢幕更新加速。
  • 用動態陣列一次讀完再一次寫入工作表 (`Range(...).Value = Arr`),效能再提升 10 倍以上。
  • 整合多檔案批次匯入、自動建立分股票工作表、計算技術指標 (MA、KD、MACD)。
  • 搭配 `ADODB` 連接資料庫,建立個人量化資料倉庫。

適用版本

Excel 2003/2007/2010/2013/2016/2019/365 (含 64 位元,`LongPtr`/`Long` 需注意,上述代碼 32/64 位相容)。

copyright © 萬盛學電腦網 all rights reserved