위험 및 규정 준수 안전장치
포지션 규모 제한, 금지 금융상품 점검, 감사 기록을 설정합니다.
위험 및 규정 준수 안전장치은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
금융 에이전트에 강력한 안전장치가 필요한 이유
제한 없이 어떤 거래든 추천할 수 있는 금융 에이전트는 사용자를 막대한 손실이나 규제 위반에 노출할 수 있습니다. 인간 자문가와 달리 에이전트는 추천 로직을 일관되게 실행합니다. 따라서 버그나 잘못된 설정이 모든 사용자에게 영향을 미칠 수 있습니다.
강력한 안전장치는 최악의 결과를 방지합니다.
포지션 규모 제한
에이전트가 포트폴리오의 어느 한 자산에 투자하도록 추천할 수 있는 금액을 제한합니다. 일반적인 규칙은 단일 포지션이 전체 포트폴리오 가치의 20%를 초과하지 않아야 한다는 것입니다. 이를 통해 치명적인 집중 위험을 방지합니다.
MAX_POSITION_PCT = 0.20 # 20% of portfolio max per asset
def check_position_size(ticker: str, trade_usd: float,
portfolio_value: float) -> dict:
proposed_pct = trade_usd / portfolio_value
if proposed_pct > MAX_POSITION_PCT:
return {
'allowed': False,
'reason': (
f'Position size {proposed_pct:.1%} exceeds limit {MAX_POSITION_PCT:.1%}. '
f'Max trade for this portfolio: USD {portfolio_value * MAX_POSITION_PCT:.0f}'
)
}
return {'allowed': True, 'position_pct': round(proposed_pct, 4)}
if __name__ == '__main__':
print('Large trade:', check_position_size('TSLA', 30000, 100000))
print('Small trade:', check_position_size('TSLA', 10000, 100000))
거래 금지 상품 목록
에이전트가 추천해서는 안 되는 상품 목록을 유지합니다. 예를 들어 페니 주식, 레버리지가 높은 ETF, 제재 대상 증권, 개인 투자자에게 적합하지 않은 상품 등이 있습니다.
PROHIBITED_TICKERS = {
'UVXY', # VIX leveraged ETF — too volatile
'TVIX', # Delisted leveraged VIX
'JDST', # 3x leveraged gold miners short
'NUGT', # 3x leveraged gold miners long
'YANG', # 3x China short
}
PROHIBITED_TYPES = {'penny_stock', 'leveraged_3x', 'inverse_volatility'}
def check_prohibited_instrument(ticker: str) -> dict:
if ticker.upper() in PROHIBITED_TICKERS:
return {
'allowed': False,
'reason': f'{ticker} is on the prohibited instruments list'
}
return {'allowed': True}
if __name__ == '__main__':
print("Checking UVXY:", check_prohibited_instrument('UVXY'))
print("Checking AAPL:", check_prohibited_instrument('AAPL'))
패턴 데이 트레이더 규칙 확인
US에서는 USD 25,000 미만인 계좌가 영업일 5일 동안 왕복 거래를 4회 이상 하면 패턴 데이 트레이더(PDT)로 분류됩니다. 에이전트는 당일 거래를 추천하기 전에 거래 빈도를 확인해야 합니다.
from datetime import datetime, timedelta, timezone
def check_pdt_rule(account_value_usd: float,
recent_trades: list[dict]) -> dict:
if account_value_usd >= 25_000:
return {'at_risk': False, 'reason': 'Account above PDT threshold'}
cutoff = datetime.now(timezone.utc) - timedelta(days=5)
recent = [
t for t in recent_trades
if datetime.fromisoformat(t['timestamp']) > cutoff
and t.get('is_day_trade', False)
]
if len(recent) >= 3:
return {
'at_risk': True,
'day_trades_in_5_days': len(recent),
'reason': (
f'Account has {len(recent)} day trades in the last 5 days. '
f'A 4th would trigger the PDT restriction.'
)
}
return {'at_risk': False, 'day_trades_in_5_days': len(recent)}
if __name__ == '__main__':
now = datetime.now(timezone.utc)
trades = [
{'timestamp': (now - timedelta(days=1)).isoformat(), 'is_day_trade': True},
{'timestamp': (now - timedelta(days=2)).isoformat(), 'is_day_trade': True},
{'timestamp': (now - timedelta(days=3)).isoformat(), 'is_day_trade': True},
]
result = check_pdt_rule(account_value_usd=10000, recent_trades=trades)
print('PDT rule check:', result)
변동성 기반 거래 규모 조정
변동성이 큰 자산일수록 위험이 큽니다. 변동성에 반비례하도록 포지션 규모를 조정합니다. 자산의 변동성이 기준값의 2배라면 포지션 규모는 절반으로 제안합니다.
import yfinance as yf, numpy as np
BASELINE_VOL = 0.15 # 15% annualized vol — S&P 500 average
def volatility_scaled_size(ticker: str, base_allocation_usd: float) -> dict:
hist = yf.Ticker(ticker).history(period='1y')['Close'].pct_change().dropna()
vol = float(hist.std() * np.sqrt(252))
scaling_factor = BASELINE_VOL / max(vol, 0.01)
adjusted_usd = base_allocation_usd * scaling_factor
return {
'ticker': ticker,
'annualized_vol': round(vol, 4),
'scaling_factor': round(scaling_factor, 3),
'adjusted_size_usd': round(adjusted_usd, 2),
'note': 'High-vol asset: position scaled down' if scaling_factor < 1 else 'Normal sizing'
}모든 추천의 감사 기록
모든 거래 추천은 수락되었는지 거부되었는지와 관계없이 전체 맥락과 함께 기록해야 합니다. 여기에는 시간 기록, 사용자 ID, 추천 조치, 실행한 안전장치 확인, 결과가 포함됩니다. 이를 통해 규정 준수 검토에 필요한 완전한 감사 추적 기록을 만들 수 있습니다.
import json, hashlib, time, logging
audit_logger = logging.getLogger('financial_agent.audit')
audit_logger.setLevel(logging.INFO)
def audit_log(user_id: str, action: str, ticker: str,
amount_usd: float, guardrail_results: list[dict],
approved: bool, reason: str):
log_entry = {
'timestamp': time.time(),
'user_id': user_id,
'action': action,
'ticker': ticker,
'amount_usd': amount_usd,
'guardrails': guardrail_results,
'approved': approved,
'reason': reason,
'entry_id': hashlib.md5(f'{user_id}{time.time()}'.encode()).hexdigest()[:12]
}
audit_logger.info(json.dumps(log_entry))
if __name__ == '__main__':
import sys
audit_logger.addHandler(logging.StreamHandler(sys.stdout))
audit_log('user_42', 'BUY', 'AAPL', 5000.0,
[{'check': 'position_size', 'allowed': True}],
True, 'Within limits')
면책 고지 삽입
에이전트의 모든 금융 출력에는 개인 맞춤형 금융 조언이 아니라는 면책 고지가 포함되어야 합니다. LLM이 일관되게 추가할 것이라고 기대하지 말고 이 고지를 자동으로 삽입합니다.
FINANCIAL_DISCLAIMER = (
'\n\n---\n'
'DISCLAIMER: This output is generated by an AI agent and is for '
'informational purposes only. It does not constitute personalized financial advice. '
'Past performance does not guarantee future results. '
'Please consult a licensed financial advisor before making investment decisions.'
)
def inject_disclaimer(response: str) -> str:
if 'DISCLAIMER' not in response:
return response + FINANCIAL_DISCLAIMER
return response
if __name__ == '__main__':
response = 'AAPL is currently trading at $150 with strong upward momentum.'
print(inject_disclaimer(response))
모든 안전장치를 순서대로 실행
모든 확인을 순서대로 실행하고 이유와 함께 통과 또는 실패 판정을 반환하는 단일 guardrail_check() 함수를 만듭니다. 에이전트는 추천을 확정하기 전에 이 함수를 호출합니다.
def guardrail_check(user_id: str, ticker: str, action: str,
amount_usd: float, portfolio_value: float,
account_value: float, recent_trades: list[dict]) -> dict:
checks = []
# 1. Prohibited instruments
prohibited = check_prohibited_instrument(ticker)
checks.append({'check': 'prohibited_instrument', **prohibited})
if not prohibited['allowed']:
audit_log(user_id, action, ticker, amount_usd, checks, False, prohibited['reason'])
return {'approved': False, 'reason': prohibited['reason'], 'checks': checks}
# 2. Position size
size_check = check_position_size(ticker, amount_usd, portfolio_value)
checks.append({'check': 'position_size', **size_check})
if not size_check['allowed']:
audit_log(user_id, action, ticker, amount_usd, checks, False, size_check['reason'])
return {'approved': False, 'reason': size_check['reason'], 'checks': checks}
# 3. PDT rule
if action == 'day_trade':
pdt = check_pdt_rule(account_value, recent_trades)
checks.append({'check': 'pdt_rule', **pdt})
if pdt['at_risk']:
return {'approved': False, 'reason': pdt['reason'], 'checks': checks}
audit_log(user_id, action, ticker, amount_usd, checks, True, 'All guardrails passed')
return {'approved': True, 'checks': checks}위험 성향별 적합성 확인
추천을 사용자가 밝힌 위험 감수 수준에 맞춥니다. 보수적인 투자자에게 베타가 높은 성장주를 추천해서는 안 되며, 공격적인 투자자는 더 높은 변동성을 감당할 수 있습니다.
RISK_PROFILES = {
'conservative': {'max_beta': 0.8, 'max_vol_pct': 15},
'moderate': {'max_beta': 1.2, 'max_vol_pct': 25},
'aggressive': {'max_beta': 2.0, 'max_vol_pct': 50},
}
def suitability_check(risk_profile: str, ticker_beta: float,
ticker_vol_pct: float) -> dict:
limits = RISK_PROFILES.get(risk_profile, RISK_PROFILES['moderate'])
if ticker_beta > limits['max_beta']:
return {
'suitable': False,
'reason': f'Beta {ticker_beta:.2f} exceeds {risk_profile} limit {limits["max_beta"]}'
}
if ticker_vol_pct > limits['max_vol_pct']:
return {
'suitable': False,
'reason': f'Volatility {ticker_vol_pct:.1f}% exceeds {risk_profile} limit {limits["max_vol_pct"]}%'
}
return {'suitable': True}
if __name__ == '__main__':
print('Conservative check:', suitability_check('conservative', ticker_beta=1.5, ticker_vol_pct=20))
print('Aggressive check: ', suitability_check('aggressive', ticker_beta=1.5, ticker_vol_pct=20))
추천 빈도 제한
거래 추천을 지나치게 자주 생성하는 에이전트는 과도한 거래를 부추기며, 이는 비용과 위험을 증가시킵니다. 동일한 자산에 대한 추천 사이에 대기 시간을 적용합니다.
import time
last_recommendation: dict[str, float] = {} # ticker -> timestamp
COOLDOWN_HOURS = 24
def check_recommendation_cooldown(ticker: str) -> dict:
last = last_recommendation.get(ticker, 0)
elapsed_hours = (time.time() - last) / 3600
if elapsed_hours < COOLDOWN_HOURS:
remaining = COOLDOWN_HOURS - elapsed_hours
return {
'allowed': False,
'reason': f'Recommendation cooldown: {remaining:.1f} hours remaining for {ticker}'
}
return {'allowed': True}
def record_recommendation(ticker: str):
last_recommendation[ticker] = time.time()
if __name__ == '__main__':
print('Before recommending:', check_recommendation_cooldown('AAPL'))
record_recommendation('AAPL')
print('Right after recommending:', check_recommendation_cooldown('AAPL'))
손절매 및 낙폭 회로 차단기
개별 포지션 제한을 넘어 포트폴리오 수준의 회로 차단기를 구현합니다. 하루 동안 전체 포트폴리오가 X%를 초과하여 손실을 기록하면, 사람이 상황을 검토할 때까지 에이전트가 새로운 매수 추천을 중단하도록 합니다.
MAX_DAILY_DRAWDOWN_PCT = 0.05 # 5% daily loss limit
def check_daily_drawdown(portfolio_start_of_day: float,
portfolio_current: float) -> dict:
daily_loss = (portfolio_current - portfolio_start_of_day) / portfolio_start_of_day
if daily_loss < -MAX_DAILY_DRAWDOWN_PCT:
return {
'circuit_breaker': True,
'daily_loss_pct': round(daily_loss * 100, 2),
'reason': (
f'Portfolio down {abs(daily_loss)*100:.1f}% today. '
f'Agent suspended — human review required.'
)
}
return {'circuit_breaker': False, 'daily_loss_pct': round(daily_loss * 100, 2)}
if __name__ == '__main__':
print('Small loss day:', check_daily_drawdown(100000, 98000))
print('Big loss day: ', check_daily_drawdown(100000, 92000))
패턴 데이 트레이더(PDT) 규칙은 무엇을 제한합니까?
PDT 규칙은 US 시장에서 운영되는 금융 에이전트가 준수해야 하는 US 규제 요건입니다. 이 규칙을 이해하면 에이전트가 실수로 증거금 계좌 제한을 초래하는 일을 방지할 수 있습니다.
위험 및 COMPLIANCE 안전장치 요약
금융 에이전트의 안전장치에는 포지션 규모 제한, 거래 금지 금융 상품 목록, PDT 규칙 확인, 변동성에 따른 규모 조정, 위험 프로필에 따른 적합성 매칭, 모든 추천에 대한 감사 로깅, 모든 출력에 대한 면책 고지 삽입이 포함됩니다.
거래 추천을 최종 확정하기 전에 항상 모든 안전장치를 실행해야 합니다.
자주 묻는 질문
“위험 및 규정 준수 안전장치” 강의는 무료인가요?
네 — “위험 및 규정 준수 안전장치” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
“위험 및 규정 준수 안전장치”에서 뭘 배우나요?
포지션 규모 제한, 금지 금융상품 점검, 감사 기록을 설정합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Agents을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“위험 및 규정 준수 안전장치” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 시장 데이터 API 통합
- 포트폴리오 분석 에이전트 도구
- 위험 및 규정 준수 안전장치
- 에이전트 결정 백테스트