【问题标题】:pandas resample .csv tick data to OHLCpandas 将 .csv 刻度数据重新采样到 OHLC
【发布时间】:2014-12-12 20:27:31
【问题描述】:

我有一个 .csv 金融报价数据文件,其中 3 列对应于日期、时间和价格。文件没有标题。

01/18/14, 04:09:28, 55.0
01/18/14, 02:18:31, 55.4
01/17/14, 10:42:34, 55.3
01/17/14, 03:18:07, 55.2
...

我想使用 pandas 重新采样到 Daily OHLC,以便我可以以正确的格式将其导入我的图表软件。

我只使用以下方法打开文件:

data = pd.read_csv('data.csv')

您能帮我将我拥有的 fomat 中的数据转换为带有 pandas resample 的 OHLC。 谢谢

【问题讨论】:

  • 那是经典。按日期分组并为每个 OHLC 列应用相应的函数。在伪代码中: data.groupby("Date").apply(max) 用于 H 或 .apply(min) 用于 L

标签: python pandas


【解决方案1】:

如果它仍然是实际的,那么在 Pandas 中有最简单的方法:

data.resample('1D').apply('ohlc')

【讨论】:

    【解决方案2】:

    使用 Python,但没有 pandas:

    #!/usr/bin/env python
    
    import datetime
    from decimal import Decimal
    
    class Tick(object):
        pass    
    
    ticks = []
    with open('data.csv') as f:
        ticksTemp = []
        lines = [x.strip('\n') for x in f.readlines()]    
    
        for line in lines:
            columns = [x.strip() for x in line.split(',')]
            if len(columns) != 3:
                continue;
            timeStr = columns[0] + '/' + columns[1]
            time  = datetime.datetime.strptime(timeStr, "%m/%d/%y/%H:%M:%S" )        
            price = columns[2]
            tick = Tick()
            tick.time = time
            tick.price = Decimal(price)
            ticksTemp.append(tick)
        ticks = sorted(ticksTemp, key = lambda x: x.time, reverse=False)
    
    
    lines = []
    first = ticks[0]
    last = ticks[-1]
    time = first.time
    o,h,l,c = first.price, first.price, first.price, first.price
    def appendLine():
        lines.append(time.strftime('%Y-%m-%d')+','+str(o)+ ','+str(h)+','+str(l)+','+str(c))
    for tick in ticks:    
        if(tick.time.year != time.year or tick.time.day != time.day):
            appendLine()
            time = tick.time
            o = tick.price
        c = tick.price
        if tick.price > h:
            h = tick.price
        if tick.price < l:
            l = tick.price
    if last != first:
        appendLine()
    with open('ohlc.csv', 'w') as f:
        f.write('\n'.join(lines))
    

    数据.csv:

    01/18/14, 04:09:28, 55.0
    01/18/14, 02:18:31, 55.4
    01/17/14, 10:42:34, 55.3
    01/17/14, 03:18:07, 55.2
    

    ohlc.csv:

    2014-01-17,55.2,55.3,55.2,55.3
    2014-01-18,55.4,55.4,55.0,55.0
    

    【讨论】:

      猜你喜欢
      • 2016-12-05
      • 2021-11-18
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-04
      • 2017-09-19
      • 2019-04-15
      相关资源
      最近更新 更多