如何通过pandas_market_calendars获取Forex的8:00-17:00交易时段?
问题:获取Forex对应区域的交易时段(替代NYSE常规时段)
背景说明
Forex各区域交易时段与NYSE常规交易时段存在差异:
- NYSE常规交易时段为当地时间9:30-16:00
- Forex各区域交易时段如下:
Forex "NYSE" New York 8am to 5pm timezone: "America/New_York" Forex "ASX" Sydney 7am to 4pm timezone: "Australia/Sydney" Forex "JPX" Tokyo 9am to 6pm timezone: "Asia/Tokyo" Forex "LSE" London 8am to 4pm timezone: "Europe/London"
用户尝试的代码及结果
用户尝试用pandas_market_calendars获取纽约Forex时段,但得到的是NYSE常规9:30-16:00的结果:
import pytz import pandas_market_calendars as mcal nyse = mcal.get_calendar("NYSE") market_open_and_close_times = nyse.schedule(start_date="2023-11-05", end_date="2023-11-11") market_open_and_close_times['market_open'] = [t.tz_convert(pytz.timezone("America/New_York")) for t in market_open_and_close_times['market_open']] market_open_and_close_times['market_close'] = [t.tz_convert(pytz.timezone("America/New_York")) for t in market_open_and_close_times['market_close']] print(type(market_open_and_close_times)) print(market_open_and_close_times)
运行结果:
<class 'pandas.core.frame.DataFrame'> market_open market_close 2023-11-06 2023-11-06 09:30:00-05:00 2023-11-06 16:00:00-05:00 2023-11-07 2023-11-07 09:30:00-05:00 2023-11-07 16:00:00-05:00 2023-11-08 2023-11-08 09:30:00-05:00 2023-11-08 16:00:00-05:00 2023-11-09 2023-11-09 09:30:00-05:00 2023-11-09 16:00:00-05:00 2023-11-10 2023-11-10 09:30:00-05:00 2023-11-10 16:00:00-05:00
解决方案
方案1:自定义pandas_market_calendars日历类
如果需要保留NYSE的假期规则(Forex纽约时段通常与NYSE假期同步),可以继承NYSE日历类,重写开盘/收盘时间:
import pytz import pandas_market_calendars as mcal from pandas_market_calendars.exchange_calendar_nyse import NYSECalendar class ForexNewYorkCalendar(NYSECalendar): # 重写Forex纽约的开盘/收盘时间(当地时间) open_time = mcal.time(8, 0) close_time = mcal.time(17, 0) timezone = pytz.timezone("America/New_York") # 使用自定义日历 forex_ny = ForexNewYorkCalendar() schedule = forex_ny.schedule(start_date="2023-11-05", end_date="2023-11-11") # 转换为纽约时区显示(可选,schedule默认已带时区) schedule['market_open'] = schedule['market_open'].dt.tz_convert("America/New_York") schedule['market_close'] = schedule['market_close'].dt.tz_convert("America/New_York") print(schedule)
运行后会输出8:00-17:00的时段,同时自动跳过NYSE的休市日。
方案2:直接生成时段(无需复杂假期处理)
如果不需要考虑假期,直接用pandas生成连续工作日的8:00-17:00时段更简单:
import pandas as pd import pytz start_date = "2023-11-05" end_date = "2023-11-11" # 生成工作日日期范围 dates = pd.bdate_range(start=start_date, end=end_date) ny_tz = pytz.timezone("America/New_York") # 创建开盘/收盘时间列 schedule = pd.DataFrame({ 'market_open': dates.to_series().apply(lambda d: ny_tz.localize(pd.Timestamp(f"{d} 08:00:00"))), 'market_close': dates.to_series().apply(lambda d: ny_tz.localize(pd.Timestamp(f"{d} 17:00:00"))) }) print(schedule)
其他区域Forex时段扩展
对于悉尼、东京、伦敦等其他区域,可参照方案1,继承对应交易所的日历类(如ASXCalendar、JPXCalendar、LSECalendar),重写open_time和close_time即可。
内容的提问来源于stack exchange,提问作者Pavel Bogdanov
相关产品推荐
相关产品推荐

