微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

利用新闻情感数据炒股 python程序

下面是编程之家 jb51.cc 通过网络收集整理的代码片段。

编程之家小编现在分享给大家,也给大家做个参考。

from CAL.PyCAL import Date

start = '2010-01-01'                       # 回测起始时间
end = '2015-05-05'                         # 回测结束时间
benchmark = 'HS300'                        # 策略参考标准
universe = set_universe('HS300')               # 证券池,支持股票和基金
capital_base = 1000000                      # 起始资金
longest_history = 0                        # handle_data 函数中可以使用的历史数据最长窗口长度
refresh_rate = 1                          # 调仓频率,即每 refresh_rate 个交易日执行一次 handle_data() 函数
longest_history = 1


def initialize(account):                   # 初始化虚拟账户状态
    account.isBuyPeriod = False
    account.dayCount = 0

def handle_data(account):                  # 每个交易日的买入卖出指令
    account.dayCount += 1 
    if account.isBuyPeriod:                # 每60个工作日(3个月)调仓
        hist = account.get_history(longest_history)
        endDate = Date.fromDateTime(account.current_date)
        startDate = endDate - 30
        res =  DataAPI.NewsSentimentIndexGet(secID=account.universe,field=['secID','newsPublishDate','sentimentIndex'],beginDate=startDate.strftime('%Y%m%d'),endDate=endDate.strftime('%Y%m%d'))
        res = res.groupby('secID')
        
        # top 10%
        top10 = res.mean().sort('sentimentIndex',ascending=False).head(int(0.1*len(res)))
        buyList = list(top10.index)
        print u"%s 买入 : %s" % (endDate,buyList)
        
        # 等权重买入
        if len(buyList) != 0:
            singleCash = account.cash / len(buyList)
            for stock in buyList:
                approximationAmount = int(singleCash / hist[stock]['closePrice'][-1]/100.0) * 100
                order(stock,approximationAmount)

        account.isBuyPeriod = False
        account.dayCount = 0
    elif account.dayCount == 59:          # 调仓日前一日清空当前仓位
        for stock in account.valid_secpos:
            order_to(stock,0)
        account.isBuyPeriod = True
    

以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐