กรอบป้องกันความเสี่ยงและการปฏิบัติตามข้อกำหนด
จำกัดขนาดสถานะ ตรวจสอบตราสารต้องห้าม และบันทึกการตรวจสอบ
กรอบป้องกันความเสี่ยงและการปฏิบัติตามข้อกำหนด เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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'))
การตรวจสอบกฎ Pattern-Day-Trader
ใน US บัญชีที่มีเงินน้อยกว่า USD 25,000 จะถูกจัดว่าเป็นผู้ค้ารายวันตามเกณฑ์ (PDT) หากทำการซื้อขายไปกลับตั้งแต่ 4 ครั้งขึ้นไปภายใน 5 วันทำการ เอเจนต์ต้องตรวจสอบความถี่ในการซื้อขายก่อนแนะนำการซื้อขายภายในวันเดียวกัน
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)
การปรับขนาดการซื้อขายตามความผันผวน
สินทรัพย์ที่มีความผันผวนสูงกว่ามีความเสี่ยงมากกว่า ให้ปรับขนาดสถานะการลงทุนแบบผกผันกับความผันผวน หากสินทรัพย์มีความผันผวนเป็นสองเท่าของค่าพื้นฐาน ให้แนะนำขนาดสถานะการลงทุนเพียงครึ่งหนึ่ง
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))
กฎ Pattern Day Trader (PDT) จำกัดสิ่งใด
กฎ PDT เป็นข้อกำหนดด้านกฎระเบียบของ US ที่เอเจนต์การเงินซึ่งทำงานในตลาด US ต้องปฏิบัติตาม การทำความเข้าใจกฎนี้ช่วยป้องกันไม่ให้เอเจนต์ทำให้เกิดข้อจำกัดกับบัญชีมาร์จิ้นโดยไม่ได้ตั้งใจ
สรุปแนวป้องกันด้านความเสี่ยงและการปฏิบัติตามข้อกำหนด
แนวป้องกันสำหรับเอเจนต์ด้านการเงินประกอบด้วย ขีดจำกัดขนาดสถานะการลงทุน รายการตราสารต้องห้าม การตรวจสอบกฎ PDT การกำหนดขนาดตามความผันผวน การจับคู่ความเหมาะสม กับระดับความเสี่ยง การบันทึกการตรวจสอบ สำหรับคำแนะนำทุกครั้ง และ การแทรกข้อความปฏิเสธความรับผิด ในผลลัพธ์ทั้งหมด
เรียกใช้แนวป้องกันทั้งหมดก่อนสรุปคำแนะนำการซื้อขายทุกครั้ง
คำถามที่พบบ่อย
บทเรียน “กรอบป้องกันความเสี่ยงและการปฏิบัติตามข้อกำหนด” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “กรอบป้องกันความเสี่ยงและการปฏิบัติตามข้อกำหนด” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “กรอบป้องกันความเสี่ยงและการปฏิบัติตามข้อกำหนด”
จำกัดขนาดสถานะ ตรวจสอบตราสารต้องห้าม และบันทึกการตรวจสอบ คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “กรอบป้องกันความเสี่ยงและการปฏิบัติตามข้อกำหนด” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม
ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การผสาน API ข้อมูลตลาด
- เครื่องมือเอเจนต์สำหรับวิเคราะห์พอร์ตการลงทุน
- กรอบป้องกันความเสี่ยงและการปฏิบัติตามข้อกำหนด
- การทดสอบย้อนหลังการตัดสินใจของเอเจนต์