Esempio n. 1
0
def analysis(k):
    # 转DataFrame格式
    df = pd.DataFrame(
        k, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
    t = k[0][0]
    # 毫秒级
    if len(str(t)) == 13:
        df['timestamp'] = df['timestamp'] / 1000
    # 分析
    stock = StockDataFrame.retype(df)
    stock['cci']
    df['date'] = df['timestamp'].apply(
        lambda x: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x)))
    df['date'] = pd.to_datetime(df['date'])
    df = df[5:]
    df['regime'] = np.where((df['cci'] >= 100) & (df['cci'].shift(1) < 100), 1,
                            0)
    df['regime'] = np.where(
        ((df['cci'] <= 100) & (df['cci'].shift(1) > 100)) |
        ((df['cci'] >= 100) & (df['stoch_d'] >= df['stoch_k'])), -1,
        df['regime'])
    # df['regime'] = np.where((df['cci'] <= -100) & (df['cci'].shift(1) >= -100), -1, df['regime'])
    # df['regime'] = np.where(((df['cci'] >= -100) & (df['cci'].shift(1) <= -100)) | ((df['cci'] <= -100) & (df['stoch_k'] >= df['stoch_d'])), 1, df['regime'])
    # 下单(只下多单)
    print(df[['date', 'close', 'cci', 'regime']])
    if (df[-1:]['regime'] == 1).bool():
        return 'long'
    elif (df[-1:]['regime'] == -1).bool():
        return 'close_long'
    else:
        return 'wait'
def cal_fitness(df, pops, pop_size=50, chromosome_length=6):
    obj_value = []
    async_funcs = []
    for i in range(pop_size):
        df_ = copy.deepcopy(df)
        stock = StockDataFrame.retype(df_)
        df_['signal'] = 'wait'
        boll_A_ = binary2decimal(pops[0][i], 1.5, 3, chromosome_length)
        boll_std_len_ = int(binary2decimal(pops[1][i], 14, 30, chromosome_length))
        macd_fast_len_ = int(binary2decimal(pops[2][i], 8, 16, chromosome_length))
        macd_slow_len_ = int(binary2decimal(pops[3][i], 20, 30, chromosome_length))
        boll_width_threshold_ = binary2decimal(pops[4][i], 0.05, 0.15, chromosome_length)
        volatility_ = binary2decimal(pops[5][i], 0.0009, 0.0011, chromosome_length)
        stop_limit_ = binary2decimal(pops[6][i], 0.01, 0.1, chromosome_length)
        trend_A1_ = binary2decimal(pops[7][i], 0.2, 0.35, chromosome_length)
        trend_A2_ = binary2decimal(pops[8][i], 0.01, 0.025, chromosome_length)
        trend_B_ = binary2decimal(pops[9][i], 0.02, 0.045, chromosome_length)
        trend_C_ = binary2decimal(pops[10][i], 0.03, 0.055, chromosome_length)
        stop_trade_times_ = int(binary2decimal(pops[11][i], 6, 12, chromosome_length))
        async_funcs.append(cal_someone_fitness(df_, stock, i, boll_A_, boll_std_len_, macd_fast_len_,
                                               macd_slow_len_,
                                               boll_width_threshold_, volatility_, stop_limit_, trend_A1_,
                                               trend_A2_,
                                               trend_B_, trend_C_, stop_trade_times_))
    loop = asyncio.get_event_loop()
    re = loop.run_until_complete(asyncio.gather(*async_funcs))
    n = len(re)
    for i in range(n - 1, 0, -1):
        for j in range(i):
            if re[j][0] > re[j + 1][0]:
                re[j], re[j + 1] = re[j + 1], re[j]
    for i in range(n):
        obj_value.append(re[i][1])
    return obj_value
Esempio n. 3
0
def analysis_(datas):
    df = pd.DataFrame(
        datas, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
    df = df.astype(float)
    stock = StockDataFrame.retype(df)
    df['date'] = pd.to_datetime(df['timestamp'], unit='s')

    df.index = df.date
    stock = StockDataFrame.retype(df)
    stock['cci']
    stock['stoch_rsi']
    # 去掉前几个cci指标不准数据
    df = df[10:]

    df['signal'] = 'wait'
    df['signal'] = np.where((df['cci'] >= 100) & (df['cci'].shift(1) < 100),
                            'long', df['signal'])
    df['signal'] = np.where(((df['cci'] <= 100) & (df['cci'].shift(1) > 100)),
                            'close_long', df['signal'])
    df['signal'] = np.where((df['cci'] <= -100) & (df['cci'].shift(1) >= -100),
                            'short', df['signal'])
    df['signal'] = np.where((df['cci'] >= -100) & (df['cci'].shift(1) <= -100),
                            'close_short', df['signal'])
    return df.iloc[-1]
Esempio n. 4
0
import pandas as pd
import numpy as np
from tools.stockstats import StockDataFrame
import time
import matplotlib.ticker as ticker
from tools import data2df
import matplotlib.pyplot as plt

# 本金
principal = 10000.0
title = 'BTC2017-09-01-now-1D'
df = data2df.csv2df(title + '.csv')
df = df.astype(float)
df['Timestamp'] = df['Timestamp'].astype(int)
stock = StockDataFrame.retype(df)

df['date'] = df['timestamp'].apply(
    lambda x: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x)))
df['date'] = pd.to_datetime(df['date'])

stock['cci']
# 去掉前几个cci指标不准数据
df = df[5:]

df['regime'] = np.where((df['cci'] >= 100) & (df['cci'].shift(1) < 100), 1, 0)
df['regime'] = np.where((df['cci'] <= 100) & (df['cci'].shift(1) > 100), -1,
                        df['regime'])
df['regime'] = np.where((df['cci'] <= -100) & (df['cci'].shift(1) >= -100), -1,
                        df['regime'])
df['regime'] = np.where((df['cci'] >= -100) & (df['cci'].shift(1) <= -100), 1,
Esempio n. 5
0
def analysis(kline):
    df = pd.DataFrame(
        kline, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
    stock = StockDataFrame.retype(df)
    # df['timestamp'] = df['timestamp'] / 1000
    df['date'] = pd.to_datetime(df['timestamp'], unit='s')
    df.index = df.date
    stock['boll']
    df['signal'] = 'wait'
    # 参数设置
    trend_A1 = 0.3
    trend_A2 = 0.02
    trend_B = 0.04
    trend_C = 0.05
    # trend_D = 0.07
    stop_trade_times = 5
    ts = 3600
    std_percentage = 0.6
    w = 200
    volatility = 0.001

    # 通道宽度
    df['boll_width'] = abs(df['boll_ub'] - df['boll_lb'])
    # 单次涨跌幅
    df['change'] = abs(
        (df['close'] - df['close'].shift(1)) / df['close'].shift(1))
    # 两次涨幅
    df['change_2'] = abs(
        (df['close'] - df['close'].shift(2)) / df['close'].shift(2))
    # 趋势判断A:超过通道一定幅度且单次涨幅超过一定幅度
    df['signal'] = np.where(
        ((df['close'] > df['boll_ub'] + df['boll_width'] * trend_A1) |
         (df['close'] < df['boll_lb'] - df['boll_width'] * trend_A1)) &
        (df['change'] > trend_A2), 'trend', df['signal'])
    # 趋势判断B:单次涨幅累计超过一定幅度
    df['signal'] = np.where(df['change'] > trend_B, 'trend', df['signal'])
    # 趋势判断C:两次涨幅累计超过一定幅度
    df['signal'] = np.where(df['change_2'] > trend_C, 'trend', df['signal'])

    for i in range(stop_trade_times):
        df['signal'] = np.where(
            (df['signal'] == 'wait') & (df['signal'].shift(1 + i) == 'trend'),
            'can_not_trade', df['signal'])
    df['signal'] = np.where(df['signal'] == 'can_not_trade', 'trend',
                            df['signal'])
    df['close_mean'] = df['close'].rolling(center=False, window=w).mean()
    df['close_std'] = df['close'].rolling(center=False, window=w).std()

    df['close_std'] = df['close_std'] * std_percentage
    df['rate'] = df['close_std'] / df['boll_width']
    # df['close_std'] = np.where(df['rate'] > 0.1, df['boll_width'] * 0.1, df['close_std'])

    # 策略1
    df['signal'] = np.where(
        (df['signal'] == 'wait') & (df['change'] > volatility) &
        (df['close'] > df['boll_ub'] - df['close_std'] / 4) &
        (df['close'] < df['boll_ub'] + df['close_std'] / 2), 'short',
        df['signal'])
    df = public_func(df, 'short', 'signal')
    df['signal'] = np.where(
        (df['signal'] == 'wait') &
        (df['high'] >= df['signal_boll_ub'] + df['close_std'] / 4),
        'close_short', df['signal'])

    # 策略2
    df['signal'] = np.where(
        (df['signal'] == 'wait') & (df['change'] > volatility) &
        (df['close'] < df['boll_lb'] + df['close_std'] / 4) &
        (df['close'] > df['boll_lb'] - df['close_std'] / 2), 'long',
        df['signal'])
    df = public_func(df, 'long', 'signal')
    df['signal'] = np.where(
        (df['signal'] == 'wait') &
        (df['low'] <= df['signal_boll_lb'] - df['close_std'] / 4),
        'close_long', df['signal'])

    # 策略3
    df['signal'] = np.where(
        (df['signal'] == 'wait') & (df['change'] > volatility) &
        (df['close'].shift(1) < df['boll'].shift(1) + df['close_std'].shift(1))
        & (df['close'] > df['boll'] + df['close_std']), 'long', df['signal'])
    df['signal'] = np.where(
        (df['signal'] == 'wait') &
        (df['close'].shift(1) >
         df['boll'].shift(1) + df['close_std'].shift(1) / 2) &
        (df['close'] < df['boll'] + df['close_std'] / 2), 'close_long',
        df['signal'])
    # 策略4
    df['signal'] = np.where(
        (df['signal'] == 'wait') & (df['change'] > volatility) &
        (df['close'].shift(1) > df['boll'].shift(1) - df['close_std'].shift(1))
        & (df['close'] < df['boll'] - df['close_std']), 'short', df['signal'])
    df['signal'] = np.where(
        (df['signal'] == 'wait') &
        (df['close'].shift(1) <
         df['boll'].shift(1) - df['close_std'].shift(1) / 2) &
        (df['close'] > df['boll'] - df['close_std'] / 2), 'close_short',
        df['signal'])

    return df.iloc[-1]
Esempio n. 6
0
def k_analysis(k):
    # 转DataFrame格式
    k_data = pd.DataFrame(
        k, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
    t = k[0][0]
    # 毫秒级
    if len(str(t)) == 13:
        k_data['timestamp'] = k_data['timestamp'] / 1000
    stock = StockDataFrame.retype(k_data)
    stock['middle_hl']
    k_data['date'] = k_data['timestamp'].apply(
        lambda x: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x)))
    k_data['date'] = pd.to_datetime(k_data['date'])

    after_fenxing = pd.DataFrame()
    temp_data = k_data.iloc[0]
    zoushi = []  # 0:持平 -1:向下 1:向上

    for i, row in k_data.iterrows():
        # 第一根包含第二根
        case1_1 = temp_data['high'] > row['high'] and temp_data['low'] < row[
            'low']
        case1_2 = temp_data['high'] > row['high'] and temp_data['low'] == row[
            'low']
        case1_3 = temp_data['high'] == row[
            'high'] and temp_data['low'] < row['low']
        # 第二根包含第一根
        case2_1 = temp_data['high'] < row['high'] and temp_data['low'] > row[
            'low']
        case2_2 = temp_data['high'] < row['high'] and temp_data['low'] == row[
            'low']
        case2_3 = temp_data['high'] == row[
            'high'] and temp_data['low'] > row['low']
        # 第一根等于第二根
        case3 = temp_data['high'] == row['high'] and temp_data['low'] == row[
            'low']
        # 向下趋势
        case4 = temp_data['high'] > row['high'] and temp_data['low'] > row[
            'low']
        # 向上趋势
        case5 = temp_data['high'] < row['high'] and temp_data['low'] < row[
            'low']

        if case1_1 or case1_2 or case1_3:
            if zoushi[-1] == -1:
                temp_data['high'] = row['high']
            else:
                temp_data['low'] = row['low']
        elif case2_1 or case2_2 or case2_3:
            temp_temp = temp_data
            temp_data = row
            if zoushi[-1] == -1:
                temp_data['high'] = temp_temp['high']
            else:
                temp_data['low'] = temp_temp['low']
        elif case3:
            zoushi.append(0)
            pass
        elif case4:
            zoushi.append(-1)
            # 使用默认index: ignore_index=True:
            after_fenxing = pd.concat(
                [after_fenxing, temp_data.to_frame().T], ignore_index=True)
            temp_data = row
        elif case5:
            zoushi.append(1)
            after_fenxing = pd.concat(
                [after_fenxing, temp_data.to_frame().T], ignore_index=True)
            temp_data = row

    # 因为使用candlestick2函数,要求输入open、close、high、low。为了美观,处理k线的最大最小值、开盘收盘价,之后k线不显示影线。
    for i, row in after_fenxing.iterrows():
        if row['open'] > row['close']:
            row['open'] = row['high']
            row['close'] = row['low']
        else:
            row['open'] = row['low']
            row['close'] = row['high']

    # 找出顶和底
    temp_num = 0  # 上一个顶或底的位置
    temp_high = 0  # 上一个顶的high值
    temp_low = 0  # 上一个底的low值
    temp_type = 0  # 上一个记录位置的类型 1-顶分型, 2-底分型
    i = 1
    fenxing_type = []  # 记录分型点的类型,1为顶分型,-1为底分型
    fenxing_time = []  # 记录分型点的时间
    fenxing_plot = []  # 记录点的数值,为顶分型去high值,为底分型去low值
    fenxing_data = pd.DataFrame()  # 分型点的DataFrame值
    interval = 4
    while (i < len(after_fenxing) - 1):
        # 顶分型
        case1 = after_fenxing.high[i - 1] < after_fenxing.high[
            i] and after_fenxing.high[i] > after_fenxing.high[i + 1]
        # 底分型
        case2 = after_fenxing.low[i - 1] > after_fenxing.low[
            i] and after_fenxing.low[i] < after_fenxing.low[i + 1]
        if case1:
            # 如果上一个分型为顶分型,则进行比较,选取更高的分型
            if temp_type == 1:
                if after_fenxing.high[i] <= temp_high:
                    i += 1
                    continue
                else:
                    temp_high = after_fenxing.high[i]
                    temp_num = i
                    temp_type = 1
                    i += interval
            # 如果上一个分型为底分型,则记录上一个分型,用当前分型与后面的分型比较,选取通向更极端的分型
            elif temp_type == 2:
                if temp_low >= after_fenxing.high[i]:
                    i += 1
                else:
                    fenxing_type.append(-1)
                    fenxing_time.append(after_fenxing.date[temp_num])
                    fenxing_data = pd.concat(
                        [fenxing_data, after_fenxing[temp_num:temp_num + 1]],
                        axis=0)
                    fenxing_plot.append(after_fenxing.high[i])
                    temp_high = after_fenxing.high[i]
                    temp_num = i
                    temp_type = 1
                    i += interval
            else:
                temp_high = after_fenxing.high[i]
                temp_num = i
                temp_type = 1
                i += interval
        elif case2:
            # 如果上一个分型为底分型,则进行比较,选取低点更低的分型
            if temp_type == 2:
                if after_fenxing.low[i] >= temp_low:
                    i += 1
                    continue
                else:
                    temp_low = after_fenxing.low[i]
                    temp_num = i
                    temp_type = 2
                    i += interval
            # 如果上一个分型为顶分型,则记录上一个分型,用当前分型与后面的分型比较,选取通向更极端的分型
            elif temp_type == 1:
                # 如果上一个顶分型的底比当前底分型的底低,则跳过当前的底分型
                if temp_high <= after_fenxing.low[i]:
                    i += 1
                else:
                    fenxing_type.append(1)
                    fenxing_time.append(after_fenxing.date[temp_num])
                    fenxing_data = pd.concat(
                        [fenxing_data, after_fenxing[temp_num:temp_num + 1]],
                        axis=0)
                    fenxing_plot.append(after_fenxing.low[i])
                    temp_low = after_fenxing.low[i]
                    temp_num = i
                    temp_type = 2
                    i += interval
            else:
                temp_low = after_fenxing.low[i]
                temp_num = i
                temp_type = 2
                i += interval
        else:
            i += 1
    return fenxing_type, fenxing_time, fenxing_plot, fenxing_data
Esempio n. 7
0
'''

import pandas as pd
import numpy as np
from tools import data2df
import time
from tools.stockstats import StockDataFrame
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt

filename = 'BTC2017-09-01-now-1H'
k_data = data2df.csv2df(filename + '.csv')
k_data = k_data.astype(float)
k_data['Timestamp'] = k_data['Timestamp'].astype(int)
stock = StockDataFrame.retype(k_data)

k_data['date'] = k_data['timestamp'].apply(
    lambda x: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x)))
k_data['date'] = pd.to_datetime(k_data['date'])

stock['middle_hl']

after_fenxing = pd.DataFrame()
temp_data = k_data.iloc[0]
zoushi = []  # 0:持平 -1:向下 1:向上

for i, row in k_data.iterrows():
    # 第一根包含第二根
    case1_1 = temp_data['high'] > row['high'] and temp_data['low'] < row['low']
    case1_2 = temp_data['high'] > row['high'] and temp_data['low'] == row['low']