Exemplo n.º 1
0
    def __init__(self, stk_code, retest_span, start_date, end_date=get_current_date_str(), reseau_quick=3, reseau_slow=6, rsv_span=4, debug=False):
        """

        :param stk_code:
        :param retest_span:
        :param start_date:
        :param end_date:
        :param reseau_quick:
        :param reseau_slow:
        :param rsv_span:
        :param debug:

        用法举例:
        r = RetestReseau(stk_code='601398', retest_span=5, start_date='2019-01-01', end_date='2019-03-10', debug=True)

        # 增加动态网格
        r.add_reseau()

        # 进行回测
        r.retest()

        # 保存结果(可选)
        r.save_csv()

        # 画图展示
        r.plot()
        """
        self.start_date = start_date
        self.end_date = end_date
        self.stk_code = stk_code
        self.debug = debug
        self.retest_span = retest_span      # 回测精度,单位为分钟
        self.days = minus_date_str(end_date, start_date)                    # 回测周期

        # 计算网格用的相关参数
        self.reseau_slow = reseau_slow
        self.reseau_quick = reseau_quick
        self.rsv_span = rsv_span

        # 计算起始时因为计算指标而无法回测的数据长度
        self.max_days = np.max([self.reseau_slow, self.rsv_span])
        self.i_start = int((self.max_days + 2) * 60 * 4 / self.retest_span)

        self.data_day = pd.DataFrame()
        self.data_minute = pd.DataFrame()

        if self.days < self.max_days:
            exit('设置天数小于最小天数!')

        if not self.prepare_data():
            exit('数据初始化失败!')

        self.opt_record = OptRecordRetest(
            money=50000,
            ratio=0.5,
            start_price=self.data_minute.head(1)['close'].values[0], money_each=5000)
Exemplo n.º 2
0
def fitness(w, df):

    stk_code = '300183'
    record_info = {
        'floor_last': 0,
        'money_remain': 20000,
        'amount_remain': 1500,
        'M_last': -1,  # 用以记录上次的均线值,在反向操作中(本次操作与上次不同的情况)使用上次均值!
        'BS_last': 'init',  # 上次是买还是卖    "buy"   "false"     "init"
        'price_last': df.head(1)['close'].values[0],  # 上次价格
        'BS_trend_now': 'init',
        'BS_real': 'NO_OPT',  # 本次实际操作
        'Price_now': 12,
        'last_opt_date': '2018-12-15',
        'time_span_from_last': 1,  # 当前距离上次操作的时间间隔
        'B_continue': 1,
        'S_continue': 1,
        'B_Reseau': -1,
        'S_Reseau': -1
    }

    origin_amount = record_info['money_remain'] / df.head(
        1)['close'].values[0] + record_info['amount_remain']

    # 遍历df
    for idx in df.index:

        # 取出当前date
        date_now = str(df.loc[idx, 'date'])

        df.loc[idx,
               'reseau'] = (df.loc[idx, 'upper'] - df.loc[idx, 'middle']) / 5
        df.loc[idx,
               'now-last'] = df.loc[idx, 'close'] - record_info['price_last']
        now_last = df.loc[idx, 'close'] - record_info['price_last']

        # 确定网格
        reseau = np.max([(df.loc[idx, 'upper'] - df.loc[idx, 'middle']),
                         0.5])  # 原始网格
        record_info['time_span_from_last'] = minus_date_str(
            date_now, record_info['last_opt_date'])

        price_now = df.loc[idx, 'close']  # 获取当前price
        ratio = record_info['money_remain'] / (
            record_info['money_remain'] +
            record_info['amount_remain'] * price_now)  # 计算ratio

        # 更新本次网格
        record_info['B_Reseau'], record_info['S_Reseau'] = calBSReseau(
            reseau_origin=reseau,
            m_remain_ratio=ratio,
            time_span=record_info['time_span_from_last'],
            continus_amount_b=record_info['B_continue'],
            continus_amount_s=record_info['S_continue'],
            m_w=w[0],
            t_w=w[1],
            c_w=w[2])

        # 向上运行,触发S操作
        if df.loc[idx, 'close'] - record_info['price_last'] > record_info[
                'S_Reseau']:
            record_info = BS_opt(stk_code=stk_code,
                                 price=df.loc[idx, 'close'],
                                 amount=300,
                                 opt='sale',
                                 record_info=record_info,
                                 debug=False,
                                 date=date_now)

        elif df.loc[idx, 'close'] - record_info[
                'price_last'] < -record_info['B_Reseau']:
            record_info = BS_opt(stk_code=stk_code,
                                 price=df.loc[idx, 'close'],
                                 amount=400,
                                 opt='buy',
                                 record_info=record_info,
                                 debug=False,
                                 date=date_now)
        else:
            record_info['BS_real'] = 'NO_OPT'

        # 将信息填写到df中去
        df.loc[idx, 'strategy_money'] = record_info['amount_remain'] * df.loc[
            idx, 'close'] + record_info['money_remain']
        df.loc[idx, 'origin_money'] = origin_amount * df.loc[idx, 'close']
        df.loc[idx, 'BS'] = record_info['BS_real']
        df.loc[idx, 'amount_remain'] = record_info['amount_remain']
        df.loc[idx, 'money_remain'] = record_info['money_remain']
        df.loc[idx, 'last_price'] = record_info['price_last']

        # 将实时的网格信息添加到df中
        df.loc[idx, 'B_Reseau'] = record_info['B_Reseau']
        df.loc[idx, 'S_Reseau'] = record_info['S_Reseau']

        df.loc[idx, 'total_money'] = record_info['money_remain'] + record_info[
            'amount_remain'] * df.loc[idx, 'close']

    return df.tail(1)['total_money'].values[0]
Exemplo n.º 3
0
    1)['close'].values[0] + record_info['amount_remain']

# 遍历df
for idx in df.index:

    # 取出当前date
    date_now = str(df.loc[idx, 'date'])

    df.loc[idx, 'reseau'] = (df.loc[idx, 'upper'] - df.loc[idx, 'middle']) / 5
    df.loc[idx, 'now-last'] = df.loc[idx, 'close'] - record_info['price_last']
    now_last = df.loc[idx, 'close'] - record_info['price_last']

    # 确定网格
    reseau = np.max([(df.loc[idx, 'upper'] - df.loc[idx, 'middle']),
                     0.5])  # 原始网格
    record_info['time_span_from_last'] = minus_date_str(
        date_now, record_info['last_opt_date'])  # 更新本次操作与上次操作的时间间隔
    price_now = df.loc[idx, 'close']  # 获取当前price
    ratio = record_info['money_remain'] / (
        record_info['money_remain'] + record_info['amount_remain'] * price_now
    )  # 计算ratio

    # 更新本次网格
    record_info['B_Reseau'], record_info['S_Reseau'] = calBSReseau(
        reseau_origin=reseau,
        m_remain_ratio=ratio,
        time_span=record_info['time_span_from_last'],
        continus_amount_b=record_info['B_continue'],
        continus_amount_s=record_info['S_continue'],
        m_w=1,
        t_w=1,
        c_w=1)
Exemplo n.º 4
0
def get_sample_flow(con_param, code_param, sample_amount, sample_length):
    '''
    获取流入量,按月为单位
    当月的日平均水流量,绝对输入量,取日均量的原因是为了防止因为数据缺失而导致月输入总量的计算错误!
    。。。先写一个月绝对总输入量的

    @:parameter code_param:     代码
    @:parameter sample_amount:  样本个数,int类型,
                                比如,4,则从当前时刻往前推4个月作为时期跨度,即返回4个数据:每个月的水量净流入
    @:parameter sample_length   样本长度,int类型,比如说30是一个月,7是一个周

    举例:sample_amount=4,sample_length=30,则以30天为单位,返回最近的四个单位的数据

    '''

    # 如果表不存在,返回空
    if not is_table_exist(conn=con_param,
                          table_name="tick" + code_param,
                          database_name=stk_tick_data_db_name):
        print("stk" + code_param + ":数据不存在!")
        return []

    # 获取该代码的dataframe
    df = get_total_table_data(conn=con_param, table_name="tick" +
                              code_param).drop_duplicates()

    # 创建用于存储结果的list
    result = list()

    # dateSeries 降序排列的date_series
    date_series = sorted(df.date, reverse=True)

    # 获取df中的最晚时间
    latest_date_in_table = date_series[0]

    # 获取df中的最早时间
    early_date_in_table = date_series[len(date_series) - 1]

    for i in range(0, sample_amount):

        # 获取本次数据的时间跨度(起止时间都取开区间)
        start_date_temp = add_date_str(latest_date_in_table,
                                       -(i + 1) * sample_length + 1)
        end_date_temp = add_date_str(latest_date_in_table, -i * sample_length)

        # 如果最早时间早于表中的最早时间,则直接返回
        if minus_date_str(end_date_temp, early_date_in_table) < 0:
            print("采样的最早时间超过了表中的最早时间,for循环break!")

        # 获取本时间段的数据
        df_span = df[(df.date > start_date_temp)
                     & (df.date <= end_date_temp)].drop_duplicates()
        if (df_span.empty):
            continue

        # 求本段时间的日均水流量
        diff_series = df_span.total_in - df_span.total_out
        in_out_avge = diff_series.sum() / len(diff_series)

        # 将结果保存到list中
        result.append(in_out_avge)

    # 按时间顺序排序
    result.reverse()

    # 返回结果
    return result
Exemplo n.º 5
0
# encoding=utf-8
"""
数据库名字:stk_JQ_money_flow
mysql 链接句柄 db_JQ_money_flow
"""
from Config.GlobalSetting import localDBInfo
from SDK.DBOpt import genDbConn, is_table_exist
import pandas as pd
from SDK.MyTimeOPT import minus_date_str, get_current_date_str, add_date_str
""" -------------------------- 定义全局参数 -------------------------------- """
start_date = '2009-01-01'
end_date = get_current_date_str()
(conn_JQ_MF, engine_JQ_MF) = genDbConn(localDBInfo, 'stk_JQ_money_flow')
""" -------------------------- 获取 all stks -------------------------------- """
all_stk_list = get_all_securities(types=['stock'], date=None)
for stk in all_stk_list.index:
    table_name = 's' + stk.split('.')[0]
    if is_table_exist(conn=conn_JQ_MF,
                      database_name='stk_JQ_money_flow',
                      table_name=table_name):
        # 读取原表,并获取最后的日期
        df = pd.read_sql('select * from ' + table_name, con=conn_JQ_MF)
        date_last = str(
            df.sort_values(by='date',
                           ascending=True).tail(1)['date'].values[0])[:10]
        # 判断是否是最新日期
        if minus_date_str(date_last, get_current_date_str()) >= 0:
            print(stk + ' 表中的日期已经是最新的了!不需要更新!')
            continue
        df = get_money_flow(stk,