BAT-004 (REQ-004, REQ-005):
- app/api/v1_tags.py: POST /v1/tags, GET /v1/tags, PATCH /v1/tags/{id}/deactivate
- app/api/v1_portfolios.py: POST/DELETE /v1/portfolios/{id}/tags
- app/api/v1_assets.py: POST/DELETE /v1/assets/{id}/tags 엔드포인트 추가
- app/schemas/v1.py: TagItem, TagCreateRequest, TagListResponse, TagApplyRequest/Response 추가
- app/repositories/portfolio_repository.py, postgres.py: append/remove_portfolio_tag_id 추가
- app/main.py: v1_portfolios_router, v1_tags_router 등록
- tests/test_tags_http_api.py: 22개 HTTP API 테스트
BAT-005 (REQ-007, REQ-008):
- app/cli/commands/tag.py: pfhub tag create/list/deactivate/apply/remove 7개 커맨드 신규
- app/cli/main.py: tag_app 등록
- app/cli/commands/portfolio.py: pfhub portfolio tag add/list/remove 완전 제거(breaking change)
- app/cli/core/utils.py: print_tag_table + list[Tag] render 분기 추가
- tests/test_tags_cli.py: REQ-007 AC-1~9 커버 24개 CLI 테스트 신규
- tests/test_cli.py: 제거된 portfolio tag 테스트 2개 삭제
- docs/data-model.md, interface-contract.md, project-structure.md, runtime-flows.md: 태그 모델 baseline 갱신(REQ-008)
- docs/batches/: BAT-004, BAT-005 전체 산출물(release-candidate)
247 passed
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
434 lines
18 KiB
Python
434 lines
18 KiB
Python
"""Portfolio CLI commands."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
from typing import Any
|
|
|
|
import typer
|
|
|
|
from app.cli.core.utils import execute_command, render_output
|
|
from app.schemas.portfolio import (
|
|
BuyRequest,
|
|
CommentCreateRequest,
|
|
CommentUpdateRequest,
|
|
CreatePortfolioRequest,
|
|
InvestRequest,
|
|
ResetPortfolioRequest,
|
|
SellRequest,
|
|
TransferRequest,
|
|
UpdatePortfolioRequest,
|
|
)
|
|
from app.services.portfolio_service import PortfolioService
|
|
|
|
_NAME_RE = re.compile(r"^[a-zA-Z0-9._:\-]{1,100}$")
|
|
|
|
portfolio_app = typer.Typer(help="Portfolio lifecycle and trade commands.")
|
|
comment_app = typer.Typer(help="Portfolio comment history commands.")
|
|
portfolio_app.add_typer(comment_app, name="comment")
|
|
|
|
|
|
def _parse_strategy_params(value: str) -> dict[str, Any]:
|
|
if not value.strip():
|
|
return {}
|
|
parsed = json.loads(value)
|
|
if not isinstance(parsed, dict):
|
|
raise ValueError("strategy params must be a JSON object")
|
|
return parsed
|
|
|
|
|
|
def _with_service(ctx: typer.Context, callback):
|
|
app_context = ctx.obj
|
|
repository = app_context.repository_factory(app_context.settings)
|
|
service = PortfolioService(repository)
|
|
try:
|
|
result = execute_command(app_context.console, callback=lambda: callback(service, app_context))
|
|
return result
|
|
finally:
|
|
if callable(getattr(type(repository), "close", None)):
|
|
repository.close()
|
|
|
|
|
|
def _with_service_and_repo(ctx: typer.Context, callback):
|
|
app_context = ctx.obj
|
|
repository = app_context.repository_factory(app_context.settings)
|
|
service = PortfolioService(repository)
|
|
try:
|
|
result = execute_command(app_context.console, callback=lambda: callback(service, repository, app_context))
|
|
return result
|
|
finally:
|
|
if callable(getattr(type(repository), "close", None)):
|
|
repository.close()
|
|
|
|
|
|
def _confirm(force: bool, message: str) -> None:
|
|
if force:
|
|
return
|
|
confirmed = typer.confirm(message)
|
|
if not confirmed:
|
|
raise typer.Exit(code=0)
|
|
|
|
|
|
def _validate_portfolio_name(name: str, ctx_console=None) -> None:
|
|
if not _NAME_RE.match(name):
|
|
msg = f"유효하지 않은 이름입니다: {name!r} — [a-zA-Z0-9._:-] 문자만 허용하며 1~100자여야 합니다."
|
|
if ctx_console is not None:
|
|
ctx_console.print(f"Error: {msg}")
|
|
raise typer.Exit(code=1)
|
|
raise ValueError(msg)
|
|
|
|
|
|
def _resolve_portfolio_id(repository, name: str, user: str) -> str:
|
|
owner = repository.get_user_by_username(user)
|
|
if owner is None:
|
|
raise ValueError(f"사용자를 찾을 수 없습니다: {user}")
|
|
portfolio = repository.get_portfolio_by_name_and_user(owner.id, name)
|
|
if portfolio is None:
|
|
raise ValueError(f"포트폴리오를 찾을 수 없습니다: {name} (user: {user})")
|
|
return portfolio.portfolio_id
|
|
|
|
|
|
@portfolio_app.command("list")
|
|
def list_portfolios(
|
|
ctx: typer.Context,
|
|
user: str | None = typer.Option(None, "--user", help="Filter by username (required)."),
|
|
broker: str | None = typer.Option(None, help="Filter by broker."),
|
|
status: str | None = typer.Option(None, help="Filter by status."),
|
|
include_tags: list[str] | None = typer.Option(None, "--include-tag", help="Include tag filter. Repeatable."),
|
|
exclude_tags: list[str] | None = typer.Option(None, "--exclude-tag", help="Exclude tag filter. Repeatable."),
|
|
match_mode: str | None = typer.Option(None, "--match-mode", help="AND or OR for include tags."),
|
|
) -> None:
|
|
if user is None:
|
|
ctx.obj.console.print("Error: --user 옵션은 필수입니다.")
|
|
raise typer.Exit(code=1)
|
|
|
|
def _callback(service, repository, app_context):
|
|
owner = repository.get_user_by_username(user)
|
|
if owner is None:
|
|
raise ValueError(f"사용자를 찾을 수 없습니다: {user}")
|
|
return service.list_portfolios(
|
|
owner_user_id=owner.id,
|
|
broker=broker,
|
|
status=status,
|
|
include_tags=include_tags,
|
|
exclude_tags=exclude_tags,
|
|
match_mode=match_mode,
|
|
)
|
|
|
|
detail = _with_service_and_repo(ctx, _callback)
|
|
render_output(ctx.obj.console, ctx.obj.output_format, detail, empty_message="No portfolios found.")
|
|
|
|
|
|
@portfolio_app.command("status")
|
|
def portfolio_status(
|
|
ctx: typer.Context,
|
|
name: str = typer.Argument(..., help="Portfolio name."),
|
|
user: str = typer.Option(..., "--user", help="Owner username (required)."),
|
|
recent: int = typer.Option(5, "--recent", min=1, help="Number of recent ledger entries."),
|
|
) -> None:
|
|
_validate_portfolio_name(name, ctx.obj.console)
|
|
|
|
def _callback(service, repository, app_context):
|
|
portfolio_id = _resolve_portfolio_id(repository, name, user)
|
|
return service.get_portfolio_status(portfolio_id=portfolio_id, recent_trades=recent)
|
|
|
|
detail = _with_service_and_repo(ctx, _callback)
|
|
render_output(ctx.obj.console, ctx.obj.output_format, detail)
|
|
|
|
|
|
@portfolio_app.command("create")
|
|
def create_portfolio(
|
|
ctx: typer.Context,
|
|
name: str = typer.Argument(..., help="Portfolio name (user-scoped unique identifier)."),
|
|
user: str = typer.Option(..., "--user", help="Owner username (required)."),
|
|
asset_id: str | None = typer.Option(None, "--asset-id", help="Asset UUID from the asset catalog."),
|
|
symbol: str | None = typer.Option(None, "--symbol", help="Asset symbol to look up asset_id (alternative to --asset-id)."),
|
|
broker: str = typer.Option("kis", help="Broker code."),
|
|
status: str = typer.Option("enabled", help="Portfolio status."),
|
|
cash_balance: float = typer.Option(0.0, min=0.0, help="Starting cash balance."),
|
|
asset_quantity: float = typer.Option(0.0, min=0.0, help="Starting asset quantity."),
|
|
asset_price: float = typer.Option(0.0, min=0.0, help="Starting asset price."),
|
|
profit_buffer: float = typer.Option(0.0, min=0.0, help="Initial profit buffer."),
|
|
strategy_name: str = typer.Option("target_value", help="Strategy name."),
|
|
strategy_params: str = typer.Option("{}", help="Strategy params as JSON object."),
|
|
force: bool = typer.Option(False, "--force", help="Skip confirmation prompt."),
|
|
) -> None:
|
|
_validate_portfolio_name(name, ctx.obj.console)
|
|
if asset_id is None and symbol is None:
|
|
ctx.obj.console.print("Error: --asset-id 또는 --symbol 중 하나는 필수입니다.")
|
|
raise typer.Exit(code=1)
|
|
|
|
def _callback(service, repository, app_context):
|
|
resolved_asset_id = asset_id
|
|
if resolved_asset_id is None:
|
|
asset = repository.get_asset_by_symbol(symbol)
|
|
if asset is None:
|
|
raise ValueError(f"symbol에 해당하는 asset을 찾을 수 없습니다: {symbol}")
|
|
resolved_asset_id = asset.asset_id
|
|
owner = repository.get_user_by_username(user)
|
|
if owner is None:
|
|
raise ValueError(f"사용자를 찾을 수 없습니다: {user}")
|
|
return service.create_portfolio(
|
|
CreatePortfolioRequest(
|
|
name=name,
|
|
asset_id=resolved_asset_id,
|
|
broker=broker,
|
|
status=status,
|
|
cash_balance=cash_balance,
|
|
asset_quantity=asset_quantity,
|
|
asset_price=asset_price,
|
|
profit_buffer=profit_buffer,
|
|
strategy_name=strategy_name,
|
|
strategy_params=_parse_strategy_params(strategy_params),
|
|
),
|
|
owner_user_id=owner.id,
|
|
)
|
|
|
|
_confirm(force, f"Create portfolio {name!r} (user: {user})?")
|
|
detail = _with_service_and_repo(ctx, _callback)
|
|
render_output(ctx.obj.console, ctx.obj.output_format, detail)
|
|
|
|
|
|
@portfolio_app.command("update")
|
|
def update_portfolio(
|
|
ctx: typer.Context,
|
|
name: str = typer.Argument(..., help="Portfolio name."),
|
|
user: str = typer.Option(..., "--user", help="Owner username (required)."),
|
|
broker: str | None = typer.Option(None, help="Broker code."),
|
|
status: str | None = typer.Option(None, help="Portfolio status."),
|
|
new_name: str | None = typer.Option(None, "--new-name", help="New portfolio name (requires --force or confirm)."),
|
|
strategy_name: str | None = typer.Option(None, help="Strategy name."),
|
|
strategy_params: str | None = typer.Option(None, help="Strategy params as JSON object."),
|
|
asset_price: float | None = typer.Option(None, min=0.0, help="Current asset price."),
|
|
daemon_id: str | None = typer.Option(None, "--daemon-id", help="Assign portfolio to this daemon (managed_by_daemon_id)."),
|
|
force: bool = typer.Option(False, "--force", help="Skip confirmation prompt."),
|
|
) -> None:
|
|
_validate_portfolio_name(name, ctx.obj.console)
|
|
if new_name is not None:
|
|
_validate_portfolio_name(new_name, ctx.obj.console)
|
|
_confirm(force, f"Rename portfolio {name!r} → {new_name!r} (user: {user})?")
|
|
else:
|
|
_confirm(force, f"Update portfolio {name!r} (user: {user})?")
|
|
|
|
parsed_strategy_params = None if strategy_params is None else _parse_strategy_params(strategy_params)
|
|
|
|
def _callback(service, repository, app_context):
|
|
portfolio_id = _resolve_portfolio_id(repository, name, user)
|
|
return service.update_portfolio(
|
|
portfolio_id,
|
|
UpdatePortfolioRequest(
|
|
broker=broker,
|
|
status=status,
|
|
name=new_name,
|
|
strategy_name=strategy_name,
|
|
strategy_params=parsed_strategy_params,
|
|
asset_price=asset_price,
|
|
managed_by_daemon_id=daemon_id,
|
|
),
|
|
)
|
|
|
|
detail = _with_service_and_repo(ctx, _callback)
|
|
render_output(ctx.obj.console, ctx.obj.output_format, detail)
|
|
|
|
|
|
@portfolio_app.command("buy")
|
|
def buy_portfolio(
|
|
ctx: typer.Context,
|
|
name: str = typer.Argument(..., help="Portfolio name."),
|
|
user: str = typer.Option(..., "--user", help="Owner username (required)."),
|
|
quantity: float = typer.Option(..., min=0.0000001, help="Quantity to buy."),
|
|
price: float = typer.Option(..., min=0.0000001, help="Execution price."),
|
|
fee: float = typer.Option(0.0, min=0.0, help="Fee amount."),
|
|
tax: float = typer.Option(0.0, min=0.0, help="Tax amount."),
|
|
note: str = typer.Option("", help="Ledger note."),
|
|
force: bool = typer.Option(False, "--force", help="Skip confirmation prompt."),
|
|
) -> None:
|
|
_validate_portfolio_name(name, ctx.obj.console)
|
|
total_cost = quantity * price + fee + tax
|
|
_confirm(force, f"Buy {quantity:g} units of {name!r} (user: {user}) at {price:,.0f} (total {total_cost:,.0f})?")
|
|
|
|
def _callback(service, repository, app_context):
|
|
portfolio_id = _resolve_portfolio_id(repository, name, user)
|
|
return service.buy(portfolio_id, BuyRequest(quantity=quantity, price=price, fee=fee, tax=tax, note=note))
|
|
|
|
detail = _with_service_and_repo(ctx, _callback)
|
|
render_output(ctx.obj.console, ctx.obj.output_format, detail)
|
|
|
|
|
|
@portfolio_app.command("sell")
|
|
def sell_portfolio(
|
|
ctx: typer.Context,
|
|
name: str = typer.Argument(..., help="Portfolio name."),
|
|
user: str = typer.Option(..., "--user", help="Owner username (required)."),
|
|
quantity: float = typer.Option(..., min=0.0000001, help="Quantity to sell."),
|
|
price: float = typer.Option(..., min=0.0000001, help="Execution price."),
|
|
fee: float = typer.Option(0.0, min=0.0, help="Fee amount."),
|
|
tax: float = typer.Option(0.0, min=0.0, help="Tax amount."),
|
|
note: str = typer.Option("", help="Ledger note."),
|
|
force: bool = typer.Option(False, "--force", help="Skip confirmation prompt."),
|
|
) -> None:
|
|
_validate_portfolio_name(name, ctx.obj.console)
|
|
net_amount = quantity * price - fee - tax
|
|
_confirm(force, f"Sell {quantity:g} units of {name!r} (user: {user}) at {price:,.0f} (net {net_amount:,.0f})?")
|
|
|
|
def _callback(service, repository, app_context):
|
|
portfolio_id = _resolve_portfolio_id(repository, name, user)
|
|
return service.sell(portfolio_id, SellRequest(quantity=quantity, price=price, fee=fee, tax=tax, note=note))
|
|
|
|
detail = _with_service_and_repo(ctx, _callback)
|
|
render_output(ctx.obj.console, ctx.obj.output_format, detail)
|
|
|
|
|
|
@portfolio_app.command("invest")
|
|
def invest_portfolio(
|
|
ctx: typer.Context,
|
|
name: str = typer.Argument(..., help="Portfolio name."),
|
|
user: str = typer.Option(..., "--user", help="Owner username (required)."),
|
|
movement_type: str = typer.Option(..., "--type", help="deposit, profit, or withdraw."),
|
|
amount: float = typer.Option(..., min=0.0000001, help="Buffer adjustment amount."),
|
|
note: str = typer.Option("", help="Ledger note."),
|
|
force: bool = typer.Option(False, "--force", help="Skip confirmation prompt."),
|
|
) -> None:
|
|
_validate_portfolio_name(name, ctx.obj.console)
|
|
_confirm(force, f"Apply {movement_type} of {amount:,.0f} to portfolio {name!r} (user: {user})?")
|
|
|
|
def _callback(service, repository, app_context):
|
|
portfolio_id = _resolve_portfolio_id(repository, name, user)
|
|
return service.invest(portfolio_id, InvestRequest(movement_type=movement_type, amount=amount, note=note))
|
|
|
|
detail = _with_service_and_repo(ctx, _callback)
|
|
render_output(ctx.obj.console, ctx.obj.output_format, detail)
|
|
|
|
|
|
@portfolio_app.command("transfer")
|
|
def transfer_portfolio(
|
|
ctx: typer.Context,
|
|
name: str = typer.Argument(..., help="Portfolio name."),
|
|
user: str = typer.Option(..., "--user", help="Owner username (required)."),
|
|
direction: str = typer.Option(..., help="to-buffer or from-buffer."),
|
|
amount: float = typer.Option(..., min=0.0000001, help="Transfer amount."),
|
|
note: str = typer.Option("", help="Ledger note."),
|
|
force: bool = typer.Option(False, "--force", help="Skip confirmation prompt."),
|
|
) -> None:
|
|
_validate_portfolio_name(name, ctx.obj.console)
|
|
_confirm(force, f"Transfer {amount:,.0f} {direction} for portfolio {name!r} (user: {user})?")
|
|
|
|
def _callback(service, repository, app_context):
|
|
portfolio_id = _resolve_portfolio_id(repository, name, user)
|
|
return service.transfer(portfolio_id, TransferRequest(direction=direction, amount=amount, note=note))
|
|
|
|
detail = _with_service_and_repo(ctx, _callback)
|
|
render_output(ctx.obj.console, ctx.obj.output_format, detail)
|
|
|
|
|
|
@portfolio_app.command("reset")
|
|
def reset_portfolio(
|
|
ctx: typer.Context,
|
|
name: str = typer.Argument(..., help="Portfolio name."),
|
|
user: str = typer.Option(..., "--user", help="Owner username (required)."),
|
|
infer_symbol: str | None = typer.Option(None, help="Fallback symbol when portfolio does not exist."),
|
|
force: bool = typer.Option(False, "--force", help="Skip confirmation prompt."),
|
|
) -> None:
|
|
_validate_portfolio_name(name, ctx.obj.console)
|
|
_confirm(force, f"Reset portfolio {name!r} (user: {user})?")
|
|
|
|
def _callback(service, repository, app_context):
|
|
portfolio_id = _resolve_portfolio_id(repository, name, user)
|
|
return service.reset(portfolio_id, ResetPortfolioRequest(infer_symbol=infer_symbol))
|
|
|
|
detail = _with_service_and_repo(ctx, _callback)
|
|
render_output(ctx.obj.console, ctx.obj.output_format, detail)
|
|
|
|
|
|
@portfolio_app.command("delete")
|
|
def delete_portfolio(
|
|
ctx: typer.Context,
|
|
name: str = typer.Argument(..., help="Portfolio name."),
|
|
user: str = typer.Option(..., "--user", help="Owner username (required)."),
|
|
keep_ledger: bool = typer.Option(False, help="Preserve ledger history."),
|
|
force: bool = typer.Option(False, "--force", help="Skip confirmation prompt."),
|
|
) -> None:
|
|
_validate_portfolio_name(name, ctx.obj.console)
|
|
suffix = " and keep ledger" if keep_ledger else ""
|
|
_confirm(force, f"Delete portfolio {name!r} (user: {user}){suffix}?")
|
|
|
|
def _callback(service, repository, app_context):
|
|
portfolio_id = _resolve_portfolio_id(repository, name, user)
|
|
service.delete(portfolio_id, keep_ledger=keep_ledger)
|
|
return portfolio_id
|
|
|
|
pid = _with_service_and_repo(ctx, _callback)
|
|
if ctx.obj.output_format == "json":
|
|
render_output(ctx.obj.console, ctx.obj.output_format, {"deleted": name, "keep_ledger": keep_ledger})
|
|
else:
|
|
ctx.obj.console.print(f"Deleted portfolio: {name}")
|
|
|
|
|
|
@comment_app.command("add")
|
|
def comment_add(
|
|
ctx: typer.Context,
|
|
portfolio_id: str = typer.Argument(..., help="Portfolio UUID."),
|
|
content: str = typer.Option(..., "--content", help="Comment text (supports multiline)."),
|
|
) -> None:
|
|
detail = _with_service(
|
|
ctx,
|
|
lambda service, app_context: service.create_comment(
|
|
portfolio_id,
|
|
CommentCreateRequest(content=content),
|
|
),
|
|
)
|
|
render_output(ctx.obj.console, ctx.obj.output_format, detail)
|
|
|
|
|
|
@comment_app.command("list")
|
|
def comment_list(
|
|
ctx: typer.Context,
|
|
portfolio_id: str = typer.Argument(..., help="Portfolio UUID."),
|
|
) -> None:
|
|
detail = _with_service(
|
|
ctx,
|
|
lambda service, app_context: service.list_comments(portfolio_id),
|
|
)
|
|
render_output(ctx.obj.console, ctx.obj.output_format, detail, empty_message="No comments found.")
|
|
|
|
|
|
@comment_app.command("update")
|
|
def comment_update(
|
|
ctx: typer.Context,
|
|
portfolio_id: str = typer.Argument(..., help="Portfolio UUID."),
|
|
comment_id: str = typer.Argument(..., help="Comment identifier."),
|
|
content: str = typer.Option(..., "--content", help="Updated comment text."),
|
|
force: bool = typer.Option(False, "--force", help="Skip confirmation prompt."),
|
|
) -> None:
|
|
_confirm(force, f"Update comment {comment_id} for portfolio {portfolio_id}?")
|
|
detail = _with_service(
|
|
ctx,
|
|
lambda service, app_context: service.update_comment(
|
|
portfolio_id,
|
|
comment_id,
|
|
CommentUpdateRequest(content=content),
|
|
),
|
|
)
|
|
render_output(ctx.obj.console, ctx.obj.output_format, detail)
|
|
|
|
|
|
@comment_app.command("delete")
|
|
def comment_delete(
|
|
ctx: typer.Context,
|
|
portfolio_id: str = typer.Argument(..., help="Portfolio UUID."),
|
|
comment_id: str = typer.Argument(..., help="Comment identifier."),
|
|
force: bool = typer.Option(False, "--force", help="Skip confirmation prompt."),
|
|
) -> None:
|
|
_confirm(force, f"Delete comment {comment_id} for portfolio {portfolio_id}?")
|
|
_with_service(
|
|
ctx,
|
|
lambda service, app_context: service.delete_comment(portfolio_id, comment_id),
|
|
)
|
|
if ctx.obj.output_format == "json":
|
|
render_output(ctx.obj.console, ctx.obj.output_format, {"deleted": comment_id, "portfolio_id": portfolio_id})
|
|
else:
|
|
ctx.obj.console.print(f"Deleted comment: {comment_id}")
|
|
|
|
|