2014-12-12 3 views
0

날짜, 시간에 해당하는 3 개의 열이있는 재무 확인 데이터의 .csv 파일이 있습니다. & 가격. 파일에는 헤더가 없습니다.pandas resample .csv 데이터를 OHLC로

01/18/14, 4시 9분 28초, 55.0
01/18/14, 2시 18분 31초, 55.4
01/17/14, 10시 42분 34초 55.2
55.3
01/17/14, 3시 18분 7초, ...

그래서 내가 올바른 형식으로 내 차트 소프트웨어로 가져올 수 있습니다 팬더를 사용하여 매일 OHLC으로 리샘플링합니다.

난 단지 사용하여 파일 열기로 지금까지 입수했습니다

:

데이터 = pd.read_csv ('data.csv')를

당신은 제가 OHLC에있는 fomat의 데이터를 변환 할 수 있습니다 팬들 리 샘플과. 감사

파이썬으로
+0

그건 고전입니다. 날짜별로 그룹화하고 각 OHLC 열에 해당 기능을 적용하십시오. 의사 코드에서 : data.groupby ("Date") .L에 대해 H 또는 .apply (min)에 적용 (최대) – tschm

답변

1

하지만 팬더없이 :

#!/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)) 

data.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 
0

여전히 실제의 경우가 가장 간단한 방법 판다 스에서 그렇게하기 :

data.resample('1D').apply('ohlc') 
관련 문제