量化策略

2019-05-20  本文已影响0人  Zzmi

第一个量化策略


# 初始化函数,设定基准等等
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)

双均线策略

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)

因子选股

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)

多因子选股

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)

均值回归

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)

布林带策略

#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)

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)

羊驼交易法测

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)
上一篇下一篇

猜你喜欢

热点阅读