文档章节

量化策略

o
 osc_4nmshwhm
发布于 2018/08/06 21:33
字数 965
阅读 14
收藏 0

钉钉、微博极速扩容黑科技,点击观看阿里云弹性计算年度发布会!>>>

0. 第一个量化策略

# 初始化函数,设定基准等等
def initialize(context):
    set_benchmark('000300.XSHG')
    g.security = get_index_stocks('000300.XSHG') # 股票池
    set_option('use_real_price', True)
    set_order_cost(OrderCost(open_tax=0, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    log.set_level('order','warning')
    
def handle_data(context, data):

    # 一般情况下先卖后买
    
    tobuy = []
    for stock in g.security:
        p = get_current_data()[stock].day_open
        amount = context.portfolio.positions[stock].total_amount
        cost = context.portfolio.positions[stock].avg_cost
        if amount > 0 and p >= cost * 1.25:
            order_target(stock, 0)   # 止盈
        if amount > 0 and p <= cost * 0.9:
            order_target(stock, 0)  # 止损
        
        if p <= 10.0 and amount == 0:
            tobuy.append(stock)
    
    if len(tobuy)>0:
        cash_per_stock = context.portfolio.available_cash / len(tobuy)
        for stock in tobuy:
            order_value(stock, cash_per_stock)

1. 双均线策略

def initialize(context):
    set_benchmark('600519.XSHG')
    set_option('use_real_price', True)
    set_order_cost(OrderCost(open_tax=0, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    
    g.security = ['600519.XSHG']
    g.p1 = 5
    g.p2 = 30
   
    
def handle_data(context, data):
    for stock in g.security:
        # 金叉:如果5日均线大于10日均线并且不持仓
        # 死叉:如果5日均线小于10日均线并且持仓
        df = attribute_history(stock, g.p2)
        ma10 = df['close'].mean()
        ma5 = df['close'][-5:].mean()
        
        if ma10 > ma5 and stock in context.portfolio.positions:
            # 死叉
            order_target(stock, 0)
        
        if ma10 < ma5 and stock not in context.portfolio.positions:
            # 金叉
            order_value(stock, context.portfolio.available_cash * 0.8)
    # record(ma5=ma5, ma10=ma10)

2. 因子选股

def initialize(context):
    set_benchmark('000002.XSHG')
    set_option('use_real_price', True)
    set_order_cost(OrderCost(open_tax=0, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    g.security = get_index_stocks('000002.XSHG')
    
    g.q = query(valuation).filter(valuation.code.in_(g.security))
    g.N = 20
    
    run_monthly(handle, 1)

def handle(context):
    df = get_fundamentals(g.q)[['code', 'market_cap']]
    df = df.sort('market_cap').iloc[:g.N,:]
    
    to_hold = df['code'].values
    
    for stock in context.portfolio.positions:
        if stock not in to_hold:
            order_target(stock, 0)
            
    to_buy = [stock for stock in to_hold if stock not in context.portfolio.positions]
    
    if len(to_buy) > 0:
        cash_per_stock = context.portfolio.available_cash / len(to_buy)
        for stock in to_buy:
            order_value(stock, cash_per_stock)

3. 多因子选股

def initialize(context):
    set_benchmark('000002.XSHG')
    set_option('use_real_price', True)
    set_order_cost(OrderCost(open_tax=0, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    g.security = get_index_stocks('000002.XSHG')
    
    g.q = query(valuation, indicator).filter(valuation.code.in_(g.security))
    g.N = 20
    
    run_monthly(handle, 1)

def handle(context):
    df = get_fundamentals(g.q)[['code', 'market_cap', 'roe']]
    df['market_cap'] = (df['market_cap'] - df['market_cap'].min()) / (df['market_cap'].max()-df['market_cap'].min())
    df['roe'] = (df['roe'] - df['roe'].min()) / (df['roe'].max()-df['roe'].min())
    df['score'] = df['roe']-df['market_cap']
    
    df = df.sort('score').iloc[-g.N:,:]
    
    to_hold = df['code'].values
    
    
    for stock in context.portfolio.positions:
        if stock not in to_hold:
            order_target(stock, 0)
            
    to_buy = [stock for stock in to_hold if stock not in context.portfolio.positions]
    
    if len(to_buy) > 0:
        cash_per_stock = context.portfolio.available_cash / len(to_buy)
        for stock in to_buy:
            order_value(stock, cash_per_stock)

4. 均值回归

import jqdata
import math
import numpy as np
import pandas as pd

def initialize(context):
    set_option('use_real_price', True)
    set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    set_benchmark('000002.XSHG')
    
    g.security = get_index_stocks('000002.XSHG')
    
    g.ma_days = 30
    g.stock_num = 10
    
    run_monthly(handle, 1)
    
def handle(context):
    
    sr = pd.Series(index=g.security)
    for stock in sr.index:
        ma = attribute_history(stock, g.ma_days)['close'].mean()
        p = get_current_data()[stock].day_open
        ratio = (ma-p)/ma
        sr[stock] = ratio
    tohold = sr.nlargest(g.stock_num).index.values
    # print(tohold)
    
    # to_hold = #
    
    for stock in context.portfolio.positions:
        if stock not in tohold:
            order_target_value(stock, 0)
    
    tobuy = [stock for stock in tohold if stock not in context.portfolio.positions]
    
    if len(tobuy)>0:
        cash = context.portfolio.available_cash
        cash_every_stock = cash / len(tobuy)
        
        for stock in tobuy:
            order_value(stock, cash_every_stock)

5. 布林带策略

#import numpy as np
#import pandas as pd

def initialize(context):
    set_option('use_real_price', True)
    set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    set_benchmark('600036.XSHG')
    
    g.security = '600036.XSHG'
    g.M = 20
    g.k = 2
    
# 初始化此策略
def handle_data(context, data):
    sr = attribute_history(g.security, g.M)['close']
    ma = sr.mean()
    up = ma + g.k * sr.std()
    down = ma - g.k * sr.std()
    p = get_current_data()[g.security].day_open
    cash = context.portfolio.available_cash
    if p < down and g.security not in context.portfolio.positions:
        order_value(g.security, cash)
    elif p > up and g.security in context.portfolio.positions:
        order_target(g.security, 0)

6. PEG策略

import jqdata
import pandas as pd

def initialize(context):
    set_benchmark('000300.XSHG')
    set_option('use_real_price', True)
    set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    g.security = get_index_stocks('000300.XSHG')
    g.N = 20
    g.q = query(valuation.code, valuation.pe_ratio, indicator.inc_net_profit_year_on_year).filter(valuation.code.in_(g.security))
    run_monthly(handle, 1)
    
def handle(context):
    df = get_fundamentals(g.q)
    df = df[(df['pe_ratio']>0) & (df['inc_net_profit_year_on_year']>0)]
    df['peg'] = df['pe_ratio'] / df['inc_net_profit_year_on_year'] / 100
    df = df.sort(columns='peg')
    tohold = df['code'][:g.N].values
    
    # tohold = # 
    
    for stock in context.portfolio.positions:
        if stock not in tohold:
            order_target_value(stock, 0)
    
    tobuy = [stock for stock in tohold if stock not in context.portfolio.positions]
    
    if len(tobuy)>0:
        cash = context.portfolio.available_cash
        cash_every_stock = cash / len(tobuy)
        
        for stock in tobuy:
            order_value(stock, cash_every_stock)

7. 羊驼交易法则

import jqdata
import pandas as pd

def initialize(context):
    set_benchmark('000002.XSHG')
    set_option('use_real_price', True)
    set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    
    g.security = get_index_stocks('000002.XSHG')
    g.period = 30
    g.N = 10
    g.change = 1
    g.init = True
    
    run_monthly(handle, 1)
        
    
def get_sorted_stocks(context, stocks):
    df = history(g.period, field='close', security_list=stocks).T
    print(df)
    df['ret'] = (df.iloc[:,len(df.columns)-1] - df.iloc[:,0]) / df.iloc[:,0]
    df = df.sort(columns='ret', ascending=False)
    return df.index.values
    
def handle(context):
    if g.init:
        stocks = get_sorted_stocks(context, g.security)[:g.N]
        cash = context.portfolio.available_cash * 0.9 / len(stocks)
        for stock in stocks:
            order_value(stock, cash)
        g.init = False
        return
    stocks = get_sorted_stocks(context, context.portfolio.positions.keys())
    
    for stock in stocks[-g.change:]:
        order_target(stock, 0)
    
    stocks = get_sorted_stocks(context, g.security)
    
    for stock in stocks:
        if len(context.portfolio.positions) >= g.N:
            break
        if stock not in context.portfolio.positions:
            order_value(stock, context.portfolio.available_cash * 0.9)
o
粉丝 0
博文 500
码字总数 0
作品 0
私信 提问
加载中
请先登录后再评论。
初始量化交易

一、介绍 1、量化交易比传统交易强多少? 它能让你的交易效率提高百倍,量化交易之于传统交易方法,如同大型收割机之于锄头镰刀,机枪大炮之于刀剑棍棒。 2、量化交易是做什么? 量化交易是指...

osc_x8jhvw7p
2019/02/22
0
0
2.初始量化交易

初始量化交易 摘要 为什么需要量化交易? 量化交易是做什么? 量化交易的价值何在? 做量化交易需要什么? 聚宽是什么? 零基础如何快速入门量化交易? 自测与自学 量化交易比传统交易强多少...

osc_13jzbgat
2019/01/23
2
0
【转载】 量化投资与策略

原文地址: https://blog.csdn.net/ebzxw/article/details/80714224 作者:周雄伟 来源:CSDN =========================================================== 版权声明:勤学 修德 明辨 笃实......

osc_bquv1gtr
2019/04/30
4
0
发明者量化新书上线《商品期货量化交易实战》

一、摘要 中国的量化交易市场规模已经超过300亿元,金融与科技的结合势在必行。发明者(FMZ.COM)携手多名量化领域专家,精心打造这门课程。跟随学习掌握量化交易知识,运用成熟的交易软件,挑...

发明者量化
07/10
11
0
WeQuant教程—1.2 从简单的量化系统开始

你大概知道量化的思想最早在古巴比伦人计算行星轨迹的时候就已经诞生(算术运算),后来借助古希腊的形式化逻辑的发展,人们日益能从量化的思想中提炼和描述自然规律并运用到生产之中。不过,...

osc_1i3i83o4
2019/09/20
2
0

没有更多内容

加载失败,请刷新页面

加载更多

未捕获ReferenceError:未定义$? - Uncaught ReferenceError: $ is not defined?

问题: How come this code throws an 此代码如何引发 Uncaught ReferenceError: $ is not defined 未捕获的ReferenceError:未定义$ when it was OK before? 以前什么时候可以? $(document......

javail
19分钟前
12
0
263. Ugly Number

题目: 263. Ugly Number 题目地址:https://leetcode.com/problems/ugly-number/ Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers......

JiaMing
42分钟前
46
0
HCIA_ARP01

ARP(地址解析协议) eNSP 常用路由器:AR2220 常用交换机:S5700、S3700 常用终端:PC、MCS(主播服务器) 设备连线:Copper(以太网用到的双绞线)、Serial(串口线,2SA接口)、Auto(自动连...

创业789
45分钟前
19
0
如何在Rails 4中使用问题 - How to use concerns in Rails 4

问题: The default Rails 4 project generator now creates the directory "concerns" under controllers and models. 默认的Rails 4项目生成器现在在控制器和模型下创建目录“Concer”。 ......

fyin1314
49分钟前
19
0
【LeetCode】 57 括号生成

题目: 解题思路: https://leetcode-cn.com/problems/generate-parentheses/solution/hui-su-suan-fa-by-liweiwei1419/ 代码: import java.util.ArrayList;import java.util.List;publ......

JaneRoad
昨天
8
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部