コード例 #1
0
ファイル: trading_signal.py プロジェクト: Haifei-ZHANG/iQuant
    def calculate_signals(self):
        self.over_ema12 = []
        self.over_ema20 = []
        self.over_ama = []
        self.ama_direction = []
        self.svm_probability = []
        for i in range(len(self.etfs)):
            # 用weekly数据计算ema12
            data = load_rawdata(self.etfs[i], 'weekly')
            data_stats = stockstats.StockDataFrame.retype(data.copy())
            self.over_ema12.append(data_stats['close_12_ema'].iloc[-1])

            # 用weekly数据计算ama
            # # 首先创建ama的模型数据
            # data = load_ama_modeldata(self.etfs[i], 'weekly')
            # input = np.array(data)[-2:, 0:-1]
            #
            # # 添加ama_direction
            # self.ama_direction.append(input[-1, 1])
            #
            # # 加载模型
            # file = open('./models/ama_models/' + self.etfs[i] + '_weekly_ama_model', 'rb')
            # ama_model = pickle.load(file)
            # # 计算ama
            # self.over_ama.append(ama_model.predict(input)[-1])
            # file.close()

            ama, ama_direction, _ = calculate_ama(
                data, data_stats, self.model_parameters['AMA']['price_type'],
                self.model_parameters['AMA']['er_window'],
                self.model_parameters['AMA']['slow_window'],
                self.model_parameters['AMA']['fast_window'])
            self.over_ama.append(ama[-1])
            self.ama_direction.append(ama_direction[-1])

            # 用weekly数据计算svm
            # 首先创建svm需要的数据
            data = load_svm_modeldata(self.etfs[i], 'weekly')
            if len(data) > 300:
                X, Y = preprocess(data.iloc[-301:-2])
            else:
                X, Y = preprocess(data)
            input = X[-2:]
            # 加载模型
            file = open(
                './models/svm_models/' + self.etfs[i] + '_weekly_svm_model',
                'rb')
            svm_model = pickle.load(file)

            self.svm_probability.append(svm_model.predict_proba(input)[-1, 1])
            file.close()

            # 用月数据计算ema20
            data = load_rawdata(self.etfs[i], 'monthly')
            data_stats = stockstats.StockDataFrame.retype(data.copy())
            self.over_ema20.append(data_stats['close_20_ema'].iloc[-1])

        self.show_signals()
コード例 #2
0
ファイル: ama_backtest.py プロジェクト: Haifei-ZHANG/iQuant
 def __init__(self,
              etf,
              start_date,
              end_date,
              model_name='AMA',
              initial_deposit=100000,
              price_type='open',
              er_window=9,
              slow_window=20,
              fast_window=4):
     self.ticker = etf
     self.start_date = start_date
     self.end_date = end_date
     self.model_name = model_name
     self.init_deposit = initial_deposit
     self.price_type = price_type
     self.er_window = er_window
     self.slow_window = slow_window
     self.fast_window = fast_window
     self.raw_data = load_rawdata(etf, 'weekly')
     self.indicators = stockstats.StockDataFrame.retype(
         self.raw_data.copy())
     ama, _, _ = calculate_ama(self.raw_data, self.indicators,
                               self.price_type, self.er_window,
                               self.slow_window, self.fast_window)
     self.raw_data['ama'] = ama
     self.report = pd.DataFrame(
         columns=['position size', 'total', 'profit'])
コード例 #3
0
    def build_model_data(self, ticker, time_frame):
        raw_data = load_rawdata(ticker, time_frame)
        data_stats = stockstats.StockDataFrame.retype(raw_data.copy())
        columns = ['ama', 'pn_er',  'tr', 'target']
        ama, pn_er, ssc = calculate_ama(raw_data, data_stats, self.price_type, self.er_window, self.slow_window, self.fast_window)
        tr = np.array(data_stats['tr'])
        tr[0] = abs(raw_data.iloc[0]['open'] - raw_data.iloc[0]['close'])
        # 计算target
        target = []
        price_open = np.array(raw_data['open'])
        price_close = np.array(raw_data['close'])
        target.append(price_close[0])
        for i in range(1, len(price_open)):
            if pn_er[i] > -0.1:
                target.append(min(price_close[i], price_open[i]) - pn_er[i] * tr[i])
            else:
                target.append(max(price_close[i], price_open[i] - 0.3 * pn_er[i] * tr[i]))
        #对ama曲线进行指数平滑, 窗口取7
        if time_frame == 'weekly':
            for i in range(1, len(target)):
                target[i] = (2 * target[i] + 6 * target[i-1])/8
        else:
            for i in range(1, len(target)):
                target[i] = (2 * target[i] + 9 * target[i-1])/11

        model_data = np.array([ama, pn_er, tr, target]).T
        print(model_data.shape)
        model_data = pd.DataFrame(model_data, index=raw_data.index, columns=columns)
        self.save_model_data(model_data, ticker, time_frame)
コード例 #4
0
ファイル: svm_backtest.py プロジェクト: Haifei-ZHANG/iQuant
 def __init__(self, etf, start_date, end_date, model_name='SVM',initial_deposit=100000):
     self.ticker = etf
     self.start_date = start_date
     self.end_date = end_date
     self.model_name = model_name
     self.init_deposit = initial_deposit
     self.raw_data = load_rawdata(etf, 'weekly')
     self.indicators = stockstats.StockDataFrame.retype(self.raw_data.copy())
     self.model_data = load_svm_modeldata(etf, 'weekly')
     self.report = pd.DataFrame(columns=['position size','total','profit'])
コード例 #5
0
    def prepare_data(self):
        # 获取被选中的etf名称和time frame
        etf = self.chosen_etf.text()
        tf = self.chosen_tf.text()
        indicators = self.chosen_indicator.text().split(';')
        _ = indicators.pop()
        # load data
        self.data = load_rawdata(etf, tf)
        self.data_stats = stockstats.StockDataFrame.retype(self.data.copy())
        # 去掉volume和adj close列
        self.data.drop(['adjclose', 'volume'], axis=1, inplace=True)

        # 添加所指标ama, ema12, ema20

        ama, _, _ = calculate_ama(self.data, self.data_stats)

        self.data['ama'] = ama

        self.data[['ema12', 'ema20'
                   ]] = self.data_stats[['close_12_ema', 'close_20_ema']]

        # 数值保留两位小数
        self.data[['open', 'high', 'low', 'close', 'ama', 'ema12',
                   'ema20']] = self.data[[
                       'open', 'high', 'low', 'close', 'ama', 'ema12', 'ema20'
                   ]].round(decimals=2)

        # 设置价格显示面板
        # 获取四个价
        self.current_price = self.data.iloc[-1]['close']
        self.open_price = self.data.iloc[-1]['open']
        self.high_price = self.data.iloc[-1]['high']
        self.low_price = self.data.iloc[-1]['low']

        self.current_label.setText('Current: ' + str(self.current_price))
        if self.current_price > self.open_price:
            self.current_label.setStyleSheet("color:green")
            self.current_label.setFont(self.myfont)
        else:
            self.current_label.setStyleSheet("color:red")
            self.current_label.setFont(self.myfont)

        self.open_label.setText('Open: ' + str(self.open_price))
        self.high_label.setText('High: ' + str(self.high_price))
        self.low_label.setText('Low: ' + str(self.low_price))
コード例 #6
0
    def build_model_data(self, ticker, time_frame):
        raw_data = load_rawdata(ticker, time_frame)
        data_stats = stockstats.StockDataFrame.retype(raw_data.copy())
        raw_data['trend'] = self.build_trend_data(raw_data)


        if time_frame == 'monthly':
            raw_data['ema'] = (data_stats["close_12_ema"].round(2))
        else:
            raw_data['ema'] = (data_stats["close_20_ema"].round(2))
        raw_data['rsi'] = data_stats['rsi_6']
        raw_data['cci'] = data_stats['cci']
        raw_data['macd'] = data_stats['macd']
        raw_data['kdjk'] = data_stats['kdjk']
        raw_data['kdjd'] = data_stats['kdjd']
        raw_data['wr'] = data_stats['wr_6']

        columns = ['h-l', 'c-o', 'h-cp', 'l-cp', 'diff_ema', 'diff_volume', 'cci', 'rsi', 'macd', 'kdjk', 'kdjd', 'wr',
                   'trend']
        new_columns = []
        # create new columns name
        for i in range(self.look_hist_window):
            offset = i + 1
            for indicator in columns:
                new_columns.append(indicator + '_' + str(offset))

        # create new data frame
        model_data = pd.DataFrame(columns=new_columns)

        # use look_hist_window(equals 4 default) candles to build the input data of current candles trend
        raw_data['h-l'] = raw_data['high'] - raw_data['low']
        raw_data['c-o'] = raw_data['open'] - raw_data['low']
        raw_data['h-cp'] = raw_data['high'] - raw_data['close'].shift(1)
        raw_data['l-cp'] = raw_data['low'] - raw_data['close'].shift(1)
        raw_data['diff_ema'] = raw_data['close'] - raw_data['ema']
        raw_data['diff_volume'] = raw_data['volume'].pct_change()
        for i in range(1, self.look_hist_window + 1):
            model_data[new_columns[(i - 1) * 13:i * 13]] = raw_data[['h-l', 'c-o', 'h-cp', 'l-cp',
                                                                     'diff_ema', 'diff_volume', 'cci', 'rsi',
                                                                     'macd', 'kdjk', 'kdjd', 'wr','trend']].shift(i).copy()
        # self.model_data = self.model_data.set_index(self.raw_data.index)
        model_data = round(model_data, 2)
        model_data['target'] = raw_data['trend']
        self.save_model_data(ticker, time_frame, model_data)
コード例 #7
0
ファイル: home_ui.py プロジェクト: Haifei-ZHANG/iQuant
    def load_data(self):
        for tf in self.tfs:
            index = -1
            for etf in self.etfs:
                index += 1
                data = load_rawdata(etf, tf)
                if data is None:
                    continue

                data_stats = stockstats.StockDataFrame.retype(data.copy())
                data[['ema12', 'ema20']] = data_stats[['close_12_ema', 'close_20_ema']]
                # 数值保留两位小数
                data[['open', 'high', 'low', 'close', 'ema12', 'ema20']] = data[
                    ['open', 'high', 'low', 'close', 'ema12', 'ema20']].round(decimals=2)
                # ama = calculate_ama(data, data_stats)[0][-1]

                # 计算ama
                ama, _, _ = calculate_ama(data, data_stats)
                ama = ama[-1]

                # 获取倒数第二行数据,是最新的
                tmp = data.iloc[-1]
                dict = {'ETF': etf,
                        'current': tmp['close'],
                        'pre close': data.iloc[-2]['close'],
                        'net change': round(tmp['close'] - data.iloc[-2]['close']),
                        'pct change': round((tmp['close'] / data.iloc[-2]['close'] -1) * 100, 2),
                        'open': tmp['open'],
                        'high': tmp['high'],
                        'low': tmp['low'],
                        'volume': int(tmp['volume']),
                        'ama': round(ama, 2),
                        'ema12': tmp['ema12'],
                        'ema20': tmp['ema20']}
                df = pd.DataFrame(dict, index=[index])
                if tf == 'weekly':
                    self.weekly_data = self.weekly_data.append(df, ignore_index=True)
                if tf == 'monthly':
                    self.monthly_data = self.monthly_data.append(df, ignore_index=True)
コード例 #8
0
    def __init__(self):
        super(PositionCalculator, self).__init__()

        # 获取本地的etf名称列表
        try:
            self.etfs = np.load('./Data/etfs.npy').tolist()
        except FileNotFoundError:
            self.etfs = [
                'SPY', 'QQQ', 'TLT', 'GLD', 'IWM', 'EFA', 'HYG', 'XLV'
            ]

        # 创建atr列表
        self.atr_list = []

        # get ATR
        self.lines = []
        for i in range(len(self.etfs)):
            raw_data = load_rawdata(self.etfs[i], 'daily')
            if raw_data is None:
                continue
            data_stats = stockstats.StockDataFrame.retype(raw_data.copy())
            atr = round(data_stats['atr'].iloc[-1], 2)
            self.atr_list.append(atr)

            #计算周上面的五条线指标
            raw_data = load_rawdata(self.etfs[i], 'weekly')
            data_stats = stockstats.StockDataFrame.retype(raw_data.copy())
            BB = round(data_stats["close_20_ema"][-1], 2)
            UBB = round(BB + 2 * data_stats["close_20_mstd"][-1], 2)
            plus_half_sd = round(BB + 0.5 * data_stats["close_20_mstd"][-1], 2)
            minus_half_sd = round(BB - 0.5 * data_stats["close_20_mstd"][-1],
                                  2)
            LBB = round(BB - 2 * data_stats["close_20_mstd"][-1], 2)
            self.lines.append([UBB, plus_half_sd, BB, minus_half_sd, LBB])

        # 开始创建页面
        # 设置主要字体
        self.myfont = QFont('Arial', 12, QFont.Bold)
        # 页面的主要布局采用垂直布局
        self.main_layout = QVBoxLayout(self)

        # 创建顶部选择控件
        top_widget = QWidget()
        # 采用水平布局
        top_layout = QHBoxLayout()

        # 创建控件
        capital_label = QLabel('Capital')
        capital_label.setFont(self.myfont)

        self.capital_lineedit = QLineEdit()
        self.capital_lineedit.setPlaceholderText('ex: 100000')
        self.capital_lineedit.setFont(self.myfont)

        risk_label = QLabel('Risk tolerance')
        risk_label.setFont(self.myfont)

        self.risk_lineedit = QLineEdit()
        self.risk_lineedit.setPlaceholderText('ex: 0.02')
        self.risk_lineedit.setFont(self.myfont)

        stop_coef_label = QLabel('Stop Coefficient')
        stop_coef_label.setFont(self.myfont)

        self.stop_coef_lineedit = QLineEdit()
        self.stop_coef_lineedit.setPlaceholderText('ex: 0.1')
        self.stop_coef_lineedit.setFont(self.myfont)

        self.calculate_btn = QPushButton('Calculate')
        self.calculate_btn.setFont(self.myfont)
        self.calculate_btn.setShortcut(Qt.Key_Return)
        self.calculate_btn.clicked.connect(self.show_position_table)

        # 将这些控件加入top_layout
        top_layout.addWidget(capital_label)
        top_layout.addWidget(self.capital_lineedit)
        top_layout.addWidget(risk_label)
        top_layout.addWidget(self.risk_lineedit)
        top_layout.addWidget(stop_coef_label)
        top_layout.addWidget(self.stop_coef_lineedit)
        top_layout.addWidget(self.calculate_btn)

        # 设置top_widget的layout
        top_widget.setLayout(top_layout)
        top_widget.setContentsMargins(0, 40, 0, 40)

        # 将top_widget加入到总的main_layout
        self.main_layout.addWidget(top_widget)

        # 创建显示position的表格
        self.rows_name = [
            'Current Price', 'Risk Exposure', 'Daily ATR', 'Trend',
            'Trend Score', 'Position', 'Entry Proximal', 'Entry Distal',
            'Target', 'Stop Price', 'Position Size', 'Position Value'
        ]
        self.position_table = QTableWidget()
        self.position_table.setColumnCount(len(self.etfs))
        self.position_table.setRowCount(len(self.rows_name))

        # 设置宽度自由扩展
        self.position_table.horizontalHeader().setMinimumHeight(60)
        self.position_table.horizontalHeader().setDefaultAlignment(
            Qt.AlignCenter)
        self.position_table.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        self.position_table.verticalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        self.position_table.verticalHeader().setDefaultAlignment(
            Qt.AlignCenter)

        # 设置表头高度
        self.position_table.horizontalHeader().setMinimumHeight(60)
        self.position_table.horizontalHeader().setFont(self.myfont)
        self.position_table.verticalHeader().setFont(self.myfont)
        # 设置表头内容
        self.position_table.setHorizontalHeaderLabels(self.etfs)
        self.position_table.setVerticalHeaderLabels(self.rows_name)

        # 禁止编辑
        self.position_table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        # 隐藏纵向header
        #self.position_table.verticalHeader().setVisible(False)

        # 将表格加入main_layout
        self.main_layout.addWidget(self.position_table)