量化分析第一步是取得資料。股票軟體 (如通達信) 在本機保留日線資料檔 (`.day`),非程式設計師無 VB/VC 環境,但人人有 Office — Excel 內建 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
Excel 2003/2007/2010/2013/2016/2019/365 (含 64 位元,`LongPtr`/`Long` 需注意,上述代碼 32/64 位相容)。