72 lines
2.0 KiB
Python
72 lines
2.0 KiB
Python
from datetime import date
|
|
from fastapi import APIRouter, Depends, Form, Request
|
|
from fastapi.responses import HTMLResponse, RedirectResponse
|
|
from sqlalchemy.orm import Session
|
|
from app.database import get_db
|
|
from app.models import PositionSnapshot
|
|
|
|
router = APIRouter(prefix="/input", tags=["input"])
|
|
|
|
INSTITUTIONS = ["中信期货", "高盛期货", "国泰君安期货", "华泰期货", "东证期货", "银河期货"]
|
|
|
|
|
|
@router.get("/", response_class=HTMLResponse)
|
|
def input_page(request: Request):
|
|
template = request.app.state.templates.get_template("input.html")
|
|
return HTMLResponse(
|
|
template.render(request=request, active_nav="input", institutions=INSTITUTIONS)
|
|
)
|
|
|
|
|
|
@router.post("/")
|
|
def submit_position(
|
|
request: Request,
|
|
institution: str = Form(...),
|
|
direction: str = Form(...),
|
|
date_str: str = Form(...),
|
|
position: int = Form(...),
|
|
avg_cost: float = Form(...),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
d = date.fromisoformat(date_str)
|
|
|
|
prev = (
|
|
db.query(PositionSnapshot)
|
|
.filter(
|
|
PositionSnapshot.institution == institution,
|
|
PositionSnapshot.direction == direction,
|
|
PositionSnapshot.date < d,
|
|
)
|
|
.order_by(PositionSnapshot.date.desc())
|
|
.first()
|
|
)
|
|
delta = position - prev.position if prev else 0
|
|
|
|
existing = (
|
|
db.query(PositionSnapshot)
|
|
.filter(
|
|
PositionSnapshot.institution == institution,
|
|
PositionSnapshot.direction == direction,
|
|
PositionSnapshot.date == d,
|
|
)
|
|
.first()
|
|
)
|
|
|
|
if existing:
|
|
existing.position = position
|
|
existing.delta = delta
|
|
existing.avg_cost = avg_cost
|
|
else:
|
|
snap = PositionSnapshot(
|
|
institution=institution,
|
|
direction=direction,
|
|
date=d,
|
|
position=position,
|
|
delta=delta,
|
|
avg_cost=avg_cost,
|
|
)
|
|
db.add(snap)
|
|
|
|
db.commit()
|
|
return RedirectResponse("/analysis", status_code=303)
|