본문 바로가기
개발일기

[개발일기] TA4J 이동평균 교차 전략이 뭐지?

by 햄리뮤 2025. 3. 24.
반응형

지금 하고있는 프로젝트에서 TA4J라이브러리를 사용하고있는데 이 라이브러리에서 이동평균교차 전략 분석 이라는 기능을 제공하고 있다. 이 "이동평균 교차" 에 대해서 알아보자!

Grok 에서 만든 이미지

이동평균 교차 전략

https://insightcampus.co.kr/2019/01/11/%EA%B8%B0%EC%88%A0%EC%A0%81%EB%B6%84%EC%84%9D-2-%EA%B8%B0%EC%88%A0%EC%A0%81-%EB%B6%84%EC%84%9D-%EC%9D%B4%EB%8F%99%ED%8F%89%EA%B7%A0-%EA%B5%90%EC%B0%A8-%EC%A0%84%EB%9E%B5%EC%9D%98-%EC%84%B1/

이동평균선(Moving Average)은 일정 기간 동안의 가격 평균을 계산한 값으로, 주식 가격의 변동성을 부드럽게 표현해 추세를 파악하는데 사용된다.

이동평균 교차 전략은 두 가지 이동평균선(단기와 장기)을 비교해 매매를 결정한다.

https://blog.naver.com/soluweb/220152595486

  • 매수 신호: 단기 이동평균선이 장기 이동평균선을 위로 교차할 때 (상향 돌파, Crossed Up).
  • 매도 신호: 단기 이동평균선이 장기 이동평균선을 아래로 교차할 때(하향 돌파, Crossed Down).

이 전략은 주식 가격이 상승 추세로 전환될 때 매수하고, 하락 추세로 전환될 때 매도하려는 기본적인 트렌드 전략 이라고 한다!

  public static void analyzeSMA(BarSeries series) {
    ClosePriceIndicator closePrice = new ClosePriceIndicator(series);

    // Bar = 10 * 5 = 50분의 이동평균 (내가 갖고있는 데이터가 5분간격의 데이터이기 때문)
    SMAIndicator shortSma = new SMAIndicator(closePrice, 10);
    // Bar = 30 * 5 = 150분의 이동평균
    SMAIndicator longSma = new SMAIndicator(closePrice, 30);

    // 전략 생성: 단기 이평선이 장기 이평선을 상향 돌파할 때 매수
    Rule buyingRule = new CrossedUpIndicatorRule(shortSma, longSma);
    // 전략 생성: 단기 이평선이 장기 이평선을 하향 돌파할 때 매도
    Rule sellingRule = new CrossedDownIndicatorRule(shortSma, longSma);

    Strategy strategy = new BaseStrategy(buyingRule, sellingRule);

    // 전략 테스트
    BarSeriesManager seriesManager = new BarSeriesManager(series);
    TradingRecord tradingRecord = seriesManager.run(strategy);

    // 결과 분석
    System.out.println("시작 인덱스: " + series.getBeginIndex() + ", 종료 인덱스: " + series.getEndIndex());
    System.out.println("거래 횟수: " + tradingRecord.getPositionCount());

    // 각 거래 정보 출력
    for (Position position : tradingRecord.getPositions()) {
      Bar entryBar = series.getBar(position.getEntry().getIndex());
      Bar exitBar = series.getBar(position.getExit().getIndex());

      System.out.println("매수: " + entryBar.getDateName() + " 가격: " + position.getEntry().getAmount());
      System.out.println("매도: " + exitBar.getDateName() + " 가격: " + position.getExit().getAmount());

      Num profit = position.getGrossProfit();
      System.out.println("수익: " + profit + " (" + profit.multipliedBy(series.numOf(100)) + "%)");
      System.out.println("-----------------------");
    }
  }

 

결과값

시작 인덱스: 0, 종료 인덱스: 50
거래 횟수: 1
매수: 2025-03-06 14:50 가격: 397.00
매도: 2025-03-06 15:20 가격: 398.50
수익: 1.50 (0.38%)

 

 

참고 문헌

https://blog.naver.com/soluweb/220152595486

 

제3장 1절: 이동평균선 원리,이동평균선,주가 예측방법

3장 : 이동평균선 1절_이동평균선 원리 r   이동평균선은 일별 주식의 가격을 산술평균으로 산출...

blog.naver.com

 

반응형

댓글