1.

# 克隆自聚宽文章:https://www.joinquant.com/post/2709
# 标题:基于SVM的机器学习策略
# 作者:走得很慢的海龟 import math
import numpy as np
#from sklearn import preprocessing, cross_validation, svm
from sklearn import preprocessing, svm
import matplotlib.pyplot as plt
from matplotlib import style
import sklearn
import time
from datetime import datetime
import cPickle as pickle def initialize(context):
g.train=True # year_date is for get_fundamentals
def train_data(year_date, index_date):
Valuation=[]
price=[]
status=[]
SZ1=get_index_stocks('399008.XSHE', date=index_date)
SZ2=get_index_stocks('399012.XSHE', date=index_date)
SH=get_index_stocks('399905.XSHE', date=index_date)
tem_index=SZ1+SZ2+SH
unix_30d=60*60*24*30
unix_weekend=60*60*24*3 q=query(
income.code, income.pubDate, income.total_operating_revenue,
income.total_operating_cost, income.administration_expense,
income.operating_profit, income.non_operating_revenue,
income.total_profit, income.net_profit, income.basic_eps,
income.diluted_eps, income.total_composite_income
).filter(
valuation.code.in_(tem_index)) incm = get_fundamentals(q, statDate=year_date)
date=incm['pubDate']
index=incm['code'] q=query(
indicator
).filter(
valuation.code.in_(index))
indictor=get_fundamentals(q, statDate=year_date)
del(indictor['code'], indictor['statDate'], indictor['pubDate']) for each in range(0,len(date)):
q=query(
valuation.pe_ratio, valuation.pb_ratio, valuation.circulating_market_cap
).filter(
valuation.code==(index[each]))
each_valuation=get_fundamentals(q, date=date[each]) date_stamp = datetime.strptime(date[each], '%Y-%m-%d')
unix=time.mktime(date_stamp.timetuple())
unix_30_late=unix+unix_30d Valuation.append(each_valuation.iloc[0].tolist()) p1=get_price(index[each], start_date=date[each],
end_date=date[each], frequency='daily', fields='close') if not p1.empty:
pass
else:
p1_weekend=datetime.fromtimestamp(unix-unix_weekend).strftime('%Y-%m-%d')
p1=get_price(index[each], start_date=p1_weekend,
end_date=p1_weekend, frequency='daily', fields='close') p1_30d=datetime.fromtimestamp(unix_30_late).strftime('%Y-%m-%d')
p2=get_price(index[each], start_date=p1_30d,
end_date=p1_30d, frequency='daily', fields='close') if not p2.empty:
pass
else:
date_stamp2 = datetime.strptime(p1_30d, '%Y-%m-%d')
unix2=time.mktime(date_stamp2.timetuple())
unix2_weekend=unix2-unix_weekend
p2_weekend=datetime.fromtimestamp(unix2_weekend).strftime('%Y-%m-%d')
p2=get_price(index[each], start_date=p2_weekend,
end_date=p2_weekend, frequency='daily', fields='close') dif = p2.values / p1.values if dif > 1.1:
s=1
else:
s=0
status.append(s) price.append(p1.iloc[0].tolist()) Valuation=pd.DataFrame(Valuation, columns=['pe','pb','cir_mkt_cap'])
price=pd.DataFrame(price, columns=['price'])
status=pd.DataFrame(status, columns=['status'])
df=pd.concat([incm,Valuation,price,indictor,status], axis=1) del(df['pubDate'], df['statDate.1'], df['code'])
#y=df['status'].values.tolist()
#df=np.random.permutation(df)
#del(df['status'], df['code'])
#X=np.array(df.replace('NaN', 9999).values.tolist())
#X=preprocessing.scale(X)
return df def fundamental(index):
Valuation=[]
price=[]
status=[] q=query(
income.total_operating_revenue,
income.total_operating_cost, income.administration_expense,
income.operating_profit, income.non_operating_revenue,
income.total_profit, income.net_profit, income.basic_eps,
income.diluted_eps, income.total_composite_income
).filter(
valuation.code.in_(index))
incm = get_fundamentals(q) q=query(
valuation.pe_ratio, valuation.pb_ratio, valuation.circulating_market_cap
).filter(
valuation.code.in_(index))
Valuation=get_fundamentals(q)#.values.tolist() q=query(
indicator
).filter(
valuation.code.in_(index))
indictor=get_fundamentals(q)#.values.tolist()
index2=indictor['code']
del(indictor['code'], indictor['statDate'], indictor['pubDate'], indictor['day']) for each in index2:
p=attribute_history(each, 1, unit='1d', fields=['close'], skip_paused=True)
price.append(p.iloc[0].tolist()) price=pd.DataFrame(price, columns=['price'])
df=pd.concat([incm,Valuation,price,indictor], axis=1)
X=np.array(df.replace('NaN', 9999).values.tolist()) X=preprocessing.scale(X)
return X, index2 def handle_data(context, data):
if g.train:
index_date=str('2014-03-01')
df1=train_data(str('2014q1'),index_date)
df2=train_data(str('2014q2'),index_date)
df3=train_data(str('2014q3'),index_date)
df4=train_data(str('2014q4'),index_date)
df=pd.concat([df1,df2,df3,df4], axis=0)
df.iloc[np.random.permutation(len(df))]
y=df['status'].values.tolist()
del(df['status'])
log.info("<===== shape of training dataset @ %s", str(df.shape))
X=np.array(df.replace('NaN', 9999).values.tolist()) X=preprocessing.scale(X) clf = svm.SVC(kernel=str("linear"), C=1.0)
clf.fit(X, y) filename = "temp.pkl"
pickle_file = open(filename, 'wb')
pickle.dump(clf, pickle_file)
pickle_file.close()
g.train=False filename = "temp.pkl"
pickle_file = open(filename, 'rb')
clf = pickle.load(pickle_file) year=context.current_dt.year
month=context.current_dt.month
day=context.current_dt.day
index_date=str(year)+'-'+str(month)+'-'+str(day) SZ1=get_index_stocks('399008.XSHE', date=index_date)
SZ2=get_index_stocks('399012.XSHE', date=index_date)
SH=get_index_stocks('399905.XSHE', date=index_date)
index=SZ1+SZ2+SH X, index2=fundamental(index) for each in range(0, len(index2)):
if clf.predict(X[each].reshape(1,X.shape[1]))[0] == 1 and index2[each] not in context.portfolio.positions.keys():
log.info("===================Buying:", index2[each])
order_target_value(index2[each], context.portfolio.cash/5)
if clf.predict(X[each].reshape(1,X.shape[1]))[0] == 0 and index2[each] in context.portfolio.positions.keys():
log.info("<<<<<<<<<<<<<<<<<<Holding:", context.portfolio.positions.keys())
log.info("-------------------selling:", index2[each])
order_target(index2[each], 0) # 止损 if context.portfolio.positions:
for stock in context.portfolio.positions.keys():
cur_price = data[stock].close
position=context.portfolio.positions[stock]
if cur_price > position.avg_cost * (1 + 0.5) or cur_price < position.avg_cost * (1 - 0.2):
order_target(stock, 0)
log.info("<<<<<<<<<<<", stock, "%s lose:", 1-cur_price/position.avg_cost)

  https://www.joinquant.com/

https://zhuanlan.zhihu.com/p/24649311

第25月第7天 聚宽 svm的更多相关文章

  1. 聚宽投资研究获取A股05年至今全部数据

    #用中正全指'000985.XSHG'获取全部A股数据pool=get_index_stocks('000985.XSHG') #date存储05年开始全部交易时间 date=get_price('0 ...

  2. 金融量化分析【day113】:聚宽自带策略

    一.策略代码 # 导入函数库 from jqdata import * # 初始化函数,设定基准等等 def initialize(context): # 设定沪深300作为基准 set_benchm ...

  3. 聚宽获取财务数据+DataFrame写入txt

    from jqdata import jy from jqdata import * #获取股票列表,这里是板块内股票 pool=get_industry_stocks(',date='2016-09 ...

  4. 第25月第26天 dispatch_group_t dispatch_semaphore_t

    1. dispatch_group_enter(group); dispatch_group_leave(group); dispatch_group_notify(group1, queue1,bl ...

  5. 第25月25日 urlsession

    1. private lazy var session: URLSession = { let configuration = URLSessionConfiguration.default conf ...

  6. 第25月第22日 django channels

    1. https://github.com/andrewgodwin/channels-examples/ https://channels.readthedocs.io/en/latest/

  7. 第25月第18天 vue

    1.cnpm sudo chown -R $USER /usr/local  npm install -g cnpm --registry=https://registry.npm.taobao.or ...

  8. 第25月第17天 django rest framwork authentication /tmp/mysql.sock

    1.authentication https://www.django-rest-framework.org/api-guide/authentication/#authentication 2.dj ...

  9. 第25月第15天 udacity cs253

    1.cs253 https://classroom.udacity.com/courses/cs253 webapp2 Install WebOb, Paste and webapp2¶ We nee ...

随机推荐

  1. JAVA版本8u171与8u172的区别

    用了java 7好几年了,今天闲来无事,想升级到 java 8,到官网下载的时候发现JAVA放出了8u171与8u172两个版本. 什么情况? 百度一下找到答案:https://blog.csdn.n ...

  2. 初识JSP知识

    一.jsp概述 JSP全称是Java Server Pages,它和servle技术一样,都是SUN公司定义的一种用于开发动态web资源的技术. JSP实际上就是Servlet. jsp = html ...

  3. jmeter自动生成测绘报告并发送邮件

    步骤: 1.安装ant,添加到环境变量(windows是将bin目录添加到path.cmd命令输入 ant -v 查看版本号) (mac:brew install ant ant –version) ...

  4. Unity Shader基本例子

    Unity中,对于一个物体我们想要改变其的外观,就需要给其增加一个材质,即Matiral 一般的Matiral采用的是标准的Shader,而标准的Shader并不是最好的渲染物体表明的效果,那么我们就 ...

  5. JAVA后端生成Token(令牌),用于校验客户端,防止重复提交

    转:https://blog.csdn.net/u011821334/article/details/79390980 转:https://blog.csdn.net/joshua1830/artic ...

  6. ES6(promise)_解决回调嵌套简单应用

    一.前言 这个小案例是在node平台上应用的所以需要保证你的电脑: 1.安装和配置node.js环境 2.需要用node.js来开启一个http-server: 开启方法:https://blog.c ...

  7. MySQL mysqldump 导入/导出 结构&数据&存储过程&函数&事件&触发器

    ———————————————-库操作———————————————-1.①导出一个库结构 mysqldump -d dbname -u root -p > xxx.sql ②导出多个库结构 m ...

  8. zTree基础

    zTree使用 zTree 是一个依靠 jQuery 实现的多功能 “树插件”, 而且拥有较好的浏览器兼容性,有着丰富的功能以及可以自定义样式,足以满足大部分业务的开发. 第一步先导入css及js文件 ...

  9. 【MSSQL】SQL Server的日期和时间类型

    参考:SQL Server的日期和时间类型 SQL Server使用 Date 表示日期,time表示时间,使用datetime和datetime2表示日期和时间. 1.秒的精度 秒的精度是指TSQL ...

  10. python 内置函数,匿名函数,sorted,filter,map,递归,二分法,冒泡算法 eval

    ############################总结#################################1. lambda 匿名函数 语法——lambda 参数:返回值 __na ...