Skip to main content
 首页 » 编程设计

python之连接点和区间数据

2025年05月04日10shihaiming

我有两个时间序列需要加入:

第一个是价格的时间序列 像这样

ticker date       price  
SBUX   01/01/2012 55 

第二个时间序列是调整因子,表示为

ticker start_date end_date    adjustment_factor 
SBUX   01/01/1993 01/01/1994  0.015 

如何在 pandas 中将这些时间序列连接在一起,以表达调整后的价格

adjusted_price = historical_prices * adjustment_factor 

我知道我需要使用 date_range 函数将 adjustment_factor 间隔时间序列扩展为每日序列。 但问题是调整时间序列的每一行都将具有不同的日期范围——有没有一种方法可以对整个调整因子时间序列的间隔日期类型进行批处理转换,而不是对每一行进行转换。

我发现我需要将第一个时间点时间序列旋转到列中,将日期放入行中,对于第二个时间序列,将间隔扩展到每日粒度并旋转它(通过 dataframe.pivot功能。通过组合两个数据框,可以编写我需要的功能。

请您参考如下方法:

您可以简单地将 dataFrame 与您的每日柱连接起来,并使用 fillna(method="ffill") 前向填充先前的值。在您的示例中,您有一个范围的调整因子。

#suppose sbux is an ohlc daily bar and adj is your adjustment factors   
adj  = pandas.DataFrame({"adj":pandas.Series(values,index = start_dates)}) 
sbux_with_adj  = sbux.join(adj) 
sbux_with_adj["Adj"] =    sbux_with_adj["Adj"].fillna(method="ffill") 
ohlc = sbux_with_adj[["Open","High","Low","Close"]] * sbux_with_adj["adj"] 

我会按照以下方式使用更常见的调整因子(例如 .985 表示 1.5% 的股息)进行调整:

sbux_with_adj  = sbux.join(adj) 
sbux_with_adj["Adj"] =    sbux_with_adj["Adj"].fillna(1.0) 
#now reverse cumulated adjustment. 
cumulated_adj = sbux_with_adj["Adj"].cumprod().values[::-1]  
ohlc = sbux_with_adj[["Open","High","Low","Close"]] * cumulated_adj