def __init__(self, market, d: date, use_db=False, institution_buy_days=0, max_count=80): super().__init__() while is_holidays(d): d -= timedelta(days=1) self.from_date = d self.max_count = max_count if max_count > 80 else 80 self.institution_buy_days = institution_buy_days self.stock = MongoClient(db.HOME_MONGO_ADDRESS)['stock'] self.codes = [] remote_codes = [] self.code_collection_name = 'KOSPI_CODES' if market == StockSearchBullChooser.KOSPI else 'KOSDAQ_CODES' self.code_bull_name = 'KOSPI_BULL' if market == StockSearchBullChooser.KOSPI else 'KOSDAQ_BULL' if use_db: codes = list(self.stock[self.code_collection_name].find()) for code in codes: remote_codes.append(code['code']) print('remote db', len(remote_codes)) if len(remote_codes) == 0: from morning.cybos_api.stock_code import get_kosdaq_company_code_list, get_kospi_company_code_list if market == StockSearchBullChooser.KOSPI: remote_codes = get_kospi_company_code_list() else: remote_codes = get_kosdaq_company_code_list() for code in remote_codes: self.stock[self.code_collection_name].insert_one( {'code': code}) self._search_day_data(remote_codes)
def _correct_date(d, now): if d > now.date(): d = now.date() if is_holidays(d): d = get_yesterday(d) if d == now.date() and now.hour < 18: d = get_yesterday(d) return d
def get_day_past_highest(code, today, days): stock_db = MongoClient(db.HOME_MONGO_ADDRESS)['stock'] yesterday = today - timedelta(days=1) while is_holidays(yesterday): yesterday -= timedelta(days=1) start = time_converter.datetime_to_intdate(yesterday - timedelta(days=days)) end = time_converter.datetime_to_intdate(yesterday) cursor = stock_db[code + '_D'].find({'0': {'$gte': start, '$lt': end}}) if cursor.count() == 0: return 0 return max([d['3'] for d in list(cursor)])
def info_changed(self, code, d): if holidays.is_holidays(d): from PyQt5.QtWidgets import QMessageBox QMessageBox.warning(self.get_figure(), 'Not available', 'Holiday') if self.current_code == code and self.current_dt == d: return self.current_code = code self.current_dt = d if len(code) == 0: self.codes = code_chooser.get_candidate_code(message.KOSDAQ, holidays.get_yesterday(d), message_reader) self.current_code = random.choice(self.codes) if len(self.current_code) > 0: self.load_data(self.current_code, d)
def run_subscriber(): while True: print('Run subscriber Wait') time.sleep(600) # wait until virtual machine is on now = datetime.now() year, month, day = now.year, now.month, now.day is_start_time = datetime(year, month, day, time_info.SUBSCRIBER_START_TIME['hour'], time_info.SUBSCRIBER_START_TIME['minute']) <= now < datetime(year, month, day, time_info.SUBSCRIBER_FINISH_TIME['hour'], time_info.SUBSCRIBER_FINISH_TIME['minute']) if not holidays.is_holidays(now.date()) and is_start_time: print('Run subscriber') subscribe_process = Process(target=main.start_vi_follower) subscribe_process.start() subscribe_process.join() time.sleep(600) print('Done subscriber')
sock.connect(server_address) message_reader = stream_readwriter.MessageReader(sock) message_reader.start() market_code = stock_api.request_stock_code(message_reader, message.KOSDAQ) from_date = date(2018, 1, 2) until_date = date(2020, 1, 4) PREV_DAYS = int(sys.argv[1]) long_codes = {} trades = [] # {'buy_date', 'buy_price', 'buy_date', 'profit'} while from_date <= until_date: if holidays.is_holidays(from_date): from_date += timedelta(days=1) continue print('RUN', from_date) for i, code in enumerate(market_code): print(f'{i+1}/{len(market_code)}', end='\r') past_data = stock_api.request_stock_day_data( message_reader, code, from_date - timedelta(days=int(PREV_DAYS * 1.5)), from_date) if PREV_DAYS * 1.5 * 0.6 > len(past_data): continue past_data_c = convert_data_readable(code, past_data) today_data = past_data_c[-1]
code_dict[code]['state'] = STATE_NONE elif abs((data['close_price'] - data['yesterday_close']) / data['yesterday_close'] * 100) > 3: code_dict[code]['state'] = STATE_NONE #TODO: STATE_BUY: buy at start price and, if reach to 10% then sell it if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (message.SERVER_IP, message.CLIENT_SOCKET_PORT) sock.connect(server_address) message_reader = stream_readwriter.MessageReader(sock) message_reader.start() market_code = stock_api.request_stock_code(message_reader, message.KOSDAQ) #market_code = ['A006050'] from_date = date(2019, 9, 1) until_date = date(2020, 1, 10) for code in market_code: code_dict[code] = {'state': STATE_NONE, 'bought_price': 0, 'bull_profit': 0, 'count': 0} while from_date <= until_date: if holidays.is_holidays(from_date): from_date += timedelta(days=1) continue start_today_trading(message_reader, market_code, from_date) from_date += timedelta(days=1)
message_reader = stream_readwriter.MessageReader(sock) message_reader.start() market_code = stock_api.request_stock_code(message_reader, message.KOSDAQ) target_code = ['A034230'] search_from = date(2019, 1, 2) search_until = date(2019, 12, 30) for code in target_code: today = datetime.now().date() yesterday = holidays.get_yesterday(today) yesterday = holidays.get_yesterday(yesterday) past_data, prices, amounts, recent_prices, recent_amounts = get_window_data(message_reader, code, yesterday) average_amount = np.array(recent_amounts).mean() while search_from <= search_until: if holidays.is_holidays(search_from): search_from += timedelta(days=1) continue for mcode in market_code: mpast_data, mprices, mamounts, recent_mprices, recent_mamounts = get_window_data(message_reader, mcode, search_from) if len(mpast_data) == 0: continue recent_amount_average = np.array(recent_mamounts).mean() if (average_amount * 0.7 > recent_amount_average or average_amount * 1.3 < recent_amount_average): continue recent_price_corr = scipy.stats.pearsonr(np.array(recent_prices), np.array(recent_mprices)) recent_amounts_corr = scipy.stats.pearsonr(np.array(recent_amounts), np.array(recent_mamounts)) if recent_price_corr[0] >= 0.5 and recent_amounts_corr[0] >= 0.5: price_corr = scipy.stats.pearsonr(np.array(prices), np.array(mprices))
def start_today_trading(reader, market_code, today, choosers): code_dict = dict() yesterday = holidays.get_yesterday(today) by_amounts = [] for progress, code in enumerate(market_code): print('collect past data', today, f'{progress+1}/{len(market_code)}', end='\r') yesterday_data = stock_api.request_stock_day_data( reader, code, yesterday, yesterday) if len(yesterday_data) != 1: continue elif yesterday_data[0]['5'] < 900: continue code_dict[code] = { 'code': code, 'past_min_data': [], 'today_min_data': None, 'time': 0, 'yesterday_close': yesterday_data[0]['5'], 'today_gap': 0, 'until_now_profit': 0 } min_req_from = today - timedelta(days=10) min_req_until = today while min_req_from <= min_req_until: if holidays.is_holidays(min_req_from): min_req_from += timedelta(days=1) continue min_data = stock_api.request_stock_minute_data( reader, code, min_req_from, min_req_from) if len(min_data) > 0: min_data_c = [] for md in min_data: min_data_c.append(dt.cybos_stock_day_tick_convert(md)) code_dict[code]['past_min_data'].append(min_data_c) min_req_from += timedelta(days=1) if len(code_dict[code]['past_min_data']) > 5: code_dict[code]['today_min_data'] = code_dict[code][ 'past_min_data'][-1] code_dict[code]['today_gap'] = ( code_dict[code]['today_min_data'][0]['start_price'] - code_dict[code]['yesterday_close'] ) / code_dict[code]['yesterday_close'] * 100 code_dict[code]['past_min_data'] = code_dict[code][ 'past_min_data'][:-1] else: #print('not enough data', code) code_dict.pop(code, None) print('') for c in choosers: new_code_dict = dict() result = c(reader, code_dict) for r in result: new_code_dict[r] = code_dict[r] code_dict = new_code_dict return code_dict
report['high_profit'] = float("{0:.2f}".format((report['post_highest'] - report['buy_price']) / report['buy_price'] * 100.0)) report['low_profit'] = float("{0:.2f}".format((report['low_price'] - report['buy_price']) / report['buy_price'] * 100.0)) result.append(report) break else: if data['highest_price'] > report['post_highest']: report['post_highest'] = data['highest_price'] report['post_high_time'] = data['time'] if report['low_price'] == 0 or data['lowest_price'] < report['low_price']: report['low_price'] = data['lowest_price'] report['post_low_time'] = data['time'] """ if __name__ == '__main__': target_date = datetime.strptime(sys.argv[1], '%Y-%m-%d').date() market_codes = morning_client.get_all_market_code() while target_date <= datetime(2020, 6, 12, 0, 0, 0).date(): if holidays.is_holidays(target_date): target_date += timedelta(days=1) continue start_trading(target_date, market_codes) target_date += timedelta(days=1) df = pd.DataFrame(result) df.to_excel('930_' + str(target_date.year * 10000 + target_date.month * 100 + target_date.day) + '.xlsx')
until_d = until_date for code in market_code: code_dict[code]['state'] = STATE_UNKNOWN code_dict[code]['today_bull'] = 0 code_dict[code]['mvg'] = 0 code_dict[code]['buy_date'] = None code_dict[code]['buy_price'] = 0 code_dict[code]['amount'] = 0 code_dict[code]['set_date'] = None code_dict[code]['highest'] = 0 code_dict[code]['last_bull_date'] = None code_dict[code]['under_line_count'] = 0 while from_d <= until_d: if holidays.is_holidays(from_d): from_d += timedelta(days=1) continue start_today_trading(message_reader, market_code, from_d, bf, buyf) meet, cut = evaluate_meet_goal(message_reader, from_d) cut_count += cut meet_count += meet #print(from_date, f"cut: {cut}, meet: {meet}, state:{code_dict['A010660']['state']}, bull:{code_dict['A010660']['today_bull']}, mvg:{code_dict['A010660']['mvg']}") #print(from_date, f"cut: {cut}, meet: {meet}, state:{code_dict['A044960']['state']}, bull:{code_dict['A044960']['today_bull']}, mvg:{code_dict['A044960']['mvg']}") #print(from_d, f"cut: {cut}, meet: {meet}") from_d += timedelta(days=1) #print('-' * 100) print( bf, buyf, 'summary succeess', meet_count, 'cut:', cut_count, "{0:.2f}".format(meet_count / (meet_count + cut_count) * 100))