Пример #1
0
    def on_post(self, req, res):
        target_req = req.context['data']
        if target_req:
            target = Target()
            target.code = target_req["code"]
            target.strategy_code = target_req["strategy_code"]
            target.name = target_req["name"]
            target.pointcut = target_req["pointcut"]

            target_est = target_dao.query_by_code(
                strategy_code=target.strategy_code, code=target.code)
            if target_est is not None:
                raise InvalidRequestException("stock has already exists")

            # 订阅
            futu_opend.subscribe(fill_market(target_req["code"]))
            state, data = futu_opend.quote_ctx.get_stock_quote(
                code_list=[fill_market(target_req["code"])])
            if state == RET_OK:
                target.price = data['last_price'].values[0]
            target_dao.add(target)

        else:
            raise InvalidRequestException(target_req)

        self.on_success(res, None)
Пример #2
0
def collect_single(code, start, end, futu_quote_ctx):
    table_name = 'k_data_weekly'
    try:
        state, data = futu_quote_ctx.get_history_kline(fill_market(code), ktype='K_WEEK', autype='qfq', start=start,end=end)
        data.to_sql(table_name, dataSource.mysql_quant_engine, if_exists='append', index=False)
    except Exception as e:
        logger.error(e)
Пример #3
0
    def get_multiple_k_data(self, code_list=None, start=None, end=None):

        if start is None:
            start = get_next_date(-720)

        if end is None:
            end = get_current_date()

        sql = None
        if code_list is None:
            sql = ('''select  *
                     from k_data  
                     where  time_key BETWEEN %(start)s and %(end)s order by time_key asc ''')
            codes_list = None
        else:

            sql = ('''select  *
                     from k_data  
                     where code in %(code_list)s and time_key BETWEEN %(start)s and %(end)s order by time_key asc ''')

            codes_list = [fill_market(code) for code in code_list]

        data = pd.read_sql(sql=sql, params={"code_list": codes_list, "start": start, "end": end}
                           , con=dataSource.mysql_quant_conn)

        return data
    def test_get_data(self):
        state, data = self.futu_quote_ctx.get_history_kline(
            fill_market('600196'),
            ktype='K_WEEK',
            autype='qfq',
            start='2018-08-01',
            end=get_current_date())

        print(data)
Пример #5
0
    def on_put(self, req, res):
        position_req = req.context['data']
        position = position_dao.query_by_id(position_req["id"])

        if position is None:
            raise ResourceNotFoundException("Can not found position.")

        position.price_in = position_req["price_in"]
        position.shares = position_req["shares"]
        position.update_time = datetime.now()

        futu_opend.subscribe(fill_market(position.code))
        state, data = futu_opend.quote_ctx.get_stock_quote(code_list=[fill_market(position.code)])
        if state == RET_OK:
            position.price = data['last_price'].values[0]

        position_dao.update(position)

        self.on_success(res, None)
Пример #6
0
    def get_k_training_data(self, code, start, end, futu_quote_ctx):

        state, data = futu_quote_ctx.get_history_kline(fill_market(code), ktype='K_DAY', autype='qfq', start=start,
                                                       end=end)

        data['next_direction'] = data['change_rate'].apply(cal_direction).shift(-1)

        feature = ['open', 'close', 'high', 'low', 'pe_ratio', 'turnover_rate', 'volume']

        data = data.dropna()

        return data, feature
Пример #7
0
def monitor_targets():
    target_all = target_dao.query_all()
    codes = [fill_market(t.code) for t in target_all]

    state, df = futu_opend.quote_ctx.get_stock_quote(codes)
    # 更新实时数据
    for index, row in df.iterrows():
        code = row['code'][3:]
        targets = [target for target in target_all if target.code == code]

        for target in targets:
            last_price = row['last_price']
            target.price = last_price
            target.update_time = datetime.now()
            target_dao.update(target)
Пример #8
0
    def on_post(self, req, res):
        position_req = req.context['data']
        if position_req:
            position = Position()
            position.code = position_req["code"]
            position.strategy_code = position_req["strategy_code"]
            position.name = position_req["name"]
            position.price_in = position_req["price_in"]
            position.shares = position_req["shares"]

            position_est = position_dao.query_by_code(strategy_code=position.strategy_code, code=position.code)
            if position_est is not None:
                raise InvalidRequestException("stock has already exists")

            futu_opend.subscribe(fill_market(position_req["code"]))
            state, data = futu_opend.quote_ctx.get_stock_quote(code_list=[fill_market(position_req["code"])])
            if state == RET_OK:
                position.price = data['last_price'].values[0]

            position_dao.add(position)
        else:
            raise InvalidRequestException(position_req)

        self.on_success(res, None)
Пример #9
0
    def get_k_data(self, code, start=None, end=None):

        if start is None:
            start = get_next_date(-720)

        if end is None:
            end = get_current_date()

        sql = ('''select  time_key, code, open, close  as close, high, low, change_rate, last_close, turnover, turnover_rate, volume, pe_ratio
                 from k_data  
                 where code=%(code)s and time_key BETWEEN %(start)s and %(end)s order by time_key asc ''')

        data = pd.read_sql(sql=sql, params={"code": fill_market(code), "start": start, "end": end}
                           , con=dataSource.mysql_quant_conn)

        return data
Пример #10
0
    def get_k_data(self, code, start, end):

        if start is None:
            start = '2013-01-01'

        if end is None:
            end = get_current_date()

        sql = ('''select  *
                 from k_data_weekly  
                 where code=%(code)s and time_key BETWEEN %(start)s and %(end)s order by time_key asc ''')

        data = pd.read_sql(sql=sql, params={"code": fill_market(code), "start": start, "end": end}
                           , con=dataSource.mysql_quant_conn)

        return data
Пример #11
0
    def init_pool(self):

        self.truncate()

        stocks = stock_dao.query_all()

        k_data_list = k_data_dao.get_multiple_k_data(start=get_next_date(-720), end=get_current_date())
        df = pd.DataFrame(columns=['code', 'name'])

        for stock in stocks:
            try:

                k_data = k_data_list.loc[k_data_list['code'] == fill_market(stock.code)]
                k_data = k_data.join(cal_macd(k_data))
                k_data['turnover7'] = cal_mavol7(k_data, column='turnover')

                k_turnover7 = k_data['turnover7'].values[-1]


                if len(k_data['code'].values) == 0:
                    continue

                stock_basic = stock_basic_dao.get_by_code(stock.code)
                eps_value = stock_basic['eps'].values[0]
                profits_yoy_value = stock_basic['profits_yoy'].values[0]

                if eps_value < 0:
                    continue

                if profits_yoy_value < 0:
                    continue

                if k_turnover7 < 65000000:
                    continue

                dict = {"code": stock.code, "name": stock.name}
                df = df.append(dict, ignore_index=True)
                logger.debug("append code:%s" % stock.code)
            except Exception as e:
                logger.debug("code:%s, error:%s" % (stock.code, traceback.format_exc()))

        df.to_sql('stock_pool', dataSource.mysql_quant_engine, if_exists='append', index=False)
        '''
Пример #12
0
    def on_put(self, req, res):
        target_req = req.context['data']

        target = target_dao.query_by_id(id=target_req["id"])

        if target is None:
            raise ResourceNotFoundException("Can not found target.")

        target.pointcut = target_req["pointcut"]

        code = fill_market(target.code)
        futu_opend.subscribe(code)
        state, data = futu_opend.quote_ctx.get_stock_quote(code_list=[code])
        if state == RET_OK:
            target.price = data['last_price'].values[0]

        target.update_time = datetime.now()
        target_dao.update(target)

        self.on_success(res, None)
Пример #13
0
def monitor_positions():
    position_all = position_dao.query_all()

    codes = [fill_market(p.code) for p in position_all]

    state, df = futu_opend.quote_ctx.get_stock_quote(codes)
    # 更新实时数据
    for index, row in df.iterrows():
        code = row['code'][3:]
        last_price = row['last_price']

        positions = [position for position in position_all if position.code == code]

        for position in positions:
            position.price = last_price

            profit = round((last_price / position.price_in - 1) * 100, 2)
            position.profit = profit
            position.worth = round(position.price * position.shares, 2)
            position.profit_value = round((position.price - position.price_in) * position.shares, 2)
            position.update_time = datetime.now()
            position_dao.update(position)
Пример #14
0
def collect_single_daily(code, futu_quote_ctx, start=None, end=None):
    table_name = 'k_data'

    if start is None:
        start = get_current_date()

    if end is None:
        end = get_current_date()

    try:
        state, data = futu_quote_ctx.get_history_kline(fill_market(code),
                                                       ktype='K_DAY',
                                                       autype='qfq',
                                                       start=start,
                                                       end=end)
        data = data.tail(1)
        data.to_sql(table_name,
                    dataSource.mysql_quant_engine,
                    if_exists='append',
                    index=False)
    except Exception as e:
        logger.error(e)
Пример #15
0
def subscribe_positions():
    positions = position_dao.query_all()
    codes = [fill_market(p.code) for p in positions]
    futu_opend.subscribe(codes)
Пример #16
0
def subscribe_targets():
    targets = target_dao.query_all()
    codes = [fill_market(t.code) for t in targets]
    futu_opend.subscribe(codes)
Пример #17
0
def cal_single_stock(code, k_data_list, w_data_list):
    try:
        w_data = w_data_list.loc[w_data_list['code'] == fill_market(code)]
        w_data = w_data.join(cal_macd(w_data))
        # w_data = w_data.join(acc_kdj(w_data))

        k_data = k_data_list.loc[k_data_list['code'] == fill_market(code)]
        k_data = k_data.join(cal_macd(k_data))
        if len(k_data['code'].values) == 0 or len(w_data['code'].values) == 0:
            return False

        k_data['ma145'] = cal_ma145(k_data)
        k_data['turnover7'] = cal_mavol7(k_data, column='turnover')

        w_pre_volume = w_data['volume'].values[-2]
        w_volume = w_data['volume'].values[-1]

        w_pre_macd = w_data['macd'].values[-1]
        w_pre_diff = w_data['diff'].values[-1]
        w_pre_dea = w_data['dea'].values[-1]
        w_last2_diff = w_data['diff'].tail(80)
        w_last2_dea = w_data['dea'].tail(80)

        w_macd = w_data['macd'].values[-1]
        w_diff = w_data['diff'].values[-1]
        w_dea = w_data['dea'].values[-1]
        # w_k_value = w_data['k_value'].values[-1]
        # w_d_value = w_data['d_value'].values[-1]

        k_close = k_data['close'].values[-1]
        k_ma145 = k_data['ma145'].values[-1]
        k_turnover7 = k_data['turnover7'].values[-1]

        k_diff = k_data['diff'].values[-1]
        k_dea = k_data['dea'].values[-1]
        k_last3_diff = k_data['diff'].tail(500)
        k_last3_dea = k_data['dea'].tail(500)

        pre_diff = k_data['diff'].values[-2]
        pre_dea = k_data['dea'].values[-2]
        macd = w_data['macd'].values[-1]
        '''
        if k_close < k_ma145:
            logger.debug("code:%s, close price less than ma145" % code)
            return False
  

        if k_turnover7 < 75000000:
            logger.debug("code:%s, turnover less than 75000000" % code)
            return False
       

        if round(w_volume / w_pre_volume, 1) < 1.3:
            logger.debug("code:%s, volume  less than pre_volume * 1.3" % code)
            return False
        0'''
        # 通过机器学习预测, 下一个diff, 和 下一个dea
        k_next_diff = macd_predict(k_last3_diff, k_diff)[0]
        k_next_dea = macd_predict(k_last3_dea, k_dea)[0]

        w_next_diff = macd_predict(w_last2_diff, w_diff)[0]
        w_next_dea = macd_predict(w_last2_dea, w_dea)[0]

        if w_pre_diff < w_pre_dea and w_macd > -0.35 and w_diff > w_dea:
            return True

        if w_dea > w_diff > -0.35 and w_next_diff > w_next_dea:
            return True

        if pre_diff < pre_dea and k_diff > -0.35 and k_diff > k_dea:

            return True

        if k_dea > k_diff > -0.35 and k_next_diff > k_next_dea:

            return True

            # if (w_pre_diff < w_pre_dea and w_macd > -0.35 and w_diff > w_dea)\
            # or (w_pre_diff < w_pre_dea and w_macd > -0.35 and w_diff < w_dea  and w_dea - w_diff < abs(w_dea * 0.2)):
        '''
        elif macd > -0.35 and abs(dea - diff) < 0.2 and abs(pre_dea - pre_diff) < 0.2:

            if (w_pre_diff < w_pre_dea and w_macd > -0.35 and w_diff > w_dea) \
                    or (w_pre_diff < w_pre_dea and w_macd > -0.35 and w_diff < w_dea and w_dea - w_diff < abs(w_dea * 0.2)):
                return True

            #macd_point = k_data_dao.get_last_macd_cross_point(k_data, window_size=8)

            # 日k上 macd已经金叉(-3days)
            #if macd_point is not None:
                #return True
        '''

        return False

    except Exception as e:
        logger.error("code:%s" % code)
        logger.error(traceback.format_exc())

    return False