示例#1
0
def profit():
    overall_history_amount = 0.0
    overall_history_profit = 0.0
    overall_current_amount = 0.0
    overall_current_profit = 0.0
    for stock in stockdata.all_stocks_1:
        if stock.has_key('trades'):
            code = stock['code']
            #print 'Getting realtime quotes...'
            df = ts.get_realtime_quotes(code)
            today_price = float(df['price'][0])
            print code + ' ' + df['name'][0]

            history_amount = 0.0
            history_profit = 0.0
            current_amount = 0.0
            current_profit = 0.0
            for trade in stock['trades']:
                theDate = dateutil2.parse_date(trade[0])
                direction = trade[1]
                volume = trade[2]
                price = trade[3]
                if direction == 2 or len(trade) > 4:
                    theSellDate = dateutil2.parse_date(trade[4])
                    sellPrice = trade[5]
                    history_amount += price * volume
                    history_profit += (sellPrice - price) * volume
                if direction == 1:
                    current_amount += price * volume
                    current_profit += (today_price - price) * volume

            if history_amount != 0.0:
                print '历史: %s/%s \t%5.2f%%' % (
                    str(history_amount), str(history_profit),
                    history_profit / history_amount * 100)
            if current_amount != 0.0:
                print '持仓: %s/%s \t%5.2f%%' % (
                    str(current_amount), str(current_profit),
                    current_profit / current_amount * 100)

            overall_history_amount += history_amount
            overall_history_profit += history_profit
            overall_current_amount += current_amount
            overall_current_profit += current_profit

            print ''

    print '\n\n'
    if overall_history_amount != 0.0:
        print '历史: %s/%s \t%5.2f%%' % (
            str(overall_history_amount), str(overall_history_profit),
            overall_history_profit / overall_history_amount * 100)
    if overall_current_amount != 0.0:
        print '持仓: %s/%s \t%5.2f%%' % (
            str(overall_current_amount), str(overall_current_profit),
            overall_current_profit / overall_current_amount * 100)
示例#2
0
def previous_data_with_date(code, datestr, log, recursive=False):

    # mem cache
    codedate = code + '__' + datestr
    if dayK_cache.has_key(codedate):
        return dayK_cache[codedate]

    originDateStr = datestr
    dh = dbman.query_dayK(code, datestr)

    if len(dh) == 0:
        log('Getting hist data for %s at %s' % (code, datestr))
        df = ts.get_hist_data(code, start=datestr, end=datestr)
        print 'x'
        log('Done hist data for %s at %s' % (code, datestr))
        d = dateutil2.parse_date(datestr)
        if df is None or df.empty:
            if not recursive:
                return None
            d = dateutil2.previous_date(d)
            datestr = dateutil2.format_date(d)
            #df = ts.get_hist_data(code, start=datestr, end=datestr)
            log('Nest previous_data_with_date call %s %s' % (code, datestr))
            dh = previous_data_with_date(code, datestr, log)
            dbman.insert_dayK(code, False, originDateStr, dh['open'],
                              dh['close'], dh['high'], dh['low'])
        else:
            dbman.insert_dayK(code, True, originDateStr, df['open'][0],
                              df['close'][0], df['high'][0], df['low'][0])
        dh = dbman.query_dayK(code, originDateStr)

    dayK_cache[codedate] = dh[0]
    return dh[0]
示例#3
0
def last_trade(code):
    print 'Getting realtime quotes...'
    df = ts.get_realtime_quotes(code)
    today_price = float(df['price'][0])
    print code + ' ' + df['name'][0]
    for stock in stockdata.all_stocks_1:
        if stock['code'] == code and stock.has_key('trades'):
            last_buy_date = date.min
            last_buy = 0.0
            last_buy_position = 0
            for trade in stock['trades']:
                theDate = dateutil2.parse_date(trade[0])
                direction = trade[1]
                volume = trade[2]
                price = trade[3]
                if direction == 1 and theDate >= last_buy_date:
                    last_buy_date = theDate
                    last_buy = price
                    last_buy_position = volume
            if last_buy != 0.0:
                print 'Last trade: ' + str(last_buy_date) + ' ' + str(
                    last_buy) + ' ' + str(last_buy_position)
                print '当前价: ' + str(today_price)
                print '盈利: ' + '%3.2f%%' % (
                    (today_price - last_buy) / last_buy * 100)
                high = get_high(code, last_buy_date)
                print ''
                print '最高价: ' + str(high)
                print '回撤: ' + '%2.0f%%' % ((high - today_price) /
                                            (high - last_buy) * 100)
示例#4
0
def compute_KDJ933(stock, theDate, close, high, low, real, log):
    baseKDJDateStr = stock['KDJ'].keys()[0]
    if dateutil2.parse_date(baseKDJDateStr) == theDate:
        #print 'hit'
        return (stock['KDJ'][baseKDJDateStr][0],
                stock['KDJ'][baseKDJDateStr][1],
                stock['KDJ'][baseKDJDateStr][2])
    (k_1, d_1, j_1) = get_previous_KDJ933(stock,
                                          dateutil2.previous_date(theDate),
                                          log)
    if not real:
        return (k_1, d_1, j_1)
    #print 'compute' + stock['code'] + ' ' + theDate.strftime('%Y-%m-%d') + ' ' + str(k_1) + ' ' + str(d_1) + " " + str(j_1)
    h9 = high
    l9 = low
    count = 1
    while count < 9:
        theDate = dateutil2.previous_date(theDate)
        datestr = dateutil2.format_date(theDate)
        dh = tdal.previous_data_with_date(stock['code'], datestr, log)
        if dh['real']:
            count += 1
            if l9 > dh['low']:
                l9 = dh['low']
            if h9 < dh['high']:
                h9 = dh['high']
    rsv = (close - l9) / (h9 - l9) * 100
    #print "rsv " + str(rsv) + " l9 " + " " + str(l9) + " h9 " + str(h9)
    k = rsv / 3 + 2 * k_1 / 3
    d = k / 3 + 2 * d_1 / 3
    j = 3 * k - 2 * d
    return (k, d, j)
示例#5
0
def advise(stock, total, index):
    df = all_stocks_realtime_quotes
    code = stock['code']
    current_price = float(df['price'][index])
    today_high = float(df['high'][index])
    today_low = float(df['low'][index])
    today_open = float(df['open'][index])
    position = stock['position']
    last_sell = stock['last_sell']
    last_buy = stock['last_buy']

    # name
    stock['name'] = df['name'][index]
    namelen = strutil.width(stock['name'])
    if namelen < 8:
        for i in range(8 - namelen):
            stock['name'] += ' '  # '_'
    #print len(stock['name'])
    #print namelen

    dh = tdal.previous_data(stock['code'], log_status)

    previous_close = float(dh['close'])
    previous_open = float(dh['open'])
    action = ''
    action_color = 1
    stock['action_color'] = action_color

    recent_low = get_recent_low(stock)
    recent_rise_rate = (current_price - recent_low
                        ) / recent_low * 100 if recent_low != 0 else 0.0

    currentAmount = 0.0
    if stock.has_key(keys.trades):
        for trade in stock[keys.trades]:
            direction = trade[1]
            volume = trade[2]
            if direction == 1:
                currentAmount += volume * current_price
    stock['currentAmount'] = currentAmount

    last_profit = stock['last_buy_position'] * (current_price - last_buy)
    if position == 0 and recent_rise_rate >= 20.0 and recent_rise_rate <= 28.0 and not stock.has_key(
            'margin'):
        pass
    # 设置了margin
    elif not g_show_all and stock.has_key('margin'):
        if len(stock['margin']) > 1 and stock['margin'][0] < current_price and stock['margin'][1] > current_price \
            or len(stock["margin"]) == 1 and stock['margin'][0] < current_price and (position == 0 or current_price < stock["last_buy"] * (1 + const.const_profitPercent)):
            stock['action'] = "HIDE"
            return
        elif last_profit > 0 and last_profit < 110.0:
            stock['action'] = "HIDE"
            return
    # 设置了reminder
    elif not g_show_all and stock.has_key('reminder'):
        if date.today() > dateutil2.parse_date(stock['reminder']):
            stock['comment'] = 'REMINDER'
            #stock['action'] = "买入"
        else:
            stock['action'] = "HIDE"
            return
    # last_buy * 0.x < current < last_buy * 1.x (暗示有仓位)
    elif not g_show_all and current_price > stock["last_buy"] * (
            1 - const.const_deficitPercent
    ) and current_price < stock["last_buy"] * (1 + const.const_profitPercent):
        stock['action'] = "HIDE"
        return
    # 空仓,但操作过,卖飞了
    elif not g_show_all and position == 0 and stock[
            "last_sell"] > 0 and current_price * (
                1 + const.const_profitPercent) > stock["last_sell"]:
        stock['action'] = "HIDE"
        return
    # 空仓,但操作过,没跌到位。熊市启用,震荡市可comment掉
    elif not g_show_all and position == 0 and stock[
            "last_sell"] > 0 and current_price > stock["last_sell"] * (
                1 - const.const_deficitPercent):
        stock['action'] = "HIDE"
        return
    # profit不足110
    elif not g_show_all and last_profit > 0 and last_profit < 110.0:
        stock['action'] = "HIDE"
        return

    j = 0
    #if stock.has_key('KDJ'):
    #    (k, d, j) = kdj.get_today_KDJ933(stock, current_price, today_high, today_low, log_status)
    # TODO: fix kdj
    if today_open == 0:
        action = "    "
    elif position == 0 and recent_rise_rate >= 20.0 and recent_rise_rate <= 28.0:
        action = '买入'
        action_color = 2
    elif current_price - today_open > 0:
        if previous_close - previous_open < 0:
            strong_buy = whether_strong_buy(current_price, last_sell, last_buy)
            strong_buy = False if (j > 80) else strong_buy
            if stock.has_key('last_buy_date'):
                # 距离上次买入需超过3个月或下跌超过30%
                strong_buy = False if (date.today() - datetime.strptime(stock['last_buy_date'], '%Y-%m-%d').date()).days < 90 or \
                    current_price > stock["last_buy"] * 0.70 else strong_buy
            if strong_buy:
                action = "买入"
                action_color = 2
            else:
                action = "弱买"
                action_color = 4
        else:
            if stock['position'] == 0:
                action = "追高"
                action_color = 4
            else:
                action = "持有"
    elif current_price - today_open < 0:
        if previous_close - previous_open < 0 or position == 0:
            action = "观望"
        elif current_price < last_buy:
            action = "亏卖"
            action_color = 5
        elif current_price > last_buy + 1.00 and current_price < last_buy * 1.1:
            strong_sell = whether_strong_sell(stock, current_price, last_sell,
                                              last_buy, today_high)
            if strong_sell:
                action = "卖出"
                action_color = 3
            else:
                action = "弱卖"
                action_color = 5
        elif current_price < last_buy + 1.00 or current_price < last_buy * 1.1:
            action = "薄卖"
            action_color = 5
        else:
            strong_sell = whether_strong_sell(stock, current_price, last_sell,
                                              last_buy, today_high)
            if strong_sell:
                action = "卖出"
                action_color = 3
            else:
                action = "忖卖"
                action_color = 5
    elif current_price == 0:
        action = "    "
    else:
        action = " -- "
    stock['action'] = action
    stock['action_color'] = action_color

    profit_percent = 0
    if last_buy > 0:  #and position > 0:
        profit_percent = math.floor(
            (current_price - last_buy) / last_buy * 100)
    elif last_sell > 0:  #and position > 0:
        profit_percent = math.floor(
            (current_price - last_sell) / last_sell * 100)
        if profit_percent > 0:
            profit_percent = 0
    #if profit_percent <= -10:
    #    profit_percent = 0

    if profit_percent == 0:
        profit_percentstr = '    '
    else:
        profit_percentstr = '%3d%%' % profit_percent

    regress_rate = 0
    if profit_percent <= 0:
        regress_ratestr = '   '
    else:
        recent_high = get_recent_high(stock, today_high)
        regress_rate = math.ceil(
            (recent_high - current_price) / (recent_high - last_buy) * 100)
        #if code == '002299':
        #    print str(recent_high) + ' ' + str(current_price) + ' ' + str(last_buy)
        regress_ratestr = '%2d%%' % regress_rate
    if position == 0 and recent_rise_rate > 0:
        regress_rate = recent_rise_rate
        regress_ratestr = '%2d%%' % regress_rate

    if (current_price == 0 or today_open == 0) and (code
                                                    not in posman.halt_codes):
        posman.halt_codes.append(code)
        pp.preprocess_all(all_stocks, stockdata.sh_index, log_status)

    (last, far) = util.get_hold_duration(stock)
    durationstr = '     '
    if position > 0:
        durationstr = '%2d/%2d' % (last, far)

    stack = 0
    stackstr = '     '
    if stock.has_key('trades'):
        for trade in stock['trades']:
            direction = trade[1]
            if direction == 1:
                stack += 1
                if stack <= 5:
                    stackstr = stackstr.replace(' ', '|', 1)
                elif stack <= 10:
                    stackstr = stackstr.replace('|', '+', 1)
                elif stack <= 15:
                    stackstr = stackstr.replace('+', '#', 1)
                else:
                    stackstr = stackstr.replace('#', '$', 1)

    index_profit_percent = 0
    buy_index = 0
    if position > 0:
        index_dh = tdal.previous_data_with_date(stockdata.sh_index['code'],
                                                stock['last_buy_date'],
                                                log_status)
        buy_index = (index_dh['high'] + index_dh['low']) / 2
        index_profit_percent = (stockdata.sh_index['price'] -
                                buy_index) / buy_index
    index_profit_percentstr = '       '
    if index_profit_percent != 0:
        index_profit_percentstr = '%6.2f%%' % (index_profit_percent * 100)

    index_cost_percent = 0
    #TODO: index_cost
    #if stock.has_key('last_sell_date'):
    #    index_dh = tdal.previous_data_with_date(stockdata.sh_index['code'], stock['last_sell_date'], log_status)
    #    sell_index = (index_dh['high'] + index_dh['low']) / 2
    #    # 处理累进买入的情况
    #    if buy_index != 0 and sell_index > buy_index and stock['last_sell_date'] != stock['last_buy_date']:
    #        sell_index = buy_index
    #    index_cost_percent = (stockdata.sh_index['price'] - sell_index) / sell_index
    index_cost_percentstr = '       '
    #if index_cost_percent < 0:
    #    index_cost_percentstr = '%6.2f%%' % (index_cost_percent * 100)

    stock['more_info_previousChange'] = previous_close - previous_open
    stock['more_info_todayChange'] = current_price - today_open
    stock['more_info_currentPrice'] = current_price
    stock['more_info_lastBuy'] = stock['last_buy']
    stock['more_info_lastSell'] = stock['last_sell']
    stock['more_info_position'] = stock['last_buy_position']  #position
    stock['more_info_profit_percent'] = profit_percent
    stock['more_info_profit_percentstr'] = profit_percentstr
    stock['more_info_regress_rate'] = regress_rate
    stock['more_info_regress_ratestr'] = regress_ratestr
    stock['more_info_currentJ'] = j
    stock['more_info_duration_last'] = last
    stock['more_info_duration_far'] = far
    stock['more_info_durationstr'] = durationstr
    stock['more_info_stack'] = stack
    stock['more_info_stackstr'] = stackstr
    stock['more_info_index_profit_percent'] = index_profit_percent
    stock['more_info_index_profit_percentstr'] = index_profit_percentstr
    stock['more_info_index_cost_percent'] = index_cost_percent
    stock['more_info_index_cost_percentstr'] = index_cost_percentstr
    stock['more_info_today_change'] = position * (current_price -
                                                  previous_close)
示例#6
0
def preprocess_stock(stock, sh_index, log):
    last_buy = 0.0
    last_buy_date = date.min
    far_buy_date = date.max
    last_sell = 0.0
    last_sell_date = date.min
    position = 0
    amount = 0
    last_buy_position = 0
    turnover = 0
    if stock.has_key(keys.trades):
        for trade in stock[keys.trades]:
            theDate = dateutil2.parse_date(trade[0])
            direction = trade[1]
            volume = trade[2]
            price = trade[3]
            if direction == 2 or len(trade) > 4:
                theSellDate = dateutil2.parse_date(trade[4])
                sellPrice = trade[5]
                # correct direction in case it has wrong value
                if direction != 2:
                    print 'wrong direction in stock ' + stock['code']
                    direction = 2
                if theSellDate >= last_sell_date:
                    last_sell_date = theSellDate
                    last_sell = sellPrice
                turnover += 1
            if direction == 1 and theDate >= last_buy_date:
                last_buy_date = theDate
                last_buy = price
                last_buy_position = volume
            if direction == 1 and theDate < far_buy_date:
                far_buy_date = theDate
            if direction == 1:
                position += direction * volume
                amount += volume * price
                posman.investments['total'] += direction * volume * price
                if stock['code'] not in posman.whitelist_codes:
                    posman.investments['totalExceptWhitelist'] += direction * volume * price
                if (stock['code'] not in posman.whitelist_codes) and (stock['code'] not in posman.halt_codes):
                    posman.investments['totalExceptWhitelistAndHalt'] += direction * volume * price
                if stock['code'] in posman.vip_codes:
                    posman.investments['totalVip'] += direction * volume * price
                #TODO: cost_index
                '''
                # sh index at trade date
                # print '#### getting sh_index at date ' + trade[0]
                dh = tdal.previous_data_with_date(sh_index['code'], trade[0], log)
                # print '#### end sh_index at date ' + trade[0]
                #dh = tdal.previous_data_with_date(sh_index['code'], trade[0], log)
                shIndex = (dh['high'] + dh['low']) / 2
                posman.investments['indexedTotal'] += shIndex * volume * price
                costIndex = int(math.floor((5000 - shIndex) / 500) + 1)
                costIndex = 0 if (costIndex < 0) else costIndex
                costIndex = 7 if (costIndex > 7) else costIndex
                posman.investments['indexed_cost'][costIndex] += volume * price
                if sh_index['price'] > 0:
                    costIndex = (int(sh_index['price']) / 100) - (int(shIndex) / 100) + 3
                    #display_info("" + costIndex + " " + amount * price, 1, 20)
                    if costIndex >= 0 and costIndex <= 7:
                        posman.investments['fine_indexed_cost'][costIndex] += volume * price
                '''
    if not stock.has_key('last_buy_date') and last_buy_date != date.min:
        stock['last_buy_date'] = last_buy_date.strftime('%Y-%m-%d')
    if not stock.has_key('far_buy_date') and far_buy_date != date.max:
        stock['far_buy_date'] = far_buy_date.strftime('%Y-%m-%d')
    if not stock.has_key('last_buy'):
        stock['last_buy'] = last_buy
    if not stock.has_key('last_buy_position'):
        stock['last_buy_position'] = last_buy_position
    if not stock.has_key('last_sell_date') and last_sell_date != date.min:
        stock['last_sell_date'] = last_sell_date.strftime('%Y-%m-%d')
    if not stock.has_key('last_sell'):
        stock['last_sell'] = last_sell
    if not stock.has_key('position'):
        stock['position'] = position
    if stock['position'] > 0:
        posman.investments['positioned_stock_count'] += 1
    stock['turnover'] = turnover
    stock['amount'] = amount