def get_past_day_data(code, from_date, until_date, mavg=MAVG): from_date = from_date if from_date.__class__.__name__ == 'date' else from_date.date( ) until_date = until_date if until_date.__class__.__name__ == 'date' else until_date.date( ) past_data = stock_api.request_stock_day_data( get_reader(), code, from_date - timedelta(days=int(mavg * 1.5)), until_date) past_data = _convert_data_readable(code, past_data) # until_date shall not be holiday cut_by_date_data = [] for data in past_data: if from_date <= data['date'].date() <= until_date: cut_by_date_data.append(data) if holidays.count_of_working_days(from_date, until_date) > len(cut_by_date_data): print('get_past_day_data days not matched', code, from_date, until_date, 'data', "expected:", holidays.count_of_working_days(from_date, until_date), "actual:", len(cut_by_date_data)) #return [] return cut_by_date_data
def load_data(self, code, target_date): yesterday = holidays.get_yesterday(target_date) print('target_date', target_date, 'yesterday', yesterday) yesterday_min_data = stock_api.request_stock_minute_data(message_reader, code, yesterday, yesterday) if len(yesterday_min_data) <= 10: print('NO or LESS YESTERDAY MIN DATA', code, yesterday) return today_min_data = stock_api.request_stock_minute_data(message_reader, code, target_date, target_date) if len(today_min_data) <= 10: print('NO or LESS TODAY MIN DATA', code, target_date) return past_datas = stock_api.request_stock_day_data(message_reader, code, yesterday - timedelta(days=30), yesterday) if len(past_datas) <= 10: print('NO or LESS PAST DATA', code, yesterday - timedelta(days=30), yesterday) return self.yesterday = yesterday self.today = target_date vol = 0 for d in past_datas: vol += d['6'] self.volume_average = int(vol / len(past_datas)) self.clear_datas() yesterday_min_close = yesterday_min_data[-1]['5'] self.price_range[0] = yesterday_min_close - int(yesterday_min_close * 0.1) self.price_range[1] = yesterday_min_close + int(yesterday_min_close * 0.1) for ym in yesterday_min_data: if ym['4'] < self.price_range[0]: self.price_range[0] = ym['4'] if ym['3'] > self.price_range[1]: self.price_range[1] = ym['3'] self.yesterday_min_data_c.append(dt.cybos_stock_day_tick_convert(ym)) for tm in today_min_data: if tm['4'] < self.price_range[0]: self.price_range[0] = tm['4'] if tm['3'] > self.price_range[1]: self.price_range[1] = tm['3'] self.today_min_data_c.append(dt.cybos_stock_day_tick_convert(tm)) self.calc_moving_average(self.yesterday_min_data_c, self.today_min_data_c) ef = edgefinder.EdgeFinder(self.moving_average) self.edges.extend(ef.get_peaks(True)) self.edges.extend(ef.get_peaks(False)) self.edges = sorted(self.edges, key=lambda x: x[0]) yesterday_average = self.create_average_data(yesterday, self.yesterday_min_data_c) today_average = self.create_average_data(target_date, self.today_min_data_c) self.average_data.extend(yesterday_average) self.average_data.extend(today_average) self.up_to = datetime.combine(yesterday, time(12)) self.set_figure_data(self.up_to)
def get_past_data(reader, code, from_date, until_date): past_data = stock_api.request_stock_day_data(reader, code, from_date, until_date) if trader_env.MAVG * 2 * 0.6 > len(past_data): #print('PAST DATA too short', len(past_data), code) return [] elif past_data[-1]['0'] != time_converter.datetime_to_intdate(until_date): #print(code, until_date, 'Cannot get last day data') return [] return past_data
def get_future_data(reader, code, from_date): past_data = stock_api.request_stock_day_data(reader, code, from_date, from_date + timedelta(days=int(future_day*2))) if len(past_data) < future_day: return [] past_data_c = [] for data in past_data[:future_day+1]: past_data_c.append(dt.cybos_stock_day_tick_convert(data)) start_price = past_data_c[0]['close_price'] profits = [] for data in past_data_c[1:]: profits.append((data['close_price'] - start_price) / start_price * 100) return profits
def get_window_data(reader, code, until_date): past_data = stock_api.request_stock_day_data(reader, code, until_date - timedelta(days=int(window_size*2)), until_date) if window_size > len(past_data): return [], [], [], [], [] elif past_data[-1]['0'] != time_converter.datetime_to_intdate(until_date): return [], [], [], [], [] past_data_c = [] for data in past_data[-90:]: past_data_c.append(dt.cybos_stock_day_tick_convert(data)) close_datas = [d['close_price'] for d in past_data_c] amount_datas = [d['amount'] for d in past_data_c] close_datas_recent = close_datas[-30:] amount_datas_recent = amount_datas[-30:] return past_data_c, close_datas, amount_datas, close_datas_recent, amount_datas_recent
def get_candidate_code(market, yesterday, message_reader): # message.KOSPI or message.KOSDAQ market_code = stock_api.request_stock_code(message_reader, market) past_datas = [] candidates = [] for i, code in enumerate(market_code): past_data = stock_api.request_stock_day_data(message_reader, code, yesterday, yesterday) if len(past_data) == 1: data = past_data[0] data['code'] = code past_datas.append(data) else: print('No DATA or over size', code) print('Code Day Data', f'{i}/{len(market_code)}') past_datas = sorted(past_datas, key=lambda x: x['7'], reverse=True) past_datas = past_datas[:150] for data in past_datas: if data['9'] > data['8']: candidates.append(data['code']) return candidates
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] past_data = past_data_c[:-1] if code in long_codes: profit = (today_data['close_price'] - long_codes[code]['buy_price'] ) / long_codes[code]['buy_price'] * 100. long_codes[code]['profit'].append(profit) if len(long_codes[code]['profit']) >= 30: trades.append({ 'code': code,
def get_past_data(reader, code, from_date, until_date): past_data = stock_api.request_stock_day_data(reader, code, from_date, until_date) return past_data
check_new_highest = False 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) candidates = [] for i, code in enumerate(market_code): past_data = stock_api.request_stock_day_data(message_reader, code, from_date - timedelta(days=MAVG*2), from_date) if MAVG * 2 * 0.6 > len(past_data): #print('PAST DATA too short', len(past_data), code) continue past_data_c = convert_data_readable(code, past_data) today_data = past_data_c[-1] past_data = past_data_c[:-1] if code in long_codes: profit = (today_data['close_price'] - long_codes[code]['buy_price']) / long_codes[code]['buy_price'] * 100. long_codes[code]['profit'].append(profit) if today_data['moving_average'] > today_data['close_price'] or profit < -5.: trades.append({'code': code, 'buy_date': long_codes[code]['buy_date'], 'sell_date': from_date,
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() code = 'A028300' #market_code = stock_api.request_stock_code(message_reader, message.KOSDAQ) from_date = date(2020, 1, 3) until_date = date(2020, 1, 8) past_data = stock_api.request_stock_day_data(message_reader, code, from_date, until_date) past_data_c = convert_data_readable(code, past_data) current_price = past_data_c[0]['close_price'] past_data_c = past_data_c[1:] x = np.linspace(-0.01, 0.01) fig, ax = plt.subplots() for data in past_data_c: # price per 1 share = amount / (cum_buy_volume + cum_sell_volume) # ax + by + c = 0 a = cum_buy_volume * pp1, b = cum_sell_volume * pp1 price_per_share = data['amount'] / (data['cum_buy_volume'] + data['cum_sell_volume']) a = data['cum_buy_volume'] b = data['cum_sell_volume'] c = (data['close_price'] - current_price) print('amount', data['amount'], 'volume',
'yesterday_moving_average', 'top_short', 'top_long', 'bottom_short', 'bottom_long' ]) while from_date <= until_date: if holidays.is_holidays(from_date): from_date += timedelta(days=1) continue yesterday = holidays.get_yesterday(from_date) yesterday_datas = [] avg_datas = [] for code in market_code: past_data = stock_api.request_stock_day_data( message_reader, code, yesterday - timedelta(days=max_days), from_date) if max_days * 0.6 > len(past_data): print('PAST DATA too short', len(past_data), code) continue today_min_data = stock_api.request_stock_minute_data( message_reader, code, from_date, from_date) if len(today_min_data) == 0: print('NO TODAY MIN DATA', code, from_date) continue yesterday_min_data = stock_api.request_stock_minute_data( message_reader, code, yesterday, yesterday) if len(yesterday_min_data) <= 10: print('NO or LESS YESTERDAY MIN DATA', code, yesterday)
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
# find moment over 1% profit moments = {} # {'profit', 'buy_sell_rate', 'amount'} while from_date <= until_date: if holidays.is_holidays(from_date): from_date += timedelta(days=1) continue print('RUN', from_date) yesterday = holidays.get_yesterday(from_date) candidates = [] for i, code in enumerate(market_code): past_data = stock_api.request_stock_day_data(message_reader, code, yesterday, yesterday) print('GET DAY DATA', f'{i+1}/{len(market_code)}', end='\r') if len(past_data) == 0: continue past_data = past_data[0] candidates.append({'code': code, 'yesterday_amount': past_data['7']}) candidates = sorted(candidates, key=lambda x: x['yesterday_amount'], reverse=True) candidates = candidates[:150] print('') for i, c in enumerate(candidates): print('Process Minute DATA', f'{i+1}/{len(candidates)}', end='\r') today_min_data = stock_api.request_stock_minute_data(message_reader, c['code'], from_date, from_date) if len(today_min_data) <= 300: continue today_min_data_c = []
def consumer(): global message_reader 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() #stock_api.subscribe_trade(message_reader, display_trade_result) while True: val = q.get(True) command = val.decode('ascii').rstrip() #print(command) if command == 'long': print(stock_api.request_long_list(message_reader)) elif command.startswith('stats'): print(stock_api.request_subscribe_stat(message_reader)) elif command.startswith('subscribe_code'): codes = stock_api.request_subscribe_codes(message_reader) for code in codes: if len(code) > 10 or not code.startswith('A'): print(code) elif command.startswith('statc'): cinfo = stock_api.request_collector_stat(message_reader) print('total collector', len(cinfo)) print('total subscribe count', sum([c['subscribe_count'] for c in cinfo])) for i, ci in enumerate(cinfo): print(i, '\t', 'name', ci['name'], 'vendor', ci['vendor'], 'subscribe count', ci['subscribe_count']) elif command.startswith('trade_subscribe'): stock_api.subscribe_trade(message_reader, display_trade_result) elif command.startswith('trade_stop_subscribe'): stock_api.stop_subscribe_trade(message_reader) elif command.startswith('min_data'): min_detail = command.split(',') if len(min_detail) != 2: print('min_data,code') else: result = stock_api.request_stock_minute_data(message_reader, min_detail[1], date(2020,2,3), date(2020,2,3)) print(result) elif command.startswith('todaym'): todaym_detail = command.split(',') if len(todaym_detail) != 2: print('todaym,code') else: result = stock_api.request_stock_today_data(message_reader, todaym_detail[1]) if len(result) > 1: print('DATA LEN', len(result)) print('HEAD', result[0]) print(result[1]) print('TAIL', result[-1]) print(result) elif command.startswith('todayt'): todaym_detail = command.split(',') if len(todaym_detail) != 2: print('todayt,code') else: result = stock_api.request_stock_today_tick_data(message_reader, todaym_detail[1]) if len(result) > 1: print('DATA LEN', len(result)) print('HEAD', result[0]) print(result[1]) print('TAIL', result[-1]) elif command.startswith('buy') or command.startswith('sell'): buy_detail = command.split(',') print(buy_detail) if len(buy_detail) != 4: print('buy|sell,code,price,quantity') else: is_buy = True if buy_detail[0] == 'buy': pass elif buy_detail[0] == 'sell': is_buy = False else: print('wrong buy/sell command') continue code = buy_detail[1] price = int(buy_detail[2]) quantity = int(buy_detail[3]) result = stock_api.order_stock(message_reader, code, price, quantity, is_buy) print(result) elif command.startswith('modify'): modify_detail = command.split(',') if len(modify_detail) != 4: print('modify,order_num,code,price') else: order_num = int(modify_detail[1]) code = modify_detail[2] price = int(modify_detail[3]) result = stock_api.modify_order(message_reader, order_num, code, price) print(result) elif command.startswith('cancel'): cancel_detail = command.split(',') if len(cancel_detail) != 4: print('cancel,order_num,code,amount') else: order_num = int(cancel_detail[1]) code = cancel_detail[2] amount = int(cancel_detail[3]) result = stock_api.cancel_order(message_reader, order_num, code, amount) print(result) elif command.startswith('queue'): print(stock_api.request_order_in_queue(message_reader)) elif command.startswith('balance'): print(stock_api.get_balance(message_reader)['balance']) elif command.startswith('subject'): subject_detail = command.split(',') if len(subject_detail) != 2: print('subject,code') else: code = subject_detail[1] stock_api.subscribe_stock_subject(message_reader, code, display_subject_data) elif command.startswith('stop_subject'): subject_detail = command.split(',') if len(subject_detail) != 2: print('stop_subject,code') else: code = subject_detail[1] stock_api.stop_subscribe_stock_subject(message_reader, code) elif command.startswith('stop_bidask'): bidask_detail = command.split(',') if len(bidask_detail) != 2: print('stop_bidask,code') else: code = bidask_detail[1] stock_api.stop_subscribe_stock_bidask(message_reader, code) elif command.startswith('bidask'): bidask_detail = command.split(',') if len(bidask_detail) != 2: print('bidask,code') else: code = bidask_detail[1] stock_api.subscribe_stock_bidask(message_reader, code, display_bidask_data) elif command.startswith('stock'): stock_detail = command.split(',') if len(stock_detail) != 2: print('stock,code') else: code = stock_detail[1] stock_api.subscribe_stock(message_reader, code, display_stock_data) elif command.startswith('stop_stock'): stock_detail = command.split(',') if len(stock_detail) != 2: print('stop_stock,code') else: code = stock_detail[1] stock_api.stop_subscribe_stock(message_reader, code) elif command.startswith('req'): req_detail = command.split(',') if len(req_detail) != 2: print('req,code') else: code = req_detail[1] print(stock_api.request_stock_day_data(message_reader, code, date(2020,1,31), date(2020,1,31))) elif command.startswith('index'): index_detail = command.split(',') if len(index_detail) != 2: print('index,code') else: code = index_detail[1] stock_api.subscribe_index(message_reader, code, display_index_data) elif command.startswith('stop_index'): index_detail = command.split(',') if len(index_detail) != 2: print('index,code') else: code = index_detail[1] stock_api.stop_subscribe_index(message_reader, code) elif command.startswith('abroad'): abroad_detail = command.split(',') if len(abroad_detail) != 2: print('abroad,code') else: code = abroad_detail[1] print(stock_api.request_abroad_data(message_reader, code, message.PERIOD_DAY, 30)) elif command.startswith('uscode'): #print(stock_api.request_us_stock_code(message_reader, message.USTYPE_ALL)) print(len(stock_api.request_us_stock_code(message_reader, message.USTYPE_ALL))) elif command.startswith('world'): world_detail = command.split(',') if len(world_detail) != 2: print('world,code') else: code = world_detail[1] stock_api.subscribe_world(message_reader, code, display_world_data) elif command.startswith('stop_world'): world_detail = command.split(',') if len(world_detail) != 2: print('stop_world,code') else: code = world_detail[1] stock_api.stop_subscribe_world(message_reader, code) elif command.startswith('investor'): inv_detail = command.split(',') if len(inv_detail) != 2: print('investor,code') else: code = inv_detail[1] print(stock_api.request_investor_data(message_reader, code, date(2020,1,31), date(2020,1,31))) elif command.startswith('kinvestorc'): invc_detail = command.split(',') if len(invc_detail) != 2: print('investorc,code') else: code = invc_detail[1] print(stock_api.request_investor_accumulate_data(message_reader, code, date(2020,2,7), date(2020,2,7))) elif command.startswith('alarm'): stock_api.subscribe_alarm(message_reader, display_alarm_data) elif command.startswith('stop_alarm'): stock_api.stop_subscribe_alarm(message_reader) elif command.startswith('code_to_name'): code_detail = command.split(',') if len(code_detail) != 2: print('code_to_name,code') else: code = code_detail[1] print(stock_api.request_code_to_name(message_reader, code))