國信證券學習系列(6)

行業輪動策略:

本策略每隔1個月定時觸發計算1000能源(399381.SZ)、1000材料(399382.SZ)、1000工業(399383.SZ)、1000可選(399384.SZ)、1000消費(399385.SZ)、1000醫藥(399386.SZ)這幾個行業指數過去20個交易日的收益率并選取了收益率最高的指數的成份股并獲取了他們的市值數據隨后把倉位調整至市值最大的5只股票上

該策略在股票指數日線下運行

獲取股票池:

index_list = ['399381.SZ','399382.SZ','399383.SZ','399384.SZ','399385.SZ','399386.SZ']

獲取收益率最高的指數的成分股:

for k in list(his.keys()):if len(his[k]) == 0:del his[k]for index in index_list:ratio = 0try:ratio = (his[index][-2] - his[index][0])/his[index][0]except KeyError:print('key error:' + index)except IndexError:print('list index out of range:' + index)return_index.append(ratio)# 獲取指定數內收益率表現最好的行業best_index = index_list[np.argmax(return_index)]

獲取股票對應的市值:

        # 獲取當天有交易的股票index_stock = ContextInfo.get_sector(best_index)stock_available = []for stock in index_stock:if ContextInfo.is_suspended_stock(stock) == False:stock_available.append(stock)for stock in stock_available:if stock in list(his.keys()):#目前歷史流通股本取不到,暫用總股本if len(his[stock]) >= 2:stocksize =his[stock][-2] * float(ContextInfo.get_financial_data(['CAPITALSTRUCTURE.total_capital'],[stock],lastdate,date).iloc[0,-1])size_dict[stock] = stocksizeelif len(his[stock]) == 1:stocksize =his[stock][-1] * float(ContextInfo.get_financial_data(['CAPITALSTRUCTURE.total_capital'],[stock],lastdate,date).iloc[0,-1])size_dict[stock] = stocksizeelse:returnsize_sorted = sorted(list(size_dict.items()), key = lambda item:item[1])pre_holding = []

策略代碼:

#coding:gbk'''
回測模型示例(非實盤交易策略)本策略每隔1個月定時觸發計算1000能源(399381.SZ)、1000材料(399382.SZ)、1000工業(399383.SZ)、
1000可選(399384.SZ)、1000消費(399385.SZ)、1000醫藥(399386.SZ)這幾個行業指數過去
20個交易日的收益率并選取了收益率最高的指數的成份股并獲取了他們的市值數據
隨后把倉位調整至市值最大的5只股票上
該策略在股票指數日線下運行
'''
import numpy as np
import math
def init(ContextInfo):MarketPosition ={}ContextInfo.MarketPosition = MarketPosition #初始化持倉index_universe = ['399381.SZ','399382.SZ','399383.SZ','399384.SZ','399385.SZ','399386.SZ'] index_stocks = []for index in index_universe:for stock in ContextInfo.get_sector(index):index_stocks.append(stock)ContextInfo.set_universe(index_universe+index_stocks)   #設定股票池ContextInfo.day = 20ContextInfo.ratio = 0.8ContextInfo.holding_amount = 5ContextInfo.accountID='testS'def handlebar(ContextInfo):buy_condition = Falsesell_condition = Falsed = ContextInfo.barposlastdate = timetag_to_datetime(ContextInfo.get_bar_timetag(d - 1), '%Y%m%d')date = timetag_to_datetime(ContextInfo.get_bar_timetag(d), '%Y%m%d')print(date)index_list = ['399381.SZ','399382.SZ','399383.SZ','399384.SZ','399385.SZ','399386.SZ']return_index = []weight = ContextInfo.ratio/ContextInfo.holding_amountsize_dict = {}if  (float(date[-4:-2]) != float(lastdate[-4:-2])):#print '---------------------------------------------------------------------------------'#print '當前交易日',date,date[-4:-2]his = ContextInfo.get_history_data(21,'1d','close')#print "his",his,timetag_to_datetime(ContextInfo.get_bar_timetag(d),"%Y%m%d")for k in list(his.keys()):if len(his[k]) == 0:del his[k]for index in index_list:ratio = 0try:ratio = (his[index][-2] - his[index][0])/his[index][0]except KeyError:print('key error:' + index)except IndexError:print('list index out of range:' + index)return_index.append(ratio)# 獲取指定數內收益率表現最好的行業best_index = index_list[np.argmax(return_index)]#print '當前最佳行業是:', ContextInfo.get_stock_name(best_index)[3:]+'行業'# 獲取當天有交易的股票index_stock = ContextInfo.get_sector(best_index)stock_available = []for stock in index_stock:if ContextInfo.is_suspended_stock(stock) == False:stock_available.append(stock)for stock in stock_available:if stock in list(his.keys()):#目前歷史流通股本取不到,暫用總股本if len(his[stock]) >= 2:stocksize =his[stock][-2] * float(ContextInfo.get_financial_data(['CAPITALSTRUCTURE.total_capital'],[stock],lastdate,date).iloc[0,-1])size_dict[stock] = stocksizeelif len(his[stock]) == 1:stocksize =his[stock][-1] * float(ContextInfo.get_financial_data(['CAPITALSTRUCTURE.total_capital'],[stock],lastdate,date).iloc[0,-1])size_dict[stock] = stocksizeelse:returnsize_sorted = sorted(list(size_dict.items()), key = lambda item:item[1])pre_holding = []for tuple in size_sorted[-ContextInfo.holding_amount:]:pre_holding.append(tuple[0])#print '買入備選',pre_holding#函數下單if len(pre_holding) > 0:sellshort_list = []for stock in list(ContextInfo.MarketPosition.keys()):if stock not in pre_holding and (stock in list(his.keys())):order_shares(stock,-ContextInfo.MarketPosition[stock],'lastest',his[stock][-1],ContextInfo,ContextInfo.accountID)print('sell',stock)sell_condition = Truesellshort_list.append(stock)if len(sellshort_list) >0:for stock in sellshort_list:del ContextInfo.MarketPosition[stock]for stock in pre_holding:if stock not in list(ContextInfo.MarketPosition.keys()):Lots = math.floor(ContextInfo.ratio * (1.0/len(pre_holding)) * ContextInfo.capital / (his[stock][-1] * 100))order_shares(stock,Lots *100,'lastest',his[stock][-1],ContextInfo,ContextInfo.accountID)print('buy',stock)buy_condition = TrueContextInfo.MarketPosition[stock] = Lots *100#ContextInfo.paint('do_buy', int(buy_condition), -1, 0)#ContextInfo.paint('do_sell', int(sell_condition), -1, 0)

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/449323.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/449323.shtml
英文地址,請注明出處:http://en.pswp.cn/news/449323.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

用Linux命令行修圖——縮放、編輯、轉換格式——一切皆有可能

本文由 極客范 - 八卦愛好者 翻譯自 How-To Geek。歡迎加入極客翻譯小組,同我們一道翻譯與分享。轉載請參見文章末尾處的要求。ImageMagick是一系列的用于修改、加工圖像的命令行工具。ImageMagick能夠快速地使用命令行對圖片進行操作,對大量的圖片進行…

劍指offer:二維數組中的查找

目錄 題目解題思路具體代碼題目 題目鏈接劍指offer:二維數組中的查找題目描述 在一個二維數組中(每個一維數組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數&a…

函數對象 函數嵌套 名稱空間與作用域

函數對象: 函數是第一類對象,即函數可以當做數據傳遞 1 可以被引用 2 可以當做參數傳遞 3 返回值可以是函數 (函數名 不帶() 就是函數名的內存地址,帶括號就是執行函數) 4 可以當做容器類型的…

國信證券學習系列(7)

跨品種套利策略: 本策略根據計算滾動的.過去的30個bar的均值正負0.5個標準差得到布林線 并在最新價差上穿上軌來做空價差,下穿下軌來做多價差 并在回歸至上下軌水平內的時候平倉 獲取數據: # 獲取兩個品種的收盤價時間序列closesContextInfo.get_ma…

dubbo-admin管理平臺搭建

一、前言 前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。 dubbo的使用,其實只需要有注冊中心,消費者,提供者這三個就可以使用了,但是并不能…

不朽傳奇-云計算技術背后的那些天才程序員:Qemu的作者法布里斯貝拉

作者:Liu Guo Hui,OpenStack中國社區,轉載請注明出處 眾所周知,虛擬化技術是構建云基礎架構不可或缺的關鍵技術之一,而在眾多虛擬化技術實現當中,KVM(Kernel Virtual Machine)因為L…

C學習筆記-字符串

對于C語言來說,字符串其實就是最后一個元素為’\0’的char數組 字符數組的初始化 字符數組常見的有兩種初始化方式 char str[] "hello";或者 char str[] {h, e, l, l, o};當使用sizeof(str)時,得到的大小為6&#xff…

Shiro安全框架入門篇(登錄驗證實例詳解與源碼)

一、Shiro框架簡單介紹 前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。 Apache Shiro是Java的一個安全框架,旨在簡化身份驗證和授權。Shiro在JavaSE和JavaEE項目中都可以使用…

國信證券學習系列(8)

我為什么要用國信,就是這個原因,可以做期權,期貨,股票,etf,可轉債的回測。滿足了我所有的需要,我要做指數增強。通常的做法是股票和期貨。但實際上,股票和期權做組合,成本…

Socket程序從Windows移植到Linux下的一些注意事項

關于這個話題網上流傳的是一個相同的版本,就是那個第一項是頭文件的區別,但后面列出的頭文件只有#include沒有(估計是原版的在不斷轉載的過程中有人不小心忘了把尖括號轉義,讓瀏覽器當html標記解析沒了)的那個。現在整…

邊緣控制平面Ambassador全解讀

Ambassador是由Datawire開源的一個API網關項目,主要在Kubernetes的容器編排框架中使用。Ambassador本質上是一個通過配置邊緣/API來管理Envoy數據面板的控制面板。而Envoy則是一個基于第7層協議的網絡代理和通信總線,它是一個由Lyft開源的云原生服務&…

Linux 文件編輯命令 詳細整理

前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。 一、vi編輯器有3種基本工作模式 首先需要知道vi編輯器有3種基本工作模式,分別是:命令模式、文本輸入模式、和末…

專訪迅雷首席工程師:迅雷的下一代互聯網底層技術構想

摘要:互聯網合縱連橫頻頻上演,迅雷與小米的聯姻也成為了熱點,有許多人為迅雷的上市和迅雷的未來擔憂,這家像工程師一樣的公司,命運會怎樣,他們未來會如何走下去?對此CSDN專訪了迅雷首席工程師劉…

YASnippet - emacs 的代碼片段管理工具

添加 snippet M-x 然后輸入 yas-new-snippet 回車 RET&#xff0c;會出現一個新的 buffer # -*- mode: snippet -*-# name: # key: # --在出現的 buffer 中填寫相應的數據 # -*- mode: snippet -*-# name: vard# key: vard# --echo <pre>;var_dump($0);die;c-x c…

深入vuex原理(上)

前言 vuex作為vue生態的重要組成部分&#xff0c;是對store進行管理的一柄利劍。簡而言之&#xff0c;vuex是vue的狀態管理器。使用vuex可用使數據流變得清晰、可追蹤、可預測&#xff0c;更可以簡單的實現 類似時光穿梭 等高級功能&#xff0c;對于復雜的大型應用來講&#xf…

Maven入門(含實例教程)

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 Maven這個個項目管理和構建自動化工具&#xff0c;越來越多的開發人員使用它來管理項目中的jar包。接下來小寶鴿&#xff0c;將從下面幾個…

進階正則表達式

本文同步自我的博客園&#xff1a;http://www.cnblogs.com/hustskyking/ 關于正則表達式&#xff0c;網上可以搜到一大片文章&#xff0c;我之前也搜集了一些資料&#xff0c;并做了排版整理&#xff0c;可以看這篇文章http://www.cnblogs.com/hustskyking/archive/2013/06/04/…

tkinter攔截關閉事件

import tkinter as tk from tkinter import messageboxroot tk.Tk()def on_closing():if messagebox.askokcancel("Quit", "Do you want to quit?"):root.destroy()root.protocol("WM_DELETE_WINDOW", on_closing) root.mainloop() 轉載于:htt…

阿里云服務器一分價錢一分貨,切記!

阿里云為了滿足低端市場的需求&#xff0c;會推出一些價格非常便宜的機器&#xff0c;但是這些機器是為新手練手用或者做測試用的&#xff0c;性能不行。你不要指望花每月9.5元&#xff0c;買一臺學生機&#xff0c;就可以放置流量大的網站還不卡&#xff0c;那個不現實。阿里云…

請記住:你的付出都會以該有的方式歸來(圖)

人&#xff0c;這一生就像一個耕種的農民。你不是在付出&#xff0c;就是在收獲。當然&#xff0c;有人說&#xff0c;付出并不一定有回報。這是大多數人都認同的&#xff0c;也就是付出與得到不一定成正比&#xff0c;不是付出的越多就得到的越多。但我想告訴你的是&#xff0…