python之在线平台与量化投资

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)
原文地址:https://www.cnblogs.com/mengqingjian/p/8385918.html