Ejemplo n.º 1
0
    def _analyze(self):
        # Summary output
        ret = self.ret
        ret = ret[ret.index >= self.s_date]
        ret.index = pd.to_datetime(ret.index)
        ret['net_close'] = ret['close'] / ret['close'].tolist()[0]
        ret['net'] = ret['net'] / ret['net'].tolist()[0]
        net_lst = ret['net'].tolist()
        annR = annROR(net_lst, 1)
        sharp = yearsharpRatio(net_lst, 1)
        max_retrace = maxRetrace(net_lst, 1)
        self.annR = annR
        self.sharp = sharp
        self.max_retrace = max_retrace

        f = plt.figure(figsize=(15, 8))
        plt.rcParams['font.sans-serif'] = ['SimHei']

        # Plot return
        ax1 = f.add_subplot(111)
        ax1.plot(ret.net, 'blue', label='net_hmm')
        ax1.plot(ret.net_close, 'red', label='net_close')
        ax1.legend()
        ax1.set_title(
            '%s特征因子%s训练窗口%s测试窗口%s净值曲线' %
            (self.asset, self.cols_features, self.train_days, self.test_days))
        ax1.set_xlabel('Time')
        ax1.set_ylabel('Value')
Ejemplo n.º 2
0
 def _analyze(self):
     # Summary output
     ret = self.ret
     ret = ret[ret.index >= self.s_date]
     ret.index = pd.to_datetime(ret.index)
     ret['net_close'] = ret['close'] / ret['close'].tolist()[0]
     ret['net'] = ret['net'] / ret['net'].tolist()[0]
     self.ret = ret
     net_lst = ret['net'].tolist()
     annR = annROR(net_lst, 1)
     sharp = yearsharpRatio(net_lst, 1)
     max_retrace = maxRetrace(net_lst, 1)
     self.annR = annR
     self.sharp = sharp
     self.max_retrace = max_retrace
Ejemplo n.º 3
0
def get_account_state(fold_path, file_lst, calen):
    net_df = []
    for date in calen:
        for i in file_lst:
            if date in i and 'account' in i:
                df_ = pd.read_csv(fold_path + i, encoding='gbk') \
                       .loc[:, ['交易日', '总资产']]
                net_df.append(df_)
                break
    net_df = pd.concat(net_df).sort_values(['交易日'])
    print(net_df)
    state_sdate = calen[0]
    state_edate = calen[-1]
    asset_lst = net_df['总资产'].tolist()
    net_lst = [i / asset_lst[0] for i in asset_lst]
    annR = annROR(net_lst, 1)
    sharp = yearsharpRatio(net_lst, 1)
    max_retrace = maxRetrace(net_lst, 1)
    total_ret = net_lst[-1] - 1
    today_ret = net_lst[-1] / net_lst[-2] - 1
    print('sharp:%s' % sharp)
    print('annR:%s' % annR)
    print('max_retrace:%s' % max_retrace)
    state_value_lst = []
    state_value_lst.append([
        state_sdate, state_edate, asset_lst[0], asset_lst[-1], total_ret,
        today_ret, annR, sharp, max_retrace
    ])
    df_today = pd.DataFrame(state_value_lst,
                            columns=[
                                '开始日期', '结束日期', '初始资产', '当前资产', '总收益', '当日收益',
                                '年化收益', '夏普', '最大回撤'
                            ])
    df_today['初始资产'] = df_today['初始资产'].apply(lambda x: '%.0f' % x)
    df_today['当前资产'] = df_today['当前资产'].apply(lambda x: '%.0f' % x)
    df_today['夏普'] = df_today['夏普'].apply(lambda x: '%.2f' % x)
    df_today['年化收益'] = df_today['年化收益'].apply(lambda x: '%.2f%%' % (x * 100))
    df_today['总收益'] = df_today['总收益'].apply(lambda x: '%.2f%%' % (x * 100))
    df_today['当日收益'] = df_today['当日收益'].apply(lambda x: '%.2f%%' % (x * 100))
    df_today['最大回撤'] = df_today['最大回撤'].apply(lambda x: '%.2f%%' % (x * 100))
    return df_today
Ejemplo n.º 4
0
                    # profit_df = profit_df.fillna(0)
                    profit_df['chg'] = (
                        profit_df['profit'] - profit_df['close'].shift(1) *
                        profit_df['count'] * VolumeMultiple * fee
                    ) * level / profit_df['close'].shift(1) / (VolumeMultiple *
                                                               2)
                    profit_df = profit_df.fillna(0)
                    if method == 'sum':
                        profit_df['net'] = 1 + profit_df['chg'].cumsum()
                    else:
                        profit_df['net'] = (1 + profit_df['chg']).cumprod()
                    print(profit_df)

                    net_lst = profit_df.net.tolist()
                    if level == 1:
                        sharpe_ratio = yearsharpRatio(net_lst, 1)
                        if method == 'sum':
                            ann_return = annROR_signal(net_lst, 1)
                        else:
                            ann_return = annROR(net_lst, 1)
                        max_drawdown = maxRetrace(net_lst, 1)

                        ret['symbol'].append(state.iloc[0, 2].split('.')[0])
                        ret['tm'].append(state.iloc[1, 2].split()[0] +
                                         state.iloc[1, 2].split()[1])
                        ret['start_time'].append(s_date)
                        ret['end_time'].append(e_date)
                        ret['复盘模型'].append(state.iloc[2, 2])
                        ret['K线数量'].append(state.iloc[5, 1])
                        ret['盈利比'].append(state.iloc[10, 1])
                        ret['trading_times'].append(int(state.iloc[13, 1]))
Ejemplo n.º 5
0
def calculate_strategy_net(calen, next_tradeday, trade_fold_path,
                           trade_file_lst, strategy_fold_path, account_hold,
                           strategy_name_lst):
    trade_detail_all = []
    for date in calen:
        trade_detail = get_trade_detail(trade_fold_path, trade_file_lst, date)
        trade_detail_all.append(trade_detail)
    trade_detail_all = pd.concat(trade_detail_all)
    trade_state_all = get_trade_state(trade_detail_all)[[
        '策略名称', '证券代码', '证券名称', '操作', '成交均价', '成交数量', '成交金额', '手续费', '日期'
    ]]
    trade_state_all['bs'] = trade_state_all['操作'].apply(
        lambda x: trans_to_bs(x))
    trade_state_all['持仓'] = trade_state_all['成交数量'] * trade_state_all['bs']
    trade_state_all['成交金额'] = -trade_state_all['成交金额'] * trade_state_all['bs']
    win_r_lst = []

    trade_base_date_all = []

    for strategy_name in strategy_name_lst:
        temp = trade_state_all[trade_state_all['策略名称'] == strategy_name]
        print(temp)
        ret_lst = []
        if len(temp) == 0:
            win_r_lst.append([strategy_name, 1, 1])
            continue
        win_time = 0
        trad_time = 0
        cost_lst = []
        buy_code_lst = []
        for date, group in temp.groupby(['日期']):
            if len(buy_code_lst) > 0:
                for i in range(len(buy_code_lst)):
                    cost_i = cost_lst[i]
                    code = buy_code_lst[i]
                    sell_df = group[(group['bs'] == -1)
                                    & (group['证券代码'] == code)]
                    if len(sell_df) > 0:
                        sell_value = abs(sell_df['成交金额'].sum()) - abs(
                            sell_df['手续费'].sum())
                        ret = sell_value - cost_i
                        ret_lst.append(ret)
                        if ret > 0:
                            win_time += 1
                            trad_time += 1
                        else:
                            trad_time += 1
                        trade_base_date_all.append([strategy_name, date, ret])
            cost_lst = []
            buy_code_lst = []
            buy_df = group[group['bs'] == 1]
            if len(buy_df) == 0:
                buy_code_lst = []
            else:
                for buy_code, buy_group in buy_df.groupby(['证券代码']):
                    buy_code_lst.append(buy_code)
                    cost = abs(buy_group['成交金额'].sum()) + abs(
                        buy_group['手续费'].sum())
                    cost_lst.append(cost)

        win_r = 1
        odd = 1
        if trad_time > 0:
            win_r = win_time / trad_time
            ret_pos = [i for i in ret_lst if i > 0]
            ret_nev = [i for i in ret_lst if i < 0]
            if len(ret_nev) > 0:
                pos_ave = 0
                if len(ret_pos) > 0:
                    pos_ave = abs(np.mean(ret_pos))
                odd = pos_ave / abs(np.mean(ret_nev))
        win_r_lst.append([strategy_name, win_r, odd])
    trade_base_date_all_df = pd.DataFrame(trade_base_date_all,
                                          columns=['策略名称', '日期', '收益'])

    win_df = pd.DataFrame(win_r_lst, columns=['策略名称', '胜率', '盈亏比'])

    trade_state_today = trade_state_all[trade_state_all['日期'] == calen[-1]]
    hold_df_firstday = trade_state_all[(trade_state_all['日期'] == calen[0])
                                       & (trade_state_all['bs'] == 1)]
    hold_df_back = trade_state_all[(trade_state_all['日期'] > calen[0])]
    hold_df = pd.concat([hold_df_firstday, hold_df_back])[['策略名称', '证券代码', '证券名称', '持仓']]\
        .groupby(['策略名称', '证券代码', '证券名称']).sum().reset_index(drop=False)

    print('==============hold_df')
    print(hold_df)
    hold_today = hold_df[hold_df['持仓'] > 0]
    hold_today = trade_state_all[['策略名称', '证券代码', '证券名称', '日期', '成交均价', 'bs']]\
        .merge(hold_today, on=['策略名称', '证券代码', '证券名称'])
    hold_today = hold_today[(hold_today['日期'] == hold_today['日期'].max())
                            & (hold_today['bs'] == 1)]

    account_hold_ = account_hold[['证券代码', '持股', '最新价']]
    account_hold_lst = account_hold['证券代码'].tolist()
    account_hold_ = account_hold_.set_index(['证券代码'])
    print('==============hold_today')
    print(hold_today)
    print('==============account_hold_')
    print(account_hold_)
    hold_ret_lst = []
    for strategy_name, group in hold_today.groupby(['策略名称']):
        for id, row_ in group.iterrows():
            code = row_['证券代码']
            if code not in account_hold_lst:
                continue
            hold = row_['持仓']
            price = account_hold_.loc[code]['最新价']
            cost__ = row_['成交均价']
            hold = min(hold, account_hold_.loc[code]['持股'])
            hold_ret_lst.append(
                [strategy_name, code, row_['证券名称'], hold, cost__, price])
    hold_strategy_today = pd.DataFrame(
        hold_ret_lst, columns=['策略名称', '证券代码', '证券名称', '持仓', '成本价', '最新价'])
    print('==============hold_strategy_today')
    print(hold_strategy_today)

    strategy_account_all_today = []
    strategy_account_all_dict = {}

    for strategy_name in strategy_name_lst:
        name = strategy_dict[strategy_name]
        hold = hold_strategy_today[hold_strategy_today['策略名称'] ==
                                   strategy_name]
        hold.index = hold['证券代码']
        trade_state = trade_state_today[trade_state_today['策略名称'] ==
                                        strategy_name]
        last_strategy_account = pd.read_csv(
            strategy_fold_path + name + '_' + calen[-1] + '.csv',
            encoding='gbk')[['策略名称', 'date', 'cash', 'position_value']]
        last_strategy_account['date'] = last_strategy_account['date'].apply(
            lambda x: str(x))
        last_strategy_account = last_strategy_account.set_index(['date'])
        #print(type(last_strategy_account['date'].tolist()[0]))

        last_cash = last_strategy_account.loc[calen[-2]]['cash']
        today_cash = last_cash + trade_state['成交金额'].sum(
        ) - trade_state['手续费'].sum()
        today_hold = 0
        print(hold)
        if len(hold) > 0:
            for code in hold['证券代码'].tolist():
                price = hold.loc[code]['最新价']
                position = hold.loc[code]['持仓']
                today_hold = today_hold + price * position
        today_strategy_account = pd.DataFrame(
            [[strategy_name,
              str(calen[-1]), today_cash, today_hold]],
            columns=['策略名称', 'date', 'cash', 'position_value'])
        print(today_strategy_account)
        last_strategy_account = last_strategy_account.reset_index(drop=False)[[
            '策略名称', 'date', 'cash', 'position_value'
        ]]
        print(last_strategy_account)
        strategy_account_new = pd.concat(
            [last_strategy_account, today_strategy_account])
        print(strategy_account_new)
        next_tradeday = str(next_tradeday).replace('-', '')
        strategy_account_new.to_csv(strategy_fold_path + name + '_' +
                                    next_tradeday + '.csv',
                                    encoding='gbk')
        strategy_account_all_today.append(today_strategy_account)
        strategy_account_all_dict[strategy_name] = strategy_account_new
    strategy_account_all_today = pd.concat(
        strategy_account_all_today).sort_values(['策略名称', 'date'])
    strategy_state = []
    strategy_net_all_dict = {}
    profolio_asset_dict = {}
    for strategy_name in strategy_account_all_dict:
        df = strategy_account_all_dict[strategy_name]
        df['asset'] = df['cash'] + df['position_value']
        df['net'] = df['asset'] / df['asset'].tolist()[0]
        net_lst = df['net'].tolist()
        strategy_net_all_dict[strategy_name] = net_lst
        profolio_asset_dict[strategy_name] = df['asset'].tolist()
        today_profit = df['asset'].tolist()[-1] - df['asset'].tolist()[-2]
        today_ret = net_lst[-1] / net_lst[-2] - 1
        today_net = net_lst[-1]
        total_ret = today_net - 1
        annR = annROR(net_lst, 1)
        sharp = yearsharpRatio(net_lst, 1)
        max_retrace = maxRetrace(net_lst, 1)
        strategy_state.append([
            strategy_name, calen[0], calen[-1], today_net, total_ret, annR,
            sharp, max_retrace, today_profit, today_ret
        ])
    profolio_asset_dict['date'] = calen
    profolio_asset_df = pd.DataFrame(profolio_asset_dict).set_index(['date'])
    profolio_asset_df['组合资产'] = profolio_asset_df.sum(axis=1)
    profolio_asset_df['组合'] = profolio_asset_df['组合资产'] / profolio_asset_df[
        '组合资产'].tolist()[0]
    net_lst = profolio_asset_df['组合'].tolist()
    strategy_net_all_dict['组合'] = net_lst
    today_profit = profolio_asset_df['组合资产'].tolist(
    )[-1] - profolio_asset_df['组合资产'].tolist()[-2]
    today_ret = net_lst[-1] / net_lst[-2] - 1
    today_net = net_lst[-1]
    total_ret = today_net - 1
    annR = annROR(net_lst, 1)
    sharp = yearsharpRatio(net_lst, 1)
    max_retrace = maxRetrace(net_lst, 1)
    strategy_state.append([
        '组合', calen[0], calen[-1], today_net, total_ret, annR, sharp,
        max_retrace, today_profit, today_ret
    ])
    strategy_state_df = pd.DataFrame(strategy_state,
                                     columns=[
                                         '策略名称', '开始日期', '结束日期', '净值', '累计收益',
                                         '年化收益', '夏普', '最大回撤', '当日盈亏', '当日收益'
                                     ])
    strategy_state_df = strategy_state_df.merge(win_df, on=['策略名称'])

    asset_df = pd.DataFrame(strategy_net_all_dict)
    asset_df['date'] = calen
    asset_df['date'] = pd.to_datetime(asset_df['date'])
    asset_df['沪深300'] = index_hq_net_lst

    title_str = '策略净值曲线'
    asset_df.set_index(['date']).plot()
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.title(title_str)
    plt.savefig(fold_path + 'fig/' + 'net_' + calen[-1] + '.png')

    return strategy_account_all_today, hold_strategy_today, strategy_state_df, trade_base_date_all_df
Ejemplo n.º 6
0
def get_account_state(fold_path, file_lst, calen):
    net_df = []
    for date in calen:
        for i in file_lst:
            if date in i and 'account' in i:
                df_ = pd.read_csv(fold_path + i, encoding='gbk') \
                       .loc[:, ['交易日', '总资产']]
                net_df.append(df_)
                break
    net_df = pd.concat(net_df).sort_values(['交易日'])
    print(net_df)
    asset_lst = net_df['总资产'].tolist()
    net_lst = [i / asset_lst[0] for i in asset_lst]
    data_daily = copy.deepcopy(net_df).rename(columns={'交易日': '日期'})
    data_daily['账户净值'] = net_lst
    data_daily['time'] = data_daily['日期'].apply(
        lambda x: pd.to_datetime(str(x)))
    data_daily.index = data_daily['time']
    data_daily = data_daily.drop(['time'], axis=1)

    data_week = data_daily.resample('W').last()
    data_week['开始日期'] = data_daily['日期'].resample('W').first()
    data_week['结束日期'] = data_daily['日期'].resample('W').last()
    data_week['总资产'] = data_daily['总资产'].resample('W').last()
    data_week['账户净值'] = data_daily['账户净值'].resample('W').last()
    data_week['周度利润'] = data_week['总资产'] - data_week['总资产'].shift(1)
    data_week['周度收益'] = data_week['周度利润'] / data_week['总资产'].shift(1)
    data_week['周度利润'] = data_week['周度利润'].fillna(
        value=data_week['总资产'].tolist()[0] - account_init)
    data_week['周度收益'] = data_week['周度收益'].fillna(
        value=data_week['周度利润'].tolist()[0] / account_init)

    data_month = data_daily.resample('M').last()
    data_month['日期'] = data_daily['日期'].resample('M').last()
    data_month['总资产'] = data_daily['总资产'].resample('M').last()
    data_month['账户净值'] = data_daily['账户净值'].resample('M').last()
    data_month['月度利润'] = data_month['总资产'] - data_month['总资产'].shift(1)
    data_month['月度收益'] = data_month['月度利润'] / data_month['总资产'].shift(1)
    data_month['月度利润'] = data_month['月度利润'].fillna(
        value=data_month['总资产'].tolist()[0] - account_init)
    data_month['月度收益'] = data_month['月度收益'].fillna(
        value=data_month['总资产'].tolist()[0] / account_init - 1)
    account_month_week_state = pd.DataFrame(
        [[
            '月度统计',
            len(data_month), data_month['月度利润'].max(),
            data_month['月度利润'].min(), data_month['月度收益'].max(),
            data_month['月度收益'].min()
        ],
         [
             '周度统计',
             len(data_week), data_week['周度利润'].max(), data_week['周度利润'].min(),
             data_week['周度收益'].max(), data_week['周度收益'].min()
         ]],
        columns=['账户统计', '周期数', '最高利润', '最低利润', '最高收益率', '最低收益率'])
    account_month_week_state['最高利润'] = account_month_week_state['最高利润'].apply(
        lambda x: '%.0f' % x)
    account_month_week_state['最低利润'] = account_month_week_state['最低利润'].apply(
        lambda x: '%.0f' % x)
    account_month_week_state['最高收益率'] = account_month_week_state[
        '最高收益率'].apply(lambda x: '%.2f%%' % (x * 100))
    account_month_week_state['最低收益率'] = account_month_week_state[
        '最低收益率'].apply(lambda x: '%.2f%%' % (x * 100))

    data_week['开始日期'] = data_week['开始日期'].apply(lambda x: str(x)[:10])
    data_week['结束日期'] = data_week['结束日期'].apply(lambda x: str(x)[:10])
    data_week['总资产'] = data_week['总资产'].apply(lambda x: '%.0f' % x)
    data_week['账户净值'] = data_week['账户净值'].apply(lambda x: '%.4f' % x)
    data_week['周度利润'] = data_week['周度利润'].apply(lambda x: '%.0f' % x)
    data_week['周度收益'] = data_week['周度收益'].apply(lambda x: '%.2f%%' % (x * 100))
    data_week = data_week[['开始日期', '结束日期', '总资产', '账户净值', '周度利润', '周度收益']]

    data_month['总资产'] = data_month['总资产'].apply(lambda x: '%.0f' % x)
    data_month['账户净值'] = data_month['账户净值'].apply(lambda x: '%.4f' % x)
    data_month['月度利润'] = data_month['月度利润'].apply(lambda x: '%.0f' % x)
    data_month['月度收益'] = data_month['月度收益'].apply(lambda x: '%.2f%%' %
                                                  (x * 100))
    data_month['月份'] = data_month['日期'].apply(lambda x: str(x)[:6])
    data_month = data_month[['月份', '总资产', '账户净值', '月度利润', '月度收益']]

    state_sdate = calen[0]
    state_edate = calen[-1]

    annR = annROR(net_lst, 1)
    sharp = yearsharpRatio(net_lst, 1)
    max_retrace = maxRetrace(net_lst, 1)
    total_ret = net_lst[-1] - 1
    today_ret = net_lst[-1] / net_lst[-2] - 1
    print('sharp:%s' % sharp)
    print('annR:%s' % annR)
    print('max_retrace:%s' % max_retrace)
    state_value_lst = []
    state_value_lst.append([
        state_sdate, state_edate, asset_lst[0], asset_lst[-1], total_ret,
        today_ret, annR, sharp, max_retrace
    ])
    df_today = pd.DataFrame(state_value_lst,
                            columns=[
                                '开始日期', '结束日期', '初始资产', '当前资产', '总收益', '当日收益',
                                '年化收益', '夏普', '最大回撤'
                            ])
    df_today['初始资产'] = df_today['初始资产'].apply(lambda x: '%.0f' % x)
    df_today['当前资产'] = df_today['当前资产'].apply(lambda x: '%.0f' % x)
    df_today['夏普'] = df_today['夏普'].apply(lambda x: '%.2f' % x)
    df_today['年化收益'] = df_today['年化收益'].apply(lambda x: '%.2f%%' % (x * 100))
    df_today['总收益'] = df_today['总收益'].apply(lambda x: '%.2f%%' % (x * 100))
    df_today['当日收益'] = df_today['当日收益'].apply(lambda x: '%.2f%%' % (x * 100))
    df_today['最大回撤'] = df_today['最大回撤'].apply(lambda x: '%.2f%%' % (x * 100))
    return df_today, data_week, data_month, account_month_week_state
Ejemplo n.º 7
0
def get_strategy_account(foldPath, file_lst, end_date, strategy_name_lst,
                         calen, init_asset):
    file_name_today = get_file_name(file_lst, end_date, 'all_today')
    all_today = pd.read_excel(foldPath+file_name_today, encoding='gbk') \
                    .loc[:, ['策略名称', '总买额', '总卖额', '净买额', '手续费', '盈亏']].dropna().set_index(['策略名称'])
    account = []
    asset_df = pd.DataFrame(calen, columns=['date'])
    for strategy_name in strategy_name_lst:
        file_name_history = get_file_name(file_lst, end_date,
                                          strategy_name + '_history')
        df_today = pd.read_excel(foldPath+file_name_history, encoding='gbk') \
                            .loc[:, ['策略名称', '日期', '当日成交额', '当日盈亏', '累计盈亏']]
        china_name = df_today['策略名称'].tolist()[0]
        df_today['日期'] = df_today['日期'].apply(lambda x: str(x)[:8])
        df_today = df_today[df_today['日期'] > calen[0]]
        asset_lst = [init_asset]
        asset_upgrate = init_asset
        for i in range(1, len(calen) - 1):
            date = calen[i]
            df_ = df_today[df_today['日期'] == date]
            if len(df_) > 0:
                asset_upgrate = asset_upgrate + df_['当日盈亏'].tolist()[0]
            asset_lst.append(asset_upgrate)
        today_asset = all_today.loc[china_name]['盈亏'] + asset_upgrate
        asset_lst.append(today_asset)
        net_lst = [i / asset_lst[0] for i in asset_lst]
        annR = annROR(net_lst, 1)
        sharp = yearsharpRatio(net_lst, 1)
        max_retrace = maxRetrace(net_lst, 1)
        total_ret = net_lst[-1] - 1
        today_ret = net_lst[-1] / net_lst[-2] - 1
        account.append([
            china_name, init_asset, today_asset, total_ret, today_ret, annR,
            sharp, max_retrace
        ])
        asset_df[china_name] = net_lst
        asset_df[strategy_name] = asset_lst
    asset_df['date'] = pd.to_datetime(asset_df['date'])
    asset_df_value = asset_df.set_index(['date']).ix[:, strategy_name_lst]
    asset_df_value['组合'] = asset_df_value.sum(axis=1)

    asset_df_value[
        '组合净值'] = asset_df_value['组合'] / asset_df_value['组合'].tolist()[0]
    asset_df['组合'] = asset_df_value['组合净值'].tolist()

    title_str = '策略净值曲线'
    name_lst = copy.deepcopy(strategy_china_name_lst)
    name_lst.append('组合')
    asset_df.set_index(['date']).ix[:, name_lst].plot()
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.title(title_str)
    plt.savefig(fold_path + 'fig/' + 'net_' + end_date + '.png')

    net_lst = asset_df_value['组合净值'].tolist()
    today_asset = asset_df_value['组合'].tolist()[-1]
    total_ret = net_lst[-1] - 1
    today_ret = net_lst[-1] / net_lst[-2] - 1
    annR = annROR(net_lst, 1)
    sharp = yearsharpRatio(net_lst, 1)
    max_retrace = maxRetrace(net_lst, 1)
    account.append([
        '组合', asset_df_value['组合'].tolist()[0], today_asset, total_ret,
        today_ret, annR, sharp, max_retrace
    ])

    account_df = pd.DataFrame(
        account,
        columns=['策略名称', '初始资产', '当前资产', '总收益', '当日收益', '年化收益', '夏普', '最大回撤'])
    all_today['总买额'] = all_today['总买额'].apply(lambda x: '%.0f' % x)
    all_today['总卖额'] = all_today['总卖额'].apply(lambda x: '%.0f' % x)
    all_today['净买额'] = all_today['净买额'].apply(lambda x: '%.0f' % x)
    all_today['手续费'] = all_today['手续费'].apply(lambda x: '%.2f' % x)
    all_today['当日盈亏'] = all_today['盈亏'].apply(lambda x: '%.0f' % x)
    all_today['策略名称'] = all_today.index
    # account_df['开始日期'] = calen[0]
    # account_df['结束日期'] = calen[-1]
    account_df['当前资产'] = account_df['当前资产'].apply(lambda x: '%.0f' % x)
    account_df['夏普'] = account_df['夏普'].apply(lambda x: '%.2f' % x)
    account_df['年化收益'] = account_df['年化收益'].apply(lambda x: '%.2f%%' %
                                                  (x * 100))
    account_df['总收益'] = account_df['总收益'].apply(lambda x: '%.2f%%' % (x * 100))
    account_df['当日收益'] = account_df['当日收益'].apply(lambda x: '%.2f%%' %
                                                  (x * 100))
    account_df['最大回撤'] = account_df['最大回撤'].apply(lambda x: '%.2f%%' %
                                                  (x * 100))
    print(account_df)

    return all_today[['策略名称', '总买额', '总卖额', '净买额', '手续费',
                      '当日盈亏']], account_df[[
                          '策略名称', '初始资产', '当前资产', '总收益', '当日收益', '年化收益', '夏普',
                          '最大回撤'
                      ]]
Ejemplo n.º 8
0
                    except:
                        data_ori = stock_price(asset, 'daily', '2010-01-01', '2020-12-30')
                    try:
                        dataFactory = DataFactory(asset, factor_lst, future_period, s_data_date, e_data_date, data_ori)
                        dataset = dataFactory.get_dataset_close()
                        data_set = dataset[dataset.index >= train_s_date]
                        print(asset, '特征因子:', feature_lst, '训练窗口:', train_days, '测试窗口:', test_days)
                        strategy_obj = HmmStrategy(
                            asset=asset, s_date=s_date, max_states=max_states, leverage=1, fee=0.001, data_set=data_set,
                            cols_features=feature_lst, price_name='close', type='stock', train_days=train_days, test_days=test_days,
                            insample=False)
                        annR, sharp, max_retrace, ret_df = strategy_obj.run_outsample()
                        f = plt.figure(figsize=(15, 8))
                        plt.rcParams['font.sans-serif'] = ['SimHei']

                        sharp_close = yearsharpRatio(ret_df.net_close.tolist(), 1)

                        # Plot return
                        # ax1 = f.add_subplot(111)
                        # ax1.plot(ret_df.net, 'blue', label='net_hmm')
                        # ax1.plot(ret_df.net_close, 'red', label='net_close')
                        # ax1.legend()
                        # ax1.set_title(
                        #     '%s特征因子%s训练窗口%s测试窗口%s净值曲线' % (asset, feature_lst, train_days, test_days))
                        # ax1.set_xlabel('Time')
                        # ax1.set_ylabel('Value')
                        # plt.show()
                        print('夏普比率: ' + str(np.around(sharp, 2))+'行情夏普比率: ' + str(np.around(sharp_close, 2))+
                              '年化收益: ' + str(np.around(annR, 2))+'最大回撤: ' + str(np.around(max_retrace, 2)))
                        period_param_state.append([
                            asset, feature_lst, train_days, test_days, annR, sharp, max_retrace, sharp_close])
Ejemplo n.º 9
0
def calculate_strategy_net(calen, next_tradeday, trade_fold_path, trade_file_lst, strategy_fold_path, account_hold, strategy_name_lst):
    trade_detail_all = []
    for date in calen:
        trade_detail = get_trade_detail(trade_fold_path, trade_file_lst, date)
        trade_detail_all.append(trade_detail)
    trade_detail_all = pd.concat(trade_detail_all)
    trade_state_all = get_trade_state(trade_detail_all)[
            ['策略名称', '证券代码', '证券名称', '操作', '成交均价', '成交数量', '成交金额', '手续费', '日期']]
    trade_state_all['bs'] = trade_state_all['操作'].apply(lambda x: trans_to_bs(x))
    trade_state_all['持仓'] = trade_state_all['成交数量'] * trade_state_all['bs']
    trade_state_all['成交金额'] = -trade_state_all['成交金额'] * trade_state_all['bs']
    trade_state_today = trade_state_all[trade_state_all['日期'] == calen[-1]]
    hold_df_firstday = trade_state_all[(trade_state_all['日期'] == calen[0]) & (trade_state_all['bs'] == 1)]
    hold_df_back = trade_state_all[(trade_state_all['日期'] > calen[0])]
    hold_df = pd.concat([hold_df_firstday, hold_df_back])[['策略名称', '证券代码', '证券名称', '持仓']]\
        .groupby(['策略名称', '证券代码', '证券名称']).sum().reset_index(drop=False)
    print('==============hold_df')
    print(hold_df)
    hold_today = hold_df[hold_df['持仓'] > 0]
    account_hold_ = account_hold[['证券代码', '持股', '最新价']]
    account_hold_lst = account_hold['证券代码'].tolist()
    account_hold_ = account_hold_.set_index(['证券代码'])
    print('==============hold_today')
    print(hold_today)
    print('==============account_hold_')
    print(account_hold_)
    hold_ret_lst = []
    for strategy_name, group in hold_today.groupby(['策略名称']):
        for id, row_ in group.iterrows():
            code = row_['证券代码']
            if code not in account_hold_lst:
                continue
            hold = row_['持仓']
            price = account_hold_.loc[code]['最新价']
            hold = min(hold, account_hold_.loc[code]['持股'])
            hold_ret_lst.append([strategy_name, code, row_['证券名称'], hold, price])
    hold_strategy_today = pd.DataFrame(hold_ret_lst, columns=['策略名称', '证券代码', '证券名称', '持仓', '最新价'])
    print('==============hold_strategy_today')
    print(hold_strategy_today)

    strategy_account_all_today = []
    strategy_account_all_dict = {}

    for strategy_name in strategy_name_lst:
        name = strategy_dict[strategy_name]
        hold = hold_strategy_today[hold_strategy_today['策略名称'] == strategy_name]
        hold.index = hold['证券代码']
        trade_state = trade_state_today[trade_state_today['策略名称'] == strategy_name]
        last_strategy_account = pd.read_csv(
            strategy_fold_path + name + '_' + calen[-1] + '.csv', encoding='gbk')[
            ['策略名称', 'date', 'cash', 'position_value']]
        last_strategy_account['date'] = last_strategy_account['date'].apply(lambda x: str(x))
        last_strategy_account = last_strategy_account.set_index(['date'])
        #print(type(last_strategy_account['date'].tolist()[0]))

        last_cash = last_strategy_account.loc[calen[-2]]['cash']
        today_cash = last_cash + trade_state['成交金额'].sum() - trade_state['手续费'].sum()
        today_hold = 0
        print(hold)
        if len(hold) > 0:
            for code in hold['证券代码'].tolist():
                price = hold.loc[code]['最新价']
                position = hold.loc[code]['持仓']
                today_hold = today_hold + price * position
        today_strategy_account = pd.DataFrame([[strategy_name, str(calen[-1]), today_cash, today_hold]],
                                              columns=['策略名称', 'date', 'cash', 'position_value'])
        print(today_strategy_account)
        last_strategy_account = last_strategy_account.reset_index(drop=False)[['策略名称', 'date', 'cash', 'position_value']]
        print(last_strategy_account)
        strategy_account_new = pd.concat([last_strategy_account, today_strategy_account])
        print(strategy_account_new)
        next_tradeday = str(next_tradeday).replace('-', '')
        strategy_account_new.to_csv(strategy_fold_path + name + '_' + next_tradeday + '.csv', encoding='gbk')
        strategy_account_all_today.append(today_strategy_account)
        strategy_account_all_dict[strategy_name] = strategy_account_new
    strategy_account_all_today = pd.concat(strategy_account_all_today).sort_values(['策略名称', 'date'])
    strategy_state = []
    strategy_net_all_dict = {}
    profolio_asset_dict = {}
    for strategy_name in strategy_account_all_dict:
        df = strategy_account_all_dict[strategy_name]
        df['asset'] = df['cash'] + df['position_value']
        df['net'] = df['asset'] / df['asset'].tolist()[0]
        net_lst = df['net'].tolist()
        strategy_net_all_dict[strategy_name] = net_lst
        profolio_asset_dict[strategy_name] = df['asset'].tolist()
        today_profit = df['asset'].tolist()[-1] - df['asset'].tolist()[-2]
        today_ret = net_lst[-1] / net_lst[-2] - 1
        today_net = net_lst[-1]
        total_ret = today_net - 1
        annR = annROR(net_lst, 1)
        sharp = yearsharpRatio(net_lst, 1)
        max_retrace = maxRetrace(net_lst, 1)
        strategy_state.append([strategy_name, calen[0], calen[-1], today_net, total_ret, annR, sharp, max_retrace, today_profit, today_ret])
    profolio_asset_dict['date'] = calen
    profolio_asset_df = pd.DataFrame(profolio_asset_dict).set_index(['date'])
    profolio_asset_df['组合资产'] = profolio_asset_df.sum(axis=1)
    profolio_asset_df['组合'] = profolio_asset_df['组合资产'] / profolio_asset_df['组合资产'].tolist()[0]
    net_lst = profolio_asset_df['组合'].tolist()
    strategy_net_all_dict['组合'] = net_lst
    today_profit = profolio_asset_df['组合资产'].tolist()[-1] - profolio_asset_df['组合资产'].tolist()[-2]
    today_ret = net_lst[-1] / net_lst[-2] - 1
    today_net = net_lst[-1]
    total_ret = today_net - 1
    annR = annROR(net_lst, 1)
    sharp = yearsharpRatio(net_lst, 1)
    max_retrace = maxRetrace(net_lst, 1)
    strategy_state.append(
        ['组合', calen[0], calen[-1], today_net, total_ret, annR, sharp, max_retrace, today_profit, today_ret])
    strategy_state_df = pd.DataFrame(strategy_state, columns=['策略名称', '开始日期', '结束日期', '净值', '累计收益', '年化收益', '夏普', '最大回撤', '当日盈亏', '当日收益'])

    asset_df = pd.DataFrame(strategy_net_all_dict)
    asset_df['date'] = calen
    asset_df['date'] = pd.to_datetime(asset_df['date'])

    title_str = '策略净值曲线'

    asset_df.set_index(['date']).plot()
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.title(title_str)
    plt.savefig(fold_path + 'fig/' + 'net_' + calen[-1] + '.png')

    return strategy_account_all_today, hold_strategy_today, strategy_state_df
        net_df_all = net_df_all.fillna(0)
        net_df_all = net_df_all.set_index(['date_time'])
        net_df_all['chg'] = net_df_all.mean(axis=1)
        # print(net_df_all)
        net_df_all['net'] = (1 + net_df_all['chg']).cumprod()
        # print(net_df_all)
        # net_df_all['date_time'] = net_df_all.index
        close_df = pd.read_csv(resualt_path + 'net_param/%s_%s_%s.csv' %
                               (asset, 240, 60),
                               encoding='gbk')[['date_time', 'close']]
        net_df_all = net_df_all.merge(close_df, on=['date_time'])
        net_df_all['close_net'] = net_df_all['close'] / net_df_all[
            'close'].tolist()[0]
        net_lst = net_df_all['net'].tolist()
        annR = annROR(net_lst, 1)
        sharp = yearsharpRatio(net_lst, 1)
        max_retrace = maxRetrace(net_lst, 1)
        print('%s: 夏普:%s 年化收益:%s 最大回撤:%s' % (asset, sharp, annR, max_retrace))
        net_df_all['date_time'] = pd.to_datetime(net_df_all['date_time'])
        net_df_all = net_df_all.set_index(['date_time'])
        title_str = '%s 夏普 %.2f 年化收益 %.2f 最大回撤 %.2f' % (
            asset, sharp, 100 * annR, 100 * max_retrace)
        net_df_all.ix[:, ['net', 'close_net']].plot()
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.title(title_str)
        # plt.savefig(fold + 'fig/' + start_day + '_profolio_' + pos_method + '.png')
        plt.show()

    # train_days_lst = [i for i in range(480, 30, -40)]
    # test_days_lst = [i for i in range(20, 250, 20)]
    # period_param_state = []