Пример #1
0
    def load_intraday_data(folder, file_name):
        picked_cols = [' Open', ' High', ' Low', 'Close', ' Volume']
        renamed_cols = ['Open', 'High', 'Low', 'Close', 'Volume']
        data_type = {'Close': np.float64, 'High': np.float64, 'Low': np.float64, 'Open': np.float64, \
                     'ProductId': np.int32, 'Symbol': np.bytes_, 'Timestamp': np.bytes_, 'Volume': np.int64}

        tmp = pandas.read_csv(folder + '/' + file_name, dtype=data_type)
        dates = [
            Helper.datetime_to_string(Helper.parse_datetime(date_str))
            for date_str in list(tmp[' Timestamp'])
        ]

        return pandas.DataFrame(np.array(tmp[picked_cols]),
                                index=dates,
                                columns=renamed_cols)
Пример #2
0
 def data_to_date(self, data, date, stock_code=None):
     _data = {}
     for _data_type in ['daily', 'weekly']:
         if _data_type not in data:
             continue
         if stock_code is not None:
             mask = data[_data_type][
                 stock_code].index < Helper.date_to_string(date)
             _data[_data_type] = _data.get(_data_type, {})
             _data[_data_type] = data[_data_type][stock_code][mask]
         else:
             codes = data[_data_type].keys()
             for code in codes:
                 mask = data[_data_type][
                     code].index < Helper.date_to_string(date)
                 _data[_data_type] = _data.get(_data_type, {})
                 _data[_data_type][code] = data[_data_type][code][mask]
     return _data
Пример #3
0
    def moving_average(date, data, type, x):
        closes = []
        if type == 'day':
            closes = data.iloc[-x:]['Close']
        elif type in ['week', 'month']:
            start_day, end_day = None, date
            last_date_func = Helper.last_friday if type == 'week' else Helper.previous_last_day_of_month
            for _ in range(x):
                end_day = last_date_func(end_day)
                delta_days = 4 if type == 'week' else (end_day.day + 1)
                start_day = end_day - timedelta(days=delta_days)

                mask = data.index.to_series().between(
                    Helper.date_to_string(start_day),
                    Helper.date_to_string(end_day))

                closes.append(
                    data[mask]['Close'][-1]) if len(data[mask]) > 0 else None

        if len(closes) == x:
            return np.mean(closes)
        return None
Пример #4
0
 def get_year_by_time_str(self, str):
     return Helper.string_to_datetime(str)
Пример #5
0
 def get_range_time(self, data):
     start_time_str, end_time_str = super(IntradayTrader,
                                          self).get_range_time(data)
     return Helper.string_to_datetime(
         start_time_str), Helper.string_to_datetime(end_time_str)
Пример #6
0
    def trade(self, data):

        self.stock_codes = data['daily'].keys()
        start_time, end_time = self.get_range_time(data['daily'])
        days_count = Helper.days_from_range_time(start_time, end_time)

        for days in range(1, days_count):
            print 'processing...', round(float(days) / days_count, 5)

            date = start_time + timedelta(days=days)
            self.new_date_init()

            take_position_indicators = {}

            for stock_code in self.stock_codes:
                stock_data = self.data_to_date(data, date, stock_code)
                if len(stock_data['daily']) > 0:
                    if stock_code in self.holding_stocks:
                        should_take_profit = self.take_profit_condition(
                            date, stock_code, stock_data)
                        should_cut_lost = self.cut_loss_condition(
                            date, stock_code, stock_data)
                        if should_take_profit or should_cut_lost:
                            open_price = self.holding_stocks[stock_code]
                            del self.holding_stocks[stock_code]
                            stock_data = data['daily'][stock_code].loc[
                                data['daily'][stock_code].index >= date]
                            if len(stock_data) > 0:
                                close_info = stock_data.iloc[0]
                                self.close_position(close_info.name,
                                                    stock_code, open_price,
                                                    close_info['Close'],
                                                    self.holding_stocks.keys())
                        else:
                            _, criterion = self.take_position_condition(
                                date, stock_code, stock_data)
                            take_position_indicators[stock_code] = criterion
                    else:
                        should_take_position, criterion = self.take_position_condition(
                            date, stock_code, stock_data)
                        if should_take_position:
                            take_position_indicators[stock_code] = criterion

            holding_stocks = self.holding_stocks.keys()
            selected_stocks = self.selecting_stocks(date,
                                                    take_position_indicators)
            candidate_stocks = set(holding_stocks + selected_stocks)

            if len(candidate_stocks):
                for stock_code in candidate_stocks:
                    mask = data['daily'][stock_code].index >= date
                    stock_data = data['daily'][stock_code].loc[mask]
                    if len(stock_data) > 0:
                        if stock_code not in selected_stocks:
                            open_price = self.holding_stocks[stock_code]
                            close_info = stock_data.iloc[0]
                            del self.holding_stocks[stock_code]
                            self.close_position(close_info.name, stock_code,
                                                open_price,
                                                close_info['Close'],
                                                self.holding_stocks.keys())
                        elif stock_code not in self.holding_stocks:
                            open_info = stock_data.iloc[0]
                            self.holding_stocks[stock_code] = open_info['Open']
                            self.history_orders.append([
                                open_info.name, stock_code, 'open',
                                open_info['Open'], '',
                                ', '.join(self.holding_stocks.keys())
                            ])
                            self.record_take_position(date, stock_code,
                                                      open_info['Open'])