等权重因子组合

策略分享
标签: #<Tag:0x00007f608eb97968>

(Rossyfu) #1
克隆策略
In [ ]:
import pandas as pd
import numpy as np
import datetime
def gen_rank(dataframe, stocklist):
    target_df = pd.DataFrame()
    df = dataframe.copy()
    df = df.drop_duplicates('instrument' ,keep='last')
    df.date = df.date.apply(lambda x:x.strftime('%Y-%m'))
    for stock in stocklist:
        a = df[df['instrument'] == stock]
        a = a.drop_duplicates('date',keep='last')
        target_df = target_df.append(a)
    target_df.fs_roe_0 = target_df.fs_roe_0.apply(lambda x:1/x)
    target_df.return_30 = target_df.return_30.apply(lambda x:-x)
    a = target_df.drop(['instrument', 'date'], axis=1)
    b = target_df['instrument']
    a = a.rank(ascending=False)
    df = pd.concat([a, b], axis=1)
    df = df.fillna(0)
    return df
def get_stock(index, date):
    df = D.history_data(D.instruments(date, date),date,date,fields=[index,'market_cap'])
    sse300 = df[df[index]==1].sort_values('market_cap', ascending=False)
    target_sse = sse300['instrument']
    stocklist=target_sse.tolist()
    return stocklist
In [1]:
# 等权重
def initialize(context):
    context.today = None
    context.yestoday = None
    context.stocklist = None
    context.i = 1
    context.target_stock = None
def filter_stock(context, data):
    target_dict = dict()
    context.stocklist = get_stock('in_csi300', context.today)
    df = D.features(context.stocklist, start_date=context.yestoday, end_date=context.today, 
                    fields=['pe_ttm_0', 'fs_roe_0', 'fs_net_profit_yoy_0', 'return_30', 
                            'volatility_30_0', 'beta_csi300_30_0'], groupped_by_instrument=False, frequency='daily')
    target = gen_rank(df, context.stocklist)
    for stock in context.stocklist:
        target_stock_info = target[target['instrument'] == stock]
        try:
            score = (target_stock_info.fs_net_profit_yoy_0.values[0]/6 + target_stock_info.pe_ttm_0.values[0]/6 +  
            target_stock_info.fs_roe_0.values[0]/6 + target_stock_info.return_30.values[0]/6 + 
            target_stock_info.volatility_30_0.values[0]/6 + target_stock_info.beta_csi300_30_0.values[0]/6)
            target_dict[stock] = score
        except:
            continue
    target_dict = pd.Series(target_dict)
    target_dict = target_dict.sort_values(ascending=False)
    target_dict = target_dict.head(10)
    context.target_stock = target_dict
    print(target_dict)
def before_trading_start(context,data):
    today = pd.to_datetime(data.current_dt.strftime('%Y-%m-%d'))
    yestoday = today - datetime.timedelta(120)
    context.yestoday = yestoday
    context.today = today
    context.i = context.i + 1
    if context.i == 2:
        filter_stock(context, data)
    elif context.i%30 == 0:
        filter_stock(context, data)
def handle_data(context,data):
    if len(context.portfolio.positions) > 0:
        stock_hold_now = {e.symbol: p.amount * p.last_sale_price
                      for e, p in context.perf_tracker.position_tracker.positions.items()} 
        for equity in stock_hold_now:
            if equity not in context.target_stock.index.tolist():
                order_target_percent(context.symbol(equity), 0)
    for equity in context.target_stock.index.tolist():
        order_target_percent(context.symbol(equity), 0.1)
m9 = M.instruments.v2(
    start_date=T.live_run_param('trading_date', '2018-01-01'),
    end_date=T.live_run_param('trading_date', '2019-04-15'),
    market='CN_STOCK_A',
    instrument_list='',
    max_count=0
)

# 启动回测
m = M.trade.v4(
    instruments=m9.data,
    start_date='20180101',
    end_date='20190415',
    initialize=initialize,
    before_trading_start=before_trading_start,
    handle_data=handle_data,
    # 买入订单以开盘价成交
    order_price_field_buy='open',
    # 卖出订单以开盘价成交
    order_price_field_sell='open',
    capital_base=10000000,
    volume_limit=1,
    product_type='stock')
  • 收益率-2.93%
  • 年化收益率-2.38%
  • 基准收益率-1.37%
  • 阿尔法-0.03
  • 贝塔0.68
  • 夏普比率-0.22
  • 胜率0.65
  • 盈亏比0.48
  • 收益波动率17.5%
  • 信息比率-0.01
  • 最大回撤21.1%
bigcharts-data-start/{"__id":"bigchart-c52972262e18482e9fd8e28abf3c744f","__type":"tabs"}/bigcharts-data-end
In [ ]: