This repository has been archived on 2025-06-07. You can view files and clone it, but cannot push or open issues or pull requests.
2025-05-06 21:23:04 +09:00

38 lines
1.3 KiB
Python

'''
risk_manage_engine/calculators/atr.py
ATR (Average True Range)를 계산하는 함수 모듈입니다.
- 목적: 주가의 평균적인 일일 변동폭을 계산하여 **변동성 기반 리스크**를 수치화함
- 특징: 종가 대비 고가/저가 차이, 전일 종가와의 차이 등을 종합적으로 고려한 지표
- 출력: 지정된 기간 동안의 평균 TR (변동폭)
'''
import pandas as pd
import numpy as np
def calculate_atr(df: pd.DataFrame, period: int = 14) -> float:
"""
Average True Range (ATR) 계산 함수
Parameters:
df (pd.DataFrame): CDS 데이터 (필수: 'high', 'low', 'close')
period (int): ATR 계산에 사용할 기간 (기본: 14일)
Returns:
float: 평균 True Range (최근 period일 기준)
"""
df = df.copy()
df['prev_close'] = df['close'].shift(1)
# True Range 계산: 세 가지 중 가장 큰 값
df['tr1'] = df['high'] - df['low']
df['tr2'] = (df['high'] - df['prev_close']).abs()
df['tr3'] = (df['low'] - df['prev_close']).abs()
df['true_range'] = df[['tr1', 'tr2', 'tr3']].max(axis=1)
# ATR: True Range의 이동 평균
atr = df['true_range'].rolling(window=period).mean().iloc[-1]
return round(atr, 4) if not np.isnan(atr) else 0.0