美文网首页python
python-策略学习(买入&持有)

python-策略学习(买入&持有)

作者: 玩er2017 | 来源:发表于2018-06-12 11:18 被阅读0次

    python-策略学习(买入&持有)

    第一个策略-买入&持有

    参考文献:http://rqalpha.io/zh_CN/latest/intro/tutorial.html


    数据包更新

    $ rqalpha update_bundle
    

    拷贝股票数据包

    $ cp -a /Users/test/.rqalpha/bundle /Users/test/Documents/bundle/rqalpha 
    

    运行策略

    $ rqalpha run -f /Users/test/Documents/buy_and_hold.py -d /Users/test/Documents/bundle/ -s 2016-06-01 -e 2016-12-01 --account stock 100000 --benchmark 000300.XSHG --plot -o result.pkl
    

    假如我们的策略存放在了 ./rqalpha/examples/buy_and_hold.py 路径下, 数据源存放在 ./rqalpha/bundle/ 路径下,回测的起始时间为 2016-06-01, 结束时间为 2016-12-01,我们给策略分配的起始资金为 100000, Benchmark 设置为 `000300.XSHG

    屏幕快照 2018-06-12 10.44.15.png

    运行过程

    1. 运行anaconda虚拟环境,打开terminal
    屏幕快照 2018-06-12 10.59.09.png
    1. 执行命令


      屏幕快照 2018-06-12 11.00.42.png
    1. 结果
    屏幕快照 2018-06-12 11.04.42.png

    策略主体

    # 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
    def init(context):
        logger.info("init")
        context.s1 = "000001.XSHE"
        update_universe(context.s1)
        # 是否已发送了order
        context.fired = False
        context.cnt = 1
    
    
    def before_trading(context):
        logger.info("Before Trading", context.cnt)
        context.cnt += 1
    
    
    # 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新
    def handle_bar(context, bar_dict):
        context.cnt += 1
        logger.info("handle_bar", context.cnt)
        # 开始编写你的主要的算法逻辑
    
        # bar_dict[order_book_id] 可以拿到某个证券的bar信息
        # context.portfolio 可以拿到现在的投资组合状态信息
    
        # 使用order_shares(id_or_ins, amount)方法进行落单
    
        # TODO: 开始编写你的算法吧!
        if not context.fired:
            # order_percent并且传入1代表买入该股票并且使其占有投资组合的100%
            order_percent(context.s1, 1)
            context.fired = True
    

    数据进行分析

    把生成的文件result.pkl移动出来。

    $ mv  /Users/test/result.pkl  /Users/test/Documents/
    

    如果想把回测的数据保存下来,可以通过-o参数将结果保存成pkl文件。等回测结束后可以通过 pandas.read_pickle 函数来读取数据进行之后的数据分析。

    分析调用pandas库,程序主体

    import pandas as pd
    
    result_dict = pd.read_pickle('result.pkl')
    
    result_dict.keys()
    # [out]dict_keys(['total_portfolios', 'summary', 'benchmark_portfolios', 'benchmark_positions', 'stock_positions', 'trades', 'stock_portfolios'])
    

    http://rqalpha.io/zh_CN/latest/intro/tutorial.html

    相关文章

      网友评论

        本文标题:python-策略学习(买入&持有)

        本文链接:https://www.haomeiwen.com/subject/cwsleftx.html