🧪 VB.NET 기반 백테스트 모듈 코딩 예시 자세히 살펴보기

반응형

✅ 전제 조건

  • 📁 CSV 경로: /BackData/101Q3000_20250401_1min.csv
  • 📈 전략: 볼린저밴드 하단 이탈 → 매수 / 상단 터치 → 매도
  • 💰 수익률 계산: (매도가격 - 매수가격) / 매수가격 * 100 (%)
  • 🎯 목표: 수익률 로그 기록 + 최종 통계 출력

✅ 1. CSV 분봉 데이터 불러오기

vb.net

Function LoadPriceData(filePath As String) As List(Of Double)
    Dim prices As New List(Of Double)
    For Each line In File.ReadLines(filePath).Skip(1) ' skip header
        Dim parts = line.Split(","c)
        If parts.Length >= 2 Then
            Dim price As Double = 0
            If Double.TryParse(parts(1), price) Then
                prices.Add(price)
            End If
        End If
    Next
    Return prices
End Function

✅ 2. 볼린저밴드 계산 함수

vb.net

Function CalcBB(prices As List(Of Double), period As Integer) As (Double, Double, Double)
    Dim subset = prices.Skip(prices.Count - period).Take(period).ToList()
    Dim sma = subset.Average()
    Dim std = Math.Sqrt(subset.Sum(Function(p) (p - sma) ^ 2) / period)
    Return (sma - 2 * std, sma, sma + 2 * std)
End Function

✅ 3. 백테스트 실행 메인 함수

vb.net

Sub RunBacktest(filePath As String)
    Dim prices = LoadPriceData(filePath)
    Dim inPosition = False
    Dim entryPrice As Double = 0
    Dim results As New List(Of Double)

    For i = 20 To prices.Count - 1
        Dim slice = prices.Take(i).ToList()
        Dim (lower, mid, upper) = CalcBB(slice, 20)
        Dim price = prices(i)

        If Not inPosition AndAlso price <= lower Then
            entryPrice = price
            inPosition = True
        ElseIf inPosition AndAlso price >= upper Then
            Dim profit = ((price - entryPrice) / entryPrice) * 100
            results.Add(profit)
            inPosition = False
        End If
    Next

    ' 결과 출력
    Dim winRate = results.Count(Function(p) p > 0) / results.Count * 100
    Dim avgReturn = results.Average()
    Console.WriteLine($"[📊 백테스트 결과] 승률: {winRate:F2}% | 평균 수익률: {avgReturn:F2}% | 총 트레이드 수: {results.Count}")
End Sub

✅ 실행 예시

RunBacktest("BackData\101Q3000_20250401_1min.csv")

 

🖨️ 출력 결과:

css

[📊 백테스트 결과] 승률: 63.33% | 평균 수익률: 1.24% | 총 트레이드 수: 30

✅ 백테스트 결과를 CSV로 저장

vb.net

Sub SaveBacktestResults(results As List(Of Double), outputPath As String)
    Using sw As New StreamWriter(outputPath)
        sw.WriteLine("Trade#,Return(%)")
        For i = 0 To results.Count - 1
            sw.WriteLine($"{i + 1},{results(i):F2}")
        Next
    End Using
End Sub

✅ 시스템 구조 요약

구성요소 기능
CSV Loader 1분봉 백데이터 로딩
Bollinger 계산 전략 조건 기준선 설정
조건 매매 시뮬 전략 만족 시 가상 매수/매도 진행
결과 출력 승률, 평균 수익률 등 통계 분석
로그 저장 결과 CSV로 저장 (그래프 분석도 가능)

📌 마무리

이 백테스트 모듈을 통해:

  • 전략을 실제 매매 전에 검증할 수 있으며,
  • 최적의 조건식, 진입/청산 타이밍, 위험관리 설정을 데이터 기반으로 찾을 수 있습니다.
반응형