Example #1
0
def filter_main(stock_new, state_dt, predict_dt, poz):

    #先更新持股天数
    DBUtils.update_hold_days()

    #根据最新的仓位调整相应持股比例
    #先卖出
    deal = Deal.Deal(state_dt)
    stock_pool_local = deal.stock_pool
    for stock in stock_pool_local:

        predict = DBUtils.get_stock_predict(state_dt, stock)
        ans = Operator.sell(stock, state_dt, predict)

    #后买入
    for stock_index in range(len(stock_new)):
        deal_buy = Deal.Deal(state_dt)

        # # 如果模型f1分值低于50则不买入
        # sql_f1_check = "select * from model_ev_resu a where a.stock_code = '%s' and a.state_dt < '%s' order by a.state_dt desc limit 1"%(stock_new[stock_index],state_dt)
        # cursor.execute(sql_f1_check)
        # done_check = cursor.fetchall()
        # db.commit()
        # if len(done_check) > 0:
        #     if float(done_check[0][4]) < 0.5:
        #         print('F1 Warning !!')
        #         continue

        ans = Operator.buy(stock_new[stock_index], state_dt,
                           poz[stock_index] * deal_buy.cur_money_rest)
        del deal_buy
Example #2
0
def filter_main(stock_new,state_dt,predict_dt,poz):
    # 建立数据库连接
    ##################################################
    # 建立数据库连接,设置tushare的token,定义一些初始化参数
    env=get_env()
    db,cursor,pro=env.db,env.cursor,env.pro
    ##################################################

    #先更新持股天数
    sql_update_hold_days = 'update my_stock_pool w set w.hold_days = w.hold_days + 1'
    cursor.execute(sql_update_hold_days)
    db.commit()

    #先卖出
    deal = Deal.Deal(state_dt)
    stock_pool_local = deal.stock_pool

    for stock in stock_pool_local:
        sql_predict = "select predict from model_ev_resu a where a.state_dt = '%s' and a.stock_code = '%s'"%(predict_dt,stock)
        cursor.execute(sql_predict)
        done_set_predict = cursor.fetchall()
        predict = 0
        if len(done_set_predict) > 0:
            predict = int(done_set_predict[0][0])
            print  "predict: %s,predictvalue: %d " % (stock ,predict)  
        ans = Operator.sell(stock,state_dt,predict)
        print "sell: %s" % stock  

    #后买入
    for stock_index in range(len(stock_new)):
        deal_buy = Deal.Deal(state_dt)
        # # 如果模型f1分值低于50则不买入
        # sql_f1_check = "select * from model_ev_resu a where a.stock_code = '%s' and a.state_dt < '%s' order by a.state_dt desc limit 1"%(stock_new[stock_index],state_dt)
        # cursor.execute(sql_f1_check)
        # done_check = cursor.fetchall()
        # db.commit()
        # if len(done_check) > 0:
        #     if float(done_check[0][4]) < 0.5:
        #         print('F1 Warning !!')
        #         continue
        # macd模型,如果预测值为1则买入
        # sql_macd_check="select * from model_macd_resu where stock_code= '%s' and state_dt= '%s' " % (stock_new[stock_index],state_dt)
        # cursor.execute(sql_macd_check)
        # done_check = cursor.fetchall()
        # print done_check
        # db.commit()
        # if len(done_check) > 0:
        #     if done_check[0][2] <> '1': # 不可买
        #         print(state_dt,': ',stock_new[stock_index],'macd forbidden !')
        #         continue
        ans = Operator.buy(stock_new[stock_index],state_dt,float(poz[stock_index])*deal_buy.cur_money_rest)
        print "stock_new[stock_index],state_dt,poz[stock_index]*deal_buy.cur_money_rest", stock_new[stock_index],state_dt,poz[stock_index]*deal_buy.cur_money_rest
        del deal_buy
 
    db.close()
Example #3
0
def filter_main(stock_new, state_dt, predict_dt, poz):
    # 建立数据库连接
    db = pymysql.connect(host='127.0.0.1',
                         user='******',
                         passwd='root',
                         db='stock',
                         charset='utf8')
    cursor = db.cursor()

    #先更新持股天数
    sql_update_hold_days = 'update my_stock_pool w set w.hold_days = w.hold_days + 1'
    cursor.execute(sql_update_hold_days)
    db.commit()

    #先卖出
    deal = Deal.Deal(state_dt)
    stock_pool_local = deal.stock_pool

    for stock in stock_pool_local:
        sql_predict = "select predict from model_ev_resu a where a.state_dt = '%s' and a.stock_code = '%s'" % (
            predict_dt, stock)
        cursor.execute(sql_predict)
        done_set_predict = cursor.fetchall()
        predict = 0
        if len(done_set_predict) > 0:
            predict = int(done_set_predict[0][0])
            print "predict: %s,predictvalue: %d " % (stock, predict)
        ans = Operator.sell(stock, state_dt, predict)
        print "sell: %s" % stock

    #后买入
    for stock_index in range(len(stock_new)):
        deal_buy = Deal.Deal(state_dt)

        # # 如果模型f1分值低于50则不买入
        # sql_f1_check = "select * from model_ev_resu a where a.stock_code = '%s' and a.state_dt < '%s' order by a.state_dt desc limit 1"%(stock_new[stock_index],state_dt)
        # cursor.execute(sql_f1_check)
        # done_check = cursor.fetchall()
        # db.commit()
        # if len(done_check) > 0:
        #     if float(done_check[0][4]) < 0.5:
        #         print('F1 Warning !!')
        #         continue
        ans = Operator.buy(stock_new[stock_index], state_dt,
                           float(poz[stock_index]) * deal_buy.cur_money_rest)
        print "stock_new[stock_index],state_dt,poz[stock_index]*deal_buy.cur_money_rest", stock_new[
            stock_index], state_dt, poz[stock_index] * deal_buy.cur_money_rest
        del deal_buy

    db.close()
Example #4
0
def filter_main(stock_new, state_dt, predict_dt, poz):
    # 建立数据库连接
    db = pymysql.connect(host='127.0.0.1',
                         user='******',
                         passwd='000109',
                         db='stock_list',
                         charset='utf8')
    cursor = db.cursor()

    #先更新持股天数
    sql_update_hold_days = 'update my_stock_pool w set w.hold_days = w.hold_days + 1'
    cursor.execute(sql_update_hold_days)
    db.commit()

    #先卖出
    deal = Deal.Deal(state_dt)
    stock_pool_local = deal.stock_pool
    for stock in stock_pool_local:
        # sql_predict = "select predict from good_pool_all a where a.state_dt = '%s' and a.stock_code = '%s'"%(predict_dt,stock)
        # cursor.execute(sql_predict)
        # done_set_predict = cursor.fetchall()
        predict = 0
        # if len(done_set_predict) > 0:
        #     # predict = int(done_set_predict[0][0])
        #     ans = Operator.sell(stock,state_dt,predict)

    #后买入
    for stock_index in range(len(stock_new)):
        deal_buy = Deal.Deal(state_dt)
        #if poz[stock_index]*deal_buy.cur_money_rest >= :
        # sql_ban_pool = "select distinct stock_code from ban_list"
        # cursor.execute(sql_ban_pool)
        # done_ban_pool = cursor.fetchall()
        # ban_list = [x[0] for x in done_ban_pool]

        # # 如果模型f1分值低于50则不买入
        # sql_f1_check = "select * from good_pool_all a where a.stock_code = '%s' and a.state_dt < '%s' order by a.state_dt desc limit 1"%(stock_new[stock_index],state_dt)
        # cursor.execute(sql_f1_check)
        # done_check = cursor.fetchall()
        # db.commit()
        # if len(done_check) > 0:
        #     if float(done_check[0][4]) < 0.5:
        #         print('F1 Warning !!')
        #         continue

        ans = Operator.buy(stock_new[stock_index], state_dt,
                           poz[stock_index] * deal_buy.cur_money_rest)
        del deal_buy
    db.close()
Example #5
0
def buy(stock_code, opdate, buy_money):
    # 建立数据库连接
    db = pymysql.connect(host='127.0.0.1',
                         user='******',
                         passwd='000109',
                         db='stock_list',
                         charset='utf8')
    cursor = db.cursor()
    deal_buy = Deal.Deal(opdate)
    #后买入
    if deal_buy.cur_money_rest + 1 >= buy_money:
        sql_buy = "select * from stock_info a where a.state_dt = '%s' and a.stock_code = '%s'" % (
            opdate, stock_code)
        cursor.execute(sql_buy)
        done_set_buy = cursor.fetchall()

        if len(done_set_buy) == 0:
            return -1
        buy_price = float(done_set_buy[0][3])
        if buy_price >= 195:
            return 0
        vol, rest = divmod(min(deal_buy.cur_money_rest, buy_money),
                           buy_price * 100)
        vol = vol * 100
        if vol == 0:
            return 0
        new_capital = deal_buy.cur_capital - vol * buy_price * 0.0005
        new_money_lock = deal_buy.cur_money_lock + vol * buy_price
        new_money_rest = deal_buy.cur_money_rest - vol * buy_price * 1.0005
        print(new_money_lock)
        sql_buy_update2 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,state_dt,deal_price)VALUES ('%.2f', '%.2f', '%.2f','%s','%s','%i','%s','%.2f')" % (
            new_capital, new_money_lock, new_money_rest, 'buy', stock_code,
            vol, opdate, buy_price)
        cursor.execute(sql_buy_update2)
        db.commit()
        if stock_code in deal_buy.stock_all:
            new_buy_price = (deal_buy.stock_map1[stock_code] *
                             deal_buy.stock_map2[stock_code] + vol * buy_price
                             ) / (deal_buy.stock_map2[stock_code] + vol)
            new_vol = deal_buy.stock_map2[stock_code] + vol
            sql_buy_update3 = "update my_stock_pool w set w.buy_price = (select '%.2f' from dual) where w.stock_code = '%s'" % (
                new_buy_price, stock_code)
            sql_buy_update3b = "update my_stock_pool w set w.hold_vol = (select '%i' from dual) where w.stock_code = '%s'" % (
                new_vol, stock_code)
            sql_buy_update3c = "update my_stock_pool w set w.hold_days = (select '%i' from dual) where w.stock_code = '%s'" % (
                1, stock_code)
            cursor.execute(sql_buy_update3)
            cursor.execute(sql_buy_update3b)
            cursor.execute(sql_buy_update3c)
            db.commit()
        else:
            sql_buy_update3 = "insert into my_stock_pool(stock_code,buy_price,hold_vol,hold_days) VALUES ('%s','%.2f','%i','%i')" % (
                stock_code, buy_price, vol, int(1))
            cursor.execute(sql_buy_update3)
            db.commit()
        db.close()
        return 1
    db.close()
    return 0
Example #6
0
def deal(request, deal_id):
    deal = Deal.getDealByID(deal_id)

    t = loader.get_template('dealviewer/deal.html')
    c = Context({
        'deal': deal
        })
    if not deal:
        return HttpResponseNotFound(t.render(c))
    return HttpResponse(t.render(c))
Example #7
0
def filter_main(stock_new, state_dt, predict_dt, year):
    # 建立数据库连接
    db = pymysql.connect(host='127.0.0.1',
                         user='******',
                         passwd='admin',
                         db='stock',
                         charset='utf8')
    cursor = db.cursor()

    #先更新持股天数
    sql_update_hold_days = 'update my_stock_pool w set w.hold_days = w.hold_days + 1'
    cursor.execute(sql_update_hold_days)
    db.commit()

    #先卖出
    deal = Deal.Deal()
    stock_pool_local = deal.stock_pool
    for stock in stock_pool_local:
        sql_predict = "select predict from good_pool a where a.state_dt = '%s' and a.stock_code = '%s'" % (
            predict_dt, stock)
        cursor.execute(sql_predict)
        done_set_predict = cursor.fetchall()
        predict = 0
        if len(done_set_predict) > 0:
            predict = int(done_set_predict[0][0])
        ans = Operator.sell(stock, state_dt, predict, year)

    #后买入
    #对于已经持仓的股票不再重复买入
    stock_new2 = [x for x in stock_new if x not in stock_pool_local]
    #每只买入股票配仓资金为3万元
    for stock_buy in stock_new2:
        deal_buy = Deal.Deal()
        if deal_buy.cur_money_rest > 30000:
            # sql_ban_pool = "select distinct stock_code from ban_list"
            # cursor.execute(sql_ban_pool)
            # done_ban_pool = cursor.fetchall()
            # ban_list = [x[0] for x in done_ban_pool]
            ans = Operator.buy(stock_buy, state_dt, 30000, year)
            break
    db.close()
Example #8
0
def since_xml(request, deal_id):
    latest_deals = [d for d in Deal.getDeals(since=deal_id)]

    sio = cStringIO.StringIO()
    if len(latest_deals):
        dealer = XMLDealer(out=sio)
        dealer.startDocument()
        dealer.addDeals(latest_deals)
        dealer.endDocument()

    t = loader.get_template('dealviewer/since.xml')
    c = Context({
        'latest_deals': sio.getvalue()
        })
    if not latest_deals:
        return HttpResponseNotFound(t.render(c))
    return HttpResponse(t.render(c), mimetype='text/xml')
Example #9
0
def search(request):
    terms = request.GET.get('q')

    found_deals = []
    if terms:
        found_deals = Deal.getDeals(num=MAX_DEALS, terms=terms)

    t = loader.get_template('dealviewer/search.html')
    c = Context({
        'page_title': 'Deal Search',
        'terms': terms,
        'deal_list': [d for d in found_deals],
        'MAX_DEALS': MAX_DEALS
        })
    if not found_deals:
        return HttpResponseNotFound(t.render(c))
    return HttpResponse(t.render(c))
Example #10
0
def buy(stock_code, opdate, buy_money):
    deal_buy = Deal.Deal(opdate)

    #后买入
    if deal_buy.cur_money_rest + 1 >= buy_money:

        stock2buy = DBUtils.select_stock_info(opdate, stock_code)
        if len(stock2buy) == 0:
            print('WARN: no stock to buy... -' + stock_code)
            return -1

        buy_price = float(stock2buy[0][3])

        if buy_price >= 195:
            print('INFO: price over 195... -' + stock_code)
            return 0

        vol, rest = divmod(min(deal_buy.cur_money_rest, buy_money),
                           buy_price * 100)
        vol = vol * 100

        if vol == 0:
            print('INFO: vol is 0, money is not enough... -' + stock_code)
            return 0

        new_capital = deal_buy.cur_capital - vol * buy_price * 0.0005
        new_money_lock = deal_buy.cur_money_lock + vol * buy_price
        new_money_rest = deal_buy.cur_money_rest - vol * buy_price * 1.0005

        DBUtils.insert_my_capital(new_capital, new_money_lock, new_money_rest,
                                  'BUY', stock_code, vol, 0.0, 0.0, 'init',
                                  opdate, buy_price)
        if stock_code in deal_buy.stock_all:
            new_buy_price = (deal_buy.stocks_buy_price[stock_code] *
                             deal_buy.stocks_hold_vol[stock_code] +
                             vol * buy_price) / (
                                 deal_buy.stocks_hold_vol[stock_code] + vol)
            new_vol = deal_buy.stocks_hold_vol[stock_code] + vol

            DBUtils.update_my_stock_poll(stock_code, new_buy_price, new_vol)
        else:
            DBUtils.insert_my_stock_poll(stock_code, buy_price, vol)

        return 1
    return 0
Example #11
0
def Black_Jack_Baby():
    Main_menu()
    game_on = True
    while game_on:
        Betting()
        Deal.initial_deal()
        hitting = True
        while hitting:
            if sum(Deal.player_cards[1:]) >= 21:
                break
            try:
                a = int(input('Would you like to hit or stay?\n(1)Hit\n(2)Stay\n'))
                if a == 1:
                    Deal.player_draw()
                    pass
                elif a == 2:
                    break
                else:
                    pass
            except ValueError:
                print('An error occurred.')
                pass

        Deal.computer_draw_1st()
        Deal.computer_draw_else()
        Check_win()
        if balance.balance == 0:
            print('You Lose')
            Black_Jack_Baby()
        play_again = True
        while play_again:
            try:
                b = int(input('Would you like to play again?\n(1)yes\n(2)no\n'))
                if b == 1:
                    break
                elif b == 2:
                    Black_Jack_Baby()
                else:
                    pass
            except ValueError:
                print('An error occurred.')
                pass
Example #12
0
def index(request):
    num_deals = int(request.GET.get('num_deals', NUM_DEFAULT))
    ### TEMP
    show_filters = bool(request.GET.get('filters',False))
    err_msg = None
    show_minus = show_plus = True
    response = HttpResponse

    if num_deals < 1:
        num_deals = NUM_DEFAULT
        err_msg = 'Too few deals specified!  Defaulting to %s.' % num_deals
        response = HttpResponseBadRequest
    elif num_deals - 5 < 1:
        show_minus = False
    #elif num_deals + 5 > MAX_DEALS:
    #    show_plus = False
    elif num_deals > MAX_DEALS:
        num_deals = MAX_DEALS
        err_msg = 'Too many deals specified!  Defaulting to %s.  To see more, contact kevin-at-pheared-dot-net' % MAX_DEALS
        response = HttpResponseBadRequest

    latest_deals = Deal.getDeals(num=num_deals)

    feed_list = models.getFeeds()

    t = loader.get_template('dealviewer/index.html')
    c = Context({
        'page_title': 'Deals!',
        'deal_list': latest_deals,
        'num_deals': num_deals,
        'err': err_msg,
        'show_minus': show_minus,
        'show_plus': show_plus,
        'show_filters': show_filters,
        'feed_list': feed_list
        })

    return response(t.render(c))
Example #13
0
def sell(stock_code, opdate, predict):

    deal = Deal.Deal(opdate)
    init_price = deal.stocks_buy_price[stock_code]
    hold_vol = deal.stocks_hold_vol[stock_code]
    hold_days = deal.stocks_hold_days[stock_code]

    stock_2_sell = DBUtils.select_stock_info(opdate, stock_code)

    if len(stock_2_sell) == 0:
        print('WARN: no stock info. wired. return. pls check')
        return -1

    sell_price = float(stock_2_sell[0][3])

    if sell_price > init_price * Utils.GOOD_THREADHOLD and hold_vol > 0:
        record_sell(deal, opdate, stock_code, init_price, sell_price, hold_vol,
                    'SELL', 'GOODSELL')
        return 1

    elif sell_price < init_price * Utils.BAD_THREADHOLD and hold_vol > 0:
        record_sell(deal, opdate, stock_code, init_price, sell_price, hold_vol,
                    'SELL', 'BADSELL')
        return 1

    elif hold_days >= Utils.OVER_DUE_DAYS and hold_vol > 0:
        record_sell(deal, opdate, stock_code, init_price, sell_price, hold_vol,
                    'OVERTIME', 'OVERTIMESELL')
        return 1

    elif predict == -1:
        record_sell(deal, opdate, stock_code, init_price, sell_price, hold_vol,
                    'Predict', 'PredictSell')
        return 1

    return 0
Example #14
0
def filter_main(sql_choose, start_dt, end_dt, slayer):
    # 建立数据库连接
    db = pymysql.connect(host='127.0.0.1',
                         user='******',
                         passwd='admin',
                         db='stock',
                         charset='utf8')
    cursor = db.cursor()

    #先更新持股天数
    sql_update_hold_days = 'update my_stock_pool w set w.hold_days = w.hold_days + 1'
    cursor.execute(sql_update_hold_days)
    db.commit()

    #先卖出
    deal = Deal.Deal()
    stock_pool_local = deal.stock_pool
    for stock in stock_pool_local:
        deal = Deal.Deal()
        init_price = deal.stock_map1[stock]
        hold_vol = deal.stock_map2[stock]
        hold_days = deal.stock_map3[stock]
        sql_sell_select = "select * from stock_price_day_list a where a.state_dt = '%s' and a.stock_code = '%s'" % (
            end_dt, stock)
        cursor.execute(sql_sell_select)
        done_set_sell_select = cursor.fetchall()
        if len(done_set_sell_select) == 0:
            continue
        sell_price = float(done_set_sell_select[0][3])

        if sell_price > init_price * 1.03 and hold_vol > 0:
            new_money_lock = deal.cur_money_lock - init_price * hold_vol
            new_money_rest = deal.cur_money_rest + sell_price * hold_vol
            new_capital = deal.cur_capital + (sell_price -
                                              init_price) * hold_vol
            new_profit = (sell_price - init_price) * hold_vol
            new_profit_rate = sell_price / init_price
            sql_sell_insert = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.2f','%.2f','%.2f','%s','%s','%.2f','%.2f','%.2f','%s','%s','%.2f')" % (
                new_capital, new_money_lock, new_money_rest, 'SELL', stock,
                hold_vol, new_profit, new_profit_rate, 'GOODSELL', end_dt,
                sell_price)
            cursor.execute(sql_sell_insert)
            db.commit()
            sql_sell_update = "delete from my_stock_pool where stock_code = '%s'" % (
                stock)
            cursor.execute(sql_sell_update)
            db.commit()
            continue

        if sell_price < init_price * 0.95 and hold_vol > 0:
            new_money_lock = deal.cur_money_lock - init_price * hold_vol
            new_money_rest = deal.cur_money_rest + sell_price * hold_vol
            new_capital = deal.cur_capital + (sell_price -
                                              init_price) * hold_vol
            new_profit = (sell_price - init_price) * hold_vol
            new_profit_rate = sell_price / init_price
            sql_sell_insert2 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.2f','%.2f','%.2f','%s','%s','%.2f','%.2f','%.2f','%s','%s','%.2f')" % (
                new_capital, new_money_lock, new_money_rest, 'SELL', stock,
                hold_vol, new_profit, new_profit_rate, 'BADSELL', end_dt,
                sell_price)
            cursor.execute(sql_sell_insert2)
            db.commit()
            sql_sell_update2 = "delete from my_stock_pool where stock_code = '%s'" % (
                stock)
            cursor.execute(sql_sell_update2)
            db.commit()
            sql_ban_insert = "insert into ban_list(stock_code) values ('%s')" % (
                stock)
            cursor.execute(sql_ban_insert)
            db.commit()
            continue

        if hold_days >= 5 and hold_vol > 0:
            new_money_lock = deal.cur_money_lock - init_price * hold_vol
            new_money_rest = deal.cur_money_rest + sell_price * hold_vol
            new_capital = deal.cur_capital + (sell_price -
                                              init_price) * hold_vol
            new_profit = (sell_price - init_price) * hold_vol
            new_profit_rate = sell_price / init_price
            sql_sell_insert3 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.2f','%.2f','%.2f','%s','%s','%.2f','%.2f','%.2f','%s','%s','%.2f')" % (
                new_capital, new_money_lock, new_money_rest, 'OVERTIME', stock,
                hold_vol, new_profit, new_profit_rate, 'OVERTIMESELL', end_dt,
                sell_price)
            cursor.execute(sql_sell_insert3)
            db.commit()
            sql_sell_update3 = "delete from my_stock_pool where stock_code = '%s'" % (
                stock)
            cursor.execute(sql_sell_update3)
            db.commit()
            continue

    deal_buy = Deal.Deal()
    #后买入
    if deal_buy.cur_money_rest > 20000:
        cursor.execute(sql_choose)
        done_set2 = cursor.fetchall()
        if len(done_set2) > 0:
            stock_pool_buy = [x[1] for x in done_set2]
            for stock_buy in stock_pool_buy:
                sql_stock_check = "SELECT * FROM stock_price_day_list a where stock_code = '%s' and state_dt >= '%s' and state_dt <= '%s' order by state_dt asc" % (
                    stock_buy, start_dt, end_dt)
                cursor.execute(sql_stock_check)
                done_set_check = cursor.fetchall()
                if len(done_set_check) > 34:
                    if stock_buy in deal_buy.ban_list:
                        continue
                    dc = DC.data_collect2(stock_buy, start_dt, end_dt)
                    if (dc.cnt_good_buy[-1] * dc.cnt_good_sell[-1]) / min(
                            1, (dc.cnt_bad_sell[-1] + dc.cnt_risk[-1])) < 1:
                        continue
                    score_list = []
                    resu_list = []
                    train = dc.data_train
                    target = dc.data_target
                    model = Sequential()
                    model.add(Dense(64, activation='linear', input_dim=14))
                    model.add(Dropout(0.5))
                    model.add(Dense(64, activation='sigmoid'))
                    model.add(Dropout(0.5))
                    model.add(Dense(1, activation='relu'))
                    sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
                    model.compile(loss='logcosh',
                                  optimizer=sgd,
                                  metrics=['accuracy'])
                    model.fit(train, target, epochs=1000)
                    score0 = model.evaluate(train, target, batch_size=128)
                    if float(score0[0]) > 0.5 or str(score0[0]) == 'nan':
                        continue
                    for i in range(5):
                        model.fit(train, target, epochs=5000)
                        score = model.evaluate(train, target, batch_size=128)
                        print('SCORE:' + str(score[0]))
                        test_case = np.array([dc.test_case])
                        ans2 = model.predict(test_case)
                        resu_list.append(ans2[0][0])
                        score_list.append(score)
                        print('RESU  ' + str(i + 1) + '  :  ' +
                              str(ans2[0][0]))
                        dc.refreshDATA(ans2[0][0])
                        train = dc.data_train
                        target = dc.data_target
                    print(score_list)
                    print(resu_list)

                    if max(resu_list) > dc.avg[-6] * 1.05 and (
                            sum(resu_list) / 5) > dc.avg[-6] * 1.02:
                        vol, rest = divmod(min(deal_buy.cur_money_rest, 20000),
                                           dc.close_list[-6] * 100)
                        vol = vol * 100
                        sql_buy_update2 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,state_dt,deal_price,score)VALUES ('%.2f', '%.2f', '%.2f','%s','%s','%i','%s','%.2f','%i')" % (
                            deal_buy.cur_capital - vol * dc.close_list[-6] *
                            0.0005, deal_buy.cur_money_lock +
                            vol * dc.close_list[-6], deal_buy.cur_money_rest -
                            vol * dc.close_list[-6] * 1.0005, 'buy', stock_buy,
                            vol, end_dt, dc.close_list[-6], slayer)
                        cursor.execute(sql_buy_update2)
                        db.commit()
                        if stock_buy in deal_buy.stock_all:
                            new_buy_price = (
                                deal_buy.stock_map1[stock_buy] *
                                deal_buy.stock_map2[stock_buy] +
                                vol * dc.close_list[-6]) / (
                                    deal_buy.stock_map2[stock_buy] + vol)
                            new_vol = deal_buy.stock_map2[stock_buy] + vol
                            sql_buy_update3 = "update my_stock_pool w set w.buy_price = (select '%.2f' from dual) where w.stock_code = '%s'" % (
                                new_buy_price, stock_buy)
                            sql_buy_update3b = "update my_stock_pool w set w.hold_vol = (select '%i' from dual) where w.stock_code = '%s'" % (
                                new_vol, stock_buy)
                            sql_buy_update3c = "update my_stock_pool w set w.hold_days = (select '%i' from dual) where w.stock_code = '%s'" % (
                                1, stock_buy)
                            cursor.execute(sql_buy_update3)
                            cursor.execute(sql_buy_update3b)
                            cursor.execute(sql_buy_update3c)
                            db.commit()
                        else:
                            sql_buy_update3 = "insert into my_stock_pool(stock_code,buy_price,hold_vol,hold_days) VALUES ('%s','%.2f','%i','%i')" % (
                                stock_buy, dc.close_list[-6], vol, int(1))
                            cursor.execute(sql_buy_update3)
                            db.commit()
                        break
    db.close()
Example #15
0
def filter_main(start_dt, end_dt):
    # 建立数据库连接
    db = pymysql.connect(host='127.0.0.1',
                         user='******',
                         passwd='admin',
                         db='stock',
                         charset='utf8')
    cursor = db.cursor()

    #先更新持股天数
    sql_update_hold_days = 'update my_stock_pool w set w.hold_days = w.hold_days + 1'
    cursor.execute(sql_update_hold_days)
    db.commit()

    #先卖出
    deal = Deal.Deal()
    for stock in deal.stock_pool:
        init_price = deal.stock_map1[stock]
        hold_vol = deal.stock_map2[stock]
        hold_days = deal.stock_map3[stock]
        sell_price_temp = ts.get_k_data(code=stock, start=start_dt, end=end_dt)
        sell_price_list = np.array(sell_price_temp.iloc[0:,
                                                        [2]].astype('float32'),
                                   dtype=np.float).ravel()
        sell_price = sell_price_list[-1]

        if sell_price > init_price * 1.03 and hold_vol > 0:
            new_money_lock = deal.cur_money_lock - init_price * hold_vol
            new_money_rest = deal.cur_money_rest + sell_price * hold_vol
            new_capital = deal.cur_capital + (sell_price -
                                              init_price) * hold_vol
            new_profit = (sell_price - init_price) * hold_vol
            new_profit_rate = sell_price / init_price
            sql_sell_insert = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%f','%f','%f','%s','%s','%f','%f','%f','%s','%s','%f')" % (
                new_capital, new_money_lock, new_money_rest, 'SELL', stock,
                hold_vol, new_profit, new_profit_rate, 'GOODSELL', end_dt,
                sell_price)
            cursor.execute(sql_sell_insert)
            db.commit()
            sql_sell_update = "delete from my_stock_pool where stock_code = '%s'" % (
                stock)
            cursor.execute(sql_sell_update)
            db.commit()
            continue

        if sell_price < init_price * 0.95 and hold_vol > 0:
            new_money_lock = deal.cur_money_lock - init_price * hold_vol
            new_money_rest = deal.cur_money_rest + sell_price * hold_vol
            new_capital = deal.cur_capital + (sell_price -
                                              init_price) * hold_vol
            new_profit = (sell_price - init_price) * hold_vol
            new_profit_rate = sell_price / init_price
            sql_sell_insert2 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%f','%f','%f','%s','%s','%f','%f','%f','%s','%s','%f')" % (
                new_capital, new_money_lock, new_money_rest, 'SELL', stock,
                hold_vol, new_profit, new_profit_rate, 'BADSELL', end_dt,
                sell_price)
            cursor.execute(sql_sell_insert2)
            db.commit()
            sql_sell_update2 = "delete from my_stock_pool where stock_code = '%s'" % (
                stock)
            cursor.execute(sql_sell_update2)
            db.commit()
            sql_ban_insert = "insert into ban_list(stock_code) values ('%s')" % (
                stock)
            cursor.execute(sql_ban_insert)
            db.commit()
            continue

        if hold_days >= 5 and hold_vol > 0:
            new_money_lock = deal.cur_money_lock - init_price * hold_vol
            new_money_rest = deal.cur_money_rest + sell_price * hold_vol
            new_capital = deal.cur_capital + (sell_price -
                                              init_price) * hold_vol
            new_profit = (sell_price - init_price) * hold_vol
            new_profit_rate = sell_price / init_price
            sql_sell_insert3 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%f','%f','%f','%s','%s','%f','%f','%f','%s','%s','%f')" % (
                new_capital, new_money_lock, new_money_rest, 'OVERTIME', stock,
                hold_vol, new_profit, new_profit_rate, 'OVERTIMESELL', end_dt,
                sell_price)
            cursor.execute(sql_sell_insert3)
            db.commit()
            sql_sell_update3 = "delete from my_stock_pool where stock_code = '%s'" % (
                stock)
            cursor.execute(sql_sell_update3)
            db.commit()
            continue

    deal_buy = Deal.Deal()
    #后买入
    if deal_buy.cur_money_rest > 20000:
        #Choose.choose_main(start_dt, end_dt)
        try:
            resu_list = []
            score_list = []
            #sql_select = "select a.stock_code from q1_cs a where a.calc_date ='%s' order by af/freq desc limit 10" %(end_dt)
            sql_select = "select a.stock_code from q1_cs a order by af/freq desc limit 50"
            cursor.execute(sql_select)
            done_set2 = cursor.fetchall()
            for row in done_set2:
                if row[0] in deal_buy.ban_list:
                    continue
                dc = DC.data_collect2(row[0], start_dt, end_dt)
                if (dc.cnt_good_buy[-1] * dc.cnt_good_sell[-1]) / min(
                        1, (dc.cnt_bad_sell[-1] + dc.cnt_risk[-1])) < 1:
                    continue
                score_list = []
                resu_list = []
                train = dc.data_train
                target = dc.data_target
                model = Sequential()
                model.add(Dense(64, activation='linear', input_dim=13))
                model.add(Dropout(0.5))
                model.add(Dense(64, activation='sigmoid'))
                model.add(Dropout(0.5))
                model.add(Dense(1, activation='relu'))
                sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
                model.compile(loss='logcosh',
                              optimizer=sgd,
                              metrics=['accuracy'])
                model.fit(train, target, epochs=1000)
                score0 = model.evaluate(train, target, batch_size=128)
                if float(score0[0]) > 0.5 or str(score0[0]) == 'nan':
                    continue
                for i in range(5):
                    model.fit(train, target, epochs=5000)
                    score = model.evaluate(train, target, batch_size=128)
                    print('SCORE:' + str(score[0]))
                    test_case = np.array([dc.test_case])
                    ans2 = model.predict(test_case)
                    resu_list.append(ans2[0][0])
                    score_list.append(score)
                    print('RESU  ' + str(i + 1) + '  :  ' + str(ans2[0][0]))
                    dc.refreshDATA(ans2[0][0])
                    train = dc.data_train
                    target = dc.data_target
                print(score_list)
                print(resu_list)

                if max(resu_list) > dc.avg[-6] * 1.05 and (
                        sum(resu_list) / 5) > dc.avg[-6] * 1.02:
                    vol, rest = divmod(min(deal_buy.cur_money_rest, 30000),
                                       dc.list_close[-6] * 100)
                    vol = vol * 100
                    sql_buy_update2 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,state_dt,deal_price)VALUES ('%f', '%f', '%f','%s','%s','%i','%s','%f')" % (
                        deal_buy.cur_capital -
                        vol * dc.list_close[-6] * 0.0005,
                        deal_buy.cur_money_lock + vol * dc.list_close[-6],
                        deal_buy.cur_money_rest - vol * dc.list_close[-6] *
                        1.0005, 'buy', row[0], vol, end_dt, dc.list_close[-6])
                    cursor.execute(sql_buy_update2)
                    db.commit()
                    if row[0] in deal_buy.stock_all:
                        new_buy_price = (deal_buy.stock_map1[row[0]] *
                                         deal_buy.stock_map2[row[0]] +
                                         vol * dc.list_close[-6]) / (
                                             deal_buy.stock_map2[row[0]] + vol)
                        new_vol = deal_buy.stock_map2[row[0]] + vol
                        sql_buy_update3 = "update my_stock_pool w set w.buy_price = (select '%f' from dual) where w.stock_code = '%s'" % (
                            new_buy_price, row[0])
                        sql_buy_update3b = "update my_stock_pool w set w.hold_vol = (select '%i' from dual) where w.stock_code = '%s'" % (
                            new_vol, row[0])
                        sql_buy_update3c = "update my_stock_pool w set w.hold_days = (select '%i' from dual) where w.stock_code = '%s'" % (
                            1, row[0])
                        cursor.execute(sql_buy_update3)
                        cursor.execute(sql_buy_update3b)
                        cursor.execute(sql_buy_update3c)
                        db.commit()
                    else:
                        sql_buy_update3 = "insert into my_stock_pool(stock_code,buy_price,hold_vol,hold_days) VALUES ('%s','%f','%i','%i')" % (
                            row[0], dc.list_close[-6], vol, int(1))
                        cursor.execute(sql_buy_update3)
                        db.commit()
                    break

        except Exception as excp:
            #db.rollback()
            print(excp)
    db.close()
Example #16
0
def sell(stock_code, opdate, predict):
    # 建立数据库连接
    db = pymysql.connect(host='127.0.0.1',
                         user='******',
                         passwd='000109',
                         db='stock_list',
                         charset='utf8')
    cursor = db.cursor()

    deal = Deal.Deal(opdate)
    init_price = deal.stock_map1[stock_code]
    hold_vol = deal.stock_map2[stock_code]
    hold_days = deal.stock_map3[stock_code]
    sql_sell_select = "select * from stock_info a where a.state_dt = '%s' and a.stock_code = '%s'" % (
        opdate, stock_code)
    cursor.execute(sql_sell_select)
    done_set_sell_select = cursor.fetchall()
    if len(done_set_sell_select) == 0:
        return -1
    sell_price = float(done_set_sell_select[0][3])

    if sell_price > init_price * 1.03 and hold_vol > 0:
        new_money_lock = deal.cur_money_lock - sell_price * hold_vol
        new_money_rest = deal.cur_money_rest + sell_price * hold_vol
        new_capital = deal.cur_capital + (sell_price - init_price) * hold_vol
        new_profit = (sell_price - init_price) * hold_vol
        new_profit_rate = sell_price / init_price
        sql_sell_insert = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.2f','%.2f','%.2f','%s','%s','%.2f','%.2f','%.2f','%s','%s','%.2f')" % (
            new_capital, new_money_lock, new_money_rest, 'SELL', stock_code,
            hold_vol, new_profit, new_profit_rate, 'GOODSELL', opdate,
            sell_price)
        cursor.execute(sql_sell_insert)
        db.commit()
        sql_sell_update = "delete from my_stock_pool where stock_code = '%s'" % (
            stock_code)
        cursor.execute(sql_sell_update)
        db.commit()
        db.close()
        return 1

    elif sell_price < init_price * 0.97 and hold_vol > 0:
        new_money_lock = deal.cur_money_lock - sell_price * hold_vol
        new_money_rest = deal.cur_money_rest + sell_price * hold_vol
        new_capital = deal.cur_capital + (sell_price - init_price) * hold_vol
        new_profit = (sell_price - init_price) * hold_vol
        new_profit_rate = sell_price / init_price
        sql_sell_insert2 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.2f','%.2f','%.2f','%s','%s','%.2f','%.2f','%.2f','%s','%s','%.2f')" % (
            new_capital, new_money_lock, new_money_rest, 'SELL', stock_code,
            hold_vol, new_profit, new_profit_rate, 'BADSELL', opdate,
            sell_price)
        cursor.execute(sql_sell_insert2)
        db.commit()
        sql_sell_update2 = "delete from my_stock_pool where stock_code = '%s'" % (
            stock_code)
        cursor.execute(sql_sell_update2)
        db.commit()
        # sql_ban_insert = "insert into ban_list(stock_code) values ('%s')" %(stock_code)
        # cursor.execute(sql_ban_insert)
        # db.commit()
        db.close()
        return 1

    elif hold_days >= 4 and hold_vol > 0:
        new_money_lock = deal.cur_money_lock - sell_price * hold_vol
        new_money_rest = deal.cur_money_rest + sell_price * hold_vol
        new_capital = deal.cur_capital + (sell_price - init_price) * hold_vol
        new_profit = (sell_price - init_price) * hold_vol
        new_profit_rate = sell_price / init_price
        sql_sell_insert3 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.2f','%.2f','%.2f','%s','%s','%.2f','%.2f','%.2f','%s','%s','%.2f')" % (
            new_capital, new_money_lock, new_money_rest, 'OVERTIME',
            stock_code, hold_vol, new_profit, new_profit_rate, 'OVERTIMESELL',
            opdate, sell_price)
        cursor.execute(sql_sell_insert3)
        db.commit()
        sql_sell_update3 = "delete from my_stock_pool where stock_code = '%s'" % (
            stock_code)
        cursor.execute(sql_sell_update3)
        db.commit()
        db.close()
        return 1

    elif predict == -1:
        new_money_lock = deal.cur_money_lock - sell_price * hold_vol
        new_money_rest = deal.cur_money_rest + sell_price * hold_vol
        new_capital = deal.cur_capital + (sell_price - init_price) * hold_vol
        new_profit = (sell_price - init_price) * hold_vol
        new_profit_rate = sell_price / init_price
        sql_sell_insert4 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.2f','%.2f','%.2f','%s','%s','%.2f','%.2f','%.2f','%s','%s','%.2f')" % (
            new_capital, new_money_lock, new_money_rest, 'Predict', stock_code,
            hold_vol, new_profit, new_profit_rate, 'PredictSell', opdate,
            sell_price)
        cursor.execute(sql_sell_insert4)
        db.commit()
        sql_sell_update3 = "delete from my_stock_pool where stock_code = '%s'" % (
            stock_code)
        cursor.execute(sql_sell_update3)
        db.commit()
        db.close()
        return 1
    db.close()
    return 0
Example #17
0
def filter_main(sql_choose, start_dt, end_dt, slayer):
    # 建立数据库连接
    db = pymysql.connect(host='127.0.0.1',
                         user='******',
                         passwd='admin',
                         db='stock',
                         charset='utf8')
    cursor = db.cursor()

    #先更新持股天数
    sql_update_hold_days = 'update my_stock_pool w set w.hold_days = w.hold_days + 1'
    cursor.execute(sql_update_hold_days)
    db.commit()

    #先卖出
    deal = Deal.Deal()
    stock_pool_local = deal.stock_pool
    for stock in stock_pool_local:
        ans = Operator.sell(stock, end_dt)

    #后买入
    deal_buy = Deal.Deal()
    if deal_buy.cur_money_rest > 20000:
        sql_ban_pool = "select distinct stock_code from ban_list"
        cursor.execute(sql_ban_pool)
        done_ban_pool = cursor.fetchall()
        ban_list = [x[0] for x in done_ban_pool]

        sql_first_pool = "select distinct stock_code from good_pool order by f1 desc"
        cursor.execute(sql_first_pool)
        done_good_pool = cursor.fetchall()
        good_pool = [x[0] for x in done_good_pool if x[0] not in ban_list]
        flag = 0
        for i in range(len(good_pool)):
            acc, recall, acc_neg, f1 = MyModel.svm_test(good_pool[i], end_dt)
            if acc >= 0.6 and f1 >= 0.5:
                sql_insert_good_pool = "insert into good_pool(state_dt,stock_code,acc,recall,f1,acc_neg)values('%s','%s','%.4f','%.4f','%.4f','%.4f')" % (
                    end_dt, good_pool[i], acc, recall, f1, acc_neg)
                cursor.execute(sql_insert_good_pool)
                db.commit()
                ans = MyModel.svm_predict(good_pool[i], end_dt)
                if ans == 1.00:
                    ans = Operator.buy(good_pool[i], end_dt, 20000, slayer)
                    flag = 1
                    break
        deal_buy = Deal.Deal()
        if flag == 0 and deal_buy.cur_money_rest >= 20000:
            cursor.execute(sql_choose)
            done_set2 = cursor.fetchall()
            if len(done_set2) > 0:
                temp_stock_pool_buy = [
                    x[1] for x in done_set2 if x[1] not in good_pool
                ]
                stock_pool_buy = [
                    x for x in temp_stock_pool_buy if x not in ban_list
                ]
                for stock_buy in stock_pool_buy:

                    acc, recall, acc_neg, f1 = MyModel.svm_test(
                        stock_buy, end_dt)
                    if acc >= 0.6 and f1 >= 0.5:
                        sql_insert_good_pool = "insert into good_pool(state_dt,stock_code,acc,recall,f1,acc_neg)values('%s','%s','%.4f','%.4f','%.4f','%.4f')" % (
                            end_dt, stock_buy, acc, recall, f1, acc_neg)
                        cursor.execute(sql_insert_good_pool)
                        db.commit()
                        ans = MyModel.svm_predict(stock_buy, end_dt)
                        if ans == 1.00:
                            ans = Operator.buy(stock_buy, end_dt, 20000,
                                               slayer)
    db.close()
Example #18
0
def sell(stock_code, opdate, predict):
    # 建立数据库连接
    db = pymysql.connect(host='localhost',
                         user='******',
                         passwd='jiage',
                         db='Stocks',
                         charset='utf8mb4')
    cursor = db.cursor()

    deal = Deal.Deal(opdate)
    init_price = deal.stock_map1[stock_code]
    hold_vol = deal.stock_map2[stock_code]
    hold_days = deal.stock_map3[stock_code]
    sql_sell_select = "select * from stock_info a where a.state_dt = '%s' and a.stock_code = '%s'" % (
        opdate, stock_code)
    cursor.execute(sql_sell_select)
    done_set_sell_select = cursor.fetchall()
    if len(done_set_sell_select) == 0:
        return -1
    sell_price = float(done_set_sell_select[0][3])

    # 市值增幅超过4%止盈
    # 平仓手续费约为0.16%
    if sell_price > init_price * 1.04 and hold_vol > 0:
        new_money_lock = deal.cur_money_lock - sell_price * hold_vol
        new_money_rest = deal.cur_money_rest + sell_price * hold_vol * 0.9984
        new_capital = new_money_lock + new_money_rest
        new_profit = (sell_price * 0.9984 - init_price * 1.0005) * hold_vol
        new_profit_rate = sell_price * 0.9984 / (init_price * 1.0005)
        sql_sell_insert = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.02f','%.2f','%.02f','%s','%s','%d','%.2f','%.04f','%s','%s','%.02f')" %\
                          (new_capital, new_money_lock, new_money_rest, 'SELL', stock_code, hold_vol, new_profit, new_profit_rate, 'GOODSELL', opdate, sell_price)
        cursor.execute(sql_sell_insert)
        db.commit()

        sql_sell_update = "delete from my_stock_pool where stock_code = '%s'" % (
            stock_code)
        cursor.execute(sql_sell_update)
        db.commit()
        db.close()
        return 1

    # 市值跌幅超过3%止损
    elif sell_price < init_price * 0.97 and hold_vol > 0:
        new_money_lock = deal.cur_money_lock - sell_price * hold_vol
        new_money_rest = deal.cur_money_rest + sell_price * hold_vol * 0.9984
        new_capital = new_money_lock + new_money_rest
        new_profit = (sell_price * 0.9984 - init_price * 1.0005) * hold_vol
        new_profit_rate = sell_price * 0.9984 / (init_price * 1.0005)
        sql_sell_insert2 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.02f','%.2f','%.02f','%s','%s','%d','%.2f','%.04f','%s','%s','%.02f')" %\
                           (new_capital, new_money_lock, new_money_rest, 'SELL', stock_code, hold_vol, new_profit, new_profit_rate, 'BADSELL', opdate, sell_price)
        cursor.execute(sql_sell_insert2)
        db.commit()
        sql_sell_update2 = "delete from my_stock_pool where stock_code = '%s'" % (
            stock_code)
        cursor.execute(sql_sell_update2)
        db.commit()

        db.close()
        return 1

    # 持仓超过4个交易日强行平仓
    elif hold_days >= 4 and hold_vol > 0:
        new_money_lock = deal.cur_money_lock - sell_price * hold_vol
        new_money_rest = deal.cur_money_rest + sell_price * hold_vol * 0.9984
        new_capital = new_money_lock + new_money_rest
        new_profit = (sell_price * 0.9984 - init_price * 1.0005) * hold_vol
        new_profit_rate = sell_price * 0.9984 / (init_price * 1.0005)
        sql_sell_insert3 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.02f','%.2f','%.02f','%s','%s','%d','%.2f','%.04f','%s','%s','%.02f')" %\
                           (new_capital, new_money_lock, new_money_rest, 'OVERTIME', stock_code, hold_vol, new_profit, new_profit_rate, 'OVERTIMESELL', opdate, sell_price)
        cursor.execute(sql_sell_insert3)
        db.commit()
        sql_sell_update3 = "delete from my_stock_pool where stock_code = '%s'" % (
            stock_code)
        cursor.execute(sql_sell_update3)
        db.commit()
        db.close()
        return 1

    # 如果预测下跌,则卖出
    elif predict == -1 and hold_vol > 0:
        new_money_lock = deal.cur_money_lock - sell_price * hold_vol
        new_money_rest = deal.cur_money_rest + sell_price * hold_vol * 0.9984
        new_capital = new_money_lock + new_money_rest
        new_profit = (sell_price * 0.9984 - init_price * 1.0005) * hold_vol
        new_profit_rate = sell_price * 0.9984 / (init_price * 1.0005)
        sql_sell_insert4 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.02f','%.2f','%.02f','%s','%s','%d','%.2f','%.04f','%s','%s','%.02f')" % (
            new_capital, new_money_lock, new_money_rest, 'Predict', stock_code,
            hold_vol, new_profit, new_profit_rate, 'PredictSell', opdate,
            sell_price)
        cursor.execute(sql_sell_insert4)
        db.commit()
        sql_sell_update3 = "delete from my_stock_pool where stock_code = '%s'" % (
            stock_code)
        cursor.execute(sql_sell_update3)
        db.commit()
        db.close()
        return 1

    db.close()
    return 0
Example #19
0
def create_and_save_all_users(cookie_limit: int or None = None):
    """
    Creates a user objects and saves them into a pickle files by a certain amount
    Filters users with outlier amount of events or employee ids
    """

    unique_cookies = sql_handler.fetch_unique_user_cookies(limit=cookie_limit)
    employee_ids = sql_handler.fetch_employee_ids()

    categories = Category.Category.load_categories()
    deals = Deal.load_all_deals()

    print('Gathered {} unique cookies representing users'.format(
        len(unique_cookies)))
    all_users = []
    pickle_file_counter = 1

    # load pre-processed data
    event_amount_outliers = load_outlier_borders()
    event_duration_medians = load_event_medians()

    # create new users
    with sql_handler.BehaviourDatabaseCursor() as db_cursor:
        for cookie in unique_cookies:

            new_user = User(db_cursor, cookie, event_amount_outliers,
                            employee_ids, event_duration_medians, categories,
                            deals)

            # filtering users
            if new_user.remove_flag:
                continue

            all_users.append(new_user)

            if len(all_users) == cfg.pickle_wrap_amount:

                save_range_start = (pickle_file_counter -
                                    1) * cfg.pickle_wrap_amount
                save_range_end = pickle_file_counter * cfg.pickle_wrap_amount
                print(f'Saving users {save_range_start}-{save_range_end}')

                pickle_filename = cfg.pickle_baseline_filename_users + str(
                    pickle_file_counter)

                with open(path.join(getcwd(), cfg.dir_users, pickle_filename),
                          'wb') as pickle_file:
                    pickle.dump(obj=all_users, file=pickle_file)

                all_users = []
                pickle_file_counter += 1

        # save last < pickle_amount users
        pickle_filename = cfg.pickle_baseline_filename_users + str(
            pickle_file_counter)

        print(f'Saving last {len(all_users)} users')

        print(all_users[0])

        with open(path.join(getcwd(), cfg.dir_users, pickle_filename),
                  'wb') as pickle_file:
            pickle.dump(obj=all_users, file=pickle_file)
Example #20
0
def sell(stock_code, opdate, predict):
    ##################################################
    # 建立数据库连接,设置tushare的token,定义一些初始化参数
    env = get_env()
    db, cursor, pro = env.db, env.cursor, env.pro
    ##################################################
    deal = Deal.Deal(opdate)
    init_price = deal.stock_map1[stock_code]
    hold_vol = deal.stock_map2[stock_code]
    hold_days = deal.stock_map3[stock_code]
    sql_sell_select = "select * from stock_all_plus a where a.state_dt = '%s' and a.stock_code = '%s'" % (
        opdate, stock_code)
    cursor.execute(sql_sell_select)
    done_set_sell_select = cursor.fetchall()
    if len(done_set_sell_select) == 0:
        return -1
    sell_price = float(done_set_sell_select[0][3])
    #跌停无法卖出
    if done_set_sell_select[0][10] < -9.9:
        print "跌停无法卖出:%s" % str(done_set_sell_select)
        return -1
    if sell_price > init_price * (1 + bt.torlence_profit) and hold_vol > 0:
        new_money_lock = deal.cur_money_lock - sell_price * hold_vol
        if new_money_lock < 0:
            print "deal.cur_money_lock:%f,new_money_lock:%f,sell_price:%f,hold_vol:%d" % (
                deal.cur_money_lock, new_money_lock, sell_price, hold_vol)
            x = raw_input('profit error....')
        new_money_rest = deal.cur_money_rest + sell_price * hold_vol
        new_capital = deal.cur_capital + (sell_price - init_price) * hold_vol
        new_profit = (sell_price - init_price) * hold_vol
        new_profit_rate = sell_price / init_price
        sql_sell_insert = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.2f','%.2f','%.2f','%s','%s','%.2f','%.2f','%.2f','%s','%s','%.2f')" % (
            new_capital, new_money_lock, new_money_rest, 'SELL', stock_code,
            hold_vol, new_profit, new_profit_rate, 'GOODSELL', opdate,
            sell_price)
        cursor.execute(sql_sell_insert)
        db.commit()
        sql_sell_update = "delete from my_stock_pool where stock_code = '%s'" % (
            stock_code)
        cursor.execute(sql_sell_update)
        db.commit()
        db.close()
        return 1

    elif sell_price < init_price * (1 - bt.torlence_lost) and hold_vol > 0:
        new_money_lock = deal.cur_money_lock - sell_price * hold_vol
        if new_money_lock < 0:
            print "deal.cur_money_lock:%f,new_money_lock:%f,sell_price:%f,hold_vol:%d" % (
                deal.cur_money_lock, new_money_lock, sell_price, hold_vol)
            x = raw_input('lost error....')
        new_money_rest = deal.cur_money_rest + sell_price * hold_vol
        new_capital = deal.cur_capital + (sell_price - init_price) * hold_vol
        new_profit = (sell_price - init_price) * hold_vol
        new_profit_rate = sell_price / init_price
        sql_sell_insert2 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.2f','%.2f','%.2f','%s','%s','%.2f','%.2f','%.2f','%s','%s','%.2f')" % (
            new_capital, new_money_lock, new_money_rest, 'SELL', stock_code,
            hold_vol, new_profit, new_profit_rate, 'BADSELL', opdate,
            sell_price)
        cursor.execute(sql_sell_insert2)
        db.commit()
        sql_sell_update2 = "delete from my_stock_pool where stock_code = '%s'" % (
            stock_code)
        cursor.execute(sql_sell_update2)
        db.commit()
        # sql_ban_insert = "insert into ban_list(stock_code) values ('%s')" %(stock_code)
        # cursor.execute(sql_ban_insert)
        # db.commit()
        db.close()
        return 1

    elif hold_days >= bt.hold_days and hold_vol > 0:
        new_money_lock = deal.cur_money_lock - sell_price * hold_vol
        if new_money_lock < 0:
            print "deal.cur_money_lock:%f,new_money_lock:%f,sell_price:%f,hold_vol:%d" % (
                deal.cur_money_lock, new_money_lock, sell_price, hold_vol)
            x = raw_input('hold days  error....')
        new_money_rest = deal.cur_money_rest + sell_price * hold_vol
        new_capital = deal.cur_capital + (sell_price - init_price) * hold_vol
        new_profit = (sell_price - init_price) * hold_vol
        new_profit_rate = sell_price / init_price
        sql_sell_insert3 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.2f','%.2f','%.2f','%s','%s','%.2f','%.2f','%.2f','%s','%s','%.2f')" % (
            new_capital, new_money_lock, new_money_rest, 'OVERTIME',
            stock_code, hold_vol, new_profit, new_profit_rate, 'OVERTIMESELL',
            opdate, sell_price)
        cursor.execute(sql_sell_insert3)
        db.commit()
        sql_sell_update3 = "delete from my_stock_pool where stock_code = '%s'" % (
            stock_code)
        cursor.execute(sql_sell_update3)
        db.commit()
        db.close()
        return 1

    elif predict == -1:
        new_money_lock = deal.cur_money_lock - sell_price * hold_vol
        new_money_rest = deal.cur_money_rest + sell_price * hold_vol
        new_capital = deal.cur_capital + (sell_price - init_price) * hold_vol
        new_profit = (sell_price - init_price) * hold_vol
        new_profit_rate = sell_price / init_price
        sql_sell_insert4 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,profit,profit_rate,bz,state_dt,deal_price)values('%.2f','%.2f','%.2f','%s','%s','%.2f','%.2f','%.2f','%s','%s','%.2f')" % (
            new_capital, new_money_lock, new_money_rest, 'Predict', stock_code,
            hold_vol, new_profit, new_profit_rate, 'PredictSell', opdate,
            sell_price)
        cursor.execute(sql_sell_insert4)
        db.commit()
        sql_sell_update3 = "delete from my_stock_pool where stock_code = '%s'" % (
            stock_code)
        cursor.execute(sql_sell_update3)
        db.commit()
        db.close()
        return 1
    db.close()
    return 0
Example #21
0
def buy(stock_code, opdate, buy_money):
    ##################################################
    # 建立数据库连接,设置tushare的token,定义一些初始化参数
    env = get_env()
    db, cursor, pro = env.db, env.cursor, env.pro
    ##################################################
    deal_buy = Deal.Deal(opdate)
    print "deal_buy info:deal_buy.rest:%s,deal_buy.cur_capital:%s" % (str(
        deal_buy.cur_money_rest), str(deal_buy.cur_capital))
    print 'buy_money: ', buy_money
    #后买入
    if deal_buy.cur_money_rest + 1 >= buy_money:
        print "deal_buy.cur_money_rest+1  : ", deal_buy.cur_money_rest + 1, "    buy_money: ", buy_money
        sql_buy = "select * from stock_all_plus a where a.state_dt = '%s' and a.stock_code = '%s'" % (
            opdate, stock_code)
        cursor.execute(sql_buy)
        done_set_buy = cursor.fetchall()
        print done_set_buy, 'donesetbuy'
        if len(done_set_buy) == 0:
            return -1
        #剔除涨跌停因素
        if done_set_buy[0][10] > 9.9:
            print "涨停无法买入:%s" % str(done_set_buy)
            return -1
        buy_price = float(done_set_buy[0][3])
        print "buy_price", buy_price
        # if buy_price >= 195:
        #     return 0
        vol, rest = divmod(min(deal_buy.cur_money_rest, buy_money),
                           buy_price * 100)
        print "vol, rest:", vol, rest
        vol = vol * 100
        if vol == 0:
            return 0
        new_capital = deal_buy.cur_capital - vol * buy_price * 0.0005
        new_money_lock = deal_buy.cur_money_lock + vol * buy_price
        new_money_rest = deal_buy.cur_money_rest - vol * buy_price * 1.0005
        sql_buy_update2 = "insert into my_capital(capital,money_lock,money_rest,deal_action,stock_code,stock_vol,state_dt,deal_price)VALUES ('%.2f', '%.2f', '%.2f','%s','%s','%i','%s','%.2f')" % (
            new_capital, new_money_lock, new_money_rest, 'buy', stock_code,
            vol, opdate, buy_price)
        print "sql_buy_update2: ", sql_buy_update2
        cursor.execute(sql_buy_update2)
        db.commit()
        if stock_code in deal_buy.stock_all:
            new_buy_price = (deal_buy.stock_map1[stock_code] *
                             deal_buy.stock_map2[stock_code] + vol * buy_price
                             ) / (deal_buy.stock_map2[stock_code] + vol)
            new_vol = deal_buy.stock_map2[stock_code] + vol
            sql_buy_update3 = "update my_stock_pool w set w.buy_price = (select '%.2f' from dual) where w.stock_code = '%s'" % (
                new_buy_price, stock_code)
            sql_buy_update3b = "update my_stock_pool w set w.hold_vol = (select '%i' from dual) where w.stock_code = '%s'" % (
                new_vol, stock_code)
            sql_buy_update3c = "update my_stock_pool w set w.hold_days = (select '%i' from dual) where w.stock_code = '%s'" % (
                1, stock_code)
            cursor.execute(sql_buy_update3)
            cursor.execute(sql_buy_update3b)
            cursor.execute(sql_buy_update3c)
            db.commit()
        else:
            sql_buy_update3 = "insert into my_stock_pool(stock_code,buy_price,hold_vol,hold_days) VALUES ('%s','%.2f','%i','%i')" % (
                stock_code, buy_price, vol, int(1))
            cursor.execute(sql_buy_update3)
            db.commit()
        db.close()
        return 1
    db.close()
    return 0