diff --git a/.agent/adl.yaml b/.agent/adl.yaml deleted file mode 100644 index 0180cc9..0000000 --- a/.agent/adl.yaml +++ /dev/null @@ -1,18 +0,0 @@ -architecture_decisions: - - id: ADL-001 - title: "하이브리드 처리 및 선택적 섹션 추출 (429 에러 해결)" - context: "10-K 원본 전체를 LLM에 전송할 경우 Token 한도 초과 및 Rate Limit(429) 발생." - decision: "정규식으로 Item 7(MD&A), Item 1A 등 핵심 텍스트만 추출(Targeted Parsing). 정량 데이터(Item 8)는 yfinance로 대체 처리하여 토큰 사용량을 80% 이상 절감." - status: "Implemented" - - - id: ADL-002 - title: "10년 2단계(2-Stage) DCF 모델 채택" - context: "고성장 기업의 경우 일반적인 5년 DCF 모델은 영구 가치(Terminal Value)를 과대평가하는 왜곡 발생." - decision: "1~5년차는 예상 성장률 적용, 6~10년차는 영구 성장률(2.5%)까지 선형 하락(Fade)시키는 기관급 10년 모델 적용." - status: "Implemented" - - - id: ADL-003 - title: "금융 데이터 다중 폴백(Fallback) 시스템" - context: "S&P 500 이외의 주식은 yfinance 등에서 특정 재무 데이터가 누락되는 문제 발생." - decision: "yahooquery를 1순위로 사용하되, 실패 시 yfinance의 여러 속성(fast_info -> info -> balance_sheet)을 순차적으로 탐색(Fallback). 연간 데이터 누락 시 분기별 데이터(TTM) 합산 처리." - status: "Implemented" \ No newline at end of file diff --git a/.agent/architecture.mermaid b/.agent/architecture.mermaid deleted file mode 100644 index 6289070..0000000 --- a/.agent/architecture.mermaid +++ /dev/null @@ -1,30 +0,0 @@ -graph TD - User([User]) -->|Inputs: API Key, Email, Ticker| UI[Streamlit UI] - - subgraph Frontend/Backend Application - UI --> Tab1[10-K & MD&A Insights] - UI --> Tab2[DCF Valuation] - UI --> Tab3[Sector Analysis] - - Tab1 --> QualParser[Regex & BeautifulSoup Parser] - Tab2 --> QuantProcessor[Pandas Financial Processor] - Tab3 --> PeerProcessor[Comps Processor] - end - - subgraph External APIs - SEC[(SEC EDGAR Database)] - YF[(yfinance / yahooquery)] - LLM[Google Gemini 2.0 Flash] - end - - QualParser -->|Fetch 10-K HTML| SEC - QualParser -->|Cleaned Text (Item 1A, 7)| LLM - LLM -->|Qualitative Insights| Tab1 - LLM -->|Industry Outlook| Tab3 - - QuantProcessor -->|Fetch Financials| YF - PeerProcessor -->|Fetch Multiples| YF - YF -->|Raw Data| QuantProcessor - - QuantProcessor -->|DCF, Ratios| Tab2 - QuantProcessor -->|DuPont, Sankey| Tab1 \ No newline at end of file diff --git a/.agent/directory_map.md b/.agent/directory_map.md deleted file mode 100644 index 024a08a..0000000 --- a/.agent/directory_map.md +++ /dev/null @@ -1,14 +0,0 @@ -# Directory Map - -```text -FQDC Project/ -├── app.py # 메인 스트림릿 애플리케이션 로직 (UI, API 연동, 데이터 처리) -├── find_toc.py # SEC EDGAR 문서를 크롤링하여 목차(TOC) 위치를 식별하는 유틸리티 스크립트 -├── push_to_github.sh # GitHub 원격 저장소 자동 커밋/푸시 스크립트 -├── requirements.txt # 의존성 패키지 (streamlit, google-generativeai, yfinance 등) -├── README.md # 프로젝트 소개, 실행 방법 및 아키텍처 설명 -├── TECHNICAL_NOTES.md # 토큰 최적화 및 Rate Limit 대응 기술 문서 (ADL 기반) -├── .env.example # 환경변수 템플릿 파일 -├── .gitignore # Git 버전 관리 제외 목록 (가상환경, 로컬 설정 파일 등) -├── data/ # (런타임 생성) 추출된 10-K 항목별 JSON 캐시 저장 폴더 -└── .app_prefs.json # (런타임 생성) 사용자 환경설정(API Key, Email)을 임시 저장하는 파일 \ No newline at end of file diff --git a/.agent/flows.md b/.agent/flows.md deleted file mode 100644 index 3e0aea9..0000000 --- a/.agent/flows.md +++ /dev/null @@ -1,15 +0,0 @@ -# Flows - -본 애플리케이션은 **정성적 흐름(Qualitative Flow)**과 **정량적 흐름(Quantitative Flow)**을 완전히 분리하여 설계되었습니다. - -## 1. 정성 데이터 흐름 (Qualitative Flow) -1. **다운로드:** `sec-edgar-downloader`를 사용하여 입력받은 티커와 이메일로 가장 최신 10-K HTML 문서를 가져옵니다. -2. **파싱 및 클렌징:** HTML 문서에서 `lxml`과 `BeautifulSoup`을 사용해 테이블, 이미지, 스크립트를 제거하고 정규식으로 Item 1A(Risk Factors)와 Item 7(MD&A) 섹션만 추출합니다. -3. **캐싱 및 Chunking:** 추출된 텍스트를 로컬 디렉토리(`data/`)에 캐시로 저장하고, Gemini API 한도를 넘지 않도록 `smart_chunk()` 함수를 통해 중간 내용을 생략하여 압축합니다. -4. **LLM 추론:** Gemini API를 호출하여 경영진 전략, 주요 리스크, 핵심 인사이트를 생성하고 결과를 화면에 스트리밍합니다. - -## 2. 정량 데이터 흐름 (Quantitative Flow) -1. **검색 및 식별:** 사용자가 입력한 기업명으로 `yahooquery`를 통해 티커 및 거래소 식별자를 추론합니다. -2. **데이터 페칭:** `yfinance` 및 `yahooquery`를 통해 재무상태표, 손익계산서, 현금흐름표를 호출합니다. -3. **폴백(Fallback) 연산:** 특정 값이 없을 경우 `fast_info`, `info`, `quarterly` 데이터 순으로 TTM(Trailing 12 Months) 값을 대체 연산합니다. -4. **모델링 및 렌더링:** 전처리된 데이터를 바탕으로 Pandas 연산을 통해 DCF 내재가치, Piotroski F-Score, DuPont 분석 값을 산출하고 Plotly 차트(Radar, Sankey)로 시각화합니다. \ No newline at end of file diff --git a/.agent/infra.yaml b/.agent/infra.yaml deleted file mode 100644 index a562748..0000000 --- a/.agent/infra.yaml +++ /dev/null @@ -1,28 +0,0 @@ -infrastructure: - environment: - language: "Python 3.9+" - framework: "Streamlit >= 1.28.0" - - external_apis: - - name: "Google Gemini API" - library: "google-generativeai >= 0.8.0" - usage: "MD&A 인사이트 도출, 리스크 분석, 산업 전망 리포트 생성" - auth: "API Key (GOOGLE_API_KEY)" - - - name: "SEC EDGAR API" - library: "sec-edgar-downloader >= 5.0.0" - usage: "최신 10-K 공시 원문(HTML) 다운로드" - auth: "User-Agent Email (SEC_EDGAR_EMAIL)" - - - name: "Yahoo Finance API" - library: ["yfinance >= 0.2.40", "yahooquery >= 2.2.0"] - usage: "티커 검색, 재무제표, 현금흐름, 주식수, 경쟁사 멀티플 추출" - auth: "None Required" - - data_processing: - - name: "Pandas" - version: ">= 2.0.0" - - name: "BeautifulSoup4 / lxml" - version: ">= 4.12.0 / 4.9.0" - - name: "Plotly" - version: ">= 5.18.0" \ No newline at end of file diff --git a/.agent/manifest.json b/.agent/manifest.json deleted file mode 100644 index a434899..0000000 --- a/.agent/manifest.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "project_name": "10-K Financial Analyzer Dashboard", - "version": "1.0.0", - "description": "A hybrid architecture application unifying qualitative LLM-driven insights and quantitative financial valuation.", - "author": "shawnkim1997", - "entrypoint": "app.py", - "components": [ - "10-K Text Extraction & LLM Summarizer", - "10-Year 2-Stage DCF Valuation Model", - "Top-down Industry Comparables Analyzer" - ], - "technologies": [ - "Python", - "Streamlit", - "Gemini 2.0 Flash", - "yfinance", - "BeautifulSoup" - ] -} \ No newline at end of file diff --git a/.agent/prd.md b/.agent/prd.md deleted file mode 100644 index e3c663a..0000000 --- a/.agent/prd.md +++ /dev/null @@ -1,20 +0,0 @@ -# Product Requirements Document (PRD) -## 프로젝트명: All-in-One Financial Analysis Dashboard - -### 1. 프로젝트 비전 및 목표 -- **목표:** 주식 리서치 과정의 비효율성(방대한 공시 자료, 분산된 밸류에이션 모델 등)을 단일 워크플로우로 통합하는 하이브리드 대시보드 구축. -- **비전:** 개인 투자자와 금융 전문가(애널리스트, 포트폴리오 매니저 등)를 대상으로 하는 B2C/B2B SaaS 형태의 상용화. - -### 2. 핵심 가치 제안 (하이브리드 아키텍처) -- 언어 모델(Gemini)은 텍스트 중심의 정성적 분석에만 사용하여 토큰 비용을 최소화. -- 정량적 수치(DCF, 멀티플 등)는 무료 API(`yfinance`, `yahooquery`)에서 가져와 재무 데이터의 정확성 확보. - -### 3. 주요 기능 (Tabs) -1. **10-K & MD&A Insights:** SEC EDGAR에서 10-K(Item 1A, Item 7)를 가져와 Gemini로 경영진 어조, 전략적 변화, 잠재적 리스크 분석. -2. **3-Scenario DCF Valuation:** 10년 2단계 DCF 모델 (1~5년 성장, 6~10년 Fade). WACC, Terminal Growth 슬라이더 지원 및 Bull/Base/Bear 시나리오별 내재가치 도출. -3. **Top-Down Sector Analysis:** 특정 산업군 선택 시 경쟁사들의 멀티플(P/E, EV/EBITDA, P/B) 비교 및 Gemini 기반 거시적 산업 전망 생성. - -### 4. 핵심 UI/UX 요구사항 -- Streamlit 기반의 3개 탭 구성. -- 사이드바를 통한 전역 설정 (Google API Key, SEC Email, 다국어 지원 기업 검색). -- 정량 차트 시각화: Sankey Diagram, Radar Chart, F-Score 등 (Plotly 사용). \ No newline at end of file diff --git a/.agent/rules.md b/.agent/rules.md deleted file mode 100644 index 7c7599f..0000000 --- a/.agent/rules.md +++ /dev/null @@ -1,19 +0,0 @@ -# Project Development Rules - -### 1. 예외 및 폴백(Fallback) 처리 필수 -- 금융 API(`yfinance`, `yahooquery`)는 데이터 누락이 잦으므로, 항상 `try-except` 구문을 사용해 에러를 방지하세요. -- 데이터 조회 실패 시 빈 데이터프레임(`pd.DataFrame()`)이나 기본값(`0.0`, `None`)을 반환하도록 설계해야 합니다. -- 수치 데이터 파싱 시에는 직접 형변환(`float(x)`)을 지양하고, 반드시 예외처리가 포함된 `_safe_float(x)` 헬퍼 함수를 사용하세요. - -### 2. LLM 호출 시 토큰 최적화 -- 대형 HTML을 LLM에 전송하기 전 반드시 `BeautifulSoup` 및 정규식(`re`)을 사용하여 태그와 표 데이터를 클렌징해야 합니다. -- 텍스트 길이가 길어질 경우 `smart_chunk()` 함수를 통해 중간 내용을 버리고 핵심(앞부분과 뒷부분)만 남겨 토큰 한도를 준수해야 합니다. -- 429 Error(Rate Limit) 방지를 위해 Gemini 호출 시 `_generate_with_retry()` 래퍼 함수를 통해 자동 재시도 로직을 적용하세요. - -### 3. 상태 관리 및 캐싱 -- 재무 데이터와 분석 결과는 `@st.cache_data(ttl=300)`을 사용해 캐싱하여 속도를 향상시킵니다. -- 10-K 분석 텍스트는 `data/` 경로 하위에 JSON 파일 형태로 영구 저장하여 불필요한 SEC API 재요청을 최소화해야 합니다. - -### 4. 코드 스타일 -- 모든 UI 출력 문자열과 변수명은 명확성을 위해 일관성 있게 작성되어야 합니다. -- Pandas 데이터프레임에서 빈 값(None, NaN)을 화면에 출력할 경우, 반드시 `"N/A"` 포맷으로 변경하여 사용자 혼동을 피하세요 (`_na()` 함수 활용). \ No newline at end of file diff --git a/.agent/schema.sql b/.agent/schema.sql deleted file mode 100644 index e69de29..0000000 diff --git a/.env.example b/.env.example index 5685198..aff4603 100644 --- a/.env.example +++ b/.env.example @@ -3,3 +3,12 @@ GOOGLE_API_KEY=your_google_api_key_here SEC_EDGAR_EMAIL=your_email@example.com + +# Optional — Financial Modeling Prep (historical ratios, transcripts, calendar) +FMP_API_KEY= + +# Optional — Korea Bank ECOS (macro series) +ECOS_API_KEY= + +# Optional — Korea DART (dart-fss company search / filings) +DART_API_KEY= diff --git a/.gitignore b/.gitignore index 2286a70..a327639 100644 --- a/.gitignore +++ b/.gitignore @@ -49,3 +49,4 @@ SEC-EDGAR-Filings/ # Prompt files CLAUDE_CODE_PROMPT.md REFACTORING_PROMPT.md +data/filings/ diff --git a/AGENT.md b/AGENT.md deleted file mode 100644 index abe6f83..0000000 --- a/AGENT.md +++ /dev/null @@ -1,21 +0,0 @@ -# Agent Navigation Hub (AGENT.md) - -이 문서는 AI 코딩 에이전트 및 개발자가 `10-K-summariser-project`의 구조와 컨텍스트를 빠르게 파악하기 위한 **진입점(Entrypoint)**입니다. - -작업을 시작하거나 코드를 수정하기 전에, 필요한 정보에 맞춰 아래의 문서를 먼저 확인하십시오. (모든 문서는 `agent/` 디렉토리에 위치합니다.) - -## 🧭 Context & Documentation Map - -| 문서명 | 역할 및 포함 내용 | -| :--- | :--- | -| **[PRD](./prd.md)** | 프로젝트 비전, 주요 기능 요구사항(3개의 탭), 타겟 유저 등 **프로젝트 기획 배경** | -| **[Architecture](./architecture.mermaid)** | 시스템의 전체적인 구조를 보여주는 **Mermaid 아키텍처 다이어그램** | -| **[Data Flows](./data_flows.md)** | 정성 파이프라인(LLM)과 정량 파이프라인(Pandas)이 어떻게 나뉘어 동작하는지 설명하는 **데이터 흐름도** | -| **[Directory Map](./directory_map.md)** | 루트 디렉토리 및 주요 파일들(`app.py`, `find_toc.py` 등)의 역할과 **파일 구조** | -| **[ADL](./adl.yaml)** | 429 에러 해결, 10년 2단계 DCF 도입, 다중 폴백 구조 등 **주요 기술적 의사결정 기록** | -| **[Infra](./infra.yaml)** | Python 버전, Streamlit, Gemini API, yfinance 등 **의존성 및 인프라 환경** | -| **[Manifest](./manifest.json)** | 프로젝트 메타데이터 (이름, 버전, 사용 기술 스택 등) | -| **[Rules](./rules.md)** | ⚠️ 에러 핸들링, 토큰 최적화, 상태 관리 등 코드를 작성할 때 반드시 지켜야 할 **개발 가드레일 및 규칙** | - ---- -**💡 Agent Action Item:** 코드를 수정하거나 새로운 기능을 구현할 때, 반드시 **[Rules](./rules.md)**를 먼저 숙지하고, 기존 아키텍처를 훼손하지 않도록 **[Architecture](./architecture.mermaid)** 및 **[Data Flows](./data_flows.md)**와 일치하게 작업하십시오. \ No newline at end of file diff --git a/ATLAS_EVALUATION.md b/ATLAS_EVALUATION.md deleted file mode 100644 index 4b79266..0000000 --- a/ATLAS_EVALUATION.md +++ /dev/null @@ -1,167 +0,0 @@ -# ATLAS Terminal — 종합 프로젝트 평가 & 빌딩 가이드 - ---- - -## PART 1: 현재 프로젝트 평가 - -### 🟢 잘한 점 (Strengths) - -**1. 하이브리드 아키텍처 — 이건 진짜 좋다** -정성(LLM)과 정량(Pandas/yfinance)을 분리한 설계는 비용 효율성과 정확도를 동시에 잡는 프로덕션 레벨 판단이다. Gemini를 텍스트 분석에만 쓰고, 숫자는 무료 API에서 가져오는 구조는 실제 FinTech 스타트업에서도 채택하는 패턴이다. - -**2. 429 토큰 최적화 — 실전 문제 해결** -200페이지 10-K를 통째로 보내지 않고, Item 1A~9A만 슬라이싱 → regex 파싱 → smart_chunk로 head+tail 보존하는 전략은 토큰 80%+ 절감을 달성했다. 이건 면접에서 강력한 스토리가 된다. - -**3. 다단계 폴백 시스템** -yahooquery → yfinance(fast_info → info → balance_sheet) → TTM/분기 합산 → 수동 입력 순으로 떨어지는 폴백 체인은 실사용에서 데이터 누락을 최소화한다. `_safe_float()` 일관 사용도 좋다. - -**4. 10년 2단계 DCF** -5년 DCF의 터미널밸류 왜곡 문제를 인식하고 Y6~10 선형 Fade를 적용한 건 학부생 수준을 넘어선다. Damodaran 참조 패널까지 있어서 학술적 근거도 확보했다. - -**5. Piotroski F-Score, Altman Z, DuPont — 정량 깊이** -단순 밸류에이션이 아닌 재무 건전성 지표까지 커버한 점이 Bloomberg Terminal 컨셉과 맞다. - -### 🟡 개선이 필요한 점 (Weaknesses) - -**1. app.py 단일 파일 2,846줄 — 가장 큰 기술 부채** -SEC 파싱, Gemini 호출, DCF 계산, 차트 생성, UI 렌더링이 전부 하나에 있다. 디버깅, 테스트, 협업 모두 어렵다. 모듈 분리가 최우선이다. - -**2. Streamlit 한계 — Bloomberg 터미널 UI와 거리가 있다** -Streamlit은 프로토타이핑엔 최고지만, 다중 패널 동시 업데이트, 실시간 웹소켓, 커스텀 레이아웃에 제약이 크다. Next.js + FastAPI로 전환하면 진정한 터미널 UX가 가능하다. - -**3. 글로벌 시장 커버리지 — 아직 US 중심** -한국(DART), 일본(EDINET), 유럽, 중국/홍콩 공시 파싱이 "Phase 2" 상태다. 가격 데이터는 yfinance 접미사로 커버되지만, 공시 분석은 미국만 된다. - -**4. 포트폴리오 — 스크린샷 OCR은 있지만 지속성 부족** -Trading 212, IBKR 스크린샷 분석은 구현되었으나, 포지션 이력 추적, 수익률 시계열, 리밸런싱 인사이트가 없다. Supabase에 저장하면 해결된다. - -**5. 뉴스 통합 없음** -회사 관련 뉴스가 아예 없다. Bloomberg 터미널의 핵심 기능 중 하나인 뉴스 피드가 빠져 있다. - -**6. 환율/암호화폐 — 별도 탭이지만 메인 대시보드와 통합 부족** -Bithumb/Binance 가격은 있지만, 포트폴리오 총 수익률에 FX 영향이 실시간으로 반영되는 통합 뷰가 없다. - -### 🔴 위험 요소 (Risks) - -- `app.py` 3000줄 단일 파일은 더 커지면 유지보수 불가능해진다 -- yfinance/yahooquery는 언제든 차단될 수 있다 (IP 제한) -- Gemini 무료 티어 rate limit은 프로덕션에서 문제가 된다 -- SEC EDGAR User-Agent 정책 위반 시 IP 차단 가능 - ---- - -## PART 2: 발전 방향 — Next.js 기반 ATLAS Terminal - -### 목표 아키텍처 - -``` -atlas-terminal/ -├── apps/ -│ └── web/ # Next.js 14 (App Router) -│ ├── app/ -│ │ ├── layout.tsx # 루트 레이아웃 (다크 테마, 글로벌 네비) -│ │ ├── page.tsx # 메인 대시보드 (그리드 레이아웃) -│ │ ├── (dashboard)/ -│ │ │ ├── overview/ # 포트폴리오 오버뷰 + 뉴스 피드 -│ │ │ ├── research/ # 10-K 분석 + 뉴스 (회사별) -│ │ │ ├── valuation/ # DCF + RIM + Comps -│ │ │ ├── markets/ # 히트맵 + 환율 + 암호화폐 -│ │ │ ├── portfolio/ # 포지션 관리 + 스크린샷 OCR -│ │ │ └── filings/ # SEC/DART/EDINET 원문 뷰어 -│ │ └── api/ # Route Handlers (BFF 패턴) -│ │ ├── search/ -│ │ ├── news/ -│ │ └── portfolio/ -│ ├── components/ -│ │ ├── ui/ # shadcn/ui 기반 원자 컴포넌트 -│ │ ├── charts/ # Recharts/D3 차트 컴포넌트 -│ │ │ ├── SankeyFlow.tsx -│ │ │ ├── RadarHealth.tsx -│ │ │ ├── DCFWaterfall.tsx -│ │ │ └── HeatmapGrid.tsx -│ │ ├── terminal/ # 터미널 스타일 컴포넌트 -│ │ │ ├── TickerBar.tsx # 상단 실시간 티커 바 -│ │ │ ├── CommandPalette.tsx # ⌘K 검색 -│ │ │ ├── PanelGrid.tsx # 리사이즈 가능 패널 -│ │ │ └── NewsFeed.tsx # 실시간 뉴스 피드 -│ │ └── portfolio/ -│ │ ├── ScreenshotUpload.tsx -│ │ └── PositionTable.tsx -│ ├── lib/ -│ │ ├── api-client.ts # FastAPI 호출 래퍼 -│ │ └── format.ts # 통화/숫자 포맷 유틸 -│ └── styles/ -│ └── terminal-theme.css # Bloomberg 스타일 CSS 변수 -│ -├── server/ # FastAPI 백엔드 -│ ├── main.py # FastAPI 엔트리포인트 -│ ├── routers/ -│ │ ├── edgar.py # SEC EDGAR 다운로드/파싱 -│ │ ├── dart.py # 한국 DART API -│ │ ├── edinet.py # 일본 EDINET API -│ │ ├── analysis.py # Gemini LLM 분석 (MD&A, Risk) -│ │ ├── valuation.py # DCF, RIM, Comps 계산 -│ │ ├── market_data.py # yfinance/yahooquery 래퍼 -│ │ ├── news.py # 뉴스 집계 (RSS + API) -│ │ ├── crypto.py # Bithumb/Binance API -│ │ ├── fx.py # 환율 데이터 -│ │ └── portfolio.py # 포트폴리오 CRUD + OCR -│ ├── services/ -│ │ ├── gemini_service.py # Gemini API 래퍼 (retry, chunk, stream) -│ │ ├── sec_parser.py # 10-K HTML → 섹션 추출 -│ │ ├── text_chunker.py # smart_chunk, clean_text_for_llm -│ │ ├── dcf_engine.py # 10Y 2-stage DCF + Reverse DCF + RIM -│ │ ├── financial_metrics.py # DuPont, Altman Z, F-Score, Red Flags -│ │ ├── market_fetcher.py # yfinance/yahooquery 폴백 체인 -│ │ └── screenshot_ocr.py # Gemini Vision 포트폴리오 OCR -│ ├── models/ -│ │ ├── schemas.py # Pydantic 요청/응답 스키마 -│ │ └── db.py # Supabase 클라이언트 -│ └── utils/ -│ ├── safe_float.py # _safe_float, _na 유틸 -│ ├── ticker_utils.py # get_global_ticker, infer_market -│ └── cache.py # Redis/인메모리 캐시 래퍼 -│ -├── supabase/ -│ └── migrations/ # DB 스키마 (포트폴리오, 캐시, 사용자) -│ -├── claude.md # ← 이 파일 (에이전트 빌딩 가이드) -├── .github/ -│ └── workflows/ -│ └── update-readme.yml # README 자동 업데이트 (GitHub Actions) -└── package.json -``` - -### UI 디자인 방향 — "Terminal Noir" - -Bloomberg Terminal + Notion의 깔끔함 + 다크 모드를 결합한 디자인 - -**컬러 팔레트:** -- Background: `#0A0A0F` (거의 검정, 살짝 네이비) -- Surface: `#12121A` (카드/패널 배경) -- Border: `#1E1E2E` (구분선) -- Primary: `#00D4AA` (민트 그린 — 핵심 액션, 상승) -- Danger: `#FF4757` (하락, 경고) -- Text Primary: `#E8E8F0` (거의 흰색) -- Text Secondary: `#6B7280` (설명 텍스트) -- Accent: `#818CF8` (인디고 — AI 분석 결과 강조) - -**타이포그래피:** -- 숫자/데이터: `JetBrains Mono` (모노스페이스, 가독성) -- 제목: `Satoshi` (기하학적 산세리프, 모던) -- 본문: `Inter` (가독성 최우선) - -**핵심 UI 패턴:** -1. **Command Palette (⌘K)**: 회사 검색, 기능 이동 — Notion/Linear 스타일 -2. **리사이즈 가능 패널 그리드**: react-grid-layout으로 사용자가 패널 배치 커스텀 -3. **상단 티커 바**: 실시간 가격 스크롤 (주식 + 암호화폐 + 환율) -4. **사이드바 워치리스트**: 즐겨찾기 종목 실시간 업데이트 -5. **AI 분석 결과**: 인디고 보더 카드 안에 스트리밍 텍스트 - ---- - -## PART 3: claude.md (Claude Code 빌딩 가이드) - -아래 내용을 프로젝트 루트의 `claude.md`로 저장하면 Claude Code가 참조한다. - ---- diff --git a/README.md b/README.md index 6a4a8a7..dd3a960 100644 --- a/README.md +++ b/README.md @@ -24,72 +24,79 @@ ATLAS Terminal is a **full-stack financial analysis platform** that brings insti --- -## Pages & Features +## Pages & Features (12 Pages, 92 API Routes) -### 📊 Overview -Company snapshot at a glance — current price, sector, industry, market cap, P/E ratio, beta, dividend yield, 52-week range, **Altman Z-Score** (safe/grey/distress zones), and **DuPont decomposition** (ROE → NPM × Asset Turnover × Equity Multiplier). +### 📊 Overview — Multi-Asset Intelligence +Auto-detects asset type and renders the appropriate dashboard: +- **Equity**: Sector/industry, market cap, P/E, beta, dividend, 52-week range, **Altman Z-Score**, **DuPont decomposition**, **KPI sparklines** (revenue growth, margins, ROE, FCF), **Peer valuation comparison** (PE/PB/PS/EV-EBITDA) +- **ETF**: Top holdings, sector breakdown, expense ratio +- **Commodity**: Monthly seasonal patterns, cross-commodity correlations -### 🔬 Research -AI-powered deep-dive analysis using Google Gemini. Ask natural-language questions about any company and receive structured financial insights with context from SEC filings, financial statements, and market data. +### 🔬 Research — Quantitative Dashboard +Grid-based research layout with five panels: +- **F-Score Panel**: Piotroski 9-criteria history with pass/fail indicators +- **DuPont Tree**: 3-factor ROE decomposition (NPM × Asset Turnover × Equity Multiplier) +- **Sankey**: Income statement flow visualization (Revenue → EBIT, @nivo/sankey) +- **Waterfall**: Operating income bridge chart (@nivo/bar) +- **Anomaly Chips**: YoY anomaly detection with Gemini AI explanations ### 💰 Valuation — 5 Analytical Models | Tab | Description | |-----|-------------| -| **DCF Model** | 2-stage discounted cash flow with smart defaults from CAPM/Beta. Adjustable WACC, terminal growth, and FCF growth sliders. Analyst consensus (target price, recommendation) displayed alongside. | -| **Sensitivity** | WACC × Terminal Growth Rate matrix table. Center cell highlighted to show base-case intrinsic value. Instantly see how assumptions shift fair value. | -| **Monte Carlo** | 5,000-simulation DCF with randomized inputs. Histogram visualization (red below / green above current price). Statistics: mean, median, P10/P90, probability of upside. | -| **Tornado** | Variable impact ranking chart. Shows which input assumption (WACC, growth rate, terminal growth, margins) has the largest effect on valuation — sorted by sensitivity range. | -| **Reverse DCF** | Solves for the implied growth rate the market is pricing in. Compares market-implied growth vs. your assumption and analyst consensus. Uses scipy's Brent root-finding method. | +| **DCF Model** | 3-scenario discounted cash flow with smart defaults from CAPM/Beta. Adjustable WACC, terminal growth, and FCF growth sliders. Analyst consensus displayed alongside. | +| **Sensitivity** | WACC × Terminal Growth Rate matrix table. Center cell highlighted to show base-case intrinsic value. | +| **Monte Carlo** | 5,000-simulation DCF with randomized inputs. Histogram (red below / green above current price). P10/P90, probability of upside. | +| **Tornado** | Variable impact ranking — which input assumption has the largest effect on valuation. | +| **Reverse DCF** | Market-implied growth rate via scipy Brent root-finding. Compares vs your assumption and analyst consensus. | ### 📈 Technical Analysis - **Candlestick chart** with volume histogram (TradingView Lightweight Charts) - Period selector: 1MO, 3MO, 6MO, 1Y, 2Y -- **RSI(14)** with overbought/oversold classification -- **MACD** with signal line and histogram -- **Bollinger Bands** — %B, bandwidth, current position +- **RSI(14)**, **MACD**, **Bollinger Bands**, **ATR**, **ADX** - **Moving Averages** table — SMA/EMA 20/50/100/200 with ABOVE/BELOW signals -- **Fibonacci retracement** levels with "near current price" highlighting -- **ATR** (Average True Range) for volatility measurement -- **ADX** for trend strength detection +- **Fibonacci retracement** levels +- **Ichimoku cloud** components ### 🌍 Financial Statements -Institutional-style financial data table with: - **Income Statement**, **Balance Sheet**, **Cash Flow** tabs -- Up to 5 annual periods with proper date headers -- **YoY Growth** badges (green for positive, red for negative) -- **Margin %** rows (Gross Margin, Operating Margin, Net Margin) -- Row groups: Revenue, COGS, Gross Profit, SG&A, R&D, Operating Income, EBITDA, Net Income, EPS -- Pipe-separated multi-key lookup to handle both yfinance and yahooquery column naming conventions +- Up to 5 annual periods with **YoY Growth** badges (green/red) +- **Margin %** rows (Gross, Operating, Net) +- **Sector heatmap** (S&P 500, NASDAQ 100, KOSPI, FTSE 100 constituents) + +### 🌐 Macro & Cycle — Global Dashboard +Five collapsible tabs plus three always-visible sections: +- **Tabs**: FRED time series, Macro Cycle Heatmap (countries + assets), OECD CLI (DBnomics), Korea indicators (ECOS), Economic Calendar +- **Global Quadrant**: Growth vs inflation Z-score scatter (4 macro regimes) +- **Yield-FX**: US 10Y spread vs FX pairs (USD/JPY, EUR/USD, USD/KRW) +- **Smart Money**: Copper/Gold ratio + RORO (Risk-On/Risk-Off) composite gauge ### 📅 Earnings - **Next earnings date** card with countdown -- **EPS Beat/Miss** visual history — green bars for beats, red for misses, with surprise percentage -- **Revenue & Earnings estimates** vs. actuals -- **Quarterly breakdown** cards +- **EPS Beat/Miss** visual history with surprise percentage +- **Quarterly breakdown** cards (revenue, net income) +- **Earnings transcript** (requires FMP API key) ### 📰 News Feed Split-view news aggregator: -- **Left panel**: Scrollable article list (40+ articles from Finviz & Google News) with source badges and timestamps -- **Right panel**: Article header bar + iframe embedding of original content -- "Open Original ↗" button for sites that block iframe embedding -- Ticker-specific filtering +- **Left panel**: 40+ articles from Finviz, Google News, Yahoo RSS with source badges +- **Right panel**: Article header + iframe; domain-aware handling for sites blocking iframes (Yahoo, Bloomberg, WSJ) — shows summary + Open Original + +### 🎯 Screener & Backtest +- **Stock Screener**: Filter by PE, sector, dividend yield +- **Strategy Backtest**: SMA Crossover, RSI Oversold, Buy & Hold — with candlestick chart visualization (lightweight-charts) ### 💼 Portfolio -Position tracking with multi-currency support (USD, KRW, GBP, EUR, JPY, CNY). P&L calculation, FX-adjusted returns, and risk metrics including: -- **VaR** (Value at Risk) -- **Sharpe Ratio** & **Sortino Ratio** -- **Maximum Drawdown** -- **Beta** & **Correlation** to benchmark +Position tracking with multi-currency support (USD, KRW, GBP, EUR, JPY, CNY). P&L calculation, FX-adjusted returns, OCR screenshot import, and risk metrics: +- **VaR**, **Sharpe Ratio**, **Sortino Ratio**, **Maximum Drawdown**, **Beta**, **Correlation** -### 📑 SEC Filings (EDGAR) -Inline 10-K filing viewer: -- Downloads and parses latest 10-K from SEC EDGAR -- **5 section tabs**: Risk Factors (1A), MD&A (7), Financial Statements (8), Legal Proceedings (3), Controls & Procedures (9A) -- Intelligent content formatting — headers detected and styled, bullets indented, paragraphs separated -- **Word count** per section -- **AI Summary** button — sends section text to Gemini for key risk/trend extraction -- Section caching to avoid repeat downloads +### 📑 Filings — Multi-Jurisdiction +Auto-detects filing jurisdiction from ticker suffix: +- **SEC EDGAR** (US stocks): 10-K section viewer (Items 1A, 3, 7, 8, 9A) +- **DART** (`.KS`/`.KQ` Korean stocks): 사업보고서 sections mapped to SEC equivalents +- **EDINET** (`.T` Japanese stocks): 有価証券報告書 sections (optional API key) + +Each with 5 section tabs, word count, and **AI Summary** via Gemini. ### ⚙️ Settings - Google Gemini API key configuration @@ -101,51 +108,40 @@ Inline 10-K filing viewer: ## Architecture ``` -┌─────────────────────────────────────────────────────────────────┐ -│ ATLAS TERMINAL │ -├────────────────────────────┬────────────────────────────────────┤ -│ Next.js 14 Frontend │ FastAPI Backend │ -│ (Port 3000) │ (Port 8000) │ -│ │ │ -│ ┌──────────────────┐ │ ┌──────────────────────┐ │ -│ │ App Router Pages │ │ │ 13 API Routers │ │ -│ │ • Overview │────────▶ │ • /api/market │ │ -│ │ • Research │ proxy │ • /api/financials │ │ -│ │ • Valuation │ /api/* │ • /api/valuation │ │ -│ │ • Technical │ │ │ • /api/technical │ │ -│ │ • Markets │ │ │ • /api/earnings │ │ -│ │ • Earnings │ │ │ • /api/edgar │ │ -│ │ • News │ │ │ • /api/news │ │ -│ │ • Portfolio │ │ │ • /api/portfolio │ │ -│ │ • Filings │ │ │ • /api/insider │ │ -│ │ • Settings │ │ │ • /api/analysis │ │ -│ └──────────────────┘ │ │ • /api/crypto │ │ -│ │ │ • /api/fx │ │ -│ ┌──────────────────┐ │ │ • /api/estimates │ │ -│ │ Components │ │ └──────────┬───────────┘ │ -│ │ • Sidebar │ │ │ │ -│ │ • Ticker Bar │ │ ┌──────────▼───────────┐ │ -│ │ • Chat Panel │ │ │ 15 Service Modules │ │ -│ │ • useTicker() │ │ │ • dcf_engine │ │ -│ └──────────────────┘ │ │ • monte_carlo │ │ -│ │ │ • sensitivity │ │ -│ ┌──────────────────┐ │ │ • risk_metrics │ │ -│ │ Design System │ │ │ • technical_analysis│ │ -│ │ Terminal Noir │ │ │ • sec_parser │ │ -│ │ #0A0A0F bg │ │ │ • news_aggregator │ │ -│ │ #00D4AA accent │ │ │ • gemini_service │ │ -│ │ #FF4757 red │ │ │ • market_data │ │ -│ └──────────────────┘ │ └──────────┬───────────┘ │ -│ │ │ │ -│ │ ┌──────────▼───────────┐ │ -│ │ │ Data Sources │ │ -│ │ │ • yfinance │ │ -│ │ │ • yahooquery │ │ -│ │ │ • SEC EDGAR API │ │ -│ │ │ • Google Gemini │ │ -│ │ │ • Finviz / RSS │ │ -│ │ └──────────────────────┘ │ -└────────────────────────────┴────────────────────────────────────┘ +┌───────────────────────────────────────────────────────────────────┐ +│ ATLAS TERMINAL │ +├─────────────────────────────┬─────────────────────────────────────┤ +│ Next.js 14 Frontend │ FastAPI Backend │ +│ (Port 3000) │ (Port 8000) │ +│ │ │ +│ ┌───────────────────┐ │ ┌───────────────────────┐ │ +│ │ 12 App Router │ │ │ 21 API Routers │ │ +│ │ Pages + AppShell │────────▶ │ 92 endpoints │ │ +│ │ + Error Boundaries│ proxy │ /api/market (17) │ │ +│ └───────────────────┘ /api/* │ /api/macro (11) │ │ +│ │ │ /api/portfolio (10) │ │ +│ ┌───────────────────┐ │ │ /api/valuation (8) │ │ +│ │ 5 Component Dirs │ │ │ /api/analysis (6) │ │ +│ │ overview/ macro/ │ │ │ + 14 more routers │ │ +│ │ research/ markets/│ │ └───────────┬───────────┘ │ +│ │ filings/ │ │ │ │ +│ └───────────────────┘ │ ┌───────────▼───────────┐ │ +│ │ │ 37 Service Modules │ │ +│ ┌───────────────────┐ │ │ dcf_engine, monte │ │ +│ │ Design System │ │ │ carlo, risk_metrics │ │ +│ │ Terminal Noir │ │ │ macro_fetcher, oecd │ │ +│ │ @nivo + recharts │ │ │ research_dashboard │ │ +│ │ lightweight-charts│ │ │ dart/edinet/fmp... │ │ +│ └───────────────────┘ │ └───────────┬───────────┘ │ +│ │ │ │ +│ │ ┌───────────▼───────────┐ │ +│ │ │ Data Sources │ │ +│ │ │ yfinance, yahooquery │ │ +│ │ │ SEC EDGAR, DART, EDNT│ │ +│ │ │ FRED, OECD, ECOS │ │ +│ │ │ FMP, Gemini, Finviz │ │ +│ │ └───────────────────────┘ │ +└─────────────────────────────┴─────────────────────────────────────┘ ``` --- @@ -155,15 +151,16 @@ Inline 10-K filing viewer: | Layer | Technology | |-------|-----------| | **Frontend** | Next.js 14 (App Router), TypeScript, Tailwind CSS | -| **Charts** | TradingView Lightweight Charts (candlestick, volume) | +| **Charts** | TradingView Lightweight Charts, @nivo/sankey, @nivo/bar, Recharts | | **Backend** | Python 3.12+, FastAPI, Pydantic v2, Uvicorn | | **AI / LLM** | Google Gemini 2.0 Flash (`google-generativeai`) | -| **Financial Data** | yfinance (primary), yahooquery (fallback) | +| **Financial Data** | yfinance (primary), yahooquery (fallback), FMP (optional) | | **Technical Indicators** | `ta` library (RSI, MACD, Bollinger, Ichimoku, ADX) | | **Valuation Engine** | NumPy (Monte Carlo), SciPy (Brent root-finding for Reverse DCF) | -| **SEC Data** | `sec-edgar-downloader`, EDGAR REST API, BeautifulSoup4 + lxml | +| **Filings** | SEC EDGAR, Korea DART (`dart-fss`), Japan EDINET | +| **Macro Data** | FRED (public CSV), OECD (DBnomics), ECOS (한국은행) | | **Database** | SQLite (local) / PostgreSQL (production) via asyncpg | -| **News** | Finviz scraping + Google News RSS via feedparser | +| **News** | Finviz scraping + Google News RSS + Yahoo RSS via feedparser | | **Design System** | Terminal Noir — custom dark theme (#0A0A0F, #00D4AA, #FF4757) | --- @@ -175,88 +172,76 @@ atlas-terminal/ │ ├── apps/web/ # Next.js 14 Frontend │ ├── src/app/ -│ │ ├── page.tsx # Overview (home) -│ │ ├── research/page.tsx # AI Research -│ │ ├── valuation/page.tsx # DCF + Sensitivity + Monte Carlo + Tornado + Reverse DCF -│ │ ├── technical/page.tsx # Technical Analysis (TradingView charts) -│ │ ├── markets/page.tsx # Financial Statements table +│ │ ├── page.tsx # Overview (Multi-Asset: Equity/ETF/Commodity) +│ │ ├── research/page.tsx # Research Grid (F-Score, DuPont, Sankey, Waterfall) +│ │ ├── valuation/page.tsx # DCF + Sensitivity + Monte Carlo + Tornado + Reverse +│ │ ├── technical/page.tsx # Technical Analysis (TradingView + Indicators) +│ │ ├── markets/page.tsx # Financial Statements + Sector Heatmap +│ │ ├── macro/page.tsx # Global Macro (Quadrant, YieldFX, SmartMoney, FRED) │ │ ├── earnings/page.tsx # Earnings history & calendar -│ │ ├── news/page.tsx # News feed (split-view) -│ │ ├── portfolio/page.tsx # Portfolio tracker -│ │ ├── filings/page.tsx # SEC EDGAR filing viewer +│ │ ├── news/page.tsx # News feed (split-view, iframe-aware) +│ │ ├── screener/page.tsx # Stock screener + Strategy backtest +│ │ ├── portfolio/page.tsx # Portfolio tracker + OCR + Risk +│ │ ├── filings/page.tsx # Multi-jurisdiction filing viewer (SEC/DART/EDINET) │ │ ├── settings/page.tsx # API keys configuration -│ │ ├── components/ -│ │ │ ├── sidebar.tsx # Navigation sidebar -│ │ │ ├── ticker-bar.tsx # Live market indices bar -│ │ │ └── chat-panel.tsx # AI Copilot chat interface +│ │ ├── components/ # 5 component directories + 3 global components +│ │ │ ├── app-shell.tsx # 3-panel layout (SSR-safe) +│ │ │ ├── sidebar.tsx # Navigation (12 items) +│ │ │ ├── ticker-bar.tsx # Live indices bar +│ │ │ ├── chat-panel.tsx # AI Copilot +│ │ │ ├── overview/ # EquityOverview, ETFOverview, CommodityOverview, KPI, Peer +│ │ │ ├── research/ # FScorePanel, DuPontTree, SankeyWidget, WaterfallWidget +│ │ │ ├── macro/ # QuadrantChart, YieldFxChart, SmartMoneyPanel +│ │ │ ├── markets/ # HeatmapSection, EconomicCalendar, KoreaMonitor, OECD +│ │ │ └── filings/ # FilingsViewer (scroll-spy) │ │ └── lib/ -│ │ ├── use-ticker.ts # Ticker state hook (localStorage + CustomEvent) -│ │ └── api.ts # API helper functions -│ ├── next.config.mjs # API proxy: /api/* → localhost:8000 -│ ├── tailwind.config.ts # Terminal Noir color system -│ └── package.json +│ │ ├── use-ticker.ts # Ticker state (localStorage + CustomEvent, hydration-safe) +│ │ ├── api.ts # API helper (apiFetch, apiPost) +│ │ ├── ticker-alias.ts # Natural language → ticker ("gold" → GC=F) +│ │ └── filing-jurisdiction.ts # Ticker → SEC/DART/EDINET inference +│ └── next.config.mjs # API proxy: /api/* → localhost:8000 │ ├── server/ # FastAPI Backend -│ ├── main.py # App entry + CORS + router mounting -│ ├── routers/ # 13 API route handlers -│ │ ├── market_data.py # Stock quotes, indices, overview -│ │ ├── financials.py # Income statement, balance sheet, cash flow -│ │ ├── valuation.py # DCF, sensitivity, Monte Carlo, tornado, reverse DCF -│ │ ├── technical.py # RSI, MACD, Bollinger, moving averages, Fibonacci -│ │ ├── earnings.py # EPS history, calendar, quarterly data -│ │ ├── insider.py # Insider transactions, institutional holders -│ │ ├── edgar.py # SEC 10-K section extraction -│ │ ├── analysis.py # Gemini AI analysis endpoints -│ │ ├── news.py # News aggregation -│ │ ├── portfolio.py # Position CRUD + risk metrics -│ │ ├── estimates.py # Analyst estimates -│ │ ├── crypto.py # Cryptocurrency prices -│ │ └── fx.py # FX rates and history -│ ├── services/ # 15 business logic modules -│ │ ├── dcf_engine.py # Excel-style DCF, 2-stage DCF, reverse DCF (scipy brentq) -│ │ ├── monte_carlo.py # Monte Carlo simulation (5000 runs, numpy) -│ │ ├── sensitivity.py # WACC × TG matrix, tornado data -│ │ ├── risk_metrics.py # VaR, Sharpe, Sortino, MDD, Beta, Correlation -│ │ ├── technical_analysis.py # All indicators via `ta` library -│ │ ├── sec_parser.py # SEC EDGAR download, HTML parse, section cache -│ │ ├── news_aggregator.py # Finviz + Google News RSS -│ │ ├── gemini_service.py # Gemini API wrapper -│ │ ├── gemini_analysis.py # Structured AI analysis prompts -│ │ ├── market_data.py # Market overview, sector data -│ │ ├── financial_metrics.py # DuPont, Altman Z, ratio calculations -│ │ └── ... # crypto, fx, screenshot OCR, text chunker -│ ├── models/ # Pydantic schemas +│ ├── main.py # App entry + 21 routers +│ ├── routers/ (21) # API route handlers +│ ├── services/ (37) # Business logic modules │ ├── db/ # SQLite + PostgreSQL repositories +│ ├── models/ # Pydantic schemas │ ├── ai/ # LLM router, context builder │ └── utils/ # safe_float, ticker utilities │ -├── tests/ # pytest test suite -├── supabase/migrations/ # Database schema └── requirements.txt # Python dependencies ``` --- -## API Endpoints +## API Endpoints (92 routes across 21 routers) -| Prefix | Methods | Description | -|--------|---------|-------------| -| `/api/market` | GET | Stock quotes, company info, market overview, sector data | -| `/api/financials` | GET | Income statement, balance sheet, cash flow, highlights, ratios | -| `/api/valuation` | GET, POST | DCF defaults, sensitivity matrix, Monte Carlo, tornado, reverse DCF | -| `/api/technical` | GET | RSI, MACD, Bollinger, moving averages, Fibonacci, ATR, ADX | -| `/api/earnings` | GET | EPS history, earnings calendar, quarterly data | -| `/api/insider` | GET | Insider transactions, institutional holders | -| `/api/edgar` | GET | SEC 10-K section extraction, Item 7 MD&A, filing comparison | -| `/api/analysis` | POST | Gemini AI analysis (MD&A, risk factors, financial health) | -| `/api/estimates` | GET | Analyst consensus estimates | -| `/api/news` | GET | Financial news aggregation (Finviz + Google News) | -| `/api/portfolio` | GET, POST, DELETE | Position management, risk metrics | -| `/api/crypto` | GET | Cryptocurrency prices (BTC, ETH, SOL, etc.) | -| `/api/fx` | GET | FX rates and historical data | -| `/health` | GET | Liveness probe with DB status | +| Prefix | Count | Description | +|--------|-------|-------------| +| `/api/market` | 17 | Stock quotes, overview (multi-asset), sectors, health, peers, F-Score, Sankey, radar, ETF holdings, commodity seasonal/correlations | +| `/api/macro` | 11 | FRED, OECD CLI, macro snapshot, **quadrant**, **yield-fx**, **smart-money**, Korea, calendar, ECOS | +| `/api/portfolio` | 10 | Position CRUD, risk metrics, OCR screenshot, exchange options | +| `/api/valuation` | 8 | DCF (3-scenario), sensitivity, Monte Carlo, tornado, reverse DCF, consensus, smart defaults | +| `/api/analysis` | 6 | Gemini AI analysis (strategy, risks, MD&A, forensic, financials) | +| `/api/financials` | 4 | Statements (IS+BS+CF), highlights, KPI history, ratios | +| `/api/technical` | 4 | Indicators, chart data, Fibonacci, Ichimoku | +| `/api/earnings` | 4 | EPS history, calendar, quarterly, transcript | +| `/api/chat` | 4 | AI Copilot (stream, complete, suggested, configure) | +| `/api/edgar` | 3 | 10-K sections, Item 7 MD&A, filing comparison | +| `/api/estimates` | 3 | Analyst consensus, history, growth | +| `/api/dart` | 2 | Korea DART company search + 사업보고서 sections | +| `/api/edinet` | 2 | Japan EDINET links + 有価証券報告書 sections | +| `/api/fmp` | 2 | Historical key metrics + ratios (FMP or Yahoo fallback) | +| `/api/screener` | 2 | Stock screener + strategy backtest | +| `/api/insider` | 2 | Insider transactions, institutional holders | +| `/api/news` | 2 | News aggregation + sentiment | +| `/api/crypto` | 2 | Cryptocurrency prices | +| `/api/fx` | 2 | FX rates and history | +| `/api/markets` | 1 | Index constituent heatmap | +| `/api/research` | 1 | Quant research dashboard (F-Score, DuPont, Sankey, Waterfall, Anomalies) | -Full interactive API documentation available at `http://localhost:8000/docs` (Swagger UI). +Full interactive API documentation at `http://localhost:8000/docs` (Swagger UI). --- @@ -287,78 +272,53 @@ npm run dev Open **http://localhost:3000** in your browser. -Configure your **Gemini API Key** and **SEC EDGAR email** in the Settings page, then search for any ticker (e.g., MSFT, AAPL, GOOGL) to explore. +### Optional API Keys + +| Key | Purpose | Where to get | +|-----|---------|-------------| +| `GOOGLE_API_KEY` | Gemini AI analysis | [Google AI Studio](https://aistudio.google.com/apikey) | +| `SEC_EDGAR_EMAIL` | SEC fair-access compliance | Any valid email | +| `FMP_API_KEY` | Analyst estimates, transcripts, calendar | [Financial Modeling Prep](https://financialmodelingprep.com/) | +| `ECOS_API_KEY` | Korea Bank economic data | [ECOS](https://ecos.bok.or.kr/) | +| `DART_API_KEY` | Korea DART 사업보고서 | [Open DART](https://opendart.fss.or.kr/) | +| `EDINET_SUBSCRIPTION_KEY` | Japan EDINET 有価証券報告書 | [EDINET API](https://disclosure.edinet-fsa.go.jp/) | --- ## Design System — Terminal Noir -ATLAS Terminal uses a custom dark theme inspired by professional trading terminals: - | Token | Value | Usage | |-------|-------|-------| | `bg-primary` | `#0A0A0F` | Main background | -| `bg-card` | `#12121A` | Card surfaces | -| `bg-elevated` | `#1A1A2E` | Hover states, elevated panels | -| `border` | `#2A2A3E` | Borders and dividers | +| `bg-card` | `#1A1A26` | Card surfaces | +| `bg-hover` | `#252536` | Hover states | +| `border` | `#2A2A3A` | Borders and dividers | | `accent-green` | `#00D4AA` | Positive values, CTAs, active states | | `accent-red` | `#FF4757` | Negative values, warnings | -| `accent-blue` | `#4A9EFF` | Informational badges, links | +| `accent-blue` | `#4DA6FF` | Information, links | | `accent-yellow` | `#FFD93D` | Caution, highlights | -| `text-primary` | `#E8E8ED` | Primary text | -| `text-secondary` | `#A0A0B0` | Secondary text | -| `text-muted` | `#6B6B80` | Muted labels | - ---- - -## Evolution: Streamlit → Next.js + FastAPI - -This project began as a **Streamlit prototype** (`app.py`, 3,909 lines) and has been fully migrated to a modern full-stack architecture: - -| Aspect | Streamlit (v1-v3) | Next.js + FastAPI (v4) | -|--------|-------------------|----------------------| -| Frontend | Streamlit widgets | Next.js 14 App Router + Tailwind | -| Backend | Embedded in Streamlit | Dedicated FastAPI with 13 routers | -| Charts | Plotly (Sankey, Radar) | TradingView Lightweight Charts | -| State | `st.session_state` | React hooks + localStorage | -| Routing | Tab-based (7 tabs) | File-based (10 pages) | -| API | Monolithic | RESTful with OpenAPI docs | -| Caching | `@st.cache_data` | SQLite/PostgreSQL persistence | -| Deployment | Single process | Frontend + Backend independently scalable | - -The original Streamlit version remains functional at the project root (`app.py`) for reference. +| `text-primary` | `#F3F4F6` | Primary text | +| `text-secondary` | `#9CA3AF` | Secondary text | +| `text-muted` | `#6B7280` | Muted labels | --- ## Technical Highlights ### Hybrid AI Architecture -Gemini handles **text interpretation only** (MD&A analysis, risk factor extraction, industry outlook). All financial figures come from yfinance/yahooquery — zero hallucination risk on numbers. +Gemini handles **text interpretation only** (MD&A analysis, risk factor extraction, anomaly explanation). All financial figures come from yfinance/yahooquery — zero hallucination risk on numbers. ### Multi-Source Data Resilience -Primary source (yfinance) with automatic yahooquery fallback. Pipe-separated multi-key column lookups handle naming differences between providers (`"TotalRevenue|Total Revenue|Revenue"`). +Primary source (yfinance) with automatic yahooquery fallback. FMP as optional premium source. Pipe-separated multi-key column lookups handle naming differences between providers (`"TotalRevenue|Total Revenue|Revenue"`). ### Quantitative Valuation Suite Five interconnected valuation models — DCF serves as the base, Sensitivity shows assumption impact, Monte Carlo quantifies uncertainty, Tornado ranks variable importance, and Reverse DCF reveals market-implied expectations. -### SEC EDGAR Integration -Full pipeline: `sec-edgar-downloader` → HTML parsing with BeautifulSoup → section extraction (Items 1A, 3, 7, 8, 9A) → local caching → AI summarization via Gemini. +### Multi-Jurisdiction Filing Support +SEC EDGAR (US), DART (Korea), EDINET (Japan) — automatically routed by ticker suffix. Each maps to a standardized 5-section view with AI summarization. ---- - -## Requirements - -See [`atlas-terminal/requirements.txt`](atlas-terminal/requirements.txt) for the full Python dependency list. Key packages: - -- `fastapi`, `uvicorn` — Web framework -- `yfinance`, `yahooquery` — Financial data -- `google-generativeai` — Gemini AI -- `sec-edgar-downloader`, `beautifulsoup4`, `lxml` — SEC filing parsing -- `ta` — Technical analysis indicators -- `numpy`, `scipy` — Monte Carlo simulation, optimization -- `pandas` — Data manipulation - -Frontend: `next`, `react`, `tailwindcss`, `lightweight-charts` +### Global Macro Analytics +Growth-vs-inflation quadrant (FRED/OECD Z-scores), yield spread vs FX pairs, copper/gold + RORO composite — institutional-grade macro regime detection. --- @@ -366,18 +326,17 @@ Frontend: `next`, `react`, `tailwindcss`, `lightweight-charts` | Date | Update | |------|--------| -| **2026-03-21** | **Full-stack migration (v4.0) — Next.js 14 + FastAPI:** Complete rewrite from Streamlit to Next.js 14 App Router + FastAPI backend. 10 dedicated pages (Overview, Research, Valuation, Technical, Markets, Earnings, News, Portfolio, Filings, Settings). 13 REST API routers with Swagger docs. 5 valuation models (DCF, Sensitivity Matrix, Monte Carlo 5000-sim, Tornado, Reverse DCF with scipy brentq). TradingView Lightweight Charts for candlestick/volume. Technical Analysis page with RSI, MACD, Bollinger, Fibonacci, Moving Averages, ADX. Earnings beat/miss visualization. News split-view with iframe article embedding. SEC EDGAR inline filing viewer with 5 section tabs + AI Summary. Financial Statements table with YoY growth badges and margin rows. Terminal Noir dark theme design system. AI Copilot chat panel with Gemini. | -| **2026-03-19** | **Modular refactoring (v3.0) + SEC filing viewer fix:** (1) **Architecture:** 3,909-line `app.py` refactored into 28 focused modules across `config/`, `utils/`, `data/`, `ai/`, `views/`. Each file under 300 lines. Strict unidirectional dependency graph (no circular imports). All `@st.cache_data` TTLs and `st.session_state` keys preserved identically. (2) **SEC Filing Viewer fixed:** Rebuilt EDGAR fetch chain using `submissions/CIK{cik}.json` → `filings.recent.primaryDocument[]` (replaces deprecated `directory.item` lookup). Added filing type `st.selectbox` (10-K, 10-Q, 8-K, 20-F, 6-K) connected to backend dynamically. Native HTML rendered via `streamlit.components.v1.html()` with injected CSS reset. Errors surfaced explicitly with `st.error()`. (3) **DART links** restored for Korean-listed companies. | -| **2026-02-18** | **Market Heatmap & FX charts:** Sector heatmap with 5d/1mo data and per-ticker fallback (weekend/holiday robust). FX Momentum normalized 1Y line chart (GBP/USD, EUR/USD, USD/JPY, KRW). 10-K language toggle (한글/영문) via Gemini translation. plotly/yfinance added to requirements. | -| **2026-02-17** | **DART, prefs, run script:** DART fetch timeout 90s; DART report titles in English (cached). SEC & DART per-category iframe viewer. Last selected company persisted in `.app_prefs.json` (survives page refresh). Single run script `run.sh` at port 8501. | -| **2025-02-15** | **Multi-currency portfolio & FX:** Per-position currency (USD/GBP/EUR/KRW/JPY/CNY), fractional quantity, FX-adjusted returns. Gemini Vision AI screenshot import (extracts ticker, price, currency, quantity). App-wide `get_currency_for_ticker`, `get_fx_rate`, `format_price_with_usd`. | -| **2025-02-14** | **Global company search:** yahooquery `search()` replaces static dropdown. Search by name in any language; filters INDEX/MUTUALFUND; auto-infers .KS/.KQ/.T/.L suffix. | -| **2025-02-13** | **Design Rationale & 10Y DCF:** Design rationale section (undergrad automation mindset, 10Y 2-stage DCF, Damodaran integration). Wall Street Assumptions panel (analyst consensus + Damodaran baselines). Smart DCF defaults from Beta/CAPM. | -| **2025-02-13** | **Robust data & comps redesign:** Multi-step shares/debt/cash fallback (fast_info → info → balance). Top-down sector analysis with `SECTORS` dict and AI Industry Outlook (Gemini). | -| **2025-02-12** | **Hybrid architecture:** Item 7 only to Gemini; yfinance for all numbers. HTML cleansing pipeline (BeautifulSoup + regex). | -| **2025-02-12** | **DuPont, Altman Z, Piotroski, sector KPIs, TTM fallback:** Full quantitative financial health suite. Sector-specific metrics (Tech: Rule of 40; Retail: Inventory Turnover; Financials: ROE/ROA). | -| **2025-02-12** | **Preference persistence:** "Remember API key & email" checkbox; `.app_prefs.json` (gitignored). | -| **2025-01-XX** | **Initial release:** SEC EDGAR 10-K download, Item 7/8 extraction, Gemini analysis, Streamlit UI. | +| **2026-03-26** | **Codebase audit & documentation sync:** (1) Fixed `requirements.txt` — added missing `numpy`, `scipy`, `dbnomics` dependencies. (2) Full `claude.md` synchronization — updated §3 File Structure (removed 6 deleted services, added 37 current services + 21 routers), §5 API Endpoints (92 routes accurately documented), §6 Frontend Pages (12 pages with feature descriptions), §13 TODO (8 items marked complete). (3) Verified all 21 routers import cleanly, 92 API routes registered, 11/12 key endpoints tested OK (macro/quadrant timeout is external FRED latency, not code issue). | +| **2026-03-24** | **Macro dashboard, layout stability, News/Filings UX:** Global Macro & Smart Money page with quadrant, yield-FX, copper/gold + RORO gauge. Hydration/white-screen fix (SSR-safe useTicker + dynamic Sidebar). Research grid rebuilt with Tailwind CSS. News domain-aware iframe handling. Filings plain-text fallback. Error boundaries. | +| **2026-03-21** | **Full-stack migration (v4.0) — Next.js 14 + FastAPI:** Complete rewrite from Streamlit. 10 pages, 13 routers, 5 valuation models, TradingView charts, Technical Analysis suite, Earnings visualization, News split-view, SEC EDGAR viewer, Terminal Noir theme, AI Copilot. | +| **2026-03-19** | **Modular refactoring (v3.0):** 3,909-line `app.py` → 28 focused modules. SEC filing viewer rebuilt with EDGAR JSON API. DART links restored for Korean stocks. | +| **2026-02-18** | **Market Heatmap & FX charts:** Sector heatmap, FX momentum chart, 10-K language toggle. | +| **2026-02-17** | **DART, prefs, run script:** DART fetch timeout, English report titles, per-category iframe viewer. | +| **2025-02-15** | **Multi-currency portfolio & FX:** Per-position currency, Gemini Vision OCR screenshot import. | +| **2025-02-14** | **Global company search:** yahooquery search, auto-infers exchange suffix. | +| **2025-02-13** | **10Y DCF & comps redesign:** Wall Street Assumptions panel, Smart DCF defaults, sector analysis. | +| **2025-02-12** | **Hybrid architecture:** Item 7 only to Gemini; yfinance for all numbers. DuPont, Altman Z, Piotroski F-Score. | +| **2025-01-XX** | **Initial release:** SEC EDGAR 10-K download, Gemini analysis, Streamlit UI. | --- diff --git a/atlas-terminal/.env.example b/atlas-terminal/.env.example new file mode 100644 index 0000000..1c09d04 --- /dev/null +++ b/atlas-terminal/.env.example @@ -0,0 +1,11 @@ +# Copy to atlas-terminal/.env or project root .env (see README) + +GOOGLE_API_KEY= +SEC_EDGAR_EMAIL= + +# Optional +FMP_API_KEY= +ECOS_API_KEY= +DART_API_KEY= +# Japan EDINET API v2 (optional — 有価証券報告書 download in Filings) +EDINET_SUBSCRIPTION_KEY= diff --git a/atlas-terminal/README.md b/atlas-terminal/README.md index 2dcb89a..e5bb7ae 100644 --- a/atlas-terminal/README.md +++ b/atlas-terminal/README.md @@ -28,7 +28,14 @@ npm run dev ## Recent Updates -- Added multi-asset analysis branching across Overview/Research/Valuation/Earnings for equity, ETF, and commodity futures. -- Implemented commodity and ETF market widgets, plus index-level stock heatmap with interactive index switching. -- Upgraded portfolio OCR with reverse-engineering logic, exchange selection (including SMSN -> `SMSN.L`), and inline edit/delete flows. -- Added portfolio exchange-aware recalculation and FX conversion matrix support for multi-currency display. +**2026-03-24** + +- **Macro:** Global Macro & Smart Money dashboard (`/macro`), Recharts widgets, FastAPI `/api/macro/quadrant`, `/yield-fx`, `/smart-money` (FRED + yfinance + OECD/DBnomics). +- **Stability:** Sidebar `dynamic(..., ssr: false)`; `useTicker` hydration-safe init; `app/error.tsx`; macro/research layouts use Tailwind grid (removed `react-grid-layout`). +- **News / Filings:** Iframe fallback for blocked publishers (e.g. Yahoo); SEC filings show plain text when HTML snapshot cache is absent. + +**Earlier** + +- Multi-asset analysis branching across Overview/Research/Valuation/Earnings for equity, ETF, and commodity futures. +- Commodity and ETF market widgets; index-level stock heatmap with interactive index switching. +- Portfolio OCR upgrades, exchange selection (e.g. SMSN → `SMSN.L`), inline edit/delete; exchange-aware recalculation and FX matrix for multi-currency display. diff --git a/atlas-terminal/apps/web/package.json b/atlas-terminal/apps/web/package.json index a65ab7d..8f1f176 100644 --- a/atlas-terminal/apps/web/package.json +++ b/atlas-terminal/apps/web/package.json @@ -3,16 +3,24 @@ "version": "0.1.0", "private": true, "scripts": { - "dev": "next dev", + "dev": "next dev -p 3000", "build": "next build", "start": "next start", - "lint": "next lint" + "lint": "next lint", + "clean": "rm -rf .next node_modules/.cache", + "dev:clean": "npm run clean && next dev -p 3000", + "dev:reset": "rm -rf .next node_modules/.cache && next dev -p 3000", + "build:clean": "npm run clean && next build" }, "dependencies": { + "@nivo/bar": "^0.99.0", + "@nivo/core": "^0.99.0", + "@nivo/sankey": "^0.99.0", "lightweight-charts": "^5.1.0", "next": "14.2.35", "react": "^18", - "react-dom": "^18" + "react-dom": "^18", + "recharts": "^2.15.4" }, "devDependencies": { "@types/node": "^20", @@ -23,5 +31,8 @@ "postcss": "^8", "tailwindcss": "^3.4.1", "typescript": "^5" + }, + "engines": { + "node": ">=18.17.0" } } diff --git a/atlas-terminal/apps/web/src/app/components/app-shell.tsx b/atlas-terminal/apps/web/src/app/components/app-shell.tsx new file mode 100644 index 0000000..53ebcac --- /dev/null +++ b/atlas-terminal/apps/web/src/app/components/app-shell.tsx @@ -0,0 +1,38 @@ +"use client"; + +import dynamic from "next/dynamic"; +import { TickerBar } from "./ticker-bar"; +import { ChatPanel } from "./chat-panel"; + +/** + * Sidebar는 usePathname()을 씁니다. Next App Router에서 SSR 출력과 클라이언트 첫 페인트가 + * 미묘하게 어긋나면 hydration 실패 → 전체 트리가 비거나(흰 화면) 콘솔에 recoverable 에러가 납니다. + * 서버에서는 사이드바를 그리지 않고(ssr: false) 클라이언트에서만 마운트해 그 클래스의 버그를 제거합니다. + */ +const SidebarClient = dynamic( + () => import("./sidebar").then((m) => ({ default: m.Sidebar })), + { + ssr: false, + loading: () => ( +