首先同意子明的回答,如果题主并不清楚如何在本地搭建相应的开发环境,估计直接用网站上的集成环境会更加好一些,毕竟和搭建环境和维护相比,相应数据的获取与清洗和接口开发(rqalpha在数据上只是ricequant的一个子集)难度要大得多。
以下题归正转。
题主的问题并不是很明确,我就假设题主的问题是如何在ipython里跑以下的指令:
rqalpha run -f buy_and_hold.py -s 2014-01-01 -e 2016-01-01 -o result.pkl --plot
首先需要明白的是python是如何找到core package以外的library的。简单来说,在Linux,Windows或者MacOS上,都有环境变量的概念,python依靠一个特殊的环境变量来加载外部lib,叫做pythonpath,外加安装时特定设置来加载lib。如果题主使用了pip进行安装,一般这些pip都是安排好,不需要额外的手动设置。如果万一ipython找不到的话,就可以通过修改PYTHONPATH的方法读取rqalpha module。
第二步是明白当我们在跑上面的命令时,究竟发生了什么。以下用Linux为例,
shawn@shawn-VirtualBox:~/.rqalpha$ which rqalpha
/home/shawn/anaconda/bin/rqalpha
shawn@shawn-VirtualBox:~/.rqalpha$ cat /home/shawn/anaconda/bin/rqalpha
#!/home/shawn/anaconda/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from rqalpha.__main__ import entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(entry_point())
shawn@shawn-VirtualBox:~/.rqalpha$
我们可以看到rqalpha其实就是一个python wrapper文件,把真正的参数和命令重新导向到rqalpha/__main__.py里的entry_point method。
打开rqalpha/__main__.py,我们能看到wiki上支持的指令在这里都能找到,run, update_bundle, plot等等。不过那些method都带有function decorator with click library,我没有找到直接call这些函数的方法,所以我复制黏贴了run method, 把新的函数命名为run_direct,并且除去了那些function decorator,如下
def run_direct(strategy_file, start_date, end_date, output_file, plot, data_bundle_path, init_cash, progress):
'''run strategy from file'''
if not os.path.exists(data_bundle_path):
print_("data bundle not found. Run `%supdate_bundle` to download data bundle." % sys.argv[0])
return
with codecs.open(strategy_file, encoding="utf-8") as f:
source_code = f.read()
results_df = run_strategy(source_code, strategy_file, start_date, end_date,
init_cash, data_bundle_path, progress)
if output_file is not None:
results_df.to_pickle(output_file)
if plot:
show_draw_result(strategy_file, results_df)
做完这些之后,打开ipython notebook,就可以用以下的code跑示例指令了。
from datetime import datetime
from rqalpha.__main__ import run_direct
strategy_file = r"/home/shawn/dev/workspace/rqalpha/rqalpha/examples/buy_and_hold.py"
start_date = datetime(2014, 1, 1)
end_date = datetime(2016, 1, 1)
output_file = r"/home/shawn/dev/workspace/rqalpha_data/result.pkl"
plot = True
data_bundle_path = r"/home/shawn/.rqalpha"
init_cash = 100000
progress = True
res = run_direct(strategy_file, start_date, end_date, output_file, plot, data_bundle_path, init_cash, progress)
示例图如下:
运用类似的逻辑和方法,你也可以直接运行rqalpha里其他的函数(在确保有合适的初始化的前提下)。如果一个函数没有wrap在click decorator里的话,也不需要额外的复制一个同样的函数并去除decorator了。
@王克勤 要不要我去ricequant也发一份,给我个置顶呀[chuckle]