def get_trading_time(target_list: 'list',
                     frequency: 'str',
                     fre_num: 'int',
                     begin_date,
                     end_date=''):
    if isinstance(target_list, str):
        target_list = [target_list]

    new_targets = todictmc(target_list)
    new_begin_date = convert_str_or_datetime_to_int_date(begin_date)
    if isinstance(end_date, str) and end_date.strip() == '':
        new_end_date = to_int_now_date('%Y%m%d')
    else:
        new_end_date = convert_str_or_datetime_to_int_date(end_date)

    if frequency in ('day', 'week', 'month') and fre_num != 1:
        raise ValueError(text.ERROR_INPUT_FREQUENCY_FREQNUM)

    if 0 < new_end_date < new_begin_date:
        raise ValueError(text.ERROR_INPUT_BEGIN_GT_ENDDATE)

    t, d = _history.get_trading_time(new_targets, frequency, new_begin_date,
                                     new_end_date, fre_num)

    if gv.freuency_to_int(frequency) >= gv.KFreq_Day:
        d = np.arange(0, t.size, 1, dtype=np.int)
    else:
        d -= 1

    return history_cvt.convert_trading_time_to_df(t, d)
def get_code_list(block: 'str', date=''):
    blocks = block.strip().split(',')
    if isinstance(date, str) and date.strip() == '':
        new_date = to_int_now_date('%Y%m%d')
    else:
        new_date = convert_str_or_datetime_to_int_date(date)
    ls = _history.get_code_list(blocks, new_date)

    return history_cvt.convert_code_list_to_df(ls)
Exemple #3
0
def _gen_run_factor_code_template(strategy_name, file_path=None):
    _code_template = """
    # -*- coding: utf-8 -*-
    from atrader.calcfactor import *
    import numpy as np
    import random


    def init(context: 'ContextFactor'):
        reg_kdata('day', 1)


    def calc_factor(context: 'ContextFactor'):
        return np.array([random.gauss(0, 1) for _ in range(len(context.target_list))]).T


    if __name__ == '__main__':
        run_factor(factor_name='{STRATEGY_NAME}', 
                   file_path='.', 
                   targets='SZ50', 
                   begin_date='{BEGIN_DATE}', 
                   end_date='{END_DATE}', 
                   fq=enums.FQ_FORWARD)
    """

    ls = _code_template.format(
        STRATEGY_NAME=strategy_name,
        BEGIN_DATE=int_date_predate(to_int_now_date(), 10, out_fmt='%Y-%m-%d'),
        END_DATE=to_int_now_date(fmt='%Y-%m-%d')).splitlines(
            keepends=False)[1:]
    context = '\n'.join([line[4:] for line in ls])

    if file_path is not None:
        with open(file_path, 'w', encoding='utf-8') as fp:
            fp.write(context)

    return context
def get_code_list_set(block, begin_date, end_date):
    blocks = block.strip().split(',')
    new_begin_date = convert_str_or_datetime_to_int_date(begin_date)

    if isinstance(end_date, str) and end_date.strip() == '':
        new_end_date = to_int_now_date('%Y%m%d')
    else:
        new_end_date = convert_str_or_datetime_to_int_date(end_date)

    if 0 < new_end_date < new_begin_date:
        raise ValueError(text.ERROR_INPUT_BEGIN_GT_ENDDATE)

    ls = _history.get_code_list_set(blocks, new_begin_date, new_end_date)

    return history_cvt.convert_code_list_set_to_df(ls)
def get_trading_days(market: 'str', begin_date, end_date=''):
    # TODO market: 支持数字货币
    new_begin_date = convert_str_or_datetime_to_int_date(begin_date)
    if isinstance(end_date, str) and end_date.strip() == '':
        new_end_date = to_int_now_date('%Y%m%d')
    else:
        new_end_date = convert_str_or_datetime_to_int_date(end_date)
    if new_begin_date > new_end_date:
        return None

    result = _history.get_trading_days_condition(market, new_begin_date,
                                                 new_end_date)
    if result.size < 1:
        return None

    return history_cvt.convert_trading_days_to_np_datetime(result)
def get_kdata_n(target_list: 'list',
                frequency: 'str',
                fre_num: 'int',
                n: 'int',
                end_date: 'str',
                fq=0,
                fill_up=False,
                df=False,
                sort_by_date=False):
    if isinstance(target_list, str):
        target_list = [target_list]

    if len(target_list) < 1:
        raise ValueError(
            text.ERROR_INPUT_EMPTY_PARAM.format(PARAMNAME='target_list'))

    if isinstance(end_date, str) and end_date.strip() == '':
        end_date = to_int_now_date('%Y%m%d')
    else:
        end_date = convert_str_or_datetime_to_int_date(end_date)

    new_targets = todictmc(target_list)
    fq = convert_internal_fq_to_atcore(fq)

    if frequency in ('day', 'week', 'month') and fre_num != 1:
        raise ValueError(text.ERROR_INPUT_FREQUENCY_FREQNUM)

    results = [None] * len(new_targets)
    for idx, target in enumerate(new_targets):
        kdata = _history.get_k_data_n([target], frequency, fre_num, n,
                                      end_date, fill_up, fq)
        results[idx] = history_cvt.convert_k_data_to_df(
            kdata[0], target_list[idx],
            cnt.env.get_target_type(todotmc(target)))

    if df:
        data_df = pd.concat(results, ignore_index=True)  # type: pd.DataFrame
        if sort_by_date:
            data_df = data_df.sort_values(
                'time', ascending=True,
                na_position='first')  # type: pd.DataFrame
            data_df.index = range(data_df.shape[0])
        return data_df
    else:
        return {target: results[idx] for idx, target in enumerate(target_list)}
Exemple #7
0
def get_factor_by_day(factor_list: 'list', target_list: 'list', date=''):
    if isinstance(factor_list, str):
        factor_list = [factor_list]

    if isinstance(target_list, str):
        target_list = [target_list]

    targets = check_target(todictmc(target_list))
    if date == '':
        new_date = to_int_now_date()
    else:
        new_date = convert_str_or_datetime_to_int_date(date)
    check_begin_end_date(new_date, new_date)
    factor_dict = _factors.get_factor_by_day(factor_list, targets, new_date)
    factor_df = factor_cvt.convert_factor_by_day_to_df(
        factor_dict) if factor_dict is not None else None

    return factor_df
def get_main_contract(main_code: 'str', begin_date, end_date):
    begin_date = convert_str_or_datetime_to_int_date(begin_date)
    if isinstance(end_date, str) and end_date.strip() == '':
        end_date = to_int_now_date('%Y%m%d')
    else:
        end_date = convert_str_or_datetime_to_int_date(end_date)
    new_targets = todictmc(main_code)

    if begin_date > end_date:
        raise ValueError(text.ERROR_INPUT_BEGIN_GT_ENDDATE)

    ls = _history.get_main_contract(new_targets['Market'], new_targets['Code'],
                                    begin_date, end_date)
    ls = [
        t for t in ls
        if str.lower(t['TargetIns']) != str.lower(new_targets['Code'])
    ]

    return history_cvt.convert_main_contract_to_df(ls, new_targets['Market'])
def get_history_instruments(target_list: 'list',
                            begin_date,
                            end_date='',
                            df=False,
                            sort_by_date=True):
    if isinstance(target_list, str):
        target_list = [target_list]

    targets = check_target(todictmc(target_list))
    new_begin_date = convert_str_or_datetime_to_int_date(begin_date)
    new_end_date = to_int_now_date(
    ) if end_date == '' else convert_str_or_datetime_to_int_date(end_date)
    if begin_date != 0 and new_begin_date > new_end_date:
        raise ValueError(text.ERROR_INPUT_BEGIN_GT_ENDDATE)

    data_matrix = _history.get_history_instruments(targets, new_begin_date,
                                                   new_end_date)

    return history_cvt.convert_history_instrument_matrix_to_output(
        target_list, data_matrix, df, sort_by_date)
Exemple #10
0
def _gen_run_back_test_code_template(strategy_name, file_path=None):
    _code_template = """
    # -*- coding: utf-8 -*-
    from atrader import *


    def double_mean(context: 'Context'):
        len1 = context.len1
        len2 = context.len2
        max_len = max(len1, len2)

        target_num = len(context.target_list)
        value = np.full((target_num, 1), np.nan)
        df_data = get_reg_kdata(target_num, target_indices=list(range(target_num)), 
                                length=max_len, fill_up=True, df=True)  # type: pd.DataFrame

        close_s = df_data['close']  # type: pd.Series
        for i in range(target_num):
            close_item = close_s.iloc[(i * max_len):(i + 1) * max_len]
            if close_item.shape[0] >= max(len1, len2):
                mean1 = np.nanmean(close_item.iloc[-len1:], dtype=np.float64)
                mean2 = np.nanmean(close_item.iloc[-len2:], dtype=np.float64)
                if mean1 - mean2 > 0.000001:
                    value[i] = 1
                if mean2 - mean1 > 0.000001:
                    value[i] = 2
        return value


    def init(context: 'Context'):
        context.len1 = 5
        context.len2 = 20
        reg_kdata('min', 1)
        reg_userindi(double_mean)


    def on_data(context: 'Context'):
        positions = context.account(0).positions
        volume_sub = positions['volume_long'] - positions['volume_short']  # type: pd.Series
        value = get_reg_userindi(context.reg_userindi[0], 1)  # type: pd.DataFrame
        for idx, _ in enumerate(context.target_list):
            if volume_sub[idx] <= 0 and value.loc[0, 'value'][idx] == 1:
                order_volume(0, idx, 100, enums.ORDERSIDE_BUY, enums.ORDERPOSITIONEFFECT_OPEN, enums.ORDERTYPE_MARKET, 0)
            elif volume_sub[idx] >= 0 and value.loc[0, 'value'][idx] == 2:
                order_volume(0, idx, 100, enums.ORDERSIDE_SELL, enums.ORDERPOSITIONEFFECT_CLOSE, enums.ORDERTYPE_MARKET, 0)


    if __name__ == '__main__':
        targets = ['szse.000001', 'sse.600000', 'dce.a0000', 'shfe.RB0000', 'cffex.if0000']
        run_backtest(strategy_name='{STRATEGY_NAME}',
                     file_path='.',
                     target_list=targets,
                     frequency='min',
                     fre_num=1,
                     begin_date='{BEGIN_DATE}',
                     end_date='{END_DATE}',
                     fq=enums.FQ_NA)
    """

    ls = _code_template.format(
        STRATEGY_NAME=strategy_name,
        BEGIN_DATE=int_date_predate(to_int_now_date(), 10, out_fmt='%Y-%m-%d'),
        END_DATE=to_int_now_date(fmt='%Y-%m-%d')).splitlines(
            keepends=False)[1:]

    context = '\n'.join([line[4:] for line in ls])

    if file_path is not None:
        with open(file_path, 'w', encoding='utf-8') as fp:
            fp.write(context)

    return context