股价条形图如果条形图在某个时间段内不存在,则在条形图的数据帧中设置下一个最接近的价格

2024-09-30 23:42:05 发布

您现在位置:Python中文网/ 问答频道 /正文

    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点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'的返回序列。你知道吗

我是一个新手,所以请告诉我,如果我可以进一步澄清。你知道吗

谢谢!你知道吗


Tags: noneclosedatetime时间价格openloc
1条回答
网友
1楼 · 发布于 2024-09-30 23:42:05

您可以按日期分组并获取第一个未平仓价格(假设数据已按时间排序)。你知道吗

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

相关问题 更多 >