量化交易研究———高级篇(3)总体代码(不完整)

from datetime import timedelta, date
import pandas as pd
def initialize(account):
    # set_commission(PerTrade(cost=0.0003, min_trade_cost=5))
    # set_slippage(PriceRelatedSlippage())
    account.selected = 400
    account.n = 15 # 持股数
    #调仓频率
    account.trade_date = range(1,13,1)
    ## 按月调用程序
    run_monthly(trade,date_rule=-1)
def trade(account, data):
    date = get_datetime()
    months = get_datetime().month
    if months in account.trade_date:   
stock_list = tradestocklist(account,data)

def handle_data(account,data):
    ## 个股止损
    last_date = get_last_datetime().strftime('%Y%m%d')
    if len(account.positions) > 0:
        # 止损:个股跌幅超过5%,卖出
        securities = list(account.positions)
        for stock in securities:
            price = data.attribute_history(stock, ['close'], 1, '1d', skip_paused=False, fq='pre')
            if account.positions[stock].cost_basis /price['close'][0]-1 < -0.05:
                order_target(stock, 0)
                log.info('%s 止损:%s' %(last_date,stock))
                
        #止损:5天内MSCI突然下跌15%,卖出
        price_bench = data.attribute_history('885745.TI',['close'],5,'1d',skip_paused = False, fq = None)
        if price_bench['close'][-5]/price_bench['close'][-1]-1 > 0.15:
            if len(list(account.positions))>0:
                for stock in list(account.positions):
                    order_target(stock,0)
                    log.info('%s 大盘突然下跌' %(last_date))








    
def tradestocklist(account,data):
last_date = get_last_datetime().strftime('%Y%m%d')
stock=get_index_stocks('885745.TI',last_date)
    price=get_price(stock, None, last_date, '1d', ['is_paused', 'is_st'], False, None, 1, is_panel=1)
    stopstk=price['is_paused'].iloc[-1]
    ststk=price['is_st'].iloc[-1]
    startstk=(stopstk[stopstk==0].index)
    okstk=(ststk[ststk==0].index)
    tradestk=list(set(startstk)&set(okstk)&set(stock))
    q = query(
    valuation.symbol,#代码编号
    valuation.pe_ttm,#PE
    profit.roe_ths,#净资产收益率ROE(平均, 同花顺计算)
    growth.opt_profit_growth_ratio,#营业利润(同比增长率)
    growth.basic_eps_year_growth_ratio,#基本每股收益(同比增长率)
    #factor.macd#macd
    ).filter(
    valuation.symbol.in_(tradestk),
    valuation.pe_ttm < 40,
    valuation.pe_ttm > 0,
    profit.roe_ths > 0.3
    ).order_by(
    profit.roe_ths.desc()
    )
    data = get_fundamentals(q,date = last_date)
    data['PEG']=data['valuation_pe_ttm']/data['growth_basic_eps_year_growth_ratio']
    #计算PEG
    df0 = data[data['PEG'] < 1.5 ]
    df1 = df0[df0['PEG'] > 0 ]
    df1 = df1.iloc[:60]
    stock1 = list(df1['valuation_symbol'])
    return stock1

你可能感兴趣的:(股票,文本分析下的量化金融)