You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求将期货换仓场景的F#伪代码转换为Deedle可运行代码

使用Deedle实现期货合约换仓对识别

需求说明

给定Deedle数据框df(行键为交易时段DateTime,列键为期货合约代码string,值为日成交量int),需要识别换仓对(日期,合约):

  • 首行取成交量最大的合约作为首个换仓对
  • 逐行处理后续数据:找到当前合约右侧首个成交量大于当前合约的合约,若找到则生成新换仓对,并更新当前合约为新找到的合约

实现代码

open Deedle
open System

// 假设df已初始化:Frame<DateTime, string>,列键按合约到期顺序排列
let identifyRollOverPairs (df: Frame<DateTime, string>) =
    if df.Rows.IsEmpty then Seq.empty else
        // 获取所有列键(按顺序),用于后续判断右侧列
        let columnKeys = df.ColumnKeys |> Array.ofSeq
        // 处理第一行:找到成交量最大的合约
        let firstRow = df.Rows.[0]
        let firstMaxCol = 
            firstRow.As<int>
            |> Series.sortBy (fun _ v -> -v) // 降序排序取最大值对应的列
            |> Series.firstKey
        // 首个换仓对
        let initialPair = (firstRow.Key, firstMaxCol)
        // 获取当前合约在列数组中的索引,方便定位右侧列
        let mutable currentColIndex = columnKeys |> Array.findIndex ((=) firstMaxCol)
        let mutable currentCol = firstMaxCol

        seq {
            yield initialPair
            // 遍历第一行之后的所有行
            for row in df.Rows |> Seq.skip 1 do
                let currentValue = row.GetAs<int>(currentCol)
                // 从当前列的下一列开始,找第一个值大于当前成交量的合约
                let foundCol = 
                    columnKeys
                    |> Array.skip (currentColIndex + 1)
                    |> Array.tryFind (fun col -> row.GetAs<int>(col) > currentValue)
                
                match foundCol with
                | Some newCol ->
                    yield (row.Key, newCol)
                    currentCol <- newCol
                    currentColIndex <- columnKeys |> Array.findIndex ((=) newCol)
                | None ->
                    // 未找到符合条件的合约,保持当前合约,不生成新换仓对
                    ()
        }

代码说明

  • 列顺序依赖:需确保df的列键按期货合约到期顺序排列(如近月到远月),这样才能正确定位当前合约的右侧合约
  • 数据类型适配:如果成交量存储为float等其他数值类型,可将As<int>和GetAs<int>替换为对应类型
  • 空数据防护:先判断数据框是否为空,避免空引用报错
  • 遍历逻辑:用Seq.skip 1跳过已处理的首行,后续逐行查找符合条件的合约,找到则更新当前合约并生成换仓对

内容的提问来源于stack exchange,提问作者Franco Tiveron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 14:40:14