Ejemplo n.º 1
0
    def prepare_data(self):
        """
        准备数据
        :return:
        """
        if self.debug:
            print('开始准备数据...')

        jq_login()

        # 准备数据
        df_m = get_k_data_JQ(self.stk_code,
                             start_date=self.start_date,
                             end_date=self.end_date,
                             freq=str(self.retest_span) + 'm')
        df_m['date'] = df_m.apply(lambda x: str(x['datetime'])[:10], axis=1)
        df_day = get_k_data_JQ(
            self.stk_code, start_date=self.start_date,
            end_date=self.end_date).sort_index(ascending=True)

        if len(df_day) < self.max_days:
            if self.debug:
                print('max_days:%d day_data_length:%d minute_data_length:%d' %
                      (self.max_days, len(df_day), len(df_m)))
            return False

        # 向day data 中 增加必要index
        self.data_day = add_stk_index_to_df(df_day).reset_index().reset_index()

        # 增加必要index
        self.data_minute = add_stk_index_to_df(
            df_m).reset_index().reset_index()

        logout()
        return True
Ejemplo n.º 2
0
def getSigleStkReseau(stk_code):
    """
    计算单只stk的当前网格
    :return:
    """
    # df = my_pro_bar(stk_code=stk_code, start=add_date_str(get_current_date_str(), -10))
    df = get_k_data_JQ(stk_code=stk_code,
                       start_date=add_date_str(get_current_date_str(), -10),
                       end_date=get_current_date_str())

    if len(df) < 7:
        # df = my_pro_bar(stk_code=stk_code, start=add_date_str(get_current_date_str(), -30))
        df = get_k_data_JQ(stk_code=stk_code,
                           start_date=add_date_str(get_current_date_str(),
                                                   -30),
                           end_date=get_current_date_str())

    df = df.reset_index()

    df = df_win_std(df, 3)
    df = df_win_std(df, 6)

    df['std_m'] = df.apply(lambda x: np.mean([x['std_3'], x['std_6']]), axis=1)

    return df.tail(1)['std_m'].values[0]
Ejemplo n.º 3
0
    def gen_stk_sea_select_pic_sub(stk_code):

        try:
            jq_login()

            # 保存路径
            save_dir = sea_select_pic_dir + get_current_date_str() + '/'

            if not os.path.exists(save_dir):
                os.makedirs(save_dir)

            # 准备 小时 和 日线 数据
            df_hour = gen_hour_macd_values(stk_code)
            df_day = get_k_data_JQ(stk_code, 800)

            # 定义图片名称
            file_name = stk_code + '.png'

            # 生成小时图片
            gen_hour_macd_pic_local(df_hour, stk_code, 'jq', '',
                                    save_dir + 'h_' + file_name)
            gen_hour_index_pic_local(df_hour[0], stk_code,
                                     save_dir + 'h_idx_' + file_name)
            gen_day_pic_local(df_day, stk_code, save_dir + 'd_' + file_name)
            gen_w_m_macd_pic_local(df_day, stk_code,
                                   save_dir + 'wm_' + file_name)
            gen_idx_pic_local(df_day, stk_code,
                              save_dir + 'd_idx_' + file_name)

        except Exception as e:
            print('生成股票走势图失败!原因:\n' + str(e))
        finally:
            logout()
Ejemplo n.º 4
0
def day_analysis_dict_pipe():
    """
    day数据分析, 放在数据处理线程中
    :return:
    """
    # 判断结果list
    result_analysis_list = []

    jq_login()
    for tab in dict_stk_list.keys():
        stk_list = dict_stk_list[tab]

        for stk_info in stk_list:
            stk = stk_info[1]
            df = get_k_data_JQ(stk, 400)

            # 其他指标
            r_tuple_index_pic = gen_idx_pic_wx(df, stk_code=stk)
            result_analysis_list = result_analysis_list + r_tuple_index_pic[1]

            # 日线分析结果汇总
            r_tuple_day_pic = gen_day_pic_wx(df, stk_code=stk)
            result_analysis_list = result_analysis_list + r_tuple_day_pic[1]

    jq.logout()

    debug_print_txt('hour_analysis', 'total_stk',
                    str(result_analysis_list) + '\n')

    return result_analysis_list
Ejemplo n.º 5
0
def get_pic_dict():
    """
    获取图片字典
    :return:
    """
    dict_stk_list = {
        'index': ['sh', 'sz', 'cyb'],
        'buy': readConfig()['buy_stk'],
        'concerned': readConfig()['concerned_stk']
    }

    pic_dict = {}
    for tab in dict_stk_list.keys():
        stk_list = dict_stk_list[tab]
        stk_list_pic_dict = {}

        for stk in stk_list:
            df = get_k_data_JQ(stk, 400)
            stk_pic_dict = {
                'hour': gen_Hour_MACD_Pic(stk),
                'day': gen_Day_Pic(df, stk_code=stk)[0],
                'wm': gen_W_M_MACD_Pic(stk),
                'index': gen_Idx_Pic(df, stk_code='')[0]
            }

            stk_list_pic_dict[stk] = stk_pic_dict

        # 将page中的stk pic存入字典
        pic_dict[tab] = stk_list_pic_dict

    return pic_dict
Ejemplo n.º 6
0
def check_single_stk_middle_level(stk_code, dict):
    """
    输入代码,返回level
    :param stk_code:
    :return:
    """
    # 获取当前价格
    current_price = get_RT_price(stk_code, source='jq')

    if stk_code in dict.keys():
        l = relativeRank(dict[stk_code], current_price)
    else:
        df_hour = get_k_data_JQ(stk_code,
                                count=None,
                                start_date=add_date_str(
                                    get_current_date_str(), -60),
                                freq='60m')
        dict[stk_code] = list(df_hour['close'].values)

        l = relativeRank(list(df_hour['close'].values), current_price)

        with open(data_dir + 'middlePeriodHourData.json', 'w') as f:
            json.dump(dict, f)

    return l
Ejemplo n.º 7
0
def calRSVRank(stk_code, Mdays, history_length=400):

    df = get_k_data_JQ(stk_code,
                       count=history_length,
                       end_date=get_current_date_str())

    # 移动平均线+RSV(未成熟随机值)
    M = Mdays

    df['low_M' + str(M)] = df['low'].rolling(window=M).mean()
    df['high_M' + str(M)] = df['high'].rolling(window=M).mean()
    df['close_M' + str(M)] = df['close'].rolling(window=M).mean()

    for idx in df.index:
        if (df.loc[idx, 'high_M' + str(M)] - df.loc[idx, 'low_M' + str(M)]
                == 0) | (df.loc[idx, 'close_M' + str(M)] -
                         df.loc[idx, 'low_M' + str(M)] == 0):
            df.loc[idx, 'RSV'] = 0.5

        else:
            df.loc[idx, 'RSV'] = (df.loc[idx, 'close_M' + str(M)] -
                                  df.loc[idx, 'low_M' + str(M)]) / (
                                      df.loc[idx, 'high_M' + str(M)] -
                                      df.loc[idx, 'low_M' + str(M)])

    # df['RSV'] = df.apply(lambda x: (x['close_M'+str(M)] - x['low_M'+str(M)])/(x['high_M'+str(M)] - x['low_M'+str(M)]), axis=1)

    return df.tail(1)['RSV'].values[0]
Ejemplo n.º 8
0
def check_single_stk_hour_idx_wx(stk_code, source='jq', debug=False):
    """
	打印常用指标
	"""
    stk_df = get_k_data_JQ(stk_code,
                           count=120,
                           end_date=add_date_str(get_current_date_str(), 1),
                           freq='30m')

    # 按升序排序
    stk_df = stk_df.sort_values(by='datetime', ascending=True)
    """
	增加指标

	'RSI5', 'RSI12', 'RSI30'
	'SAR'
	'slowk', 'slowd'
	'upper', 'middle', 'lower'
	'MOM'
	"""
    # 删除volume为空值的情况!
    stk_df = stk_df.loc[
        stk_df.apply(lambda x: not (int(x['volume']) == 0), axis=1), :]

    # 计算index
    stk_df = add_stk_index_to_df(stk_df).tail(60)

    result_analysis = []

    # 检查SAR
    sar_tail_origin = stk_df.tail(2)
    sar_tail = sar_tail_origin.copy()
    sar_tail['compare'] = sar_tail_origin.apply(
        lambda x: x['SAR'] - x['close'], axis=1)

    if sar_tail.head(1)['compare'].values[0] * sar_tail.tail(
            1)['compare'].values[0] < 0:
        if sar_tail.tail(1)['SAR'].values[0] < sar_tail.tail(
                1)['close'].values[0]:
            title_tmp = stk_code + ' ' + code2name(
                stk_code) + ' 注意 SAR 指标翻转,后续数小时可能上涨!'
            result_analysis.append(title_tmp)
            GenPic.set_background_color(bc='b_r')
        else:
            title_tmp = stk_code + ' ' + code2name(
                stk_code) + ' 注意 SAR 指标翻转,后续数小时可能下跌!'
            result_analysis.append(title_tmp)

    # 打印过程日志
    if debug:
        txt_name = 'hour_index'

        # 打印原始数据
        debug_print_txt(txt_name, stk_code, stk_df.to_string() + '\n\n')

        # 打印结果
        debug_print_txt(txt_name, stk_code,
                        '结果:\n' + str(result_analysis) + '\n\n')

    return result_analysis
Ejemplo n.º 9
0
 def cal_rt_bias(self):
     """
     实时计算bias
     :return:
     """
     df = get_k_data_JQ(stk=self.stk_code, freq=self.freq, count=self.span_s + 2)
     df_bias = self.add_bias(df)
     
     return df_bias.tail(1)['bias'].values[0]
Ejemplo n.º 10
0
def checkWeekStrayForAll():

    towho = '影子2'
    send_qq(towho, '以下是今晚海选结果:')

    df_total = ts.get_stock_basics()

    # 过滤掉年龄小于四岁的
    df_age_filter = df_total[df_total.apply(lambda x: int(
        str(x['timeToMarket'])[:4]) <= int(get_current_date_str()[:4]) - 4,
                                            axis=1)]

    # 根据week反转情况进行过滤,保留有反转的单位
    df_age_filter_stray = list(df_age_filter.reset_index().apply(
        lambda x: (x['code'], week_MACD_stray_judge(x['code'], towho)),
        axis=1))

    # 过滤掉非反转的情况
    df_age_f2 = list(filter(lambda x: x[1][0], df_age_filter_stray))

    # 增加stk的水平信息
    df_level = [(x[0], x[1][1], cal_stk_p_level(x[1][1]['close'].values))
                for x in df_age_f2]

    # 按总体水平排序,筛选优异者
    df_level.sort(key=lambda x: x[2]['total_last'])
    df_level = df_level[:math.floor(len(df_level) / 3 * 2)]

    # 按照近30的波动率进行排序,筛选优异者
    df_level.sort(key=lambda x: x[2]['std'], reverse=True)
    df_level = df_level[:math.floor(len(df_level) / 3 * 2)]

    # 按照近30的水平排序,留下最后8只
    df_level.sort(key=lambda x: x[2]['t30_last'], reverse=False)
    df_level = df_level[:np.min([math.floor(len(df_level) / 3 * 2), 15])]

    # 打印信息
    stk_list = [k[0] for k in df_level]

    for stk in stk_list:

        # 打印周与月信息
        send_W_M_MACD(stk_code=stk, towho=towho)

        # 打印日线信息
        df = get_k_data_JQ(stk, count=400, end_date=get_current_date_str())
        fig, _, _ = genStkPicForQQ(df)

        plt.title(str(stk))
        send_pic_qq(towho, fig)
        plt.close()

        fig, _, _ = genStkIdxPicForQQ(df)

        plt.title(str(stk))
        send_pic_qq(towho, fig)
        plt.close()
Ejemplo n.º 11
0
    def get_single_stk_reseau(self, stk_code):
        """
        计算单只stk的当前网格
        :return:
        """
        # df = my_pro_bar(stk_code=stk_code, start=add_date_str(get_current_date_str(), -10))
        df_ = get_k_data_JQ(stk=stk_code,
                            start_date=add_date_str(get_current_date_str(),
                                                    -10),
                            end_date=get_current_date_str())

        if len(df_) < 7:
            # df = my_pro_bar(stk_code=stk_code, start=add_date_str(get_current_date_str(), -30))
            df_ = get_k_data_JQ(stk=stk_code,
                                start_date=add_date_str(
                                    get_current_date_str(), -30),
                                end_date=get_current_date_str())

        return self.get_single_stk_reseau_sub(df_)
Ejemplo n.º 12
0
    def cal_stk_rsv_rank(self, stk_code, m_days, history_length=400):

        df = get_k_data_JQ(stk_code, count=history_length, end_date=get_current_date_str())

        debug_print_txt('rsv_cal', '', code2name(stk_code) + '开始计算rsv:', True)

        rsv = self.cal_rsv_rank_sub(df, m_days)

        debug_print_txt('rsv_cal', '', '最终rsv:' + '%0.3f' % rsv, True)

        return rsv
Ejemplo n.º 13
0
    def prepare_data(self, period='5m', count=48 * 100):
        """
        准备数据
        :return:
        """
        jq_login()

        # 准备数据
        df_5m = get_k_data_JQ(self.stk_code, count=count, freq=period)
        df_5m['date'] = df_5m.apply(lambda x: str(x['datetime'])[:10], axis=1)
        df_day = get_k_data_JQ(self.stk_code, count=8 * 100,
                               freq='30m').sort_index(ascending=True)

        # 想day data 中 增加必要index
        self.data_day = add_stk_index_to_df(df_day)

        # 增加必要index
        self.data_minute = add_stk_index_to_df(df_5m)

        logout()
Ejemplo n.º 14
0
def update_middle_period_hour_data():
    stk_list = read_config()['buy_stk'] + read_config()['concerned_stk']
    # stk_list = readConfig()['buy_stk']

    # 获取stk的小时数据
    result = {}
    for stk in stk_list:
        df_hour = get_k_data_JQ(stk, count=None, start_date=add_date_str(get_current_date_str(), -60), freq='60m')
        result[stk] = list(df_hour['close'].values)

    with open(data_dir+'middlePeriodHourData.json', 'w') as f:
        json.dump(result, f)
Ejemplo n.º 15
0
    def plot_test(self):
        """
        用以测试效果
        :return:
        """
        df = get_k_data_JQ(stk=self.stk_code, freq=self.freq, count=self.hist_count)
        df_bias = self.add_bias(df)

        # 增加rank数据
        df_bias['rank'] = df_bias.apply(lambda x: self.cal_rank_now(x['bias']), axis=1)

        df_bias.reset_index().reset_index().plot('level_0', ['close', 'rank'], subplots=True, style='*--')
Ejemplo n.º 16
0
def download_stk_list_day_data(stk_list, days=None):
    """
    给定stk_list,下载日期数据,以tuple的形式返回
    :return:
    """

    jq_login()
    stk_list_data = [(x, get_k_data_JQ(x, count=days)) for x in stk_list]
    stk_list_data = list(filter(lambda x: not x[1].empty, stk_list_data))
    logout()

    return stk_list_data
Ejemplo n.º 17
0
def gen_hour_macd_values(stk_code, source='jq', title=''):
    if source == 'jq':
        # df_30 = get_k_data_JQ(stk_code, start_date=add_date_str(get_current_date_str(), -20),
        #                       end_date=add_date_str(get_current_date_str(), 1), freq='30m')
        # df_60 = get_k_data_JQ(stk_code, start_date=add_date_str(get_current_date_str(), -20),
        #                       end_date=add_date_str(get_current_date_str(), 1), freq='60m')
        df_30 = get_k_data_JQ(stk_code, count=120,
                              end_date=add_date_str(get_current_date_str(), 1), freq='30m')
        df_60 = get_k_data_JQ(stk_code, count=120,
                              end_date=add_date_str(get_current_date_str(), 1), freq='60m')

    elif source == 'ts':
        df_30 = my_pro_bar(stk_code, start=add_date_str(get_current_date_str(), -20), freq='30min')
        df_60 = my_pro_bar(stk_code, start=add_date_str(get_current_date_str(), -20), freq='60min')

    # 去掉volume为空的行
    df_30 = df_30.loc[df_30.apply(lambda x: not (x['volume'] == 0), axis=1), :]
    df_60 = df_60.loc[df_60.apply(lambda x: not (x['volume'] == 0), axis=1), :]

    df_30['MACD'], _, _ = talib.MACD(df_30.close,
                                     fastperiod=12, slowperiod=26,
                                     signalperiod=9)

    df_60['MACD'], _, _ = talib.MACD(df_60.close,
                                     fastperiod=12, slowperiod=26,
                                     signalperiod=9)

    # 生成图片
    df_30 = df_30.dropna()
    df_60 = df_60.dropna()

    if str(df_60.index[-1]) > get_current_datetime_str():
        df_30 = df_30[:-1]
        df_60 = df_60[:-1]

    return df_30, df_60
Ejemplo n.º 18
0
    def gen_hist_data(self):
        """
        将历史bias数据保存到本地
        :return:
        """
        df = get_k_data_JQ(stk=self.stk_code,
                           freq=self.freq,
                           count=self.hist_count)

        bias_values = self.add_bias(df)['bias'].values

        bias_p = list(filter(lambda x: x >= 0, bias_values))
        bias_n = list(filter(lambda x: x < 0, bias_values))

        self.bias_dict = {'bias_p': bias_p, 'bias_n': bias_n}
Ejemplo n.º 19
0
def day_analysis_dict():
    """
    day数据分析
    :return:
    """
    # 判断结果list
    result_analysis_list = []

    pic_dict = {}
    for tab in dict_stk_list.keys():
        stk_list = dict_stk_list[tab]
        stk_list_pic_dict = {}

        for stk_info in stk_list:
            stk = stk_info[1]
            df = get_k_data_JQ(stk, 400)

            # 其他指标
            r_tuple_index_pic = gen_idx_pic_wx(df, stk_code=stk)
            result_analysis_list = result_analysis_list + r_tuple_index_pic[1]

            # 日线分析结果汇总
            r_tuple_day_pic = gen_day_pic_wx(df, stk_code=stk)
            result_analysis_list = result_analysis_list + r_tuple_day_pic[1]

            # stk_pic_dict = {
            #     'hour': gen_hour_macd_pic_wx(stk),
            #     'hour_index': gen_hour_index_pic_wx(stk),
            #     'day': r_tuple_day_pic[0],
            #     'wm': gen_w_m_macd_pic_wx(stk),
            #     'index': r_tuple_index_pic[0]
            # }
            #
            # stk_list_pic_dict[stk] = (stk_info[0], stk_pic_dict)

        # 将page中的stk pic存入字典
        # pic_dict[tab] = stk_list_pic_dict
    debug_print_txt('day_analysis', 'total_stk',
                    str(result_analysis_list) + '\n')

    return pic_dict, result_analysis_list
Ejemplo n.º 20
0
def download_stk_list_hour_data(stk_list):
    """
    给定stk_list,下载半小时数据,以tuple的形式返回
    :return:
    """

    jq_login()
    stk_list_data = [
        (x,
         get_k_data_JQ(x,
                       count=120,
                       end_date=add_date_str(get_current_date_str(), 1),
                       freq='30m')) for x in stk_list
    ]

    # 清除空值
    stk_list_data = list(filter(lambda x: not x[1].empty, stk_list_data))

    logout()

    return stk_list_data
Ejemplo n.º 21
0
    def down_minute_data(stk_code, freq):
        try:
            df = get_k_data_JQ(stk_code,
                               count=300,
                               end_date=add_date_str(get_current_date_str(),
                                                     1),
                               freq=freq)

            # 去掉volume为空的行
            df = df.loc[df.apply(lambda x: not (x['volume'] == 0), axis=1), :]

            # 增加指标计算
            df = add_stk_index_to_df(df)

            if str(df.index[-1]) > get_current_datetime_str():
                df = df[:-1]
            return df

        except Exception as e_:
            # self.log = self.log + '函数down_minute_data:\n %s\n' % str(e_)
            print('函数down_minute_data:\n %s\n' % str(e_))
            return pd.DataFrame()
Ejemplo n.º 22
0
def get_pic_dict():
    """
    获取图片字典
    :return:
    """
    # 判断结果list
    result_analysis_list = []

    pic_dict = {}
    for tab in dict_stk_list.keys():
        stk_list = dict_stk_list[tab]
        stk_list_pic_dict = {}

        for stk_info in stk_list:
            stk = stk_info[1]
            df = get_k_data_JQ(stk, 400)

            # 其他指标
            r_tuple_index_pic = gen_Idx_Pic_wx(df, stk_code=stk)
            result_analysis_list = result_analysis_list + r_tuple_index_pic[1]

            # 日线分析结果汇总
            r_tuple_day_pic = gen_Day_Pic_wx(df, stk_code=stk)
            result_analysis_list = result_analysis_list + r_tuple_day_pic[1]

            stk_pic_dict = {
                'hour': gen_Hour_MACD_Pic_wx(stk),
                'day': r_tuple_day_pic[0],
                'wm': gen_W_M_MACD_Pic_wx(stk),
                'index': r_tuple_index_pic[0]
            }

            stk_list_pic_dict[stk] = (stk_info[0], stk_pic_dict)

        # 将page中的stk pic存入字典
        pic_dict[tab] = stk_list_pic_dict

    return pic_dict, result_analysis_list
Ejemplo n.º 23
0
def send_W_M_MACD(stk_code, towho):
    """

    :param stk_code:
    :param towho:
    :return:
    """

    # 获取今天的情况,涨幅没有超过3%的不考虑
    # df_now = get_k_data_JQ(stk_code, count=2, end_date=get_current_date_str()).reset_index()
    #
    # if (df_now.tail(1)['close'].values[0]-df_now.head(1)['close'].values[0])/df_now.head(1)['close'].values[0] < 0.03:
    #     print('函数week_MACD_stray_judge:' + stk_code + '涨幅不够!')
    #     return False

    df = get_k_data_JQ(stk_code, count=400,
                       end_date=get_current_date_str()).reset_index()

    if len(df) < 350:
        print('函数week_MACD_stray_judge:' + stk_code + '数据不足!')
        return False

    # 规整
    df_floor = df.tail(math.floor(len(df) / 20) * 20 - 19)

    # 增加每周的星期几
    df_floor['day'] = df_floor.apply(
        lambda x: calendar.weekday(int(x['date'].split('-')[
            0]), int(x['date'].split('-')[1]), int(x['date'].split('-')[2])),
        axis=1)

    # 增加每周的星期几
    df_floor['day'] = df_floor.apply(
        lambda x: calendar.weekday(int(x['date'].split('-')[
            0]), int(x['date'].split('-')[1]), int(x['date'].split('-')[2])),
        axis=1)

    # 隔着5个取一个
    if df_floor.tail(1)['day'].values[0] != 4:
        df_floor_slice_5 = pd.concat(
            [df_floor[df_floor.day == 4],
             df_floor.tail(1)], axis=0)
    else:
        df_floor_slice_5 = df_floor[df_floor.day == 4]

    # 获取最后的日期
    date_last = df_floor_slice_5.tail(1)['date'].values[0]

    # 计算指标
    df_floor_slice_5['MACD'], df_floor_slice_5['MACDsignal'], df_floor_slice_5[
        'MACDhist'] = talib.MACD(df_floor_slice_5.close,
                                 fastperiod=6,
                                 slowperiod=12,
                                 signalperiod=9)

    # 隔着20个取一个(月线)
    df_floor_slice_20 = df_floor.loc[::20, :]

    # 计算指标
    df_floor_slice_20['MACD'], df_floor_slice_20[
        'MACDsignal'], df_floor_slice_20['MACDhist'] = talib.MACD(
            df_floor_slice_20.close,
            fastperiod=4,
            slowperiod=8,
            signalperiod=9)
    """ --------------------------------------- 生成图片 -------------------------------------"""
    fig, ax = plot_W_M(df_floor_slice_5, df_floor_slice_20)

    # 增加标题
    plt.title(stk_code + 'month-stray' + date_last)

    # 发送图片
    send_pic_qq(towho, fig)

    # 关闭图片
    plt.close()
Ejemplo n.º 24
0
def stk_sea_select(stk_code, towho, tc, debug_plot=False):

    try:
        # 获取今天的情况,涨幅没有超过3%的不考虑
        # df_now = get_k_data_JQ(stk_code, count=2, end_date=get_current_date_str()).reset_index()
        #
        # if (df_now.tail(1)['close'].values[0]-df_now.head(1)['close'].values[0])/df_now.head(1)['close'].values[0] < -0.05:
        #     print('函数week_MACD_stray_judge:' + stk_code + '涨幅不够!')
        #     return False, pd.DataFrame()
        """ ------------------------ 下载原始数据 ------------------------------- """
        df = get_k_data_JQ(stk_code,
                           count=400,
                           end_date=get_current_date_str()).reset_index()

        if len(df) < 350:
            print('函数week_MACD_stray_judge:' + stk_code + '数据不足!')
            return False, pd.DataFrame()

        # 规整
        df_floor = df.tail(math.floor(len(df) / 20) * 20 - 19)
        """ ------------------------ 判断周线是否达标 ------------------------------- """
        # 增加每周的星期几
        df_floor['day'] = df_floor.apply(lambda x: calendar.weekday(
            int(x['date'].split('-')[0]), int(x['date'].split('-')[1]),
            int(x['date'].split('-')[2])),
                                         axis=1)

        # 增加每周的星期几
        df_floor['day'] = df_floor.apply(lambda x: calendar.weekday(
            int(x['date'].split('-')[0]), int(x['date'].split('-')[1]),
            int(x['date'].split('-')[2])),
                                         axis=1)

        # 隔着5个取一个
        if df_floor.tail(1)['day'].values[0] != 4:
            df_floor_slice_5 = pd.concat(
                [df_floor[df_floor.day == 4],
                 df_floor.tail(1)], axis=0)
        else:
            df_floor_slice_5 = df_floor[df_floor.day == 4]

        # 计算周线指标
        df_floor_slice_5['MACD'], df_floor_slice_5[
            'MACDsignal'], df_floor_slice_5['MACDhist'] = talib.MACD(
                df_floor_slice_5.close,
                fastperiod=6,
                slowperiod=12,
                signalperiod=9)

        # 判断周线的走势,周线不是底部,直接返回
        MACD_5 = df_floor_slice_5.tail(3)['MACD'].values
        if not (MACD_5[1] == np.min(MACD_5)):
            tc.AppendText(stk_code + code2name(stk_code) + ':“周线”不符合要求!')
            return False
        """ ------------------------ 判断月线是否达标 ------------------------------- """
        # 隔着20个取一个(月线)
        df_floor_slice_20 = df_floor.loc[::20, :]

        # 计算指标
        df_floor_slice_20['MACD'], df_floor_slice_20[
            'MACDsignal'], df_floor_slice_20['MACDhist'] = talib.MACD(
                df_floor_slice_20.close,
                fastperiod=4,
                slowperiod=8,
                signalperiod=9)

        # 获取最后的日期
        date_last = df_floor_slice_5.tail(1)['date'].values[0]

        # 判断月线的走势,不符合条件直接返回
        MACD_20 = df_floor_slice_20.tail(4)['MACD'].values
        if not ((MACD_20[1] != np.max(MACD_20)) &
                (MACD_20[2] != np.max(MACD_20))):
            tc.AppendText(stk_code + code2name(stk_code) + ':“月线”不符合要求!')
            return False
        """ ------------------------ 判断日线SAR是否达标 ------------------------------- """

        # 判断日线SAR指标
        df_floor['SAR'] = talib.SAR(df_floor.high,
                                    df_floor.low,
                                    acceleration=0.05,
                                    maximum=0.2)
        if df_floor.tail(1)['SAR'].values[0] > df_floor.tail(
                1)['SAR'].values[0]:
            tc.AppendText(stk_code + code2name(stk_code) + ':“日线SAR指标”不符合要求!')
            return False
        """ ------------------------ 判断半小时SAR是否达标 ------------------------------- """
        df_half_hour = get_k_data_JQ(stk_code,
                                     count=120,
                                     end_date=add_date_str(
                                         get_current_date_str(), 1),
                                     freq='30m')

        # 判断日线SAR指标
        df_half_hour['SAR'] = talib.SAR(df_half_hour.high,
                                        df_half_hour.low,
                                        acceleration=0.05,
                                        maximum=0.2)
        if df_half_hour.tail(1)['SAR'].values[0] > df_half_hour.tail(
                1)['SAR'].values[0]:
            tc.AppendText(stk_code + code2name(stk_code) + ':“半小时SAR指标”不符合要求!')
            return False

        # 符合要求,返回True
        tc.AppendText(stk_code + code2name(stk_code) + ':符合要求!')
        return True

    except Exception as e:
        tc.AppendText(stk_code + '出错:\n' + str(e))
        return False
Ejemplo n.º 25
0
def week_MACD_stray_judge(stk_code, towho, debug_plot=False):

    try:
        # 获取今天的情况,涨幅没有超过3%的不考虑
        df_now = get_k_data_JQ(stk_code,
                               count=2,
                               end_date=get_current_date_str()).reset_index()

        if (df_now.tail(1)['close'].values[0] - df_now.head(1)
            ['close'].values[0]) / df_now.head(1)['close'].values[0] < -0.05:
            print('函数week_MACD_stray_judge:' + stk_code + '涨幅不够!')
            return False, pd.DataFrame()

        df = get_k_data_JQ(stk_code,
                           count=400,
                           end_date=get_current_date_str()).reset_index()

        if len(df) < 350:
            print('函数week_MACD_stray_judge:' + stk_code + '数据不足!')
            return False, pd.DataFrame()

        # 规整
        df_floor = df.tail(math.floor(len(df) / 20) * 20 - 19)

        # 增加每周的星期几
        df_floor['day'] = df_floor.apply(lambda x: calendar.weekday(
            int(x['date'].split('-')[0]), int(x['date'].split('-')[1]),
            int(x['date'].split('-')[2])),
                                         axis=1)

        # 增加每周的星期几
        df_floor['day'] = df_floor.apply(lambda x: calendar.weekday(
            int(x['date'].split('-')[0]), int(x['date'].split('-')[1]),
            int(x['date'].split('-')[2])),
                                         axis=1)

        # 隔着5个取一个
        if df_floor.tail(1)['day'].values[0] != 4:
            df_floor_slice_5 = pd.concat(
                [df_floor[df_floor.day == 4],
                 df_floor.tail(1)], axis=0)
        else:
            df_floor_slice_5 = df_floor[df_floor.day == 4]

        # 计算指标
        df_floor_slice_5['MACD'], df_floor_slice_5[
            'MACDsignal'], df_floor_slice_5['MACDhist'] = talib.MACD(
                df_floor_slice_5.close,
                fastperiod=6,
                slowperiod=12,
                signalperiod=9)

        # 隔着20个取一个(月线)
        df_floor_slice_20 = df_floor.loc[::20, :]

        # 计算指标
        df_floor_slice_20['MACD'], df_floor_slice_20[
            'MACDsignal'], df_floor_slice_20['MACDhist'] = talib.MACD(
                df_floor_slice_20.close,
                fastperiod=4,
                slowperiod=8,
                signalperiod=9)

        # 获取最后的日期
        date_last = df_floor_slice_5.tail(1)['date'].values[0]

        # 判断背离
        MACD_5 = df_floor_slice_5.tail(3)['MACD'].values
        MACD_20 = df_floor_slice_20.tail(4)['MACD'].values
        if (MACD_5[1] == np.min(MACD_5)) & (MACD_20[1] != np.max(MACD_20)) & (
                MACD_20[2] != np.max(MACD_20)):

            if debug_plot:
                """ --------------------------------------- 生成图片 -------------------------------------"""
                fig, ax = plot_W_M(df_floor_slice_5, df_floor_slice_20)

                # 增加标题
                plt.title(stk_code + 'month-stray' + date_last)

                # 发送图片
                send_pic_qq(towho, fig)

                # 关闭图片
                plt.close()
            return True, df
        else:
            return False, pd.DataFrame()
    except Exception as e:
        send_qq(towho, stk_code + '出错:\n' + str(e))
        return False, pd.DataFrame()
Ejemplo n.º 26
0
if __name__ == '__main__':

    from DataSource.auth_info import *

    # week_MACD_stray_judge('603421', '影子')

    checkWeekStrayForAll()
    send_W_M_MACD('000001', '影子')

    r = calendar.weekday(2019, 12, 5)
    # week_MACD_stray_judge('300508', '影子')

    checkWeekStrayForAll()

    stk_code = '600707'
    df = get_k_data_JQ(stk_code, count=600,
                       end_date=get_current_date_str()).reset_index()

    # 规整
    df_floor = df.tail(math.floor(len(df) / 20) * 20 - 19)

    # 取均值
    df_floor['close_m5'] = df_floor['close'].rolling(window=5).mean()

    # 增加每周的星期几
    df_floor['day'] = df_floor.apply(
        lambda x: calendar.weekday(int(x['date'].split('-')[
            0]), int(x['date'].split('-')[1]), int(x['date'].split('-')[2])),
        axis=1)

    # 隔着5个取一个
    # df_floor_slice_5 = df_floor.loc[::5, :]
Ejemplo n.º 27
0
def gen_kind_pic(kind, pool):
    """
	造图片,存本地
	:param kind:
	h:小时
	h_idx:小时idx
	d:天
	wm:周、月
	idx: 指数
	:return:

	返回的图片应该 执行page和行号,便于更新!
	以多层字典的方式返回结果,第一层区分page,第二层区分行号!
	"""

    r_dic = {'Index': {}, 'Buy': {}, 'Concerned': {}}
    dict_stk_hour = copy.deepcopy(dict_stk_list)

    jq_login()
    """ 在外部下载需要的数据,防止多进程中重复连接聚宽 """
    for page in dict_stk_hour.keys():
        for stk_info in dict_stk_list[page]:
            stk = stk_info[1]
            if kind is 'h':
                r_dic[page][stk + '_d'] = GenPic.gen_hour_macd_values(stk)
            elif kind is 'h_idx':
                r_dic[page][stk + '_d'] = GenPic.gen_hour_macd_values(stk)[0]
            elif kind is 'd':
                r_dic[page][stk + '_d'] = get_k_data_JQ(stk, 400)
            elif kind is 'wm':
                r_dic[page][stk + '_d'] = get_k_data_JQ(
                    stk, count=400).reset_index()
            elif kind is 'd_idx':
                r_dic[page][stk + '_d'] = get_k_data_JQ(stk, 400)
    jq.logout()
    """ 生成pic """
    for page in dict_stk_hour.keys():
        for stk_info in dict_stk_list[page]:
            stk = stk_info[1]

            # 保存路径
            save_dir = hist_pic_dir + get_current_date_str(
            ) + '/' + stk + kind + '/'
            file_name = get_current_datetime_str()[:-3].replace(
                ':', '').replace(' ', '').replace('-', '') + '.png'
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)

            if kind is 'h':
                r_dic[page][stk + '_res'] = pool.apply_async(
                    GenPic.gen_hour_macd_pic_local,
                    (r_dic[page][stk + '_d'], stk, save_dir + file_name))

            elif kind is 'h_idx':
                r_dic[page][stk + '_res'] = pool.apply_async(
                    GenPic.gen_hour_index_pic_local,
                    (r_dic[page][stk + '_d'], stk, save_dir + file_name))
            elif kind is 'd':
                r_dic[page][stk + '_res'] = pool.apply_async(
                    GenPic.gen_day_pic_local,
                    (r_dic[page][stk + '_d'], stk, save_dir + file_name))
            elif kind is 'wm':
                r_dic[page][stk + '_res'] = pool.apply_async(
                    GenPic.gen_w_m_macd_pic_local,
                    (r_dic[page][stk + '_d'], stk, save_dir + file_name))
            elif kind is 'd_idx':
                r_dic[page][stk + '_res'] = pool.apply_async(
                    GenPic.gen_idx_pic_local,
                    (r_dic[page][stk + '_d'], stk, save_dir + file_name))

            # if kind is 'h':
            #     r_dic[page][stk + '_res'] = pool.apply_async(gen_hour_macd_pic_local, (
            #     r_dic[page][stk + '_d'], stk, 'jq', '', save_dir + file_name))
            #
            # elif kind is 'h_idx':
            #     r_dic[page][stk + '_res'] = pool.apply_async(gen_hour_index_pic_local,
            #                                                  (r_dic[page][stk + '_d'], stk, save_dir + file_name))
            # elif kind is 'd':
            #     r_dic[page][stk + '_res'] = pool.apply_async(gen_day_pic_local,
            #                                                  (r_dic[page][stk + '_d'], stk, save_dir + file_name))
            # elif kind is 'wm':
            #     r_dic[page][stk + '_res'] = pool.apply_async(gen_w_m_macd_pic_local,
            #                                                  (r_dic[page][stk + '_d'], stk, save_dir + file_name))
            # elif kind is 'd_idx':
            #     r_dic[page][stk + '_res'] = pool.apply_async(gen_idx_pic_local,
            #                                                  (r_dic[page][stk + '_d'], stk, save_dir + file_name))

            # 在字典中保存图片路径
            r_dic[page][stk + '_url'] = save_dir + file_name

    return r_dic
Ejemplo n.º 28
0
    # 获取pcr
    reseau_judge.get_pcr()

    # 打印日志
    reseau_judge.bs_info_print()

    # 进行bs判断
    reseau_judge.bs_judge()

    return reseau_judge.str_gui


if __name__ == '__main__':
    jq_login()

    df = get_k_data_JQ('000001', 400)

    buy_stk_list = list(
        set(read_config()['buy_stk'] + read_config()['index_stk']))

    # 局部变量
    note_list = []

    # 对stk进行检查
    for stk in buy_stk_list:
        str_gui = judge_single_stk(stk_code=stk,
                                   stk_amount_last=400,
                                   gui=True,
                                   debug=True)
    logout()
    app = wx.App()
Ejemplo n.º 29
0
# encoding=utf-8
Ejemplo n.º 30
0
stk_code = '000001'
if __name__ == '__main__':

    jq_login()
    """ --------------------- 生成相关图片 ------------------------ """

    # 保存路径
    save_dir = sea_select_pic_dir + get_current_date_str() + '/'

    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    # 准备 小时 和 日线 数据
    df_hour = gen_hour_macd_values(stk_code)
    df_day = get_k_data_JQ(stk_code, 800)

    # 定义图片名称
    file_name = stk_code + '.png'

    # 生成小时图片
    gen_hour_macd_pic_local(df_hour, stk_code, 'jq', '',
                            save_dir + 'h_' + file_name)
    gen_hour_index_pic_local(df_hour[0], stk_code,
                             save_dir + 'h_idx_' + file_name)
    gen_day_pic_local(df_day, stk_code, save_dir + 'd_' + file_name)
    gen_w_m_macd_pic_local(df_day, stk_code, save_dir + 'wm_' + file_name)
    gen_idx_pic_local(df_day, stk_code, save_dir + 'd_idx_' + file_name)
    """ --------------------- 读取图片生成pdf ------------------------ """

    end = 0