• 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)
  • 相关阅读:
    IDL读取TXT文件并写入二维数组中【转】
    远程连接ArcSDE
    Silverlight项目启动出现System.NullReferenceException未将对象引用到对象实例
    ENVI扩展工具:HDF5 Browser
    READF: End of file encountered. Unit: 100
    ENVI4.8下从两幅分类结果的栅格图中计算土地利用类型转换矩阵
    IDL中去掉数组中相同的元素方法
    利用IDL程序自动添加ENVI菜单【转】
    WIN7远程桌面连接知识
    对COM组件的调用返回了错误"HRESULT E_FAIL”的错误分析(c#与IDL混合编程)转
  • 原文地址:https://www.cnblogs.com/mengqingjian/p/8385918.html
Copyright © 2020-2023  润新知