问题描述
当我从Interactive broker(IB)下载外汇每日开-高-低-收(OHLC)蜡烛时,我得到的值与ProRealTime(PRT)的蜡烛不匹配(至少在法国是这样)。
我弄清楚了PRT如何建立蜡烛(根据IB数据):
- 星期一-PRT =星期日(23:15)->星期二(02:00)
- 星期二-PRT =星期二(02:00)->星期三(02:00)
- 星期三-PRT =星期三(02:00)->星期四(02:00)
- 星期四-PRT =星期四(02:00)->星期五(02:00)
- 星期二-PRT =星期五(02:00)->星期五(22:00)
因此,我想使用熊猫从IB每小时的蜡烛中重建PRT每天的蜡烛。
以下提供了带有IB-hourly-candles的起始代码:
import pandas as pd
import dateutils
df = pd.read_csv(
'https://gist.githubusercontent.com/marc-moreaux/d6a910952b8c8243a4fcb8e377cc2de9/raw/d811445bbb782743e71193dbbe31f84adc6f8a5f/EURUSD-daily.csv',index_col=0,usecols=[1,2,3,4,5],parse_dates=True,date_parser=dateutil.parser.isoparse))
与此帖子并行的是,我提供了一段代码为我完成了工作。
解决方法
我花了一些时间解决所有问题,所以我分享了我对这个问题的解决方案,而且我想知道是否有更清晰的方法可以实现相同的目标:
import pandas as pd
import dateutils
# Read the csv
df = pd.read_csv(
'https://gist.githubusercontent.com/marc-moreaux/d6a910952b8c8243a4fcb8e377cc2de9/raw/d811445bbb782743e71193dbbe31f84adc6f8a5f/EURUSD-daily.csv',index_col=0,usecols=[1,2,3,4,5],parse_dates=True,date_parser=dateutil.parser.isoparse))
# OHLC Agglomeration scheme
ohlc_agg = {
'open': 'first','high': 'max','low': 'min','close': 'last' }
# Set data to Central European Time (+1/+2) and convert it to UTC (+0)
df = (df.tz_localize('CET',ambiguous='infer')
.tz_convert(None)
.resample('1d')
.agg(ohlc_agg)
.dropna())
# Identify Sundays and Mondays by their weekday
df['wd'] = df.index.weekday
# Aggregate 1 week of data where only Sundays and Mondays exists; shift these
# aggregated values to corresponding monday; and update df.
df.update(df[(df.wd == 6) | (df.wd == 0)]
.ressample('1W-MON')
.agg(ohlc_agg))
# Finally delete sundays
df = df[df.wd != 6]