FinBuddy 自选股与计费重构

· FinBuddy

今日进展

  1. 新增自选股(Watchlist)完整功能:前端面板、API 路由、中间件、服务层、同步差异算法
  2. 计费系统重构:FC 冻结-结算-退款事务完整性,按模型层级计费
  3. 研究架构重构:research_schemas 拆分为 7 个子包(base/business/industry/macro/market/policy/result/template)
  4. 新增行业模板引擎和业务画像服务
  5. 新增机构调研和机构持仓接口及 AI 解读本地存储

关键代码/伪代码

自选股同步差异算法

# 自选股同步:本地 ↔ 服务器差异合并
# 不是简单的全量覆盖,而是增量差异合并

CLASS WatchlistSyncService:
    """自选股同步差异算法"""

    ASYNC DEF sync(self, local_list, server_list):
        # 1. 计算差异:新增、删除、移动
        local_codes = SET(item.code FOR item IN local_list)
        server_codes = SET(item.code FOR item IN server_list)

        to_add = server_codes - local_codes    # 服务器有本地没有
        to_remove = local_codes - server_codes  # 本地有服务器没有

        # 2. 合并:以服务器为基准,保留本地排序偏好
        merged = []
        FOR item IN server_list:
            IF item.code IN local_codes:
                # 本地已有:保留本地排序和分组
                local_item = FIND(local_list, code=item.code)
                merged.append(local_item)
            ELSE:
                # 服务器新增:追加到末尾
                merged.append(item)

        # 3. 上传本地独有项到服务器
        FOR code IN to_remove:
            AWAIT self.api.add_to_server(code)

        RETURN merged

计费系统 — FC 冻结-结算-退款

# FinCredits (FC) 计费流程
# 三步事务:冻结 → 结算 → 退款(超时未用完的退回)

CLASS BillingService:
    """FC 积分计费服务"""

    ASYNC DEF execute_with_billing(self, user_id, task):
        # Step1: 冻结 — 预估最大消耗,冻结 FC
        estimated_cost = self._estimate_max_cost(task)
        AWAIT self.fc.freeze(user_id, estimated_cost)

        TRY:
            # Step2: 执行任务
            result = AWAIT task.execute()
            # Step3a: 结算 — 按实际消耗扣费
            actual_cost = self._calculate_actual(task, result)
            AWAIT self.fc.settle(user_id, estimated_cost, actual_cost)
            RETURN result
        EXCEPT Exception:
            # Step3b: 退款 — 出错时全额退回冻结的 FC
            AWAIT self.fc.refund(user_id, estimated_cost)
            RAISE

遇到的问题

  • 自选股同步差异算法在弱网环境下容易丢数据,需要加本地操作日志和冲突解决策略
  • 计费系统的冻结-结算-退款需要数据库事务保证,SQLite 的事务锁在高并发下性能差
  • research_schemas 拆分为 7 个子包后,导入路径变了,需要更新所有引用

明日计划

  • 优化自选股弱网同步
  • 新增通达信技能模块