def compute_trading_points(self, stocks, szTimeAxis, n_ahead): assert len( stocks ) == 1, "This strategy allows only a daily candlestick data of one stock." code = next(iter(stocks)) cst = stocks[code].cst # get candlestick data DataTimeAxis = cst['1Day'].index # skip extra data TimeAxis = DataTimeAxis[n_ahead:] # buy with half capital at the first day ticker = TimeAxis[0] price = cst['1Day'].at[ticker, 'close'] _, shares, cash = buy(code, price, str(ticker), ratio=0.5) share = shares[code] # start trading for ticker in TimeAxis[1:]: price = cst['1Day'].at[ticker, 'close'] oneboardlot = 100 * price # One board lot is 100 shares in Chinese market stock_equity = share * oneboardlot if (stock_equity <= cash * (1 - self.fall_ratio)): # make even: make the stock equity approximate to current cash _, shares, cash = buy(code, price, str(ticker), cash=(cash - stock_equity) / 2.0) share = shares[code] if (stock_equity >= cash * (1 + self.rise_ratio)): quantity_to_sell = int( (stock_equity - cash) / 2.0 / oneboardlot) # make even: make the stock equity approximate to current cash shares, cash = sell(code, price, str(ticker), quantity_to_sell) share = shares[code]
def compute_trading_points(self, stocks, szTimeAxis, n_ahead): assert len(stocks) == 1, "This strategy allows only a daily candlestick data of one stock." code = next(iter(stocks)) cst = stocks[code].cst # get candlestick data DataTimeAxis = cst['1Day'].index # skip extra data TimeAxis = DataTimeAxis[n_ahead:] # buy with half capital at the first day ticker = TimeAxis[0] price = cst['1Day'].at[ticker,'close'] _, shares, cash = buy(code, price, str(ticker), ratio = 0.5) share = shares[code] # start trading for ticker in TimeAxis[1:]: price = cst['1Day'].at[ticker,'close'] oneboardlot = 100 * price # One board lot is 100 shares in Chinese market stock_equity = share * oneboardlot if (stock_equity <= cash*(1-self.fall_ratio)): # make even: make the stock equity approximate to current cash _, shares, cash = buy(code, price, str(ticker), cash = (cash-stock_equity)/2.0) share = shares[code] if (stock_equity >= cash*(1+self.rise_ratio)): quantity_to_sell = int((stock_equity-cash)/2.0/oneboardlot) # make even: make the stock equity approximate to current cash shares, cash = sell(code, price, str(ticker), quantity_to_sell) share = shares[code]
def compute_trading_points(self, stocks, szTimeAxis, n_ahead): assert len(stocks) == 1, "This strategy allows only a daily candlestick data of one stock." code = next(iter(stocks)) cst = stocks[code].cst # get candlestick data DataTimeAxis = cst['1Day'].index # MACD dif, dea, _ = self.MACD(cst['1Day']['close'].values) # skip extra data TimeAxis = DataTimeAxis[n_ahead:] df_macd = pd.DataFrame({'dif': dif[n_ahead:], 'dea': dea[n_ahead:]}, index = TimeAxis) # start trading start_flag, state_flag = 0, 0 for ticker in TimeAxis: # skip null value at the beginning if np.isnan(df_macd.at[ticker, 'dif']) or np.isnan(df_macd.at[ticker, 'dea']): continue # Skip the days of 'dif'>='dea' at the beginning. Those should be the days waiting for \ # selling, not buying, thus not suitable for a start if (start_flag == 0) and (df_macd.at[ticker, 'dif'] >= df_macd.at[ticker, 'dea']): continue else: start_flag = 1 # start trading if (start_flag == 1): price = cst['1Day'].at[ticker,'close'] oneboardlot = 100 * price # One board lot is 100 shares in Chinese market # the first buying if (state_flag == 0) and (price <= self.level) and\ (df_macd.at[ticker, 'dif'] > df_macd.at[ticker, 'dea']): quantity, shares, cash = buy(code, price, str(ticker), ratio=0.5) stock_equity = shares[code] * oneboardlot cost = quantity * oneboardlot state_flag = 1 continue # the second buying if price falls if (state_flag == 1) and (stock_equity < cost*(1-self.fall_ratio)): quantity, shares, cash = buy(code, price, str(ticker), ratio=1) cost += quantity * oneboardlot state_flag = 2 continue # sell if (state_flag >= 1) and (df_macd.at[ticker, 'dif'] <= df_macd.at[ticker, 'dea']): if (shares[code]*oneboardlot > cost*(1+self.rise_ratio)): shares, cash = sell(code, price, str(ticker), shares[code]) state_flag = 0 continue
def compute_trading_points(self, stocks, szTimeAxis, n_ahead): assert len(stocks) >= self.N, \ "This strategy requires at least N daily candlestick data of different stocks." self.init_stock_status(stocks, n_ahead) # start for ticker in szTimeAxis: # try to plant saplings if self.check_ready_to_buy( stocks ): # are we planting a sapling now? do the following if not ready_saplings = self.get_ready_saplings(stocks, ticker) if len(ready_saplings) > 0: planting_sapling = ready_saplings.pop(0) price = stocks[planting_sapling].cst['1Day'].at[ticker, 'close'] stocks[planting_sapling].quantity, _, _ = buy(planting_sapling, price, str(ticker), \ ratio = self.ratios[self.n_saplings]) stocks[planting_sapling].buy_price = price self.state_flags[planting_sapling] = 1 self.n_saplings += 1 else: # we are planting a sapling try: price = stocks[planting_sapling].cst['1Day'].at[ticker, 'close'] buy_price = stocks[planting_sapling].buy_price status = self.check_planting_sapling_status( planting_sapling, price, buy_price, ticker) # remove dead sapling if status == self.DEAD: sell(planting_sapling, price, str(ticker), stocks[planting_sapling].quantity) self.state_flags[planting_sapling] = 0 self.n_saplings -= 1 # record alive sapling if status == self.ALIVE: self.state_flags[planting_sapling] = 2 except KeyError: # candlestick data is not available at this datetime pass # try to harvest for code in stocks.keys(): if (self.start_flags[code] == 1) and stocks[code].quantity > 0: try: if (self.state_flags[code] == 2) and (self.macd[code].at[ticker, 'dif'] \ < self.macd[code].at[ticker, 'dea']): price = stocks[code].cst['1Day'].at[ticker, 'close'] sell(code, price, str(ticker), stocks[code].quantity) self.state_flags[code] = 0 self.n_saplings -= 1 except KeyError: # candlestick data is not available at this datetime pass
def compute_trading_points(self, stocks, szTimeAxis, n_ahead): assert len( stocks ) == 1, "This strategy allows only a daily candlestick data of one stock." code = next(iter(stocks)) cst = stocks[code].cst # get candlestick data DataTimeAxis = cst['1Day'].index # Moving average maf = MA(cst['1Day']['close'].values, self.nfast) mas = MA(cst['1Day']['close'].values, self.nslow) # skip extra data TimeAxis = DataTimeAxis[n_ahead:] df_ma = pd.DataFrame( { 'ma_fast': maf[n_ahead:], 'ma_slow': mas[n_ahead:] }, index=TimeAxis) #df_ma.plot() #plt.show() start_flag = 0 hold_flag = 0 for ticker in TimeAxis: # skip null value at the beginning if np.isnan(df_ma.at[ticker, 'ma_fast']) or np.isnan( df_ma.at[ticker, 'ma_slow']): continue # skip the days of 'ma_fast'>='ma_slow' at the beginning # those should be the days waiting fo selling, not buying, thus not suitable for a start if (start_flag == 0) and (df_ma.at[ticker, 'ma_fast'] <= df_ma.at[ticker, 'ma_slow']): continue else: start_flag = 1 # start trading if (start_flag == 1): price = cst['1Day'].at[ticker, 'close'] if (hold_flag == 0) and (df_ma.at[ticker, 'ma_fast'] > df_ma.at[ticker, 'ma_slow']): # quantity is the number of shares (unit: boardlot) you buy this time quantity, _, _ = buy(code, price, str(ticker), ratio=1) hold_flag = 1 if (hold_flag == 1) and (df_ma.at[ticker, 'ma_fast'] < df_ma.at[ticker, 'ma_slow']): # sell all the shares bought last time sell(code, price, str(ticker), quantity) hold_flag = 0
def compute_trading_points(self, stocks, szTimeAxis, n_ahead): assert len(stocks) >= self.N, \ "This strategy requires at least N daily candlestick data of different stocks." self.init_stock_status(stocks, n_ahead) # start for ticker in szTimeAxis: # try to plant saplings if self.check_ready_to_buy(stocks): # are we planting a sapling now? do the following if not ready_saplings = self.get_ready_saplings(stocks, ticker) if len(ready_saplings) > 0: planting_sapling = ready_saplings.pop(0) price = stocks[planting_sapling].cst['1Day'].at[ticker,'close'] stocks[planting_sapling].quantity, _, _ = buy(planting_sapling, price, str(ticker), \ ratio = self.ratios[self.n_saplings]) stocks[planting_sapling].buy_price = price self.state_flags[planting_sapling] = 1 self.n_saplings += 1 else: # we are planting a sapling try: price = stocks[planting_sapling].cst['1Day'].at[ticker,'close'] buy_price = stocks[planting_sapling].buy_price status = self.check_planting_sapling_status(planting_sapling, price, buy_price, ticker) # remove dead sapling if status == self.DEAD: sell(planting_sapling, price, str(ticker), stocks[planting_sapling].quantity) self.state_flags[planting_sapling] = 0 self.n_saplings -= 1 # record alive sapling if status == self.ALIVE: self.state_flags[planting_sapling] = 2 except KeyError: # candlestick data is not available at this datetime pass # try to harvest for code in stocks.keys(): if (self.start_flags[code] == 1) and stocks[code].quantity > 0: try: if (self.state_flags[code] == 2) and (self.macd[code].at[ticker, 'dif'] \ < self.macd[code].at[ticker, 'dea']): price = stocks[code].cst['1Day'].at[ticker,'close'] sell(code, price, str(ticker), stocks[code].quantity) self.state_flags[code] = 0 self.n_saplings -= 1 except KeyError: # candlestick data is not available at this datetime pass
def compute_trading_points(self, stocks, szTimeAxis, n_ahead): assert len(stocks) == 1, "This strategy allows only a daily candlestick data of one stock." code = next(iter(stocks)) cst = stocks[code].cst # get candlestick data DataTimeAxis = cst['1Day'].index # Moving average maf = MA(cst['1Day']['close'].values, self.nfast) mas = MA(cst['1Day']['close'].values, self.nslow) # skip extra data TimeAxis = DataTimeAxis[n_ahead:] df_ma = pd.DataFrame({'ma_fast': maf[n_ahead:], 'ma_slow': mas[n_ahead:]}, index = TimeAxis) #df_ma.plot() #plt.show() start_flag = 0 hold_flag = 0 for ticker in TimeAxis: # skip null value at the beginning if np.isnan(df_ma.at[ticker, 'ma_fast']) or np.isnan(df_ma.at[ticker, 'ma_slow']): continue # skip the days of 'ma_fast'>='ma_slow' at the beginning # those should be the days waiting fo selling, not buying, thus not suitable for a start if (start_flag == 0) and (df_ma.at[ticker, 'ma_fast'] <= df_ma.at[ticker, 'ma_slow']): continue else: start_flag = 1 # start trading if (start_flag == 1): price = cst['1Day'].at[ticker,'close'] if (hold_flag == 0) and (df_ma.at[ticker, 'ma_fast'] > df_ma.at[ticker, 'ma_slow']): # quantity is the number of shares (unit: boardlot) you buy this time quantity, _, _ = buy(code, price, str(ticker), ratio = 1) hold_flag = 1 if (hold_flag == 1) and (df_ma.at[ticker, 'ma_fast'] < df_ma.at[ticker, 'ma_slow']): # sell all the shares bought last time sell(code, price, str(ticker), quantity) hold_flag = 0
def compute_trading_points(self, stocks, szTimeAxis, n_ahead): assert len( stocks ) == 1, "This strategy allows only a daily candlestick data of one stock." code = next(iter(stocks)) cst = stocks[code].cst # get candlestick data DataTimeAxis = cst['1Day'].index close = cst['1Day']['close'].values # ExtremePrice highest, lowest = self.ExtremePrice(close, self.m) # skip extra data TimeAxis = DataTimeAxis[n_ahead:] df_extreme = pd.DataFrame({'close': close[n_ahead:], 'highest': highest[n_ahead:], \ 'lowest': lowest[n_ahead:]}, index = TimeAxis) #df_extreme.plot() #plt.show() hold_flag = 0 for ticker in TimeAxis: # skip null value at the beginning if np.isnan(df_extreme.at[ticker, 'highest']) or np.isnan( df_extreme.at[ticker, 'lowest']): continue # start trading price = cst['1Day'].at[ticker, 'close'] if (hold_flag == 0) and (df_extreme.at[ticker, 'close'] > df_extreme.at[ticker, 'highest']): # quantity is the number of shares (unit: boardlot) you buy this time quantity, _, _ = buy(code, price, str(ticker), ratio=1) hold_flag = 1 if (hold_flag == 1) and (df_extreme.at[ticker, 'close'] < df_extreme.at[ticker, 'lowest']): # sell all the shares bought last time sell(code, price, str(ticker), quantity) hold_flag = 0
def compute_trading_points(self, stocks, szTimeAxis, n_ahead): assert len(stocks) == 1, "This strategy allows only a daily candlestick data of one stock." code = next(iter(stocks)) cst = stocks[code].cst # get candlestick data DataTimeAxis = cst['1Day'].index close = cst['1Day']['close'].values # ExtremePrice highest, lowest = self.ExtremePrice(close, self.m) # skip extra data TimeAxis = DataTimeAxis[n_ahead:] df_extreme = pd.DataFrame({'close': close[n_ahead:], 'highest': highest[n_ahead:], \ 'lowest': lowest[n_ahead:]}, index = TimeAxis) #df_extreme.plot() #plt.show() # set position management and Risk control parameters # the proportion of your current cash for the first investment (if you earn # some profits, you would invest the rest of the cash). first_position = 0.25 # stop_loss: stop out when your loss of 1th position reach this proportion stop_loss = 0.04 # lock_profit: if your floating earn of 1th position reach this proportion, # enter state 2: sell all at a proper time that before you # lose the profits. lock_profit = 0.03 # start start_flag = 0 state_flag = 0 for ticker in TimeAxis: # skip null value at the beginning if np.isnan(df_extreme.at[ticker, 'highest']) or np.isnan(df_extreme.at[ticker, 'lowest']): continue # start trading price = cst['1Day'].at[ticker,'close'] if (state_flag == 0) and (df_extreme.at[ticker, 'close'] > df_extreme.at[ticker, 'highest']): # quantity is the number of shares (unit: boardlot) you buy this time # record quantity1 quantity1, _, _ = buy(code, price, str(ticker), ratio = first_position) price1 = price # record the first buying price state_flag = 1 if state_flag ==1: floating_earn_rate = (price - price1)/price1 if floating_earn_rate <= -stop_loss: # stop out sell(code, price, str(ticker), quantity1) state_flag = 0 elif floating_earn_rate >= lock_profit: # enter state 2: lock in profits # record quantity2 quantity2, _, _ = buy(code, price, str(ticker), ratio = 1) price2 = first_position * price1 + (1-first_position) * price state_flag = 2 else: # just wait pass if state_flag == 2: if (price < price2) or (df_extreme.at[ticker, 'close'] < df_extreme.at[ticker, 'lowest']): # sell all the shares bought last time sell(code, price, str(ticker), quantity1 + quantity2) state_flag = 0
def compute_trading_points(self, stocks, szTimeAxis, n_ahead): assert len( stocks ) == 1, "This strategy allows only a daily candlestick data of one stock." code = next(iter(stocks)) cst = stocks[code].cst # get candlestick data DataTimeAxis = cst['1Day'].index # MACD dif, dea, _ = self.MACD(cst['1Day']['close'].values) # skip extra data TimeAxis = DataTimeAxis[n_ahead:] df_macd = pd.DataFrame({ 'dif': dif[n_ahead:], 'dea': dea[n_ahead:] }, index=TimeAxis) # start trading start_flag, state_flag = 0, 0 for ticker in TimeAxis: # skip null value at the beginning if np.isnan(df_macd.at[ticker, 'dif']) or np.isnan( df_macd.at[ticker, 'dea']): continue # Skip the days of 'dif'>='dea' at the beginning. Those should be the days waiting for \ # selling, not buying, thus not suitable for a start if (start_flag == 0) and (df_macd.at[ticker, 'dif'] >= df_macd.at[ticker, 'dea']): continue else: start_flag = 1 # start trading if (start_flag == 1): price = cst['1Day'].at[ticker, 'close'] oneboardlot = 100 * price # One board lot is 100 shares in Chinese market # the first buying if (state_flag == 0) and (price <= self.level) and\ (df_macd.at[ticker, 'dif'] > df_macd.at[ticker, 'dea']): quantity, shares, cash = buy(code, price, str(ticker), ratio=0.5) stock_equity = shares[code] * oneboardlot cost = quantity * oneboardlot state_flag = 1 continue # the second buying if price falls if (state_flag == 1) and (stock_equity < cost * (1 - self.fall_ratio)): quantity, shares, cash = buy(code, price, str(ticker), ratio=1) cost += quantity * oneboardlot state_flag = 2 continue # sell if (state_flag >= 1) and (df_macd.at[ticker, 'dif'] <= df_macd.at[ticker, 'dea']): if (shares[code] * oneboardlot > cost * (1 + self.rise_ratio)): shares, cash = sell(code, price, str(ticker), shares[code]) state_flag = 0 continue
def compute_trading_points(self, stocks, szTimeAxis, n_ahead): assert len( stocks ) == 1, "This strategy allows only a daily candlestick data of one stock." code = next(iter(stocks)) cst = stocks[code].cst # get candlestick data DataTimeAxis = cst['1Day'].index close = cst['1Day']['close'].values # ExtremePrice highest, lowest = self.ExtremePrice(close, self.m) # skip extra data TimeAxis = DataTimeAxis[n_ahead:] df_extreme = pd.DataFrame({'close': close[n_ahead:], 'highest': highest[n_ahead:], \ 'lowest': lowest[n_ahead:]}, index = TimeAxis) #df_extreme.plot() #plt.show() # set position management and Risk control parameters # the proportion of your current cash for the first investment (if you earn # some profits, you would invest the rest of the cash). first_position = 0.25 # stop_loss: stop out when your loss of 1th position reach this proportion stop_loss = 0.04 # lock_profit: if your floating earn of 1th position reach this proportion, # enter state 2: sell all at a proper time that before you # lose the profits. lock_profit = 0.03 # start start_flag = 0 state_flag = 0 for ticker in TimeAxis: # skip null value at the beginning if np.isnan(df_extreme.at[ticker, 'highest']) or np.isnan( df_extreme.at[ticker, 'lowest']): continue # start trading price = cst['1Day'].at[ticker, 'close'] if (state_flag == 0) and (df_extreme.at[ticker, 'close'] > df_extreme.at[ticker, 'highest']): # quantity is the number of shares (unit: boardlot) you buy this time # record quantity1 quantity1, _, _ = buy(code, price, str(ticker), ratio=first_position) price1 = price # record the first buying price state_flag = 1 if state_flag == 1: floating_earn_rate = (price - price1) / price1 if floating_earn_rate <= -stop_loss: # stop out sell(code, price, str(ticker), quantity1) state_flag = 0 elif floating_earn_rate >= lock_profit: # enter state 2: lock in profits # record quantity2 quantity2, _, _ = buy(code, price, str(ticker), ratio=1) price2 = first_position * price1 + (1 - first_position) * price state_flag = 2 else: # just wait pass if state_flag == 2: if (price < price2) or (df_extreme.at[ticker, 'close'] < df_extreme.at[ticker, 'lowest']): # sell all the shares bought last time sell(code, price, str(ticker), quantity1 + quantity2) state_flag = 0