def get_window_profit(code, start_date, end_date): initial_deposit = 10000000 initial_price = 0 money = initial_deposit prev_close = 0 bought = {'quantity': 0, 'price': 0, 'balance': 0} trade_count = 0 today = start_date while today < end_date: while today.weekday() > 4: today += timedelta(days=1) _, today_data = stock_chart.get_day_period_data(code, today, today) price_list = list( map(lambda x: { 'high': x['3'], 'low': x['4'], 'close': x['5'] }, today_data)) if len(price_list) == 0: print('No data') today += timedelta(days=1) continue _, data = stock_chart.get_day_period_data(code, today - timedelta(days=40), today - timedelta(days=1)) low = price_list[0]['low'] high = price_list[0]['high'] close = price_list[0]['close'] mac = MovingAverageCross(data, 20, 120) mac.generate_signals() last_position = mac.df.signal[-1] if bought['quantity'] != 0 and last_position == 0: money = close * bought['quantity'] money -= money * 0.003 print('SELL', close) bought['quantity'] = 0 elif bought['quantity'] == 0 and last_position == 1 and prev_close != 0: bought['quantity'] = money / close money = 0 trade_count += 1 print('BUY', close) if initial_price == 0: initial_price = close prev_close = close left = money if money != 0 else bought['quantity'] * prev_close yield today, left / initial_deposit * 100, last_position, close / initial_price * 100, trade_count print(today, 'P:', '{0:0.3f}'.format(left / initial_deposit * 100), 'POS:', last_position, '{0:0.3f}'.format(close / initial_price * 100)) today += timedelta(days=1)
def get_profit(code, start_date, end_date, buy_rate, sell_rate): initial_deposit = 10000000 money = initial_deposit prev_close = 0 bought = {'quantity': 0, 'price': 0} trade_count = 0 while end_date > start_date: start_date += timedelta(days=1) l, data = stock_chart.get_day_period_data( code, start_date, start_date + timedelta(days=1)) if l == 0: continue high, low, close = data[0]['3'], data[0]['4'], data[0]['5'] buy_threshold = prev_close * buy_rate sell_threshold = prev_close * sell_rate if bought['quantity'] is not 0 and high >= prev_close + buy_threshold: money = close * bought['quantity'] money -= money * 0.003 bought['quantity'] = 0 elif bought[ 'quantity'] is 0 and prev_close != 0 and low <= prev_close - sell_threshold: bought['quantity'] = money / close money = 0 trade_count += 1 prev_close = close left = money if money is not 0 else bought['quantity'] * prev_close return (left / initial_deposit * 100, trade_count)
def get_window_profit(code, start_date, end_date, method): initial_deposit = 10000000 money = initial_deposit prev_close = 0 bought = {'quantity': 0, 'price': 0, 'balance': 0} trade_count = 0 method_apply = { profit_calc.NORMAL: profit_calc.right_profit, profit_calc.SHORT: profit_calc.short_profit, profit_calc.MEET_DESIRED_PROFIT: profit_calc.right_sell_profit, profit_calc.BUY_WHEN_BEARISH: profit_calc.left_profit, profit_calc.LIMIT: profit_calc.right_limit_profit, } today = start_date while today < end_date: while today.weekday() > 4: today += timedelta(days=1) s = speculation.Speculation() sdf = s.get_speculation(today, [code], method) if len(sdf) == 0: today += timedelta(days=1) continue buy_rate = sdf.iloc[0]['buy_rate'] sell_rate = sdf.iloc[0]['sell_rate'] _, data = stock_chart.get_day_period_data(code, today, today) price_list = list(map(lambda x: {'high': x['3'], 'low': x['4'], 'close': x['5']}, data)) if len(price_list) == 0: print('No data') today += timedelta(days=1) continue elif len(price_list) > 1: print('Something wrong', today) low = price_list[0]['low'] high = price_list[0]['high'] close = price_list[0]['close'] buy_threshold = prev_close * buy_rate sell_threshold = prev_close * sell_rate money, t = method_apply[method](bought, low, high, close, prev_close, buy_threshold, sell_threshold, money, trade_count) trade_count += t prev_close = close today += timedelta(days=1) if method == profit_calc.SHORT: left = money if money is not 0 else (bought['price'] - prev_close) * bought['quantity'] + bought['balance'] else: left = money if money != 0 else bought['quantity'] * prev_close return left / initial_deposit * 100, trade_count
def get_window_profit(code, start_date, end_date): initial_deposit = 10000000 initial_price = 0 money = initial_deposit prev_close = 0 bought = {'quantity': 0, 'price': 0, 'balance': 0} trade_count = 0 today = start_date while today < end_date: while today.weekday() > 4: today += timedelta(days=1) s = speculation.Speculation() sdf = s.get_speculation(today, [code], profit_calc.MEET_DESIRED_PROFIT) if len(sdf) == 0: today += timedelta(days=1) continue buy_rate = sdf.iloc[0]['buy_rate'] sell_rate = sdf.iloc[0]['sell_rate'] _, data = stock_chart.get_day_period_data(code, today, today) price_list = list(map(lambda x: {'high': x['3'], 'low': x['4'], 'close': x['5']}, data)) if len(price_list) == 0: print('No data') today += timedelta(days=1) continue elif len(price_list) > 1: print('Something wrong', today) low = price_list[0]['low'] high = price_list[0]['high'] close = price_list[0]['close'] sell_threshold = prev_close * sell_rate buy_threshold = prev_close * buy_rate #print('CLOSE:', close, 'LOW:', low, 'SELL_THRESHOLD') if bought['quantity'] != 0 and (low <= prev_close - sell_threshold or sdf.iloc[0]['profit_expected'] < 100.): money = close * bought['quantity'] money -= money * 0.003 bought['quantity'] = 0 elif bought['quantity'] == 0 and prev_close != 0 and sdf.iloc[0]['profit_expected'] > 100. and high >= prev_close + buy_threshold: bought['quantity'] = money / close money = 0 trade_count += 1 if initial_price == 0: initial_price = close prev_close = close left = money if money != 0 else bought['quantity'] * prev_close yield today, left / initial_deposit * 100, sdf.iloc[0]['profit_expected'], sell_rate, close / initial_price * 100, trade_count print(today, 'P:', '{0:0.3f}'.format(left / initial_deposit * 100), 'E:', '{0:0.3f}'.format(sdf.iloc[0]['profit_expected']), '{0:0.3f}'.format(sell_rate), '{0:0.3f}'.format(close / initial_price * 100)) today += timedelta(days=1)
def get_yesterday(yesterday): max_depth = 10 while True: if max_depth <= 0: return None, None l, data = stock_chart.get_day_period_data(code, yesterday, yesterday + timedelta(days=1)) if l == 0: yesterday = yesterday - timedelta(days=1) max_depth -= 1 else: break return yesterday - timedelta(days=1), data
def get_tomorrow(tomorrow): max_depth = 10 while True: if max_depth <= 0: return None, None l, data = stock_chart.get_day_period_data(code, tomorrow, tomorrow + timedelta(days=1)) if l == 0: tomorrow = tomorrow + timedelta(days=1) max_depth -= 1 else: break return tomorrow + timedelta(days=1), data
self.df['signal'] = 0.0 self.df['mavg'] = self.df['close'].rolling(self.period, min_periods=1).mean() self.df['emavg'] = self.df['close'].ewm(span=self.period, min_periods=1, adjust=False, ignore_na=False).mean() self.df['signal'][self.period:] = np.where( self.df.emavg[self.period:] < self.df['close'][self.period:], 1.0, 0.0) self.df['positions'] = self.df['signal'].diff() print(self.df) if __name__ == '__main__': _, data = stock_chart.get_day_period_data('A005380', datetime(2015, 1, 1), datetime(2018, 11, 30)) mac = MovingAverageCross(data, 20) mac.generate_signals() fig = plt.figure() fig.patch.set_facecolor('white') ax1 = fig.add_subplot(111, ylabel='price') mac.df['close'].plot(ax=ax1, color='r', lw=2.) mac.df[['mavg', 'emavg']].plot(ax=ax1, lw=2.) ax1.plot(mac.df.ix[mac.df.positions == -1.0].index, mac.df.close[mac.df.positions == -1.0], 'v', markersize=10, color='k') ax1.plot(mac.df.ix[mac.df.positions == 1.0].index,
def get_window_profit(code, start_date, end_date, cons): initial_deposit = 10000000 initial_price = 0 money = initial_deposit prev_close = 0 bought = {'quantity': 0, 'price': 0, 'balance': 0} trade_count = 0 today = start_date while today < end_date: while today.weekday() > 4: today += timedelta(days=1) _, data = stock_chart.get_day_period_data(code, today, today) price_list = list(map(lambda x: {'high': x['3'], 'low': x['4'], 'close': x['5']}, data)) if len(price_list) == 0: print('No data') today += timedelta(days=1) continue elif len(price_list) > 1: print('Something wrong', today) high_past = [] low_past = [] collecting = False yesterday = today - timedelta(days=1) while True: if len(high_past) == cons: collecting = True break yesterday, ydata = get_yesterday(yesterday) if ydata is None: break ylist = list(map(lambda x: {'high': x['3'], 'low': x['4'], 'close': x['5']}, ydata))[0] high_past.append(ylist['high']) low_past.append(ylist['low']) if not collecting: print('failed to get past data') continue low = price_list[0]['low'] high = price_list[0]['high'] close = price_list[0]['close'] b_condition = max(high_past) < high s_condition = min(low_past) > low if bought['quantity'] != 0 and s_condition: money = close * bought['quantity'] money -= money * 0.003 bought['quantity'] = 0 elif bought['quantity'] == 0 and b_condition and prev_close != 0: bought['quantity'] = money / close money = 0 trade_count += 1 if initial_price == 0: initial_price = close prev_close = close left = money if money != 0 else bought['quantity'] * prev_close yield today, left / initial_deposit * 100, close / initial_price * 100, trade_count print(today, 'P:', '{0:0.3f}'.format(left / initial_deposit * 100), '{0:0.3f}'.format(close / initial_price * 100), 'T:', trade_count) today += timedelta(days=1)
return today_low, today_max, today_close print(today, '\t{0:0.2f}'.format(today_max), '\t{0:0.2f}'.format(today_low), '\t{0:0.2f}'.format(today_close)) return None #print(today) if __name__ == '__main__': code_list = stock_code.get_kospi200_list() df = pd.DataFrame(columns=['code', 'date', 'low', 'max', 'close']) for code in code_list: today = datetime(2015, 1, 1) test = 10 while datetime.now() > today: l, data = stock_chart.get_day_period_data( code, today, today + timedelta(days=1)) if l == 0: today += timedelta(days=1) continue else: r = get_today_profit(code, today, data) if r is not None: df = df.append( { 'code': code, 'date': today, 'low': r[0], 'max': r[1], 'close': r[2] }, ignore_index=True)
code_list = stock_code.get_kospi200_list() start_date = datetime(2018, 10, 22) s = speculation.Speculation() sp_list = s.get_speculation(start_date, code_list) df = pd.DataFrame(sp_list) n = datetime.now() df['real_profit'] = np.zeros(len(df)) for code in code_list: _, data = stock_chart.get_day_period_data(code, start_date + timedelta(days=1), datetime.now()) price_list = list( map(lambda x: { 'high': x['3'], 'low': x['4'], 'close': x['5'] }, data)) buy_rate = df[df['code'] == code].iloc[0]['buy_rate'] sell_rate = df[df['code'] == code].iloc[0]['sell_rate'] profit, _ = profit_calc.get_avg_profit_by_day_data( pd.DataFrame(price_list), buy_rate, sell_rate) df.loc[df['code'] == code, 'real_profit'] = profit
#code_list = ['A298040'] total_p = pd.DataFrame(columns=['code', 'profit']) PERIOD = 24 * 3 for code in code_list: df = pd.DataFrame(columns=[ 'code', 'date', 'price', 'trend_upper', 'trend_lower', 'signal', 'bought', 'sold', 'volume', 'foreign', 'profit' ]) df.set_index('date') bought_price = 0 total_profit = 100 count, total = stock_chart.get_day_period_data(code, datetime(2016, 1, 1), datetime(2018, 1, 1)) if count == 0: print("NO DATA", code) continue day_window = PERIOD + 1 for i in range(0, count - day_window): data = total[i:day_window + i] ptl = PriceTrendLine(data) result = ptl.generate_line() bought, sold = False, False profit = 0 skip_current = False trend_upper, trend_lower = result[0][2], result[1][2]
code_list = ['A003850', 'A047050', 'A001740'] for loss in [-2]: total_p = pd.DataFrame(columns=['code', 'profit']) for code in code_list: df = pd.DataFrame(columns=[ 'code', 'date', 'price', 'trend_upper', 'trend_lower', 'buy_price', 'sell_price', 'profit' ]) today = datetime(2015, 1, 1) bought_price = 0 total_profit = 100 skip_flow = False count, total = stock_chart.get_day_period_data( code, today, datetime.now()) day_window = 91 - 24 # 3 month + 1 day for i in range(0, count - day_window): data = total[i:day_window + i] ptl = PriceTrendLine(data) result = ptl.generate_line() sell_price = 0 profit = 0 trend_upper, trend_lower = result[0][2], result[1][2] if not (trend_upper and trend_lower): skip_flow = False if bought_price > 0 and not (trend_upper and trend_lower):
def generate_line(self): upper_line = self._find_line(True) lower_line = self._find_line(False) return upper_line, lower_line if __name__ == '__main__': # A005930: 2016,10,6 if len(sys.argv) < 5: print('python trendline.py [code] [year] [month] [day]') sys.exit(1) today = datetime(int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4])) _, data = stock_chart.get_day_period_data(sys.argv[1], today - timedelta(days=30), today) mac = PriceTrendLine(data) upper_line, lower_line = mac.generate_line() fig = plt.figure() fig.patch.set_facecolor('white') ax1 = fig.add_subplot(311, ylabel='price') ax2 = fig.add_subplot(312, ylabel='volume') ax3 = fig.add_subplot(313, ylabel='foreign') mac.df['close'].plot(ax=ax1, color='r', lw=2.) ax1.plot(upper_line[0], upper_line[1], color='b', lw=2., marker='o') ax1.plot(lower_line[0], lower_line[1], color='g', lw=2., marker='o') mac.df['volume'].plot(ax=ax2, color='g') mac.df['foreign'].plot(ax=ax3, color='b') plt.show()
self.calculating = df[:90] self.simulation = {} self.simulation['Actual'] = list(df.close.iloc[90:].values) for i in range(RandomWalk.SIMULATION_COUNT): self.simulation['Simulation' + str(i)] = [df.close.iloc[90]] def generate_signals(self): mu = self.calculating.close.pct_change().mean() sigma = self.calculating.close.pct_change().std() for s in range(RandomWalk.SIMULATION_COUNT): for i in range(len(self.simulation['Actual']) - 1): next_day = self.simulation['Simulation' + str(s)][-1] * np.exp((mu - (sigma ** 2 / 2)) + sigma * np.random.normal()) self.simulation['Simulation' + str(s)].append(next_day) return self.simulation if __name__ == '__main__': _, data = stock_chart.get_day_period_data('A005380', datetime(2019, 1, 1), datetime.now()) mac = RandomWalk(data) simulation_df = pd.DataFrame(mac.generate_signals()) fig = plt.figure() fig.patch.set_facecolor('white') ax1 = fig.add_subplot(111, ylabel='price') _ = simulation_df.plot(ax=ax1) #simulation_df[['Actual', 'Simulation']].plot(ax=ax1, lw=1.) plt.show()