Пример #1
0
class AccountSnapshot:
    """
        账户信息快照,提供调用时刻的实时账户信息
        公有属性:
        ::
            name: str: 账户名称
            account_idx: int 账户索引
            type: int 账户类型
        ..
        公有方法:
        ::
            position:获取指定标的和方向的仓位信息
            positions: 获得所有仓位的双向仓位信息
            cash: 获得账户的资金信息
        ..
    """

    def __init__(self, account_idx, acc_type, name, env):
        self.name = name
        self.account_idx = account_idx
        self.account_type = acc_type
        self._env = env

    @property
    def positions(self) -> 'pd.DataFrame':
        """ 账户的双向仓位信息

        :return: pandas.df or OrderDict 双向持仓信息
        """
        return self._env.snap.positions(self.account_idx, True)

    @property
    def cash(self) -> 'pd.DataFrame':
        """ 账户的资金信息

        :return: pandas.df or OrderDict 账户资金信息
        """
        return self._env.snap.cash(self.account_idx, True)

    @apply_rule(verify_that('target_idx').is_instance_of(*INTEGERSTYPE, list, tuple))
    def position(self, target_idx=(), side=0, df=True) -> 'pd.DataFrame':
        """
        从positions中构建position
        :param target_idx: 标的索引
        :param side: 持仓方向
        :param df: 是否生成dataframe对象
        :return: df or OrderDict position对象
        """
        if isinstance(target_idx, INTEGERSTYPE):
            target_idx = [target_idx]
        if len(target_idx) < 1:
            target_idx = list(range(self._env.target_idx_count))
        else:
            _, target_idx = self._env.check_idx('position', None, target_idx, False)
        return self._env.snap.position(self.account_idx, target_idx, side, df)
Пример #2
0
    'get_support',
    'get_version',
    'clear_cache',
    'run_factor',
    'ContextFactor',
    'get_auto_value',
    *factors_api.__all__,
    *history_api.__all__,
    *reg_api.__all__,
    # *fundamental_api.__all__
]


@smm.force_mode(gv.RUNMODE_CONSOLE)
@smm.force_phase(gv.RUMMODE_PHASE_DEFAULT)
@apply_rule(verify_that('factor_name').is_instance_of(str),
            verify_that('targets').is_instance_of(str),
            verify_that('begin_date').is_valid_date(),
            verify_that('end_date').is_valid_date(),
            verify_that('fq').is_in((enums.FQ_BACKWARD,
                                     enums.FQ_FORWARD,
                                     enums.FQ_NA)))
def run_factor(factor_name='', file_path='.', targets='', begin_date='', end_date='', fq=enums.FQ_NA):
    config = {
        'entry': {
            'factor_name': factor_name,
            'strategy_path': file_path,
            'targets': targets,
            'begin_date': begin_date,
            'end_date': end_date,
            'fq': fq,
Пример #3
0
    'get_stop_info',
    'get_daily_orders',
    'get_last_execution',
    'get_unfinished_orders',
    'get_daily_executions',
    'get_order_info',
    'get_last_order',
]


#################################
# 交易函数: 普通下单指令
@smm.force_mode(gv.RUNMODE_BACKTEST, gv.RUNMODE_REALTRADE)
@smm.force_phase(gv.RUMMODE_PHASE_ONDATA)
@apply_rule(
    verify_that('account_idx').is_instance_of(*INTEGERSTYPE),
    verify_that('target_idx').is_instance_of(*INTEGERSTYPE),
    verify_that('volume').is_instance_of(*INTEGERSTYPE),
    verify_that('side').is_in((enums.ORDERSIDE_BUY, enums.ORDERSIDE_SELL)),
    verify_that('position_effect').is_in(
        (enums.ORDERPOSITIONEFFECT_OPEN, enums.ORDERPOSITIONEFFECT_CLOSE,
         enums.ORDERPOSITIONEFFECT_CLOSETODAY)),
    verify_that('order_type').is_in(
        (enums.ORDERTYPE_LIMIT, enums.ORDERTYPE_MARKET)),
    verify_that('price').is_greater_or_equal_than(0))
def order_volume(account_idx: 'int',
                 target_idx: 'int',
                 volume: 'int',
                 side: 'int',
                 position_effect: 'int',
                 order_type: 'int',
Пример #4
0
from atrader.tframe import sysclsbase as cnt
# noinspection PyUnresolvedReferences
from atrader.tframe.sysclsbase import smm
# noinspection PyUnresolvedReferences
from atrader.tframe.sysclsbase import gv
# noinspection PyUnresolvedReferences
from atrader.tframe.utils.argchecker import apply_rule, verify_that

__all__ = [
    'run_realtrade',
]


@smm.force_mode(gv.RUNMODE_CONSOLE)
@smm.force_phase(gv.RUMMODE_PHASE_DEFAULT)
@apply_rule(verify_that('strategy_name').is_instance_of(str),
            verify_that('account_list').is_instance_of(tuple, list),
            verify_that('target_list').is_instance_of(Iterable),
            verify_that('frequency').is_valid_frequency(),
            verify_that('fre_num').is_instance_of(int).is_greater_than(0),
            verify_that('begin_date').is_valid_date(),
            verify_that('fq').is_in((enums.FQ_BACKWARD,
                                     enums.FQ_FORWARD,
                                     enums.FQ_NA)))
def run_realtrade(strategy_name='',
                  file_path='.',
                  account_list=(),
                  target_list=(),
                  frequency='',
                  fre_num=1,
                  begin_date='',
Пример #5
0
from atrader.tframe.utils.argchecker import apply_rule, verify_that
from atrader.tframe.sysclsbase import gv
from atrader.tframe.sysclsbase import smm
from . import _factors
from . import convertor as factor_cvt

__all__ = [
    'get_factor_by_factor',
    'get_factor_by_day',
    'get_factor_by_code',
]


@smm.force_phase(gv.RUMMODE_PHASE_USERINIT, gv.RUMMODE_PHASE_DEFAULT)
@apply_rule(
    verify_that('factor').is_instance_of(str),
    verify_that('target_list').is_instance_of(str, tuple, list),
    verify_that('begin_date').is_valid_date(),
    verify_that('end_date').is_valid_date())
def get_factor_by_factor(factor: 'str', target_list: 'list', begin_date,
                         end_date):
    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 = 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)
    check_begin_end_date(new_begin_date, new_end_date)
    factor_dict = _factors.get_factor_by_factor(factor, targets,
Пример #6
0
from atrader.tframe.sysclsbase import smm
from . import convertor as reg_func_cvt
from . import _regfuncs

__all__ = [
    'get_current_bar', 'reg_kdata', 'reg_factor', 'reg_userdata',
    'reg_userindi', 'get_reg_kdata', 'get_reg_kdata_adj', 'get_reg_userdata',
    'get_reg_userindi', 'get_reg_factor', 'get_instruments'
]


#################################
# 刷新频率对应的kdata
@smm.force_phase(gv.RUMMODE_PHASE_ONDATA, gv.RUMMODE_PHASE_CALC_FACTOR)
@apply_rule(
    verify_that('target_indices').is_instance_of(*INTEGERSTYPE, list, tuple))
def get_current_bar(target_indices=()):
    if not isinstance(target_indices, np.ndarray):
        target_indices = np.array([target_indices]).ravel()
    if len(target_indices) < 1:
        target_indices = cnt.vr.g_ATraderCache['input_targets_idx_range']
    else:
        _, target_indices = cnt.env.check_idx('get_current_bar',
                                              None,
                                              target_indices,
                                              toarray=True)
    result = cnt.env.get_bar(target_indices)
    if result is None:
        return None

    return reg_func_cvt.convert_current_bar_to_df(result)
Пример #7
0
__all__ = [
    'get_code_list', 'get_code_list_set', 'get_main_contract', 'get_kdata',
    'get_kdata_n', 'get_trading_days', 'get_trading_time', 'get_stock_info',
    'get_future_info', 'get_history_instruments', 'get_strategy_id',
    'get_performance'
]

#################################

# 非策略结构使用函数


@smm.force_phase(gv.RUMMODE_PHASE_USERINIT, gv.RUMMODE_PHASE_DEFAULT,
                 gv.RUMMODE_PHASE_ONDATA)
@apply_rule(
    verify_that('block').is_instance_of(str),
    verify_that('date').is_valid_date(allow_empty_str=True))
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)


@smm.force_phase(gv.RUMMODE_PHASE_USERINIT, gv.RUMMODE_PHASE_DEFAULT)
@apply_rule(
    verify_that('block').is_instance_of(str),
Пример #8
0
    *history_api.__all__,
    *orders_api.__all__,
    *reg_api.__all__,
    *fundamental_api.__all__,
    'Context',
    'ContextFactor',
    'AccountSnapshot',
    'ExecutionSnapshot',
    'OrderSnapshot',
    'enums',
]


@smm.force_mode(gv.RUNMODE_CONSOLE)
@smm.force_phase(gv.RUMMODE_PHASE_DEFAULT)
@apply_rule(verify_that('strategy_name').is_instance_of(str),
            verify_that('target_list').is_instance_of(Iterable),
            verify_that('frequency').is_valid_frequency(),
            verify_that('fre_num').is_instance_of(int).is_greater_than(0),
            verify_that('begin_date').is_instance_of((str, datetime)).is_valid_date(),
            verify_that('end_date').is_instance_of((str, datetime)).is_valid_date(),
            verify_that('fq').is_in((enums.FQ_BACKWARD,
                                     enums.FQ_FORWARD,
                                     enums.FQ_NA)))
def run_backtest(strategy_name='',
                 file_path='.',
                 target_list=(),
                 frequency='day',
                 fre_num=1,
                 begin_date='',
                 end_date=0,