Files
stock/backend/app/data/repository.py
2026-08-15 15:36:11 +08:00

70 lines
1.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""K 线数据访问(从库读)。
写入由 DataProvider 适配器负责阶段1 接 Tushare/AKShare
MVP 的数据由 synthetic.seed_if_empty 灌入。
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..models import Candle
async def get_candles(
session: AsyncSession,
symbol: str,
timeframe: str = "1d",
start: datetime | None = None,
end: datetime | None = None,
limit: int = 5000,
) -> list[Candle]:
stmt = select(Candle).where(
Candle.symbol == symbol,
Candle.timeframe == timeframe,
)
if start is not None:
stmt = stmt.where(Candle.ts >= start)
if end is not None:
stmt = stmt.where(Candle.ts <= end)
stmt = stmt.order_by(Candle.ts.asc()).limit(limit)
result = await session.execute(stmt)
return list(result.scalars().all())
async def get_recent_candles(
session: AsyncSession,
symbol: str,
timeframe: str = "1d",
limit: int = 5000,
) -> list[Candle]:
"""取最近 limit 根 K 线(含最新交易日),按时间升序返回。"""
stmt = (
select(Candle)
.where(Candle.symbol == symbol, Candle.timeframe == timeframe)
.order_by(Candle.ts.desc())
.limit(limit)
)
result = await session.execute(stmt)
return list(reversed(result.scalars().all()))
async def get_candles_before(
session: AsyncSession,
symbol: str,
timeframe: str,
before: datetime,
limit: int = 5000,
) -> list[Candle]:
"""取 before 之前(不含)的最近 limit 根 K 线,按时间升序返回(历史向前翻页用)。"""
stmt = (
select(Candle)
.where(Candle.symbol == symbol, Candle.timeframe == timeframe, Candle.ts < before)
.order_by(Candle.ts.desc())
.limit(limit)
)
result = await session.execute(stmt)
return list(reversed(result.scalars().all()))