
等级: 新手上路
- 注册:
- 2025-4-8
- 曾用名:
|

楼主 |
发表于 2025-6-11 10:59
|
显示全部楼层
以下是针对history_bars和history_bar_date进行联合使用的程序,目前只有history_bars返回值好使,但是返回的收盘价却是不准的。
def get_previous_day_close(context, contract, current_time):
"""获取前一交易日下午15:00的收盘价"""
try:
previous_day = current_time.date() - datetime.timedelta(days=1)
current_day = current_time.date()
previous_str = previous_day.strftime('%Y-%m-%d') + '00:00:00'
current_str = current_day.strftime('%Y-%m-%d') + '00:00:00'
bars = history_bars_date(contract, previous_str, current_str, '1d', ['close'], skip_suspended=True, include_now=False)
if bars is None:
print(f"无法获取 {contract} 的前一日收盘价,数据为 None")
return None
if isinstance(bars, np.ndarray):
if bars.shape[0] >= 1:
previous_close = float(bars[-1, 0] if bars.ndim == 2 else bars[-1])
else:
fb = history_bars(contract, 2, '1d', ['close'],skip_suspended=True, include_now=False)
if isinstance(fb, np.ndarray) and fb.shape[0] >= 2:
return float(fb[-2,0] if fb.ndim==2 else fb[-2])
if isinstance(fb, list) and len(fb) >= 2 and isinstance(fb[-2], dict):
return float(fb[-2]['close'])
print(f"无法获取 {contract} 的前一日收盘价,数组长度不足")
return None
elif isinstance(bars, list):
if len(bars) >= 1 and isinstance(bars[-1], dict) and 'close' in bars[-1]:
previous_close = float(bars[-1]['close'])
else:
print(f"无法获取 {contract} 的前一日收盘价,列表数据不符合要求")
return None
else:
print(f"无法获取 {contract} 的前一日收盘价,数据类型未知: {type(bars)}")
return None
return previous_close
except Exception as e:
print(f"获取 {contract} 的前一日收盘价失败: {str(e)}")
return None |
|