def testPolicy(self, symbol = "IBM", \ sd=dt.datetime(2009,1,1), \ ed=dt.datetime(2010,1,1), \ sv = 10000): dates = pd.date_range(sd - dt.timedelta(days=(self.n_days + 30)), ed) df_prices = ut.get_data(['IBM'], dates) # Get data including SPY df_prices = df_prices.rename(columns={'IBM': 'Adj Close'}) indic = ind.Indicators(df_prices, self.verbose) df_indicators = indic.get_indicators() adj_sd_pos = np.searchsorted( df_indicators.index, sd.date()) #Position of adjusted start date df_indicators = df_indicators.ix[ adj_sd_pos:-1, :] # Trim anything before the start date #self.printv('Trimmed Indicators DF: \n%s' %(df_indicators)) # Normalize the data, required so that discretization of test data will work same as training data #df_indicators = df_indicators/(df_indicators.ix[0]) #self.printv('Normalized DF Indicators: %s' %(df_indicators)) # Set buckets for indicator values, this helps to discretize the values for use with QLearner self.bollinger_buckets = pd.cut(df_indicators['UBB'], 10, labels=np.arange(0, 10)) self.macd_buckets = pd.cut(df_indicators['MACD'], 10, labels=np.arange(0, 10)) self.rsi_buckets = pd.cut(df_indicators['RSI'], 10, labels=np.arange(0, 10)) df_trades = pd.DataFrame( index=df_indicators.index) # Create DF to track trades df_trades["Trade"] = 0 df_trades[:] = 0 # Init to zero holding = 0 # Starts out with 0 holdings # Iterate throughout the indicators/price data frame for index, row in df_indicators.iterrows(): current_row = df_indicators.index.get_loc( index) # Get the current row number s = self.discretize( index) # Get the discretized state for this day a = self.q_learner.querysetstate(s) action = self.process_action( a, holding ) # Determines buy/sell action based on a and current holding holding = holding + action df_trades.ix[index, 'Trade'] = action if self.verbose == True: df_trades.to_csv('test_df_trades.csv') return df_trades
xlsx_processor = initializer.xlsx_processor dxf_processor = initializer.dxf_processor dxf_processor_2 = initializer.dxf_processor_2 print('GUI_inputchecker start') inputchecker = gui.inputChecker(xlsx_processor.traffic_day, xlsx_processor.traffic_hour) print('GUI_inputchecker stop') print('GUI_datechooser start') datechooser = gui.dateChooser(xlsx_processor.dates) duration = (datechooser.dates_chosen[0], datechooser.dates_chosen[-1]) print('GUI_datechooser stop') #输入指标 print('GUI_indicatorinput start') indicatorinput = gui.indicatorInput(xlsx_processor.mainstore) print('GUI_indicatorinput stop') indicators = indicators.Indicators(xlsx_processor, indicatorinput.inds, indicatorinput.area_mainstore, duration) indicators.write(indicatorinput.path) os.startfile(indicatorinput.path) img_path = os.path.split(indicatorinput.path)[0] #print(img_path) '''for date in datechooser.dates_chosen: print('main draw'+date) draw(xlsx_processor,dxf_processor,dxf_processor_2,date)''' draw(xlsx_processor, dxf_processor, dxf_processor_2, duration, img_path)
def addEvidence(self, symbol = "IBM", \ sd=dt.datetime(2008,1,1), \ ed=dt.datetime(2009,1,1), \ sv = 10000): # Get the data for the date range (in addition go back n-days plus 30 for tech indicators to work) dates = pd.date_range(sd - dt.timedelta(days=(self.n_days + 30)), ed) df_prices = ut.get_data(['IBM'], dates) # Get data including SPY df_prices = df_prices.rename(columns={'IBM': 'Adj Close'}) indic = ind.Indicators(df_prices, self.verbose) df_indicators = indic.get_indicators() adj_sd_pos = np.searchsorted( df_indicators.index, sd.date()) #Position of adjusted start date df_indicators = df_indicators.ix[ adj_sd_pos:-1, :] # Trim anything before the start date #self.printv('Trimmed Indicators DF: \n%s' %(df_indicators)) # Normalize the data, required so that discretization of test data will work same as training data #df_indicators = df_indicators/(df_indicators.ix[0]) #self.printv('Normalized DF Indicators: %s' %(df_indicators)) # Set buckets for indicator values, this helps to discretize the values for use with QLearner self.bollinger_buckets = pd.qcut(df_indicators['UBB'], 10, labels=np.arange(0, 10)) self.macd_buckets = pd.qcut(df_indicators['MACD'], 10, labels=np.arange(0, 10)) self.rsi_buckets = pd.qcut(df_indicators['RSI'], 10, labels=np.arange(0, 10)) #self.printv('MACD Buckets: %s. \n Bollinger Buckets: %s' %(self.macd_buckets, self.bollinger_buckets)) # Start Training converged = False prev_df_trades = None # df_trades of last iteration, used to check convergence current_iter = 1 # Start out at iteration 1, used to ensure enough iterations are ran but not too many leading to timeout while not converged: df_trades = pd.Series( index=df_indicators.index) # Create DF to track trades df_trades[:] = 0 # Init to zero holding = 0 # Starts out with 0 holdings # Iterate throughout the indicators/price data frame for index, row in df_indicators.iterrows(): current_row = df_indicators.index.get_loc( index) # Get the current row number s = self.discretize( index) # Get the discretized state for this day if current_row == 0: # First day so just set-up the state a = self.q_learner.querysetstate(s) action = self.process_action( a, holding ) # Determines buy/sell action based on a and current holding holding = holding + action else: # Not first day, so adjust q-table # Calculate reward as percentage change multiplied by holding prev_close = df_indicators['Adj Close'].iloc[current_row - 1] today_close = row['Adj Close'] r = ((today_close / prev_close) - 1) * holding self.printv('Reward for %s is %s' % (index, r)) a = self.q_learner.query(s, r) action = self.process_action(a, holding) holding = holding + action df_trades[index] = action self.printv(df_trades) # Check for convergence if current_iter > self.max_iters: converged = True if current_iter > self.min_iters and prev_df_trades.all( ) == df_trades.all(): converged = True prev_df_trades = df_trades # Track history of last df trades for comparison for convergence current_iter = current_iter + 1 # Increase iteration if self.verbose == True: df_trades.to_csv('df_trades.csv')
s = stock.Stock(sym) chart = charts.Charts(s) data_d = tdapi.get_price_history_api('day', '1', 'minute', '1', 'false', sym)['candles'] print(data_d) chart.plot_custom_plot(data_d, no_time=True) pp = point_parser.PointParser(data_d) y_coordinates = [pp.nine_window_ema[x] for x in pp.crossed] closes = [f['close'] for f in data_d] sma_120 = indicators.Indicators().simple_moving_average(closes, 120) x_s = [i for i in range(len(sma_120))] chart.plot_as_line(pp.xs, pp.nine_window_ema, 2) x = [f[0] for f in pp.print_significant()] y = [f[1] for f in pp.print_significant()] print(pp.print_significant()) print(stategy.find_resistance(pp.print_significant(), 56)) rsi = indicators.Indicators().relative_strength(closes) rsi_xs = [x for x in range(len(rsi))] chart.plot_as_point(x, y, 2) chart.plot_macd_histogram(3, data_d) chart.plot_as_line(rsi_xs, rsi, 1)