open high low close volume date time
0 0.9738 0.9742 0.9738 0.9740 48 2009-09-27 1900-01-01 18:00:00
1 0.9738 0.9739 0.9737 0.9737 11 2009-09-27 1900-01-01 18:01:00
2 0.9733 0.9734 0.9733 0.9734 6 2009-09-27 1900-01-01 18:02:00
3 0.9734 0.9734 0.9734 0.9734 1 2009-09-27 1900-01-01 18:03:00
4 0.9735 0.9735 0.9735 0.9735 1 2009-09-27 1900-01-01 18:04:00
我有一个大型数据框,如上图所示(股票价格的1分钟日内柱)。
问题: 如果上午8:00在1分钟的酒吧没有价格,我如何获得下一个价格?我希望能够获得时间=上午8:00:00或下一个最接近的价格的每一天的开盘价。
下面的函数得到开放的,累积的高,累积的低点,以及从一些连续的条形区域重建的结束(从设定的开放时间到设定的关闭时间不断)。
def getOpenHighLowClose(x=None, openTime=None, closeTime=None):
x.loc[(x['time']==openTime), 'openPriceOfDay'] = x['open']
x.loc[(x['time']==closeTime), 'closePriceOfDay'] = x['close']
x['openPriceOfDay']=x['openPriceOfDay'].fillna(0)
x['closePriceOfDay']=x['closePriceOfDay'].fillna(0)
x['OpenCashMkt']=x['openPriceOfDay'].max()
x['CloseCashMkt']=x['closePriceOfDay'].max()
x.loc[(x['time']>=openTime) & (x['time']<=closeTime), 'cumHigh'] = x['high'].cummax()
x.loc[(x['time']>=openTime) & (x['time']<=closeTime), 'cumLow'] = x['low'].cummin()
我以这种方式编写代码,以便我可以为任何时间帧构建自己的[open high low close]并使用.shift(x)使用groupby'date'创建返回系列。
我是新手所以请告诉我是否可以进一步澄清。
谢谢!
答案 0 :(得分:0)
您可以按日期分组并采用第一个开盘价(假设数据已经按时间排序)。
df.groupby('date')['open'].first()
您还可以将索引设置为时间戳:
df.set_index(pd.to_datetime(df['date'] + ' ' + df['time']), inplace=True)
这样您就可以轻松访问数据了:
def ohlc(start, end):
ticks = df.loc[start:end]
open = ticks['open'].dropna()[0]
high = ticks['high'].max()
low = ticks['low'].min()
close = ticks['close'].dropna()[-1]
vol = ticks['volume'].sum()
return pd.Series({'start': start, 'end': end, 'open': open, 'high': high, 'low': low, 'close': close, 'volume': vol})
另请参阅Converting OHLC stock data into a different timeframe with python and pandas