feat: backtest engine baseline milestone tasks and domain updates
- Add backtest engine baseline milestone tasks (G05, G06, G07) - Update roadmaps and phase files - Add backtest domain types and tests - Move data-foundation phase to archive
This commit is contained in:
parent
128c57bb06
commit
b2f98f3e19
13 changed files with 1221 additions and 7 deletions
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -25,3 +25,7 @@ build/
|
|||
|
||||
# Agent-Ops Private Rules
|
||||
agent-ops/rules/private/
|
||||
|
||||
# Agent-Ops Local Test Rules
|
||||
agent-test/local/
|
||||
agent-test/runs/
|
||||
|
|
|
|||
|
|
@ -13,8 +13,8 @@ ALT는 개인용 quant system workspace로, 한국장 일봉 MVP에서 시작해
|
|||
- [완료] 기반 정렬
|
||||
- 경로: `agent-roadmap/archive/phase/foundation-alignment/PHASE.md`
|
||||
- 요약: agent-first monorepo, Go workspace, contracts, proto-socket session loop, PostgreSQL/Redis worker backbone을 안정화한다.
|
||||
- [검토중] 데이터 기반
|
||||
- 경로: `agent-roadmap/phase/data-foundation/PHASE.md`
|
||||
- [완료] 데이터 기반
|
||||
- 경로: `agent-roadmap/archive/phase/data-foundation/PHASE.md`
|
||||
- 요약: 한국장 일봉을 대상으로 provider-neutral market data import, normalization, persistence를 만든다.
|
||||
- [진행중] 백테스트 루프
|
||||
- 경로: `agent-roadmap/phase/backtest-loop/PHASE.md`
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
## 상태
|
||||
|
||||
[검토중]
|
||||
[완료]
|
||||
|
||||
## 목표
|
||||
|
||||
|
|
@ -2,8 +2,6 @@
|
|||
|
||||
## 활성 Phase
|
||||
|
||||
- [검토중] 데이터 기반
|
||||
- 경로: `agent-roadmap/phase/data-foundation/PHASE.md`
|
||||
- [진행중] 백테스트 루프
|
||||
- 경로: `agent-roadmap/phase/backtest-loop/PHASE.md`
|
||||
- [계획] 운영 표면
|
||||
|
|
|
|||
|
|
@ -33,8 +33,8 @@
|
|||
일봉 기반 전략 실행, portfolio state, result 저장과 fixture 검증 흐름을 묶는다.
|
||||
|
||||
- [ ] [run-lifecycle] backtest run의 pending/running/succeeded/failed/canceled lifecycle이 있다. 검증: worker가 backtest 실행을 소유하고 API는 실행 요청/조회 경계만 담당한다.
|
||||
- [ ] [strategy-port] strategy를 engine에 주입할 port 또는 interface가 있다.
|
||||
- [ ] [portfolio-state] cash, position, equity를 계산하는 최소 portfolio state가 있다.
|
||||
- [x] [strategy-port] strategy를 engine에 주입할 port 또는 interface가 있다.
|
||||
- [x] [portfolio-state] cash, position, equity를 계산하는 최소 portfolio state가 있다.
|
||||
- [ ] [result-store] backtest result가 저장되고 조회된다. 검증: 결과가 contracts/client에서 조회 가능한 형태로 연결될 수 있다.
|
||||
- [ ] [fixture-test] fixture daily bars로 deterministic test가 통과한다. 검증: 동일한 fixture와 strategy 입력으로 동일한 result가 나오고 `bin/test`와 `bin/lint`가 통과한다.
|
||||
|
||||
|
|
@ -61,4 +61,5 @@
|
|||
- 표준선(선택): Go는 Hexagonal Architecture, light CQRS, domain event 표현을 기본 설계 프레임으로 삼는다.
|
||||
- 선행 작업: Korea Daily Data Foundation
|
||||
- 후속 작업: Backtest Analysis Surface
|
||||
- 진행 근거(2026-05-30): `[strategy-port]`, `[portfolio-state]`는 `packages/domain/backtest/types.go`, `packages/domain/backtest/types_test.go`, `go test ./packages/domain/...`로 확인했다.
|
||||
- 확인 필요: 없음
|
||||
|
|
|
|||
|
|
@ -0,0 +1,115 @@
|
|||
<!-- task=m-backtest-engine-baseline/01_worker_lifecycle plan=0 tag=API -->
|
||||
|
||||
# Code Review Reference - API
|
||||
|
||||
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
|
||||
> The task is NOT complete until every implementation-owned section below is filled in.
|
||||
> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving.
|
||||
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
|
||||
> If implementation is blocked by a user-only decision, external environment prerequisite, or scope conflict, fill `사용자 리뷰 요청` with evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`.
|
||||
> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume.
|
||||
> Follow the ownership table at the bottom of this file for which sections you own.
|
||||
|
||||
## 개요
|
||||
|
||||
date=2026-05-30
|
||||
task=m-backtest-engine-baseline/01_worker_lifecycle, plan=0, tag=API
|
||||
|
||||
## 이 파일을 읽는 리뷰 에이전트에게
|
||||
|
||||
> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다.
|
||||
|
||||
각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요.
|
||||
리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다.
|
||||
|
||||
1. 판정을 append한다.
|
||||
2. `CODE_REVIEW-cloud-G06.md` → `code_review_cloud_G06_N.log`, `PLAN-local-G05.md` → `plan_local_G05_M.log`로 아카이브한다.
|
||||
3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-backtest-engine-baseline/01_worker_lifecycle/`로 이동한다. WARN/FAIL이면 user-review gate를 확인한 뒤 다음 active plan/review 파일 또는 `USER_REVIEW.md`를 작성한다.
|
||||
4. PASS이고 task group이 `m-<milestone-slug>`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다.
|
||||
5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다.
|
||||
|
||||
---
|
||||
|
||||
## 구현 항목별 완료 여부
|
||||
|
||||
| 항목 | 완료 여부 |
|
||||
|------|---------|
|
||||
| [API-1] Worker-owned run lifecycle | [ ] |
|
||||
|
||||
## 구현 체크리스트
|
||||
|
||||
- [ ] `run_backtest` payload decode와 validation을 추가한다.
|
||||
- [ ] worker-owned lifecycle handler를 추가해 pending/running/succeeded/failed 상태를 `BacktestRunStore`에 기록한다.
|
||||
- [ ] strategy port와 bar source를 주입받는 최소 executor를 추가한다.
|
||||
- [ ] lifecycle 성공/실패 unit test를 작성하고 `go test ./services/worker/...`를 통과시킨다.
|
||||
- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
|
||||
|
||||
## 코드리뷰 전용 체크리스트
|
||||
|
||||
> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다.
|
||||
> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다.
|
||||
|
||||
- [ ] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다.
|
||||
- [ ] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다.
|
||||
- [ ] active `CODE_REVIEW-*-G??.md`를 `code_review_{review_lane}_GNN_N.log`로 아카이브한다.
|
||||
- [ ] active `PLAN-*-G??.md`를 `plan_{build_lane}_GNN_M.log`로 아카이브한다.
|
||||
- [ ] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다.
|
||||
- [ ] PASS이면 active task 디렉터리 `agent-task/{task_name}/`를 `agent-task/archive/YYYY/MM/{task_name}/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다.
|
||||
- [ ] PASS이고 task group이 `m-<milestone-slug>`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다.
|
||||
- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/{task_group}/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다.
|
||||
- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-{build_lane}-GNN.md`와 `CODE_REVIEW-{review_lane}-GNN.md`를 작성하고 `complete.log`를 작성하지 않는다.
|
||||
- [ ] USER_REVIEW이면 `agent-ops/skills/common/code-review/templates/user-review-template.md` 기준으로 `USER_REVIEW.md`를 작성하고 active `PLAN-*.md`, `CODE_REVIEW-*.md`, `complete.log`를 남기지 않는다.
|
||||
- [ ] USER_REVIEW가 사용자 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다.
|
||||
|
||||
## 계획 대비 변경 사항
|
||||
|
||||
_구현 에이전트가 계획과 다르게 구현한 부분을 이유와 함께 기록한다._
|
||||
|
||||
## 주요 설계 결정
|
||||
|
||||
_구현 에이전트가 주요 설계 결정 사항을 기록한다._
|
||||
|
||||
## 사용자 리뷰 요청
|
||||
|
||||
_기본값은 `없음`이다. 구현 중 사용자 결정, 외부 환경 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. code-review가 이 내용을 검증해 `USER_REVIEW.md`를 작성한다._
|
||||
|
||||
- 상태: 없음
|
||||
- 사유 유형: 없음
|
||||
- 결정 필요: 없음
|
||||
- 차단 근거: 없음
|
||||
- 실행한 검증/명령: 없음
|
||||
- 재개 조건: 없음
|
||||
|
||||
## 리뷰어를 위한 체크포인트
|
||||
|
||||
- `KindRunBacktest`가 placeholder 성공 경로가 아니라 worker-owned handler로 override되는지 확인한다.
|
||||
- failure path가 failed run status를 남기고 원 error를 보존하는지 확인한다.
|
||||
- result persistence나 API/client 작업이 이 subtask에 섞이지 않았는지 확인한다.
|
||||
|
||||
## 검증 결과
|
||||
|
||||
_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._
|
||||
|
||||
필수 규칙:
|
||||
- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다.
|
||||
- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다.
|
||||
- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다.
|
||||
- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다.
|
||||
|
||||
### API-1 중간 검증
|
||||
```
|
||||
$ go test ./services/worker/...
|
||||
(output)
|
||||
```
|
||||
|
||||
### 최종 검증
|
||||
```
|
||||
$ go test ./services/worker/...
|
||||
(output)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?**
|
||||
> If anything is blank, go back and fill it in before saving this file.
|
||||
> Leave review-agent-only sections unchanged.
|
||||
|
|
@ -0,0 +1,153 @@
|
|||
<!-- task=m-backtest-engine-baseline/01_worker_lifecycle plan=0 tag=API -->
|
||||
|
||||
# Backtest Worker Lifecycle Plan
|
||||
|
||||
## 이 파일을 읽는 구현 에이전트에게
|
||||
|
||||
`CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션 작성은 필수다. 구현 후 검증을 실행하고 실제 변경 내용, 검증 출력, 계획 대비 변경 사항을 채운 뒤 active 파일을 그대로 두고 리뷰 준비를 보고한다. 사용자 결정, 외부 환경 준비, 범위 충돌 없이는 진행할 수 없으면 review stub의 `사용자 리뷰 요청` 섹션을 근거와 함께 채우고 멈춘다. `USER_REVIEW.md`, archive log, `complete.log` 작성은 code-review 전용이다.
|
||||
|
||||
## 배경
|
||||
|
||||
현재 worker는 `run_backtest` kind를 갖고 있지만 built-in placeholder만 등록한다. `Backtest Engine Baseline`의 lifecycle 조건을 만족하려면 worker가 run 상태 전이를 소유하고 API는 요청/조회 경계에 머물 수 있는 실행 포트가 필요하다. 이 subtask는 result persistence 전 단계로, 실행 시작부터 성공/실패 상태 기록까지의 worker lifecycle skeleton을 만든다.
|
||||
|
||||
## 사용자 리뷰 요청 흐름
|
||||
|
||||
구현 중 blocker는 active review stub의 `사용자 리뷰 요청` 섹션에 기록한다. code-review가 이 내용을 검증하고 실제 `USER_REVIEW.md` 작성 여부를 결정한다.
|
||||
|
||||
## 분석 결과
|
||||
|
||||
### 읽은 파일
|
||||
|
||||
- `agent-roadmap/current.md`
|
||||
- `agent-roadmap/phase/backtest-loop/PHASE.md`
|
||||
- `agent-roadmap/phase/backtest-loop/milestones/backtest-engine-baseline.md`
|
||||
- `agent-ops/rules/project/domain/domain-model/rules.md`
|
||||
- `agent-ops/rules/project/domain/worker/rules.md`
|
||||
- `agent-test/local/rules.md`
|
||||
- `agent-test/local/domain-model-smoke.md`
|
||||
- `agent-test/local/worker-smoke.md`
|
||||
- `packages/domain/backtest/types.go`
|
||||
- `packages/domain/backtest/types_test.go`
|
||||
- `packages/domain/market/types.go`
|
||||
- `services/worker/internal/jobs/job.go`
|
||||
- `services/worker/internal/jobs/runner.go`
|
||||
- `services/worker/internal/jobs/builtin.go`
|
||||
- `services/worker/internal/jobs/runner_test.go`
|
||||
- `services/worker/internal/jobs/marketdata_jobs.go`
|
||||
- `services/worker/internal/jobs/marketdata_jobs_test.go`
|
||||
- `services/worker/internal/storage/ports.go`
|
||||
- `services/worker/internal/storage/postgres/store.go`
|
||||
- `services/worker/internal/storage/postgres/mapping.go`
|
||||
- `services/worker/internal/storage/postgres/mapping_test.go`
|
||||
- `services/worker/cmd/alt-worker/main.go`
|
||||
|
||||
### 테스트 커버리지 공백
|
||||
|
||||
- `KindRunBacktest`는 `services/worker/internal/jobs/builtin.go:21`에서 placeholder만 테스트 없이 성공한다. 새 handler decode, store 상태 전이, strategy 호출, 실패 상태 전이 테스트가 필요하다.
|
||||
- `backtest.Strategy`와 `PortfolioState`는 `packages/domain/backtest/types_test.go`에서 주입/계산 기본 테스트가 있다.
|
||||
- worker runner dispatch/panic/cancel coverage는 `services/worker/internal/jobs/runner_test.go`에 있다.
|
||||
|
||||
### 심볼 참조
|
||||
|
||||
- renamed/removed symbols: none.
|
||||
- `KindRunBacktest` call sites: `services/worker/internal/jobs/job.go:11`, `services/worker/internal/jobs/builtin.go:21`.
|
||||
|
||||
### 분할 판단
|
||||
|
||||
Split policy를 먼저 평가했다. Shared task group은 `m-backtest-engine-baseline`이다.
|
||||
|
||||
- `01_worker_lifecycle`: worker execution lifecycle skeleton. 독립 시작 가능.
|
||||
- `02+01_result_store`: storage/protobuf result persistence. `01_worker_lifecycle`의 run execution boundary에 의존한다.
|
||||
- `03+01,02_fixture_verification`: deterministic fixture full-path test. lifecycle과 result store 둘 다에 의존한다.
|
||||
|
||||
worker lifecycle, storage/schema, fixture verification은 ownership과 위험이 달라 multi-plan이 맞다.
|
||||
|
||||
### 범위 결정 근거
|
||||
|
||||
이 plan은 `run_backtest` worker handler와 execution skeleton만 다룬다. `backtest_results` schema, protobuf result 확장, API/client 조회 연결은 `02+01_result_store`에서 다룬다. fixture full-cycle과 `bin/test`/`bin/lint` milestone 검증은 `03+01,02_fixture_verification`에서 다룬다.
|
||||
|
||||
### 빌드 등급
|
||||
|
||||
build=`local-G05`, review=`cloud-G06`. worker 내부 handler와 unit test 중심이라 local 구현이 가능하지만 lifecycle 상태 전이는 review에서 의미 검증이 필요하다.
|
||||
|
||||
## 구현 체크리스트
|
||||
|
||||
- [ ] `run_backtest` payload decode와 validation을 추가한다.
|
||||
- [ ] worker-owned lifecycle handler를 추가해 pending/running/succeeded/failed 상태를 `BacktestRunStore`에 기록한다.
|
||||
- [ ] strategy port와 bar source를 주입받는 최소 executor를 추가한다.
|
||||
- [ ] lifecycle 성공/실패 unit test를 작성하고 `go test ./services/worker/...`를 통과시킨다.
|
||||
- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
|
||||
|
||||
### [API-1] Worker-owned run lifecycle
|
||||
|
||||
#### 문제
|
||||
|
||||
`services/worker/internal/jobs/builtin.go:21`-`24`는 `KindRunBacktest`를 성공하는 placeholder로 처리한다.
|
||||
|
||||
```go
|
||||
runner.Register(KindRunBacktest, func(ctx context.Context, payload json.RawMessage) error {
|
||||
slog.Info("executing built-in job: run backtest", "payload_len", len(payload))
|
||||
return nil
|
||||
})
|
||||
```
|
||||
|
||||
이 상태에서는 worker가 backtest 실행을 소유한다는 검증 조건을 충족하지 못하고, run 상태도 `pending/running/succeeded/failed`로 전이되지 않는다.
|
||||
|
||||
#### 해결 방법
|
||||
|
||||
`services/worker/internal/jobs/backtest_jobs.go`를 추가해 `RunBacktestPayload`, `DecodeRunBacktestPayload`, `RegisterRunBacktestHandler`를 둔다. handler는 payload를 `backtest.RunSpec`으로 변환하고, `storage.BacktestRunStore`에 running 상태를 기록한 뒤 executor를 호출하고 succeeded/failed 상태로 갱신한다.
|
||||
|
||||
```go
|
||||
type BacktestExecutor interface {
|
||||
Execute(ctx context.Context, run backtest.Run) error
|
||||
}
|
||||
|
||||
func RegisterRunBacktestHandler(runner *Runner, store storage.BacktestRunStore, executor BacktestExecutor, now func() time.Time)
|
||||
```
|
||||
|
||||
실제 engine 계산은 작게 유지한다. bar source와 strategy port를 받는 executor skeleton은 `services/worker/internal/backtest/` 아래에 두고, result persistence는 다음 subtask로 넘긴다.
|
||||
|
||||
#### 수정 파일 및 체크리스트
|
||||
|
||||
- [ ] `services/worker/internal/jobs/backtest_jobs.go` 추가
|
||||
- [ ] `services/worker/internal/jobs/backtest_jobs_test.go` 추가
|
||||
- [ ] `services/worker/internal/jobs/builtin.go`는 placeholder 유지 여부를 결정하되 live handler가 override하는 패턴을 daily import와 맞춘다.
|
||||
- [ ] `services/worker/internal/backtest/engine.go` 추가
|
||||
- [ ] `services/worker/internal/backtest/engine_test.go` 추가
|
||||
|
||||
#### 테스트 작성
|
||||
|
||||
작성한다.
|
||||
|
||||
- `TestRegisterRunBacktestHandlerTransitionsSucceeded`: decoded payload -> running -> succeeded UpsertRun 순서와 executor 호출 확인
|
||||
- `TestRegisterRunBacktestHandlerTransitionsFailed`: executor error -> failed UpsertRun 확인
|
||||
- `TestDecodeRunBacktestPayloadRejectsMissingFields`: strategy_id, market, timeframe, from/to 누락 또는 역전 거부
|
||||
- `TestEngineCallsStrategyForBars`: fixture bars를 strategy input으로 전달하는 최소 engine test
|
||||
|
||||
#### 중간 검증
|
||||
|
||||
```bash
|
||||
go test ./services/worker/...
|
||||
```
|
||||
|
||||
기대 결과: exit code 0. Go test cache 출력은 허용한다.
|
||||
|
||||
## 수정 파일 요약
|
||||
|
||||
| 파일 | 항목 |
|
||||
|------|------|
|
||||
| `services/worker/internal/jobs/backtest_jobs.go` | API-1 |
|
||||
| `services/worker/internal/jobs/backtest_jobs_test.go` | API-1 |
|
||||
| `services/worker/internal/jobs/builtin.go` | API-1 |
|
||||
| `services/worker/internal/backtest/engine.go` | API-1 |
|
||||
| `services/worker/internal/backtest/engine_test.go` | API-1 |
|
||||
|
||||
## 최종 검증
|
||||
|
||||
```bash
|
||||
go test ./services/worker/...
|
||||
```
|
||||
|
||||
기대 결과: exit code 0. Go test cache 출력은 허용한다.
|
||||
|
||||
모든 코드 변경 완료 후 반드시 `CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다.
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
<!-- task=m-backtest-engine-baseline/02+01_result_store plan=0 tag=API -->
|
||||
|
||||
# Code Review Reference - API
|
||||
|
||||
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
|
||||
> The task is NOT complete until every implementation-owned section below is filled in.
|
||||
> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving.
|
||||
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
|
||||
> If implementation is blocked by a user-only decision, external environment prerequisite, or scope conflict, fill `사용자 리뷰 요청` with evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`.
|
||||
> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume.
|
||||
> Follow the ownership table at the bottom of this file for which sections you own.
|
||||
|
||||
## 개요
|
||||
|
||||
date=2026-05-30
|
||||
task=m-backtest-engine-baseline/02+01_result_store, plan=0, tag=API
|
||||
|
||||
## 이 파일을 읽는 리뷰 에이전트에게
|
||||
|
||||
> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다.
|
||||
|
||||
각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요.
|
||||
리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다.
|
||||
|
||||
1. 판정을 append한다.
|
||||
2. `CODE_REVIEW-cloud-G07.md` → `code_review_cloud_G07_N.log`, `PLAN-cloud-G07.md` → `plan_cloud_G07_M.log`로 아카이브한다.
|
||||
3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-backtest-engine-baseline/02+01_result_store/`로 이동한다. WARN/FAIL이면 user-review gate를 확인한 뒤 다음 active plan/review 파일 또는 `USER_REVIEW.md`를 작성한다.
|
||||
4. PASS이고 task group이 `m-<milestone-slug>`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다.
|
||||
5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다.
|
||||
|
||||
---
|
||||
|
||||
## 구현 항목별 완료 여부
|
||||
|
||||
| 항목 | 완료 여부 |
|
||||
|------|---------|
|
||||
| [API-1] Result domain and contract shape | [ ] |
|
||||
| [API-2] Result persistence and query | [ ] |
|
||||
|
||||
## 구현 체크리스트
|
||||
|
||||
- [ ] `backtest.Result`에 trades/positions summary를 additive로 확장한다.
|
||||
- [ ] protobuf `BacktestResult`를 additive field number로 확장하고 generated Go/Dart code를 갱신한다.
|
||||
- [ ] PostgreSQL `backtest_results` schema, sqlc queries, storage port/store/mapping을 추가한다.
|
||||
- [ ] result mapping/store tests와 parser map regression을 작성하거나 갱신한다.
|
||||
- [ ] `bin/contracts-check`, `bin/worker-storage-gen`, `go test ./packages/domain/...`, `go test ./services/worker/...`, `go test ./services/api/...`를 통과시킨다.
|
||||
- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
|
||||
|
||||
## 코드리뷰 전용 체크리스트
|
||||
|
||||
> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다.
|
||||
> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다.
|
||||
|
||||
- [ ] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다.
|
||||
- [ ] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다.
|
||||
- [ ] active `CODE_REVIEW-*-G??.md`를 `code_review_{review_lane}_GNN_N.log`로 아카이브한다.
|
||||
- [ ] active `PLAN-*-G??.md`를 `plan_{build_lane}_GNN_M.log`로 아카이브한다.
|
||||
- [ ] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다.
|
||||
- [ ] PASS이면 active task 디렉터리 `agent-task/{task_name}/`를 `agent-task/archive/YYYY/MM/{task_name}/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다.
|
||||
- [ ] PASS이고 task group이 `m-<milestone-slug>`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다.
|
||||
- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/{task_group}/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다.
|
||||
- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-{build_lane}-GNN.md`와 `CODE_REVIEW-{review_lane}-GNN.md`를 작성하고 `complete.log`를 작성하지 않는다.
|
||||
- [ ] USER_REVIEW이면 `agent-ops/skills/common/code-review/templates/user-review-template.md` 기준으로 `USER_REVIEW.md`를 작성하고 active `PLAN-*.md`, `CODE_REVIEW-*.md`, `complete.log`를 남기지 않는다.
|
||||
- [ ] USER_REVIEW가 사용자 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다.
|
||||
|
||||
## 계획 대비 변경 사항
|
||||
|
||||
_구현 에이전트가 계획과 다르게 구현한 부분을 이유와 함께 기록한다._
|
||||
|
||||
## 주요 설계 결정
|
||||
|
||||
_구현 에이전트가 주요 설계 결정 사항을 기록한다._
|
||||
|
||||
## 사용자 리뷰 요청
|
||||
|
||||
_기본값은 `없음`이다. 구현 중 사용자 결정, 외부 환경 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. code-review가 이 내용을 검증해 `USER_REVIEW.md`를 작성한다._
|
||||
|
||||
- 상태: 없음
|
||||
- 사유 유형: 없음
|
||||
- 결정 필요: 없음
|
||||
- 차단 근거: 없음
|
||||
- 실행한 검증/명령: 없음
|
||||
- 재개 조건: 없음
|
||||
|
||||
## 리뷰어를 위한 체크포인트
|
||||
|
||||
- protobuf field numbers 1-3이 보존되고 additive field만 추가되었는지 확인한다.
|
||||
- generated Go/Dart output이 source proto와 일치하는지 확인한다.
|
||||
- storage mapping이 numeric decimal을 float 의미로 손상하지 않는지 확인한다.
|
||||
- `02+01_result_store`가 `01_worker_lifecycle` 완료에 의존한다는 실행 순서를 지켰는지 확인한다.
|
||||
|
||||
## 검증 결과
|
||||
|
||||
_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._
|
||||
|
||||
필수 규칙:
|
||||
- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다.
|
||||
- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다.
|
||||
- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다.
|
||||
- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다.
|
||||
|
||||
### API-1 중간 검증
|
||||
```
|
||||
$ bin/contracts-check
|
||||
(output)
|
||||
```
|
||||
|
||||
### API-2 중간 검증
|
||||
```
|
||||
$ bin/worker-storage-gen && go test ./services/worker/...
|
||||
(output)
|
||||
```
|
||||
|
||||
### 최종 검증
|
||||
```
|
||||
$ bin/contracts-check
|
||||
$ bin/worker-storage-gen
|
||||
$ go test ./packages/domain/...
|
||||
$ go test ./services/worker/...
|
||||
$ go test ./services/api/...
|
||||
(output)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?**
|
||||
> If anything is blank, go back and fill it in before saving this file.
|
||||
> Leave review-agent-only sections unchanged.
|
||||
|
|
@ -0,0 +1,200 @@
|
|||
<!-- task=m-backtest-engine-baseline/02+01_result_store plan=0 tag=API -->
|
||||
|
||||
# Backtest Result Store Plan
|
||||
|
||||
## 이 파일을 읽는 구현 에이전트에게
|
||||
|
||||
`CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션 작성은 필수다. 구현 후 검증을 실행하고 실제 변경 내용, 검증 출력, 계획 대비 변경 사항을 채운 뒤 active 파일을 그대로 두고 리뷰 준비를 보고한다. 사용자 결정, 외부 환경 준비, 범위 충돌 없이는 진행할 수 없으면 review stub의 `사용자 리뷰 요청` 섹션을 근거와 함께 채우고 멈춘다. `USER_REVIEW.md`, archive log, `complete.log` 작성은 code-review 전용이다.
|
||||
|
||||
## 배경
|
||||
|
||||
`BacktestResult` 계약은 이미 있지만 worker storage에는 run만 있고 result 저장/조회가 없다. 마일스톤 범위는 starting cash, ending equity, trades/positions summary를 요구하므로 domain, storage, contract가 같은 shape로 연결되어야 한다. 이 subtask는 lifecycle handler가 만든 run을 기준으로 result persistence와 query port를 만든다.
|
||||
|
||||
## 사용자 리뷰 요청 흐름
|
||||
|
||||
구현 중 blocker는 active review stub의 `사용자 리뷰 요청` 섹션에 기록한다. code-review가 이 내용을 검증하고 실제 `USER_REVIEW.md` 작성 여부를 결정한다.
|
||||
|
||||
## 분석 결과
|
||||
|
||||
### 읽은 파일
|
||||
|
||||
- `agent-roadmap/current.md`
|
||||
- `agent-roadmap/phase/backtest-loop/PHASE.md`
|
||||
- `agent-roadmap/phase/backtest-loop/milestones/backtest-engine-baseline.md`
|
||||
- `agent-ops/rules/project/domain/contracts/rules.md`
|
||||
- `agent-ops/rules/project/domain/domain-model/rules.md`
|
||||
- `agent-ops/rules/project/domain/worker/rules.md`
|
||||
- `agent-test/local/rules.md`
|
||||
- `agent-test/local/contracts-smoke.md`
|
||||
- `agent-test/local/domain-model-smoke.md`
|
||||
- `agent-test/local/worker-smoke.md`
|
||||
- `packages/domain/backtest/types.go`
|
||||
- `packages/contracts/proto/alt/v1/backtest.proto`
|
||||
- `services/api/internal/contracts/parser_map.go`
|
||||
- `services/api/internal/contracts/parser_map_test.go`
|
||||
- `services/worker/internal/storage/ports.go`
|
||||
- `services/worker/internal/storage/postgres/migrations/000001_worker_backbone.up.sql`
|
||||
- `services/worker/internal/storage/postgres/migrations/000001_worker_backbone.down.sql`
|
||||
- `services/worker/internal/storage/postgres/queries/queries.sql`
|
||||
- `services/worker/internal/storage/postgres/store.go`
|
||||
- `services/worker/internal/storage/postgres/mapping.go`
|
||||
- `services/worker/internal/storage/postgres/mapping_test.go`
|
||||
- `services/worker/sqlc.yaml`
|
||||
- `bin/contracts-gen`
|
||||
- `bin/contracts-check`
|
||||
- `bin/worker-storage-gen`
|
||||
|
||||
### 테스트 커버리지 공백
|
||||
|
||||
- `services/worker/internal/storage/ports.go:22`-`25` exposes run persistence only; result store behavior has no tests.
|
||||
- `services/worker/internal/storage/postgres/migrations/000001_worker_backbone.up.sql:23`-`33` creates `backtest_runs`, but no `backtest_results` table exists.
|
||||
- `packages/contracts/proto/alt/v1/backtest.proto:51`-`55` has cash/equity only, so trades/positions summary is not representable yet.
|
||||
- API parser already registers `BacktestResult` and result request/response, but generated changes still need parser map tests rerun.
|
||||
|
||||
### 심볼 참조
|
||||
|
||||
- renamed/removed symbols: none. Additive proto fields only.
|
||||
- `BacktestResult` references: `packages/contracts/proto/alt/v1/backtest.proto`, generated Go/Dart contracts, `services/api/internal/contracts/parser_map.go`, `services/api/internal/contracts/parser_map_test.go`, `apps/client/lib/src/contracts/alt_contracts.dart`.
|
||||
|
||||
### 분할 판단
|
||||
|
||||
Split policy를 먼저 평가했다. 이 subtask는 `02+01_result_store`이며 `01_worker_lifecycle` complete.log에 의존한다. Storage/migration/protocol schema가 함께 움직이므로 별도 cloud-grade plan이 필요하다. `03+01,02_fixture_verification`은 이 subtask 이후에 전체 deterministic result를 검증한다.
|
||||
|
||||
### 범위 결정 근거
|
||||
|
||||
이 plan은 result shape, persistence, query store, generated contract drift만 다룬다. 실제 worker execution wiring은 `01_worker_lifecycle` 범위다. fixture full-cycle과 `bin/test`/`bin/lint` 완료 판정은 `03+01,02_fixture_verification`에서 다룬다.
|
||||
|
||||
### 빌드 등급
|
||||
|
||||
build=`cloud-G07`, review=`cloud-G07`. Migration, sqlc generation, protobuf compatibility, generated code가 함께 움직이는 고위험 cross-domain 작업이다.
|
||||
|
||||
## 의존 관계 및 구현 순서
|
||||
|
||||
이 task directory 이름은 `02+01_result_store`다. 같은 task group의 `01_worker_lifecycle`이 `complete.log`를 만든 뒤 시작한다.
|
||||
|
||||
## 구현 체크리스트
|
||||
|
||||
- [ ] `backtest.Result`에 trades/positions summary를 additive로 확장한다.
|
||||
- [ ] protobuf `BacktestResult`를 additive field number로 확장하고 generated Go/Dart code를 갱신한다.
|
||||
- [ ] PostgreSQL `backtest_results` schema, sqlc queries, storage port/store/mapping을 추가한다.
|
||||
- [ ] result mapping/store tests와 parser map regression을 작성하거나 갱신한다.
|
||||
- [ ] `bin/contracts-check`, `bin/worker-storage-gen`, `go test ./packages/domain/...`, `go test ./services/worker/...`, `go test ./services/api/...`를 통과시킨다.
|
||||
- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
|
||||
|
||||
### [API-1] Result domain and contract shape
|
||||
|
||||
#### 문제
|
||||
|
||||
`packages/contracts/proto/alt/v1/backtest.proto:51`-`55`는 `BacktestResult`에 `run_id`, `starting_cash`, `ending_equity`만 둔다.
|
||||
|
||||
```proto
|
||||
message BacktestResult {
|
||||
string run_id = 1;
|
||||
Price starting_cash = 2;
|
||||
Price ending_equity = 3;
|
||||
}
|
||||
```
|
||||
|
||||
마일스톤 범위의 trades/positions summary가 wire format과 domain vocabulary에 없다.
|
||||
|
||||
#### 해결 방법
|
||||
|
||||
`packages/domain/backtest/types.go`의 `Result`에 `Trades []TradeSummary`, `Positions []PositionSummary`를 추가한다. `backtest.proto`에는 `BacktestTrade`와 `BacktestPosition` message를 추가하고 `BacktestResult`에 `repeated` fields를 새 field number로 추가한다. 기존 field number 1-3은 변경하지 않는다.
|
||||
|
||||
#### 수정 파일 및 체크리스트
|
||||
|
||||
- [ ] `packages/domain/backtest/types.go`
|
||||
- [ ] `packages/domain/backtest/types_test.go`
|
||||
- [ ] `packages/contracts/proto/alt/v1/backtest.proto`
|
||||
- [ ] `packages/contracts/gen/go/alt/v1/backtest.pb.go` generated
|
||||
- [ ] `apps/client/lib/src/generated/alt/v1/backtest.pb.dart` generated
|
||||
- [ ] 관련 generated enum/json 파일 generated
|
||||
|
||||
#### 테스트 작성
|
||||
|
||||
작성한다. Domain result summary field construction test를 추가하고, contract generation 후 API parser map test가 계속 통과하는지 확인한다.
|
||||
|
||||
#### 중간 검증
|
||||
|
||||
```bash
|
||||
bin/contracts-check
|
||||
```
|
||||
|
||||
기대 결과: exit code 0. Generated drift가 있으면 `bin/contracts-gen`으로 반영 후 같은 명령을 재실행한다.
|
||||
|
||||
### [API-2] Result persistence and query
|
||||
|
||||
#### 문제
|
||||
|
||||
`services/worker/internal/storage/ports.go:22`-`25`는 `BacktestRunStore`만 제공한다.
|
||||
|
||||
```go
|
||||
type BacktestRunStore interface {
|
||||
UpsertRun(ctx context.Context, run backtest.Run) error
|
||||
GetRun(ctx context.Context, id backtest.RunID) (backtest.Run, error)
|
||||
}
|
||||
```
|
||||
|
||||
`services/worker/internal/storage/postgres/migrations/000001_worker_backbone.up.sql:23`-`33`에도 run table만 있고 result table이 없다.
|
||||
|
||||
#### 해결 방법
|
||||
|
||||
`BacktestResultStore`를 추가하고 `UpsertResult`, `GetResult`를 제공한다. Migration에는 `backtest_results`를 `run_id` PK/FK로 추가하고 cash/equity numeric fields와 trades/positions JSONB summary를 저장한다. `queries.sql`에 `UpsertResult`, `GetResult`를 추가하고 `bin/worker-storage-gen`으로 sqlc code를 갱신한다.
|
||||
|
||||
#### 수정 파일 및 체크리스트
|
||||
|
||||
- [ ] `services/worker/internal/storage/ports.go`
|
||||
- [ ] `services/worker/internal/storage/postgres/migrations/000001_worker_backbone.up.sql`
|
||||
- [ ] `services/worker/internal/storage/postgres/migrations/000001_worker_backbone.down.sql`
|
||||
- [ ] `services/worker/internal/storage/postgres/queries/queries.sql`
|
||||
- [ ] `services/worker/internal/storage/postgres/sqlc/*.go` generated
|
||||
- [ ] `services/worker/internal/storage/postgres/store.go`
|
||||
- [ ] `services/worker/internal/storage/postgres/mapping.go`
|
||||
- [ ] `services/worker/internal/storage/postgres/mapping_test.go`
|
||||
|
||||
#### 테스트 작성
|
||||
|
||||
작성한다.
|
||||
|
||||
- `TestBacktestResultMappingRoundTrip`: domain result -> sqlc params/row -> domain result
|
||||
- `TestBacktestResultMappingRejectsInvalidDecimal`: invalid numeric fields fail before persistence
|
||||
- Migration embed test는 기존 `migrate_test.go`가 up/down count를 확인하므로 추가 migration 파일을 만들면 version order를 맞춘다.
|
||||
|
||||
#### 중간 검증
|
||||
|
||||
```bash
|
||||
bin/worker-storage-gen && go test ./services/worker/...
|
||||
```
|
||||
|
||||
기대 결과: exit code 0. sqlc generated output이 repo 안에 반영되어야 한다.
|
||||
|
||||
## 수정 파일 요약
|
||||
|
||||
| 파일 | 항목 |
|
||||
|------|------|
|
||||
| `packages/domain/backtest/types.go` | API-1 |
|
||||
| `packages/domain/backtest/types_test.go` | API-1 |
|
||||
| `packages/contracts/proto/alt/v1/backtest.proto` | API-1 |
|
||||
| `packages/contracts/gen/go/alt/v1/backtest.pb.go` | API-1 |
|
||||
| `apps/client/lib/src/generated/alt/v1/backtest.pb.dart` | API-1 |
|
||||
| `services/worker/internal/storage/ports.go` | API-2 |
|
||||
| `services/worker/internal/storage/postgres/migrations/*.sql` | API-2 |
|
||||
| `services/worker/internal/storage/postgres/queries/queries.sql` | API-2 |
|
||||
| `services/worker/internal/storage/postgres/sqlc/*.go` | API-2 |
|
||||
| `services/worker/internal/storage/postgres/store.go` | API-2 |
|
||||
| `services/worker/internal/storage/postgres/mapping.go` | API-2 |
|
||||
| `services/worker/internal/storage/postgres/mapping_test.go` | API-2 |
|
||||
|
||||
## 최종 검증
|
||||
|
||||
```bash
|
||||
bin/contracts-check
|
||||
bin/worker-storage-gen
|
||||
go test ./packages/domain/...
|
||||
go test ./services/worker/...
|
||||
go test ./services/api/...
|
||||
```
|
||||
|
||||
기대 결과: 모든 명령 exit code 0. Generated output이 바뀌면 변경으로 포함한다.
|
||||
|
||||
모든 코드 변경 완료 후 반드시 `CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다.
|
||||
|
|
@ -0,0 +1,117 @@
|
|||
<!-- task=m-backtest-engine-baseline/03+01,02_fixture_verification plan=0 tag=TEST -->
|
||||
|
||||
# Code Review Reference - TEST
|
||||
|
||||
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
|
||||
> The task is NOT complete until every implementation-owned section below is filled in.
|
||||
> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving.
|
||||
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
|
||||
> If implementation is blocked by a user-only decision, external environment prerequisite, or scope conflict, fill `사용자 리뷰 요청` with evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`.
|
||||
> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume.
|
||||
> Follow the ownership table at the bottom of this file for which sections you own.
|
||||
|
||||
## 개요
|
||||
|
||||
date=2026-05-30
|
||||
task=m-backtest-engine-baseline/03+01,02_fixture_verification, plan=0, tag=TEST
|
||||
|
||||
## 이 파일을 읽는 리뷰 에이전트에게
|
||||
|
||||
> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다.
|
||||
|
||||
각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요.
|
||||
리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다.
|
||||
|
||||
1. 판정을 append한다.
|
||||
2. `CODE_REVIEW-cloud-G06.md` → `code_review_cloud_G06_N.log`, `PLAN-local-G06.md` → `plan_local_G06_M.log`로 아카이브한다.
|
||||
3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-backtest-engine-baseline/03+01,02_fixture_verification/`로 이동한다. WARN/FAIL이면 user-review gate를 확인한 뒤 다음 active plan/review 파일 또는 `USER_REVIEW.md`를 작성한다.
|
||||
4. PASS이고 task group이 `m-<milestone-slug>`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다.
|
||||
5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다.
|
||||
|
||||
---
|
||||
|
||||
## 구현 항목별 완료 여부
|
||||
|
||||
| 항목 | 완료 여부 |
|
||||
|------|---------|
|
||||
| [TEST-1] Deterministic fixture full path | [ ] |
|
||||
|
||||
## 구현 체크리스트
|
||||
|
||||
- [ ] fixture daily bars와 deterministic test strategy를 추가한다.
|
||||
- [ ] engine execution이 동일 fixture와 strategy 입력에서 동일 result를 두 번 생성함을 검증한다.
|
||||
- [ ] result store 조회가 expected starting cash, ending equity, trades/positions summary를 반환함을 검증한다.
|
||||
- [ ] `bin/test`와 `bin/lint`를 실행해 fixture-test 검증 조건을 충족한다.
|
||||
- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
|
||||
|
||||
## 코드리뷰 전용 체크리스트
|
||||
|
||||
> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다.
|
||||
> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다.
|
||||
|
||||
- [ ] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다.
|
||||
- [ ] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다.
|
||||
- [ ] active `CODE_REVIEW-*-G??.md`를 `code_review_{review_lane}_GNN_N.log`로 아카이브한다.
|
||||
- [ ] active `PLAN-*-G??.md`를 `plan_{build_lane}_GNN_M.log`로 아카이브한다.
|
||||
- [ ] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다.
|
||||
- [ ] PASS이면 active task 디렉터리 `agent-task/{task_name}/`를 `agent-task/archive/YYYY/MM/{task_name}/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다.
|
||||
- [ ] PASS이고 task group이 `m-<milestone-slug>`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다.
|
||||
- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/{task_group}/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다.
|
||||
- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-{build_lane}-GNN.md`와 `CODE_REVIEW-{review_lane}-GNN.md`를 작성하고 `complete.log`를 작성하지 않는다.
|
||||
- [ ] USER_REVIEW이면 `agent-ops/skills/common/code-review/templates/user-review-template.md` 기준으로 `USER_REVIEW.md`를 작성하고 active `PLAN-*.md`, `CODE_REVIEW-*.md`, `complete.log`를 남기지 않는다.
|
||||
- [ ] USER_REVIEW가 사용자 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다.
|
||||
|
||||
## 계획 대비 변경 사항
|
||||
|
||||
_구현 에이전트가 계획과 다르게 구현한 부분을 이유와 함께 기록한다._
|
||||
|
||||
## 주요 설계 결정
|
||||
|
||||
_구현 에이전트가 주요 설계 결정 사항을 기록한다._
|
||||
|
||||
## 사용자 리뷰 요청
|
||||
|
||||
_기본값은 `없음`이다. 구현 중 사용자 결정, 외부 환경 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. code-review가 이 내용을 검증해 `USER_REVIEW.md`를 작성한다._
|
||||
|
||||
- 상태: 없음
|
||||
- 사유 유형: 없음
|
||||
- 결정 필요: 없음
|
||||
- 차단 근거: 없음
|
||||
- 실행한 검증/명령: 없음
|
||||
- 재개 조건: 없음
|
||||
|
||||
## 리뷰어를 위한 체크포인트
|
||||
|
||||
- 동일 fixture와 동일 strategy 입력이 실제로 두 번 같은 result를 내는지 확인한다.
|
||||
- result store 조회까지 검증하는지, domain-only 계산 테스트로 축소되지 않았는지 확인한다.
|
||||
- `bin/test`와 `bin/lint` 출력이 실제이며 toolchain blocker가 정확히 기록되었는지 확인한다.
|
||||
|
||||
## 검증 결과
|
||||
|
||||
_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._
|
||||
|
||||
필수 규칙:
|
||||
- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다.
|
||||
- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다.
|
||||
- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다.
|
||||
- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다.
|
||||
|
||||
### TEST-1 중간 검증
|
||||
```
|
||||
$ go test ./services/worker/...
|
||||
(output)
|
||||
```
|
||||
|
||||
### 최종 검증
|
||||
```
|
||||
$ go test ./services/worker/...
|
||||
$ bin/test
|
||||
$ bin/lint
|
||||
(output)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?**
|
||||
> If anything is blank, go back and fill it in before saving this file.
|
||||
> Leave review-agent-only sections unchanged.
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
<!-- task=m-backtest-engine-baseline/03+01,02_fixture_verification plan=0 tag=TEST -->
|
||||
|
||||
# Backtest Fixture Verification Plan
|
||||
|
||||
## 이 파일을 읽는 구현 에이전트에게
|
||||
|
||||
`CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션 작성은 필수다. 구현 후 검증을 실행하고 실제 변경 내용, 검증 출력, 계획 대비 변경 사항을 채운 뒤 active 파일을 그대로 두고 리뷰 준비를 보고한다. 사용자 결정, 외부 환경 준비, 범위 충돌 없이는 진행할 수 없으면 review stub의 `사용자 리뷰 요청` 섹션을 근거와 함께 채우고 멈춘다. `USER_REVIEW.md`, archive log, `complete.log` 작성은 code-review 전용이다.
|
||||
|
||||
## 배경
|
||||
|
||||
마일스톤의 마지막 검증은 동일 fixture daily bars와 동일 strategy 입력이 항상 같은 result를 만든다는 것이다. lifecycle과 result store가 준비된 뒤에는 engine, storage, contract shape를 잇는 deterministic test가 필요하다. 이 subtask는 full-cycle fixture와 workspace-level 검증을 묶는다.
|
||||
|
||||
## 사용자 리뷰 요청 흐름
|
||||
|
||||
구현 중 blocker는 active review stub의 `사용자 리뷰 요청` 섹션에 기록한다. code-review가 이 내용을 검증하고 실제 `USER_REVIEW.md` 작성 여부를 결정한다.
|
||||
|
||||
## 분석 결과
|
||||
|
||||
### 읽은 파일
|
||||
|
||||
- `agent-roadmap/current.md`
|
||||
- `agent-roadmap/phase/backtest-loop/PHASE.md`
|
||||
- `agent-roadmap/phase/backtest-loop/milestones/backtest-engine-baseline.md`
|
||||
- `agent-test/local/rules.md`
|
||||
- `agent-test/local/domain-model-smoke.md`
|
||||
- `agent-test/local/worker-smoke.md`
|
||||
- `agent-test/local/contracts-smoke.md`
|
||||
- `packages/domain/backtest/types.go`
|
||||
- `packages/domain/backtest/types_test.go`
|
||||
- `packages/domain/market/types.go`
|
||||
- `services/worker/internal/marketdata/importer/importer.go`
|
||||
- `services/worker/internal/marketdata/importer/importer_test.go`
|
||||
- `services/worker/internal/storage/ports.go`
|
||||
- `services/worker/internal/storage/postgres/store.go`
|
||||
- `bin/test`
|
||||
- `bin/lint`
|
||||
|
||||
### 테스트 커버리지 공백
|
||||
|
||||
- Current tests cover importer idempotence and domain portfolio math, but no test currently drives bars -> strategy -> fills -> result store.
|
||||
- `bin/test` also runs Flutter tests; this may expose environment blockers unrelated to Go backtest code and must be reported with actual output.
|
||||
- `bin/lint` runs Go vet and Flutter analyze; final milestone verification requires it only after fixture path is implemented.
|
||||
|
||||
### 심볼 참조
|
||||
|
||||
- renamed/removed symbols: none.
|
||||
- New symbols from `01_worker_lifecycle` and `02+01_result_store` must be referenced by deterministic fixture tests.
|
||||
|
||||
### 분할 판단
|
||||
|
||||
Split policy를 먼저 평가했다. 이 task directory는 `03+01,02_fixture_verification`이며 `01_worker_lifecycle`과 `02+01_result_store` 둘 다의 `complete.log`에 의존한다. Fixture verification is deliberately last because failures should point to integrated behavior, not missing lifecycle/storage foundation.
|
||||
|
||||
### 범위 결정 근거
|
||||
|
||||
이 plan은 deterministic fixture와 final verification만 다룬다. New trading strategy catalog, advanced performance metrics, live/paper trading, API/client UI are out of scope.
|
||||
|
||||
### 빌드 등급
|
||||
|
||||
build=`local-G06`, review=`cloud-G06`. Work is test-heavy and deterministic, but it depends on two prior subtasks and full workspace scripts.
|
||||
|
||||
## 의존 관계 및 구현 순서
|
||||
|
||||
이 task directory 이름은 `03+01,02_fixture_verification`이다. 같은 task group의 `01_worker_lifecycle`과 `02+01_result_store`가 모두 `complete.log`를 만든 뒤 시작한다.
|
||||
|
||||
## 구현 체크리스트
|
||||
|
||||
- [ ] fixture daily bars와 deterministic test strategy를 추가한다.
|
||||
- [ ] engine execution이 동일 fixture와 strategy 입력에서 동일 result를 두 번 생성함을 검증한다.
|
||||
- [ ] result store 조회가 expected starting cash, ending equity, trades/positions summary를 반환함을 검증한다.
|
||||
- [ ] `bin/test`와 `bin/lint`를 실행해 fixture-test 검증 조건을 충족한다.
|
||||
- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
|
||||
|
||||
### [TEST-1] Deterministic fixture full path
|
||||
|
||||
#### 문제
|
||||
|
||||
현재 `packages/domain/backtest/types_test.go:54`-`116`은 portfolio fill/equity 계산만 검증한다. Worker 쪽에는 fixture bars가 strategy execution과 result persistence를 거쳐 같은 결과를 내는 테스트가 없다.
|
||||
|
||||
```go
|
||||
func TestPortfolioStateAppliesFillsAndCalculatesEquity(t *testing.T) {
|
||||
state := NewPortfolioState(price("1000"))
|
||||
// domain-only portfolio checks...
|
||||
}
|
||||
```
|
||||
|
||||
#### 해결 방법
|
||||
|
||||
`services/worker/internal/backtest/engine_test.go` 또는 `services/worker/internal/backtest/fixture_test.go`에 in-memory bar source, strategy, result store를 둔다. 동일 fixture를 두 번 실행해 `backtest.Result` 전체가 동일한지 비교하고, expected cash/equity/trades/positions를 명시한다.
|
||||
|
||||
#### 수정 파일 및 체크리스트
|
||||
|
||||
- [ ] `services/worker/internal/backtest/fixture_test.go`
|
||||
- [ ] 필요한 경우 `services/worker/internal/backtest/testdata/*.json`
|
||||
- [ ] 필요하면 `services/worker/internal/backtest/engine.go`의 public test seam 조정
|
||||
|
||||
#### 테스트 작성
|
||||
|
||||
작성한다.
|
||||
|
||||
- `TestEngineProducesDeterministicResultFromFixtureBars`: 동일 input 두 번 실행 결과가 `cmp` 또는 manual equality로 동일
|
||||
- `TestEngineStoresAndQueriesFixtureResult`: result store fake 또는 in-memory store에서 조회 결과가 expected summary와 동일
|
||||
|
||||
#### 중간 검증
|
||||
|
||||
```bash
|
||||
go test ./services/worker/...
|
||||
```
|
||||
|
||||
기대 결과: exit code 0. Fresh execution이 필요하므로 cache가 의심되면 `go test -count=1 ./services/worker/...`로 대체하고 reason을 review stub에 기록한다.
|
||||
|
||||
## 수정 파일 요약
|
||||
|
||||
| 파일 | 항목 |
|
||||
|------|------|
|
||||
| `services/worker/internal/backtest/fixture_test.go` | TEST-1 |
|
||||
| `services/worker/internal/backtest/testdata/*.json` | TEST-1 |
|
||||
| `services/worker/internal/backtest/engine.go` | TEST-1 |
|
||||
|
||||
## 최종 검증
|
||||
|
||||
```bash
|
||||
go test ./services/worker/...
|
||||
bin/test
|
||||
bin/lint
|
||||
```
|
||||
|
||||
기대 결과: 모든 명령 exit code 0. `bin/test` 또는 `bin/lint`가 Flutter/toolchain 환경 때문에 막히면 `command -v flutter` 결과와 실제 stderr를 review stub의 `사용자 리뷰 요청` 또는 검증 결과에 기록한다.
|
||||
|
||||
모든 코드 변경 완료 후 반드시 `CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다.
|
||||
|
|
@ -1,6 +1,9 @@
|
|||
package backtest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.toki-labs.com/toki/alt/packages/domain/market"
|
||||
|
|
@ -40,3 +43,215 @@ type Result struct {
|
|||
StartingCash market.Price
|
||||
EndingEquity market.Price
|
||||
}
|
||||
|
||||
type Strategy interface {
|
||||
ID() StrategyID
|
||||
Decide(input StrategyInput) ([]OrderIntent, error)
|
||||
}
|
||||
|
||||
type StrategyInput struct {
|
||||
Run Run
|
||||
Bar market.Bar
|
||||
Portfolio PortfolioState
|
||||
History []market.Bar
|
||||
}
|
||||
|
||||
type OrderSide string
|
||||
|
||||
const (
|
||||
OrderSideBuy OrderSide = "buy"
|
||||
OrderSideSell OrderSide = "sell"
|
||||
)
|
||||
|
||||
type OrderIntent struct {
|
||||
InstrumentID market.InstrumentID
|
||||
Side OrderSide
|
||||
Quantity market.Quantity
|
||||
}
|
||||
|
||||
type Fill struct {
|
||||
InstrumentID market.InstrumentID
|
||||
Side OrderSide
|
||||
Quantity market.Quantity
|
||||
Price market.Price
|
||||
}
|
||||
|
||||
type Position struct {
|
||||
InstrumentID market.InstrumentID
|
||||
Quantity market.Quantity
|
||||
LastPrice market.Price
|
||||
}
|
||||
|
||||
type PortfolioState struct {
|
||||
Cash market.Price
|
||||
Positions map[market.InstrumentID]Position
|
||||
}
|
||||
|
||||
func NewPortfolioState(cash market.Price) PortfolioState {
|
||||
return PortfolioState{
|
||||
Cash: cash,
|
||||
Positions: make(map[market.InstrumentID]Position),
|
||||
}
|
||||
}
|
||||
|
||||
func (p PortfolioState) Position(id market.InstrumentID) (Position, bool) {
|
||||
position, ok := p.Positions[id]
|
||||
return position, ok
|
||||
}
|
||||
|
||||
func (p PortfolioState) ApplyFill(fill Fill) (PortfolioState, error) {
|
||||
if fill.InstrumentID == "" {
|
||||
return PortfolioState{}, fmt.Errorf("fill instrument id is required")
|
||||
}
|
||||
if fill.Price.Currency != p.Cash.Currency {
|
||||
return PortfolioState{}, fmt.Errorf("fill price currency %q does not match cash currency %q", fill.Price.Currency, p.Cash.Currency)
|
||||
}
|
||||
|
||||
quantity, err := decimalRat(fill.Quantity.Amount)
|
||||
if err != nil {
|
||||
return PortfolioState{}, fmt.Errorf("invalid fill quantity: %w", err)
|
||||
}
|
||||
if quantity.Sign() <= 0 {
|
||||
return PortfolioState{}, fmt.Errorf("fill quantity must be positive")
|
||||
}
|
||||
|
||||
price, err := decimalRat(fill.Price.Amount)
|
||||
if err != nil {
|
||||
return PortfolioState{}, fmt.Errorf("invalid fill price: %w", err)
|
||||
}
|
||||
if price.Sign() < 0 {
|
||||
return PortfolioState{}, fmt.Errorf("fill price must not be negative")
|
||||
}
|
||||
|
||||
cash, err := decimalRat(p.Cash.Amount)
|
||||
if err != nil {
|
||||
return PortfolioState{}, fmt.Errorf("invalid cash amount: %w", err)
|
||||
}
|
||||
|
||||
next := p.clone()
|
||||
position := next.Positions[fill.InstrumentID]
|
||||
position.InstrumentID = fill.InstrumentID
|
||||
position.LastPrice = fill.Price
|
||||
|
||||
positionQuantity, err := positionQuantityRat(position)
|
||||
if err != nil {
|
||||
return PortfolioState{}, fmt.Errorf("invalid position quantity: %w", err)
|
||||
}
|
||||
|
||||
notional := new(big.Rat).Mul(quantity, price)
|
||||
switch fill.Side {
|
||||
case OrderSideBuy:
|
||||
if cash.Cmp(notional) < 0 {
|
||||
return PortfolioState{}, fmt.Errorf("insufficient cash for fill")
|
||||
}
|
||||
cash.Sub(cash, notional)
|
||||
positionQuantity.Add(positionQuantity, quantity)
|
||||
case OrderSideSell:
|
||||
if positionQuantity.Cmp(quantity) < 0 {
|
||||
return PortfolioState{}, fmt.Errorf("insufficient position quantity for fill")
|
||||
}
|
||||
cash.Add(cash, notional)
|
||||
positionQuantity.Sub(positionQuantity, quantity)
|
||||
default:
|
||||
return PortfolioState{}, fmt.Errorf("unsupported fill side %q", fill.Side)
|
||||
}
|
||||
|
||||
next.Cash.Amount = decimalValue(cash)
|
||||
if positionQuantity.Sign() == 0 {
|
||||
delete(next.Positions, fill.InstrumentID)
|
||||
return next, nil
|
||||
}
|
||||
position.Quantity.Amount = decimalValue(positionQuantity)
|
||||
next.Positions[fill.InstrumentID] = position
|
||||
return next, nil
|
||||
}
|
||||
|
||||
func (p PortfolioState) MarkPrice(id market.InstrumentID, price market.Price) (PortfolioState, error) {
|
||||
if price.Currency != p.Cash.Currency {
|
||||
return PortfolioState{}, fmt.Errorf("mark price currency %q does not match cash currency %q", price.Currency, p.Cash.Currency)
|
||||
}
|
||||
position, ok := p.Positions[id]
|
||||
if !ok {
|
||||
return PortfolioState{}, fmt.Errorf("position %q not found", id)
|
||||
}
|
||||
if _, err := decimalRat(price.Amount); err != nil {
|
||||
return PortfolioState{}, fmt.Errorf("invalid mark price: %w", err)
|
||||
}
|
||||
|
||||
next := p.clone()
|
||||
position.LastPrice = price
|
||||
next.Positions[id] = position
|
||||
return next, nil
|
||||
}
|
||||
|
||||
func (p PortfolioState) Equity() (market.Price, error) {
|
||||
equity, err := decimalRat(p.Cash.Amount)
|
||||
if err != nil {
|
||||
return market.Price{}, fmt.Errorf("invalid cash amount: %w", err)
|
||||
}
|
||||
|
||||
for id, position := range p.Positions {
|
||||
if position.LastPrice.Currency != p.Cash.Currency {
|
||||
return market.Price{}, fmt.Errorf("position %q price currency %q does not match cash currency %q", id, position.LastPrice.Currency, p.Cash.Currency)
|
||||
}
|
||||
quantity, err := decimalRat(position.Quantity.Amount)
|
||||
if err != nil {
|
||||
return market.Price{}, fmt.Errorf("invalid position %q quantity: %w", id, err)
|
||||
}
|
||||
price, err := decimalRat(position.LastPrice.Amount)
|
||||
if err != nil {
|
||||
return market.Price{}, fmt.Errorf("invalid position %q price: %w", id, err)
|
||||
}
|
||||
equity.Add(equity, new(big.Rat).Mul(quantity, price))
|
||||
}
|
||||
|
||||
return market.Price{
|
||||
Currency: p.Cash.Currency,
|
||||
Amount: decimalValue(equity),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p PortfolioState) clone() PortfolioState {
|
||||
positions := make(map[market.InstrumentID]Position, len(p.Positions))
|
||||
for id, position := range p.Positions {
|
||||
positions[id] = position
|
||||
}
|
||||
return PortfolioState{
|
||||
Cash: p.Cash,
|
||||
Positions: positions,
|
||||
}
|
||||
}
|
||||
|
||||
func decimalRat(decimal market.Decimal) (*big.Rat, error) {
|
||||
value := strings.TrimSpace(decimal.Value)
|
||||
if value == "" {
|
||||
return nil, fmt.Errorf("empty decimal value")
|
||||
}
|
||||
rat, ok := new(big.Rat).SetString(value)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid decimal value %q", decimal.Value)
|
||||
}
|
||||
return rat, nil
|
||||
}
|
||||
|
||||
func decimalValue(rat *big.Rat) market.Decimal {
|
||||
if rat.Sign() == 0 {
|
||||
return market.Decimal{Value: "0"}
|
||||
}
|
||||
if rat.IsInt() {
|
||||
return market.Decimal{Value: rat.Num().String()}
|
||||
}
|
||||
value := strings.TrimRight(rat.FloatString(18), "0")
|
||||
value = strings.TrimRight(value, ".")
|
||||
if value == "" || value == "-0" {
|
||||
value = "0"
|
||||
}
|
||||
return market.Decimal{Value: value}
|
||||
}
|
||||
|
||||
func positionQuantityRat(position Position) (*big.Rat, error) {
|
||||
if position.Quantity.Amount.Value == "" {
|
||||
return new(big.Rat), nil
|
||||
}
|
||||
return decimalRat(position.Quantity.Amount)
|
||||
}
|
||||
|
|
|
|||
154
packages/domain/backtest/types_test.go
Normal file
154
packages/domain/backtest/types_test.go
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
package backtest
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.toki-labs.com/toki/alt/packages/domain/market"
|
||||
)
|
||||
|
||||
type thresholdStrategy struct{}
|
||||
|
||||
func (thresholdStrategy) ID() StrategyID {
|
||||
return StrategyID("threshold")
|
||||
}
|
||||
|
||||
func (thresholdStrategy) Decide(input StrategyInput) ([]OrderIntent, error) {
|
||||
if input.Bar.Close.Amount.Value != "100" {
|
||||
return nil, nil
|
||||
}
|
||||
return []OrderIntent{{
|
||||
InstrumentID: input.Bar.InstrumentID,
|
||||
Side: OrderSideBuy,
|
||||
Quantity: market.Quantity{Amount: market.Decimal{Value: "2"}},
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func TestStrategyInterfaceAllowsInjection(t *testing.T) {
|
||||
var strategy Strategy = thresholdStrategy{}
|
||||
bar := market.Bar{
|
||||
InstrumentID: market.InstrumentID("KRX:005930"),
|
||||
Close: market.Price{
|
||||
Currency: market.CurrencyKRW,
|
||||
Amount: market.Decimal{Value: "100"},
|
||||
},
|
||||
}
|
||||
|
||||
orders, err := strategy.Decide(StrategyInput{
|
||||
Bar: bar,
|
||||
Portfolio: NewPortfolioState(price("1000")),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Decide returned error: %v", err)
|
||||
}
|
||||
if strategy.ID() != StrategyID("threshold") {
|
||||
t.Fatalf("strategy ID mismatch: got %q", strategy.ID())
|
||||
}
|
||||
if len(orders) != 1 {
|
||||
t.Fatalf("orders length: got %d, want 1", len(orders))
|
||||
}
|
||||
if orders[0].Side != OrderSideBuy {
|
||||
t.Fatalf("order side: got %q, want %q", orders[0].Side, OrderSideBuy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPortfolioStateAppliesFillsAndCalculatesEquity(t *testing.T) {
|
||||
state := NewPortfolioState(price("1000"))
|
||||
|
||||
state, err := state.ApplyFill(Fill{
|
||||
InstrumentID: market.InstrumentID("KRX:005930"),
|
||||
Side: OrderSideBuy,
|
||||
Quantity: quantity("2"),
|
||||
Price: price("100"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ApplyFill buy returned error: %v", err)
|
||||
}
|
||||
if state.Cash.Amount.Value != "800" {
|
||||
t.Fatalf("cash after buy: got %q, want %q", state.Cash.Amount.Value, "800")
|
||||
}
|
||||
position, ok := state.Position(market.InstrumentID("KRX:005930"))
|
||||
if !ok {
|
||||
t.Fatal("expected position after buy")
|
||||
}
|
||||
if position.Quantity.Amount.Value != "2" {
|
||||
t.Fatalf("position quantity after buy: got %q, want %q", position.Quantity.Amount.Value, "2")
|
||||
}
|
||||
|
||||
equity, err := state.Equity()
|
||||
if err != nil {
|
||||
t.Fatalf("Equity after buy returned error: %v", err)
|
||||
}
|
||||
if equity.Amount.Value != "1000" {
|
||||
t.Fatalf("equity after buy: got %q, want %q", equity.Amount.Value, "1000")
|
||||
}
|
||||
|
||||
state, err = state.MarkPrice(market.InstrumentID("KRX:005930"), price("125"))
|
||||
if err != nil {
|
||||
t.Fatalf("MarkPrice returned error: %v", err)
|
||||
}
|
||||
equity, err = state.Equity()
|
||||
if err != nil {
|
||||
t.Fatalf("Equity after mark returned error: %v", err)
|
||||
}
|
||||
if equity.Amount.Value != "1050" {
|
||||
t.Fatalf("equity after mark: got %q, want %q", equity.Amount.Value, "1050")
|
||||
}
|
||||
|
||||
state, err = state.ApplyFill(Fill{
|
||||
InstrumentID: market.InstrumentID("KRX:005930"),
|
||||
Side: OrderSideSell,
|
||||
Quantity: quantity("1"),
|
||||
Price: price("150"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ApplyFill sell returned error: %v", err)
|
||||
}
|
||||
if state.Cash.Amount.Value != "950" {
|
||||
t.Fatalf("cash after sell: got %q, want %q", state.Cash.Amount.Value, "950")
|
||||
}
|
||||
position, ok = state.Position(market.InstrumentID("KRX:005930"))
|
||||
if !ok {
|
||||
t.Fatal("expected remaining position after partial sell")
|
||||
}
|
||||
if position.Quantity.Amount.Value != "1" {
|
||||
t.Fatalf("position quantity after sell: got %q, want %q", position.Quantity.Amount.Value, "1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPortfolioStateRejectsInvalidFills(t *testing.T) {
|
||||
state := NewPortfolioState(price("100"))
|
||||
|
||||
_, err := state.ApplyFill(Fill{
|
||||
InstrumentID: market.InstrumentID("KRX:005930"),
|
||||
Side: OrderSideBuy,
|
||||
Quantity: quantity("2"),
|
||||
Price: market.Price{
|
||||
Currency: market.CurrencyUSD,
|
||||
Amount: market.Decimal{Value: "10"},
|
||||
},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected currency mismatch error")
|
||||
}
|
||||
|
||||
_, err = state.ApplyFill(Fill{
|
||||
InstrumentID: market.InstrumentID("KRX:005930"),
|
||||
Side: OrderSideSell,
|
||||
Quantity: quantity("1"),
|
||||
Price: price("10"),
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected oversell error")
|
||||
}
|
||||
}
|
||||
|
||||
func price(amount string) market.Price {
|
||||
return market.Price{
|
||||
Currency: market.CurrencyKRW,
|
||||
Amount: market.Decimal{Value: amount},
|
||||
}
|
||||
}
|
||||
|
||||
func quantity(amount string) market.Quantity {
|
||||
return market.Quantity{Amount: market.Decimal{Value: amount}}
|
||||
}
|
||||
Loading…
Reference in a new issue