我有(时间,价格)元组中的股票价格数据列表:
from datetime import datetime
prices = [(datetime(2015, 1, 9), 101.9), (datetime(2015, 1, 12), 101.5), (datetime(2015, 1, 13), 101.7)]
我希望将其作为RxPY Observable
,以便我可以逐个回溯测试交易策略:
def myStrategy(date, price): # SELL if date is a Monday and price is above 101.6
strategy = 'SELL' if date.weekday() and price > 101.6 else 'BUY'
print 'date=%s price=%s strategy=%s' % (date, price, strategy)
我希望从2015年1月12日开始回测,所以我假设我必须使用以下调度程序:
from rx.concurrency import HistoricalScheduler
scheduler = HistoricalScheduler(datetime(2015, 1, 12))
要进行我的测试,我会这样做:
from rx import Observable
observable = Observable.from_iterable(prices, scheduler=scheduler).timestamp()
observable.subscribe(lambda price: myStrategy(price.timestamp, price.value))
scheduler.start()
我希望看到:
date=2015-01-12 00:00:00 price=101.5 strategy=BUY
date=2015-01-13 00:00:00 price=101.7 strategy=SELL
但我得到了
date=2015-12-20 08:43:45.882000 price=(datetime.datetime(2015, 1, 9, 0, 0), 101.9) strategy=SELL
date=2015-12-20 08:43:45.882000 price=(datetime.datetime(2015, 1, 12, 0, 0), 101.5) strategy=SELL
date=2015-12-20 08:43:45.882000 price=(datetime.datetime(2015, 1, 13, 0, 0), 101.7) strategy=SELL
问题是:
2015-12-20 08:43:45.882000
而不是历史日期(例如datetime(2015, 1, 12)
)我也尝试过使用scheduler.now()
:
observable.subscribe(lambda price: myStrategy(scheduler.now(), price.value))
但由于某种原因,日期因date=2015-01-12 00:00:00
而停留:
date=2015-01-12 00:00:00 price=(datetime.datetime(2015, 1, 9, 0, 0), 101.9) strategy=BUY
date=2015-01-12 00:00:00 price=(datetime.datetime(2015, 1, 12, 0, 0), 101.5) strategy=BUY
date=2015-01-12 00:00:00 price=(datetime.datetime(2015, 1, 13, 0, 0), 101.7) strategy=BUY
如何解决上述问题并获得我原先预期的结果?
答案 0 :(得分:1)
rx也是新手,
"默认情况下,timestamp在超时计划程序上运行,但也有一个变体,允许您通过将其作为参数传入来指定计划程序。" http://reactivex.io/documentation/operators/timestamp.html
只有rxjs的文档,但rx的美妙之处在于一切都随之而来。
请查看这是否适合您。
observable = Observable.from_iterable(prices,scheduler=scheduler).timestamp(scheduler=scheduler)
observable.subscribe(lambda price: myStrategy(price.timestamp, price.value[1]))
scheduler.start()