因子選股策略 sql
因子:選擇股票的某種標準ide
增加率、市值、市盈率、ROE(淨資產收益率)............函數
選股策略:lua
對於某個因子,選取表現最好(因子最大或最小)的N支股票持倉spa
每隔一段時間調倉一次,若是一段時間沒有漲能夠賣了換code
小市值策略:選取股票池中市值最小的N只股票持倉對象
例如:選擇20支市值最小的股票持有,一個月調一次倉:blog
from jqdata import * 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') # 選市值做爲因子,要從表valuation中market_cap字段獲取sqlachmy的query對象 g.q = query(valuation).filter(valuation.code.in_(g.security)) g.N = 20 #20支市值最小的股票 # 假設因子選股策略是每30天執行一次 #方式一: # g.days = -1 # def handle_data(context,data): # g.days += 1 # if g.days % 30 == 0: # pass #方式二: # 定時執行函數,每一個月第1個交易日執行handle函數 run_monthly(handle, 1) def handle(context): df = get_fundamentals(g.q)[['code','market_cap']] df = df.sort_values('market_cap').iloc[:g.N,:] #選出20支 print(df) 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)
多因子選股策略排序
如何同時綜合多個因子來選股?get
評分模型:
每一個股票針對每一個因子進行評分,將評分相加
選出總評分最大的N只股票持倉
如何計算股票在某個因子下的評分:歸一化(標準化),下面是兩種標準化的方式
好比選擇兩個因子:市值和ROE(淨資產收益率)做爲選股評價標準
from jqdata import * 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') # 選市值做爲因子,要從表valuation中market_cap字段獲取sqlachmy的query對象 g.q = query(valuation, indicator).filter(valuation.code.in_(g.security)) g.N = 20 #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'] # 對評分排序,選最大的20支股票 df = df.sort_values('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)