IdiotQuant API 문서

Cloudflare Workers 기반 퀀트 투자 백엔드 REST API

Base URL https://idiotquant-backend.tofu89223.workers.dev
권한: Public인증 불필요 — 누구나 호출 가능 · X-User-Id 헤더 필요 · 🔒 AdminDB role=admin 계정만

📈 NCAV 스캔 데이터 NEW

GET /ncav/daily Public ▶ 직접 열기

날짜별 NCAV 조건 충족 종목 목록. 배치(7종목)마다 D1에 즉시 저장되므로 첫 스캔 5분 후부터 조회 가능.

파라미터타입기본값설명
datestringlatest날짜 YYYYMMDD 또는 latest (최근 스캔일)
min_rationumber1.0최소 NCAV 비율. 1.0 = (유동자산-총부채) ≥ 시가총액
limitnumber50최대 반환 수 (1~200)
sortstringncav_rationcav_ratio · pbr · per · last_price · market_cap
orderstringdescasc · desc
# 최근 날짜 기준 NCAV ≥ 1.5 종목, 상위 20개
curl "https://idiotquant-backend.tofu89223.workers.dev/ncav/daily?date=latest&min_ratio=1.5&limit=20&sort=ncav_ratio&order=desc"

# 특정 날짜 조회
curl "https://idiotquant-backend.tofu89223.workers.dev/ncav/daily?date=20260531&min_ratio=1.0"
const res = await fetch(
  'https://idiotquant-backend.tofu89223.workers.dev/ncav/daily?date=latest&min_ratio=1.5&limit=20'
);
const { data, meta } = await res.json();
// data: [{ ticker, name, ncav_ratio, pbr, per, last_price, ... }]
console.log(`${meta.scanDate} 기준 ${meta.total}개 종목`);
// 응답 예시
{
  "success": true,
  "data": [
    {
      "ticker": "004830",  "name": "덕성",
      "scan_date": "20260531",
      "ncav_ratio": 2.341,
      "current_assets": 85200,   "total_liabilities": 12400,
      "market_cap": 31100,       "last_price": 4280,
      "net_income": 3200000000,
      "per": 9.8,  "pbr": 0.42,  "eps": 437,  "bps": 10190
    }
  ],
  "meta": { "scanDate": "20260531", "total": 20, "filters": { "min_ratio": 1.5 } }
}
GET /ncav/daily/ticker/:ticker Public

특정 종목의 날짜별 NCAV 시계열. :ticker는 6자리 종목 코드.

파라미터타입기본값설명
:tickerstring필수종목 코드 (예: 005930)
limitnumber30최대 반환 수 (1~200)
curl "https://idiotquant-backend.tofu89223.workers.dev/ncav/daily/ticker/005930?limit=10"
const { data } = await fetch(
  'https://idiotquant-backend.tofu89223.workers.dev/ncav/daily/ticker/005930?limit=10'
).then(r => r.json());
// data: scan_date 내림차순 시계열
GET /ncav/archive Public

월별 압축 아카이브. period 없이 호출하면 월별 요약, period=YYYY-MM 지정 시 해당 월 종목 상세.

파라미터타입기본값설명
periodstring없음YYYY-MM 지정 시 해당 월 상세, 없으면 월별 요약
min_rationumber0최소 NCAV 비율 필터
limitnumber50최대 반환 수 (1~200)
sortstringncav_rationcav_ratio · pbr · per · last_price
# 월별 요약 목록
curl "https://idiotquant-backend.tofu89223.workers.dev/ncav/archive"

# 2026년 5월 상세 (NCAV ≥ 1.0)
curl "https://idiotquant-backend.tofu89223.workers.dev/ncav/archive?period=2026-05&min_ratio=1.0&sort=ncav_ratio"
// 월별 요약
const { data } = await fetch('https://idiotquant-backend.tofu89223.workers.dev/ncav/archive').then(r => r.json());
// [{ period_label, total_stocks, ncav_stocks, avg_ncav_ratio }]

// 특정 월 상세
const { data: detail } = await fetch(
  'https://idiotquant-backend.tofu89223.workers.dev/ncav/archive?period=2026-05&min_ratio=1.0'
).then(r => r.json());
GET /ncav/archive/ticker/:ticker Public

특정 종목의 월별 NCAV 추이. 장기 가치 변화 분석·백테스트에 활용.

# 덕성(004830) 최근 24개월 추이
curl "https://idiotquant-backend.tofu89223.workers.dev/ncav/archive/ticker/004830?limit=24"
const { data } = await fetch(
  'https://idiotquant-backend.tofu89223.workers.dev/ncav/archive/ticker/004830?limit=24'
).then(r => r.json());
// data: [{ period_label, ncav_ratio, last_price, days_scanned, ... }]
POST /ncav/scan/run 🔒 Admin

오프시간 제약 없이 수동으로 1배치(7종목) 즉시 스캔. 테스트·디버깅용.

curl -X POST "https://idiotquant-backend.tofu89223.workers.dev/ncav/scan/run" -H "X-User-Id: ADMIN_ID"

// 응답
{ "success": true, "data": { "before": { "lastIndex": 0 }, "after": { "lastIndex": 7 }, "advanced": 7 }, "meta": { "message": "1 배치 스캔 완료" } }
GET /ncav/status 🔒 Admin

현재 스캔 진행 상태 (KV), 날짜별 D1 저장 현황, 아카이브 현황을 JSON으로 반환.

curl "https://idiotquant-backend.tofu89223.workers.dev/ncav/status" -H "X-User-Id: YOUR_USER_ID"

// 응답
{
  "success": true,
  "data": {
    "scan": {
      "scanDate": "20260531", "lastIndex": 350,
      "totalStocks": 2000,    "progressPct": 18, "done": false
    },
    "dailyStats":  [{ "scan_date": "20260531", "cnt": 47 }, ...],
    "archiveStats":[{ "period_label": "2026-05", "cnt": 1847 }, ...]
  },
  "meta": { "generatedAt": "2026-05-31 14:23:10" }
}
GET /ncav/dashboard Public

스캔 현황·NCAV 종목·아카이브를 한눈에 보는 HTML 대시보드. 60초 자동 갱신.

/dashboard/ncav 에서 바로 확인  ·  전체 대시보드 목록

🔐 인증

GET /kakao/login Public

Kakao OAuth 로그인 리다이렉트. 성공 시 cf_token HttpOnly 쿠키 발급 (유효기간 1시간).

# 브라우저에서 접근
https://idiotquant-backend.tofu89223.workers.dev/kakao/login
POST /kakao/logout

Kakao 세션 로그아웃. cf_token 쿠키 만료.

curl -X POST "https://idiotquant-backend.tofu89223.workers.dev/kakao/logout" --cookie "cf_token=YOUR_TOKEN"
POST /kakao/message 🔒 Admin

카카오 메시지 전송.

GET /kakao/member/list 🔒 Admin

카카오 멤버 목록 조회.

GET /user/starred-stocks

현재 로그인 유저의 관심 종목 목록 조회.

GET /user/info

현재 로그인 유저 프로필 조회.

curl "https://idiotquant-backend.tofu89223.workers.dev/user/info" -H "X-User-Id: 2825510472"

📊 시장 데이터

GET /stock/:ticker Public ▶ 직접 열기

종목 코드로 최신 NCAV 정보를 조회합니다. D1 ncav_daily 테이블 기반으로 인증 없이 누구나 호출 가능합니다.
NCAV 스캔을 통과한 종목만 조회됩니다 (NCAV 비율 ≥ 1.0 이상의 종목).

파라미터위치설명예시
:tickerpath6자리 종목코드 (국내) 또는 심볼 (해외)005930, AAPL
# 삼성전자(005930) 조회 — 인증 불필요
curl "https://idiotquant-backend.tofu89223.workers.dev/stock/005930"

# 덕성(004830) 조회
curl "https://idiotquant-backend.tofu89223.workers.dev/stock/004830"
// 인증 없이 바로 호출
const res = await fetch('https://idiotquant-backend.tofu89223.workers.dev/stock/005930');
const { success, ticker, name, latest, history } = await res.json();

if (success) {
  console.log(`${name}(${ticker})`);
  console.log(`NCAV 비율: ${latest.ncav_ratio.toFixed(2)}`);
  console.log(`현재가: ${latest.last_price.toLocaleString()}원`);
  console.log(`PER: ${latest.per} / PBR: ${latest.pbr}`);
  console.log(`최근 ${history.length}개 스캔 이력 포함`);
}
▶ 응답 예시 보기
{
  "success": true,
  "ticker": "005930",
  "name": "삼성전자",
  "latest": {
    "scan_date": "20260601",
    "ncav_ratio": 1.423,
    "last_price": 58400,
    "market_cap": 3913440,
    "current_assets": 218193000,
    "total_liabilities": 96299000,
    "net_income": 34400000,
    "per": 11.3,
    "pbr": 0.98,
    "eps": 5170,
    "bps": 59600
  },
  "history": [
    { "scan_date": "20260601", "ncav_ratio": 1.423, "last_price": 58400 },
    { "scan_date": "20260525", "ncav_ratio": 1.401, "last_price": 57200 }
  ]
}

// 종목이 없거나 NCAV 조건 미충족 시
{ "success": false, "error": "NCAV 스캔 결과에 '000000' 종목 없음. 아직 스캔되지 않았거나 NCAV 조건 미충족." }

💡 NCAV 비율 = (유동자산 − 총부채) ÷ 시가총액. 1.0 이상이면 이론적으로 청산가치 이하에 거래중인 종목입니다.

GET /uapi/*

한국투자증권 UAPI 프록시. 국내·해외 시세/잔고/주문.

헤더: X-User-Id, X-User-Role, X-User-Plan 필요

GET /algorithm/trade Public

자동매매 알고리즘 거래 로그 조회. KV IQ_PURCHASE_LOG 기반.

curl "https://idiotquant-backend.tofu89223.workers.dev/algorithm/trade" -H "X-User-Id: YOUR_ID"

🌐 외부 데이터

GET /fmp/* Public

Financial Modeling Prep API 프록시. 미국 재무제표·가격 데이터.

curl "https://idiotquant-backend.tofu89223.workers.dev/fmp/AAPL"
GET /finnhub/* Public

Finnhub API 프록시. 미국 NCAV용 재무제표 (financials-reported). KV 캐시 적용.

curl "https://idiotquant-backend.tofu89223.workers.dev/finnhub/AAPL"
POST /laboratory/llm

Cloudflare Workers AI (LLM) 추론. 모델: @cf/meta/llama-4-scout-17b-16e-instruct

curl -X POST "https://idiotquant-backend.tofu89223.workers.dev/laboratory/llm" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "삼성전자의 NCAV를 설명해줘"}'

🔬 백테스트 / Strategy

GET /backtest/kr/year/:year 🔒 Admin

국내 NCAV 백테스트 수동 실행. KIS API로 전체 종목 스캔 후 KV 저장. index로 중단점 재개 가능.

# 2025년 백테스트 시작
curl "https://idiotquant-backend.tofu89223.workers.dev/backtest/kr/year/2025" -H "X-User-Id: ADMIN_ID"

# 100번 종목부터 재개
curl "https://idiotquant-backend.tofu89223.workers.dev/backtest/kr/year/2025/index/100" -H "X-User-Id: ADMIN_ID"
GET /backtest/us/year/:year 🔒 Admin

미국 NCAV 백테스트 수동 실행. Finnhub + KIS Overseas API 사용.

curl "https://idiotquant-backend.tofu89223.workers.dev/backtest/us/year/2025" -H "X-User-Id: ADMIN_ID"
GET /strategy/kr/ncav/date/latest Public

국내 NCAV 전략 최신 결과 조회 (KV 기반 구버전). 신규 개발에는 /ncav/daily 사용 권장.

curl "https://idiotquant-backend.tofu89223.workers.dev/strategy/kr/ncav/date/latest"
curl "https://idiotquant-backend.tofu89223.workers.dev/strategy/all/ncav/list"

💰 자동매매 계정 / Capital 토큰

자동매매 계정은 D1 trading_accounts 테이블에 등록합니다. KR / US 시장별로 별도 행이며, 스케줄러는 이 테이블을 조회해 활성 계정을 병렬 실행합니다.
Capital 토큰은 D1 capital_tokens 테이블에 저장되며, 매 5분 틱마다 월 예산을 기반으로 active 종목에 균등 적립됩니다.

🔒 Admin trading_accounts 계정 등록 (D1 직접 삽입)

신규 유저 추가는 코드 배포 없이 D1 insert로만 처리합니다. quant_rule_jsonNULL이면 전역 KV 룰 사용.

# KR 계정 등록
npx wrangler d1 execute D1_IDIOTQUANT_MAIN --command="
  INSERT INTO trading_accounts
    (user_id, country, appkey, appsecret, account_number, monthly_budget_krw)
  VALUES ('USER_ID', 'KR', 'APPKEY', 'APPSECRET', 'ACCOUNT_NO', 2000000)
"

# US 계정 등록 (같은 user_id, country만 다름)
npx wrangler d1 execute D1_IDIOTQUANT_MAIN --command="
  INSERT INTO trading_accounts
    (user_id, country, appkey, appsecret, account_number, monthly_budget_krw)
  VALUES ('USER_ID', 'US', 'APPKEY', 'APPSECRET', 'ACCOUNT_NO', 1000000)
"

# per-user 투자 룰 지정 (NULL이면 전역 룰 사용)
npx wrangler d1 execute D1_IDIOTQUANT_MAIN --command="
  UPDATE trading_accounts SET quant_rule_json='{"ncav_ratio":1.5,"active_count":10}'
  WHERE user_id='USER_ID' AND country='KR'
"

💡 monthly_budget_krw: KR과 US 각각의 월 예산(원화). 스케줄러가 자동으로 틱당 적립량 계산.
KR charge rate = monthly×12 / 365 / 10h / 12틱 ÷ active종목수
US charge rate = monthly / 30 / 8h / 12틱 ÷ active종목수

GET /kr/capital 🔒 Admin

국내 자본 토큰 상태 조회 (D1 capital_tokens). 종목별 누적 토큰, 매수/매도 액션, 스캔 인덱스 포함.

curl "https://idiotquant-backend.tofu89223.workers.dev/kr/capital" -H "X-User-Id: ADMIN_ID"

// 응답 (stock_list 발췌)
{
  "stock_list": [
    { "symbol": "005930", "name": "삼성전자", "token": 45200, "action": "active", "ncavRatio": "1.42" },
    ...
  ],
  "charge_info": { "capital_charge_rate": 164 },
  "token_info":  { "refill_stock_index": 3 },
  "action": "buy"
}
GET /us/capital 🔒 Admin

해외 자본 토큰 상태 조회. 환율(frst_bltn_exrt) 포함.

curl "https://idiotquant-backend.tofu89223.workers.dev/us/capital" -H "X-User-Id: ADMIN_ID"
POST /kr/capital/token/plus/{amount}/all 🔒 Admin

active 종목 전체에 토큰 수동 추가. 특정 종목만 추가하려면 /ticker/{symbol} 사용. minus도 동일 패턴.

# 전체 active 종목에 3만원 추가
curl -X POST "https://idiotquant-backend.tofu89223.workers.dev/kr/capital/token/plus/30000/all" -H "X-User-Id: ADMIN_ID"

# 특정 종목(005930)에만 추가
curl -X POST "https://idiotquant-backend.tofu89223.workers.dev/kr/capital/token/plus/30000/ticker/005930" -H "X-User-Id: ADMIN_ID"

# 차감 (전체 / 특정 종목)
curl -X POST "https://idiotquant-backend.tofu89223.workers.dev/kr/capital/token/minus/30000/all" -H "X-User-Id: ADMIN_ID"
curl -X POST "https://idiotquant-backend.tofu89223.workers.dev/us/capital/token/plus/50000/all"  -H "X-User-Id: ADMIN_ID"

변경 내용은 D1 capital_tokens에 즉시 반영되며, 다음 스케줄 틱에 자동매매 로직이 바로 읽습니다.

⚙️ 기타

GET /timestamp

유저 활동 타임스탬프 조회 및 갱신 (KV IQ_TIMESTAMP).

curl "https://idiotquant-backend.tofu89223.workers.dev/timestamp" -H "X-User-Id: YOUR_ID"
GET /api/search-log Public

최근 24시간 종목 검색 순위 조회 (D1 D1_IQ_SEARCH_LOG). 헤더 count로 개수 지정.

# 검색 순위 상위 20개
curl "https://idiotquant-backend.tofu89223.workers.dev/api/search-log" -H "count: 20"

# 검색 기록 저장
curl -X POST "https://idiotquant-backend.tofu89223.workers.dev/api/search-log" \
  -H "Content-Type: application/json" \
  -d '{"ticker":"005930","name":"삼성전자","isUs":false}'
// 검색 순위 조회
const data = await fetch('https://idiotquant-backend.tofu89223.workers.dev/api/search-log', {
  headers: { count: '20' }
}).then(r => r.json());

// 검색 기록 저장
await fetch('https://idiotquant-backend.tofu89223.workers.dev/api/search-log', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ ticker: '005930', name: '삼성전자', isUs: false })
});

📋 공통 응답 형식

모든 NCAV API는 아래 형식으로 응답합니다.

// 성공
{ "success": true,  "data": [...], "meta": { "total": 50, ... } }

// 오류 (400/403/500)
{ "success": false, "error": "오류 메시지" }

• 모든 API는 CORS 헤더를 포함합니다.
• Admin 전용 API는 D1 users 테이블에 role='admin'인 유저만 접근 가능합니다.
X-User-Role 헤더는 무시됩니다 — role은 DB에서만 결정됩니다.

✓ 복사됨!