【问题标题】:Stock price bars--get next closest price in dataframe of bars if bar doesn't exist for some X timeframe股票价格柱 - 如果柱在某个 X 时间范围内不存在,则在柱的数据框中获取下一个最接近的价格
【发布时间】:2016-01-18 09:00:14
【问题描述】:
    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: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' 创建一个返回序列。

我是新手,请告诉我是否可以进一步澄清。

谢谢!

【问题讨论】:

  • 在电子交易之前的“旧时代”,“未平仓”是第一分钟(或几分钟,取决于交易所)所有交易的平均值。换句话说,这不是一个新问题。
  • 太好了,您对搜索什么有什么建议吗?我还想返回与下一个可用柱相关的结果时间

标签: python pandas finance


【解决方案1】:

您可以按日期分组并取第一个开盘价(假设数据已经按时间排序)。

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

【讨论】:

  • 那么我将这个开盘价映射到我的框架?我希望该开盘价成为该日期每一行中的一个值
  • 我对您的示例数据中的时间列感到困惑。您是否有时间戳列或单独的日期和时间列?
  • 我有单独的时间和日期列
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
相关资源
最近更新 更多