def execute(self, job): q = Quotation() shibor_ON = q.get_today_shibor_ON() print shibor_ON job.status = 1 return 0
def execute(self, job): broker = job.broker balance = broker.balance() enable_balance = balance[0].enable_balance q = Quotation() quote = q.get_realtime_quotes([self.GC001, self.R001]) # for (k,v) in quote.items(): # string = v.__str__() # print string.encode('utf-8') # job.result.invest = [] job.result.clear() if quote[self.GC001].buy > quote[self.R001].buy and enable_balance >= self.GC001_UNIT * self.HAND: amount = int(enable_balance / self.HAND / self.GC001_UNIT) * self.GC001_UNIT # invest = Invest({'name':'GC001', 'code':self.GC001, 'amount':amount, 'price':quote[self.GC001].buy}) invest = {'code': self.GC001, 'name': 'GC001', 'amount': amount, 'price': quote[self.GC001].buy, 'deal': Invest.INVEST_DEAL_SELL} job.result.append(invest) enable_balance = enable_balance - amount * self.HAND quote = q.get_realtime_quotes([self.GC001, self.R001]) amount = int(enable_balance / self.HAND / self.R001_UNIT) * self.R001_UNIT # invest = Invest({'name':'R001', 'code':self.R001, 'amount':amount, 'price':quote[self.R001].buy}) invest = {'code': self.R001, 'name': 'R001', 'amount': amount, 'price': quote[self.R001].buy, 'deal': Invest.INVEST_DEAL_SELL} job.result.append(invest) return True
def main(argv): #get_all_tick_data('000001') try: opts, args = getopt.getopt(argv[1:], "dhe:m:i:t:s:a:") except getopt.GetoptError as err: print(err) return -1 log_level = logging.INFO mode = '' index = 0 thread = 1 symbol = '000000' date = date_time.get_today_str() for ok, ov in opts: if ok in ('-d', '--debug'): log_level = logging.DEBUG if ok in ('-e', '--expire'): global g_expire g_expire = int(ov) if ok in ('-m', '--mode'): mode = ov if ok in ('-i', '--index'): index = int(ov) if ok in ('-t', '--thread'): thread = int(ov) if ok in ('-s', '--symbol'): symbol = ov if ok in ('-a', '--date'): date = ov if ok in ('-h', '--help'): help() return logging.basicConfig( level=log_level, format= '%(levelname)s: %(asctime)s [%(pathname)s:%(lineno)d] %(message)s', datefmt='%Y-%M-%d %H:%M:%S', filename=CT.LOG_DIR + 'tick.log', filemode='a') log_str = 'running model[%s] index[%d] thread[%d] symbol[%s] date[%s]' % ( mode, index, thread, symbol, date) print(log_str) logging.info(log_str) if mode == 'symbol': get_tick_data_symbol(symbol, index, thread) elif mode == 'date': get_tick_data_date(date, index, thread) elif mode == 'allsince': get_tick_data_since(date, index, thread) elif mode == 'since': get_symbol_tick_data_since(symbol, date) elif mode == 'tick': q = Quotation() q.get_tick_data(symbol, date) else: print(('args err mode[%s]' % (mode))) logging.error('args err mode[%s]' % (mode)) return
def dd_analysis(): t = Quotation() code = '600066' d = t.get_h_data(code) d.to_csv('tt.csv', sep='\t') date_set = d.index[0:20] for date in date_set: buy = 0 sell = 0 total = 0 d = t.get_sina_dd(code, date=date, vol=1) for i in d.index: total += d['volume'][i] print((date + '\t' + str(total/len(d)))) #d = t.get_sina_dd(code, date=date, vol=600) #if d is None: # continue ##d.to_csv('tt.csv', sep='\t') #for i in d.index: # total += d['volume'][i] # if d['type'][i].decode('utf-8') == u'买盘': # buy += d['volume'][i] # if d['type'][i].decode('utf-8') == u'卖盘': # sell += d['volume'][i] #print 'buy: ' + str(buy) #print 'sell: ' + str(sell) ##print 'arerage: ' + str(total/len(d)) ##print date + '\t' + str(total/len(d)) return
def main(argv): from quotation.quotation import Quotation q = Quotation() d = q.get_daily_data('000001') d = d.reset_index() # d = pd.read_csv('/Users/zhangyunsheng/Dev/sonata/data/AAPL.csv') d = d.sort_values('date') e = StockTradingEnv(d) e.reset() print(e._nextObservation()) e.render()
def test_get_realtime_quotes(self): q = Quotation() d = q.get_realtime_quotes('sh') self.assertIn('sh', d) self.assertEqual(d['sh'].symbol, 'sh000001') self.assertEqual(d['sh'].code, 'sh') self.assertEqual(d['sh'].name, '上证指数') d = q.get_realtime_quotes(['000002', '601992']) self.assertIn('000002', d) self.assertIn('601992', d)
def predict(self, code): if self.model == None: self.load() q = Quotation() d = q.get_daily_data(code) d = d.reset_index() n = len(d.loc[:, 'open'].values) last_five_d = d.loc[n - 6:, :] obs = StockTradingEnv.observation(last_five_d) action, _states = self.model.predict(obs) print(action) print(_states) return
def execute(self, job): q = Quotation() hgt = q.get_hgt_capital() hgt_estimate = estimate_to_close(hgt) #沪港通指标 buy = 0 if hgt > self.HGT_LIM: buy = 1 if get_exchange_time( ) > 30 * 60 and hgt_estimate > self.HGT_ESTIMATE_LIM: buy = 1 if buy == 0: job.status = 0 job.result.clear() return 0 if buy == 1: job.status = 1 t = Trader.get_instance(job['trader']) position = t.position() balance = t.balance() enable_balance = balance[0].enable_balance codes = [] for i, v in enumerate(job.result): codes.append(v.code) quotes = q.get_realtime_quotes(codes) temp_result = copy.copy(job.result) job.result.clear() for i, v in enumerate(temp_result): #找到该股的持仓数据 v_position = '' for p in position: if p.stock_code == v.code: v_position = p #达到持仓上限 if v_position != '' and v_position.current_amount >= v.amount: continue #设置买入参数 v.price = quotes[v.code].buy if get_turnover_brokerage(v.price * v.amount) > enable_balance: continue enable_balance -= get_turnover_brokerage(v.price * v.amount) job.result.append(v) return 0
def get_tick_data_symbol(symbol, index, thrd_cnt): """ 获取一支股票所有的tick数据 """ if not os.path.exists(CT.TICK_DIR + symbol): os.makedirs(CT.TICK_DIR + symbol) q = Quotation() d = q.get_his_data(symbol) sep_len = (len(d.index) + thrd_cnt - 1) / thrd_cnt start = sep_len * index end = sep_len * (index + 1) dates = d.index[start:end] get_tick_data_mul(symbol, dates) return True
def load(self): try: q = Quotation() d = q.get_daily_data('000001') d = d.reset_index() # d = pd.read_csv('/Users/zhangyunsheng/Dev/sonata/data/AAPL.csv') d = d.sort_values('date') env = DummyVecEnv([lambda: StockTradingEnv(d)]) self.model = PPO2(MlpPolicy, env, verbose=1) self.model = PPO2.load(self.model_dir) except Exception as e: Logger.warn(e) return False return True
def get_symbol_tick_data_since(symbol, date): """ 获取一支股票从指定日期至今所有的tick数据 -------- symbol: string,000001 date: string,1900-01-01 """ since = date_time.str_to_date(date) today = datetime.datetime.today() days = (today - since).days q = Quotation() for delta in range(0, days + 1): day = date_time.compute_date(since, delta) q.get_tick_data(symbol, day) return True
def train(self): q = Quotation() d = q.get_daily_data('000001') #d = q.get_daily_data('000651') d = d.reset_index() # d = pd.read_csv('/Users/zhangyunsheng/Dev/sonata/data/AAPL.csv') d = d.sort_values('date') #print(d.head(10).loc[0: 6, 'open'].values) #return True train_data = d.head(3718) test_data = d.tail(1500).reset_index() # The algorithms require a vectorized environment to run #env = DummyVecEnv([lambda: StockTradingEnv(d)]) #env = StockTradingEnv(d) env = StockTradingEnv(train_data) m = PPO2(MlpPolicy, env, verbose=1) m.learn(total_timesteps=200000) m.save(self.model_dir) env = StockTradingEnv(test_data) m = PPO2.load(self.model_dir) #m = PPO2.load('/Users/zhangyunsheng/Dev/sonata/data/model/demo.2M.zip') obs = env.reset() for i in range(1500): action, _states = m.predict(obs) #print(action) # TODO act = '' #if action[0][0] < 1: # if action[0][1] != 0: if action[0] < 1: if action[1] != 0: act = 'BUY' print('BUY') # TODO #elif action[0][0] < 2: # if action[0][1] != 0: elif action[0] < 2: if action[1] != 0: act = 'SELL' print('SELL') # TODO obs, rewards, done, info = env.step(action) if act != '': env.render() env.render() return True
def get_tick_data_date(date, index, thrd_cnt): """ 获取一天内所有股票tick数据 """ symbols = open(CT.BASICS_DIR + 'symbols.csv') symbols_list = [] for c in symbols: symbols_list.append(c.strip()) sep_list_len = (len(symbols_list) + thrd_cnt - 1) / thrd_cnt start = sep_list_len * index end = sep_list_len * (index + 1) sep_symbols_list = symbols_list[start:end] q = Quotation() for s in sep_symbols_list: q.get_tick_data(s, date) return True
def get_h_data_mul(index, thread): """ 获取所有股票的历史数据 """ symbols = open(CT.BASICS_DIR + 'symbols.csv') symbols_list = [] for c in symbols: symbols_list.append(c.strip()) sep_list_len = (len(symbols_list) + thread - 1) / thread start = sep_list_len * index end = sep_list_len * (index + 1) sep_symbols_list = symbols_list[start:end] #print sep_symbols_list for c in sep_symbols_list: global g_expire q = Quotation() q.get_h_data(c, g_expire)
def execute(self, job): t = Trader.get_instance(job['trader']) balance = t.balance() enable_balance = balance[0].enable_balance q = Quotation() quote = q.get_realtime_quotes([self.GC001, self.R001]) for (k,v) in quote.items(): string = v.__str__() print string.encode('utf-8') if quote[self.GC001].buy > quote[self.R001].buy and enable_balance >= self.GC001_UNIT * self.HAND: amount=int(enable_balance/self.HAND/self.GC001_UNIT)*self.GC001_UNIT ret = t.sell(self.GC001, price=quote[self.GC001].buy, amount=int(enable_balance/self.HAND/self.GC001_UNIT)*self.GC001_UNIT) job.notice(str(ret)) job.trade(str(ret)) quote = q.get_realtime_quotes([self.GC001, self.R001]) amount=int(enable_balance/self.HAND/self.R001_UNIT)*self.R001_UNIT ret = t.sell(self.R001, price=quote[self.R001].buy, amount=amount) job.notice(str(ret)) job.trade(str(ret)) #t = Trader.get_instance(job['trader']) #d = t.position() ##d = t.entrust() ##d = t.buy('601288', price=3.1, amount=100) ##d = t.sell('601288', price=3.5, amount=100) ##d = t.entrust() ##d = t.check_available_cancels() ##d = t.cancel_all_entrust() ##d = t.cancel_entrust('500', '601288') ##d = t.get_deal('2017-04-11') #job.notice(str(d)) #job.trade(str(d)) return 0
cerebro.addstrategy(TestStrategy) #strats = cerebo.optstrategy( # TestStrategy, # maperiod=range(10, 31)) # modpath = os.path.dirname(os.path.abspath(sys.argv[0])) # datapath = os.path.join(modpath, 'orcl-1995-2014.txt') # data = bt.feeds.YahooFinanceCSVData( # dataname=datapath, # fromdate=datetime.datetime(2000, 1, 1), # todate=datetime.datetime(2000, 12, 31), # reverse=False # ) from quotation.quotation import Quotation q = Quotation() d = q.get_daily_data('000001') print(d) # import pandas # #d = pandas.read_csv(datapath, skiprows=0, parse_dates=True, header=0, index_col=0) # datapath = "/Users/zhangyunsheng/Dev/sonata/data/daily/000001" # d = pandas.read_csv(datapath, sep='\t', skiprows=0, parse_dates=True, header=0, index_col=0) # print(d) # exit() #data = bt.feeds.PandasData( # dataname=d, # fromdate=datetime.datetime(2001, 1, 1), # todate=datetime.datetime(2001, 12, 31), # )
def run(self): q = Quotation() for date in self.dates: q.get_tick_data(self.symbol, date)
def test_get_tick_data(self): q = Quotation() d = q.get_tick_data('000001', '2021-03-05') self.assertTrue(len(d) > 100)
def customerController(self, userObj): """This method contains all functionality related to the customer along with the flow Args: - userObj -- User Raises: Returns: """ state = 2 while state >= 2: #display menu for customer while state == 2: pageName = 'Customer Home Screen' userName = userObj.getFirstName() optionDisplay = {'1': 'View Halls', '2': 'Search Hall', '3': 'Book Hall', '4': 'View Quotation Requests', '5': 'View Bookings'} pageNavDict = {'O': 'Logout', 'E': 'Exit'} headerDisplay = 'Input key to select corresponding option' displayDict = {'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'headerDisplay': headerDisplay} self.displayPage(displayDict) invalidSelectionFlag, selection = self.selectOption(optionDisplay, pageNavDict) # for navigation menu if not invalidSelectionFlag: if selection in pageNavDict: state = self.navOptions(selection, state) elif selection == '1': state = 3 elif selection == '2': state = 4 elif selection == '3': state = 7 elif selection == '4': state = 7 elif selection == '5': state = 9 else: print('Invalid selection, Please input again') #display list of halls and provide selection option while state == 3: pageName = 'View All Halls' userName = userObj.getFirstName() optionDisplay = Hall.viewAllHalls() pageNavDict = {'B': 'Go Back', 'O': 'Logout', 'E': 'Exit'} headerDisplay = 'Select ID to view detail and request quotation' displayDict = {'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'state': state, 'headerDisplay': headerDisplay} self.displayPage(displayDict) invalidSelectionFlag, selection = self.selectOption(optionDisplay, pageNavDict) if not invalidSelectionFlag: if selection in pageNavDict: if selection == 'B': state = 2 else: state = self.navOptions(selection, state) else: state = 5 index = selection else: print('Invalid selection, Please input again') #display hall details of the hall id entered while state == 4: print('Filter by Date') #accept date from user for booking start date dateCounter = 3 while dateCounter > 0: dateFlag, dateObj = self.acceptDate() if dateFlag: startDate = dateObj break else: dateCounter = dateCounter - 1 # input(str(dateCounter)) print(dateObj,', please try again') else: print('Maximum retry reached, navigating back') time.sleep(3) state = 2 #accept date from user for booking end date if dateFlag: dateCounter = 3 while dateCounter > 0: dateFlag, dateObj = self.acceptDate(startDate) if dateFlag: endDate = dateObj break else: dateCounter = dateCounter - 1 print(dateObj,', please try again') else: print('Maximum retry reached, navigating back') time.sleep(3) state = 2 if dateFlag: pageName = "Halls available on selected dates" userName = userObj.getFirstName() optionDisplay = self.getAvailableHalls(startDate, endDate) pageNavDict = {'B': 'Go Back', 'O': 'Logout', 'E': 'Exit'} headerDisplay = "Input ID to view hall details and request quotation" displayDict = {'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'headerDisplay': headerDisplay} self.displayPage(displayDict) invalidSelectionFlag, selection = self.selectOption(optionDisplay, pageNavDict) if not invalidSelectionFlag: if selection in pageNavDict: if selection == 'B': state = 2 else: state = self.navOptions(selection, state) else: state = 5 index = selection else: print('Invalid selection, Please input again') #intermediary state not to be jumped onto while state == 5: pageName = 'Hall Details' userName = userObj.getFirstName() optionDisplay = Hall.viewHallDetails(index) pageNavDict = {'R': 'Request Quote', 'B': 'Go Back', 'O': 'Logout', 'E': 'Exit'} hallDetails = Hall.viewHallDetails(index) pageNavDict = {'R': 'Request Quote', 'B': 'Go Back', 'O': 'Logout', 'E': 'Exit'} displayDict = {'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'state': state} self.displayPage(displayDict) placeHolder = dict() invalidSelectionFlag, selection = self.selectOption(placeHolder, pageNavDict) if not invalidSelectionFlag: if selection in pageNavDict: if selection == 'R': state = 6 if selection == 'B': state = 3 else: state = self.navOptions(selection, state) else: print('Invalid selection, Please input again') #create quotation request while state == 6: # pageName = pageName # userName = userName # optionDisplay = optionDisplay # pageNavDict = pageNavDict # message = message # state = state # headerDisplay = headerDisplay quotationInfo = dict() quotationInfo['reqDate'] = datetime.datetime.now() dateCounter = 3 #accept date from user for booking start date while dateCounter > 0: dateFlag, dateObj = self.acceptDate() if dateFlag: quotationInfo['bookingStartDate'] = dateObj break else: dateCounter = dateCounter - 1 input(str(dateCounter)) print(dateObj,', please try again') else: print('Maximum retry reached, navigating back') state = 5 #accept date from user for booking end date if dateFlag: dateCounter = 3 while dateCounter > 0: dateFlag, dateObj = self.acceptDate(quotationInfo['bookingStartDate']) if dateFlag: quotationInfo['bookingEndDate'] = dateObj break else: dateCounter = dateCounter - 1 print(dateObj,', please try again') else: print('Maximum retry reached, navigating back') state = 5 if dateFlag: quotationInfo['hallId'] = index quotationInfo['customerId'] = userObj.getRowId() quotationInfo['quotationAmount'] = self.calculateQuote(quotationInfo['bookingStartDate'], quotationInfo['bookingEndDate'], quotationInfo['hallId']) print('Charge for booking from {} to {} is {}.'.format(quotationInfo['bookingStartDate'].isoformat(),quotationInfo['bookingEndDate'].isoformat(),quotationInfo['quotationAmount'])) customerConfirmCounter = 3 while customerConfirmCounter > 0: confirmation = input('Confirm Quotation Request(Y/N): ') if confirmation.isalpha(): if confirmation.lower() == 'y': #create object of quotations quotationObj = Quotation(quotationInfo) state = 7 break elif confirmation.lower() == 'n': print('Taking back to previous menu') time.sleep(2) state = 5 break else: print('Invalid input!! Try again') customerConfirmCounter = customerConfirmCounter - 1 else: print('Invalid input!! Try again') customerConfirmCounter = customerConfirmCounter - 1 if customerConfirmCounter == 0: print('Maximum Taking back to previous menu') time.sleep(2) state = 5 #display all quotation requests made by the customer while state == 7: pageName = 'Quotation Requests' userName = userObj.getFirstName() optionDisplay = Quotation.listQuotationRequests(userObj.getRowId()) pageNavDict = {'B': 'Go Back', 'O': 'Logout', 'E': 'Exit'} headerDisplay = 'Select an ID to make a booking' footerDisplay = 'Booking can be made only for approved requests' displayDict = {'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'state': state, 'headerDisplay': headerDisplay, 'footerDisplay': footerDisplay} self.displayPage(displayDict) placeholder = dict() invalidSelectionFlag, selection = self.selectOption(optionDisplay, pageNavDict) if not invalidSelectionFlag: if selection in pageNavDict: if selection == 'B': state = 2 else: state = self.navOptions(selection, state) else: quotationObj = Quotation({'quotationId': selection}) if quotationObj.getStatus() == 'Approved': state = 8 elif quotationObj.getStatus() == 'Pending': print('Quotation ID {} is pending at Owner'.format(quotationObj.getQuotationId())) time.sleep(2) state = 7 elif quotationObj.getStatus() == 'Completed': print('Booking for the Quotation ID {} is already made by you, try another Quotation ID'.format(quotationObj.getQuotationId())) time.sleep(2) state = 7 else: print('Quotation ID {} is rejected by Owner'.format(quotationObj.getQuotationId())) time.sleep(2) state = 7 else: print('Invalid selection, Please input again') time.sleep(2) #display the hall details before booking while state == 8: bookingInfo = {'bookingStartDate': quotationObj.getBookingStartDate(),'bookingEndDate': quotationObj.getBookingEndDate(),'hallId': quotationObj.getHallId(), 'customerId': quotationObj.getCustomerId(),'bookingAmount': quotationObj.getQuotationAmount(),'quotationId': quotationObj.getQuotationId()} optionDisplay = bookingInfo pageName = 'Book Hall' userName = userObj.getFirstName() pageNavDict = {'P': 'Make Payment', 'B': 'Go Back', 'O': 'Logout', 'E': 'Exit'} footerDisplay = 'Make payment and complete the booking' # state = state # headerDisplay = headerDisplay displayDict = {'footerDisplay': footerDisplay, 'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'state': state} # tableHeader = self.displayPage(displayDict) placeHolder = dict() invalidSelectionFlag, selection = self.selectOption(placeHolder, pageNavDict) if not invalidSelectionFlag: if selection in pageNavDict: if selection == 'B': state = 7 elif selection == 'P': paytype = input('Select Payment Option: \n [1] Cash \n [2] Coupon \n Enter your choice: ') if paytype.isdigit(): if paytype == '1': #create object of quotations bookingObj = Booking(bookingInfo) Quotation.changeStatus(quotationObj.getQuotationId(), 'Completed') paymentInfo = dict() paymentInfo['paymentType'] = 'Cash' paymentInfo['paymentAmount'] = bookingInfo['bookingAmount'] paymentInfo['bookingId'] = bookingObj.getRowId() paymentInfo['customerId'] = userObj.getRowId() paymentObj = Payment(paymentInfo) bookingObj.addPaymentInfo(paymentObj.getRowId()) state = 9 break elif paytype == '2': couponCode = input('Please Enter the coupon code: ') bookingObj = Booking(bookingInfo) Quotation.changeStatus(quotationObj.getQuotationId(), 'Completed') paymentInfo = dict() paymentInfo['paymentType'] = 'Cash' paymentInfo['couponCode'] = couponCode paymentInfo['paymentAmount'] = bookingInfo['bookingAmount'] paymentInfo['bookingId'] = bookingObj.getRowId() paymentInfo['customerId'] = userObj.getRowId() paymentObj = Payment(paymentInfo) bookingObj.addPaymentInfo(paymentObj.getRowId()) state = 9 break else: print('Invalid input!! Try again') else: state = self.navOptions(selection, state) else: print('Invalid selection, Please input again') #creation of booking object while state == 9: optionDisplay = Booking.viewUserBookings(userObj) pageName = 'Completed Bookings' userName = userObj.getFirstName() pageNavDict = {'B': 'Go Back', 'O': 'Logout', 'E': 'Exit'} displayDict = {'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'state': state} # tableHeader = self.displayPage(displayDict) placeHolder = dict() invalidSelectionFlag, selection = self.selectOption(placeHolder, pageNavDict) if not invalidSelectionFlag: if selection in pageNavDict: if selection == 'B': state = 2 else: state = self.navOptions(selection, state) else: print('Invalid selection, Please input again') self.state = state
def test_get_today_ticks(self): q = Quotation() d = q.get_today_ticks('sh') self.assertEqual(d.symbol, 'sh000001')
def ownerController(self, userObj): """ This method contains all functionality related to the owner along with the flow Args: - userObj -- User Raises: Returns: """ state = 2 while state >= 2: while state == 2: pageName = 'Owner Home Screen' userName = userObj.getFirstName() optionDisplay = { '1': 'Manage Halls', '2': 'View Quotation Request', '3': 'Manage Bookings', '4': 'Manage Payments' } pageNavDict = {'O': 'Logout', 'E': 'Exit'} headerDisplay = 'Input key to select corresponding option' displayDict = { 'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'headerDisplay': headerDisplay } self.displayPage(displayDict) invalidSelectionFlag, selection = self.selectOption( optionDisplay, pageNavDict) # for navigation menu if not invalidSelectionFlag: if selection in pageNavDict: state = self.navOptions(selection, state) elif selection == '1': # take to next state to display hall listing state = 3 elif selection == '2': state = 5 elif selection == '3': state = 7 elif selection == '4': state = 8 else: print('Invalid selection, Please input again') while state == 3: optionDisplay = Hall.viewUserHalls(userObj) pageName = 'Manage Hall Page' userName = userObj.getFirstName() pageNavDict = { 'O': 'Logout', 'E': 'Exit', 'B': 'Back', 'A': 'Add New Hall' } headerDisplay = 'Select ID to view corresponding Hall Information and modify' displayDict = { 'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'headerDisplay': headerDisplay } self.displayPage(displayDict) invalidSelectionFlag, selection = self.selectOption( optionDisplay, pageNavDict) # for navigation menu if not invalidSelectionFlag: if selection in pageNavDict: if selection == 'A': hallExistFlag, hallInfo = self.acceptHallDetails( userObj) # create a user object if hallExistFlag: state = 3 else: confirmation = input( 'Confirm Addition Request(Y/N): ') if confirmation.isalpha(): if confirmation.lower() == 'y': #create object of quotations hallObj = Hall(hallInfo) elif confirmation.lower() == 'n': print('Taking back to previous menu') time.sleep(1) state = 3 if selection == 'B': state = 2 state = self.navOptions(selection, state) else: # take to next state to display hall listing state = 4 else: print('Invalid selection, Please input again') while state == 4: index = int(selection) optionDisplay = Hall.viewHallDetails(index) pageName = 'Hall Detail Page' userName = userObj.getFirstName() pageNavDict = { 'M': 'Modify Hall', 'D': 'Delete Hall', 'B': 'Go Back', 'O': 'Logout', 'E': 'Exit' } displayDict = { 'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'state': state } self.displayPage(displayDict) #placeholder dictionary bookHallPage = dict() #displayPage('Hall Details', userObj.getFirstName(), hallDetails, navPageDict, state) invalidSelectionFlag, selection = self.selectOption( optionDisplay, pageNavDict) if not invalidSelectionFlag: if selection in pageNavDict: if selection == 'B': state = 3 if selection == 'M': hallExistFlag, hallModify = self.acceptModifyHallDetails( userObj, optionDisplay) # create a user object if not hallExistFlag: hallModify['hallId'] = optionDisplay[0] confirmation = input( 'Confirm Modification Request(Y/N): ') if confirmation.isalpha(): if confirmation.lower() == 'y': #create object of quotations hallObj = Hall(hallModify) hallObj.modifyhall( optionDisplay[0], hallModify) elif confirmation.lower() == 'n': print('Taking back to previous menu') time.sleep(1) state = 3 elif selection == 'D': hallDelete = dict() hallDelete['hallId'] = optionDisplay[0] confirmation = input( 'Confirm Delete Request(Y/N): ') if confirmation.isalpha(): if confirmation.lower() == 'y': #create object of quotations hallObj = Hall(hallDelete) hallObj.deletehall(optionDisplay[0]) elif confirmation.lower() == 'n': print('Taking back to previous menu') time.sleep(1) state = 3 else: state = self.navOptions(selection, state) else: print('Invalid selection, Please input again') while state == 5: optionDisplay = Quotation.listOwnerQuotationRequests( userObj.getRowId()) pageName = 'Requested Quotations Page' userName = userObj.getFirstName() pageNavDict = {'O': 'Logout', 'E': 'Exit', 'B': 'Back'} headerDisplay = 'Select ID to Modify Quotation Requests' displayDict = { 'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'headerDisplay': headerDisplay, 'state': state } self.displayPage(displayDict) #navPageDict = {'O': 'Logout', 'E': 'Exit', 'B': 'Back'} #displayPage('Requested Quotations Page', userObj.getFirstName(), quotationList, navPageDict, state) invalidSelectionFlag, selection = self.selectOption( optionDisplay, pageNavDict) if not invalidSelectionFlag: if selection == 'B': state = 2 elif selection in pageNavDict: state = self.navOptions(selection, state) else: # take to next state to display hall listing state = 6 else: print('Invalid selection, Please input again') while state == 6: index = int(selection) optionDisplay = Quotation.viewQuotationDetails(index) pageName = 'Quotation Details Page' userName = userObj.getFirstName() if (optionDisplay[5] == 'Pending'): pageNavDict = { 'A': 'Accept', 'M': 'Modify', 'R': 'Reject', 'B': 'Go Back', 'O': 'Logout', 'E': 'Exit' } else: pageNavDict = {'B': 'Go Back', 'O': 'Logout', 'E': 'Exit'} displayDict = { 'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'state': state } self.displayPage(displayDict) #displayPage('Quotation Details', userObj.getFirstName(), quotationDetails, navPageDict, state) #placeholder dictionary placeHolder = dict() invalidSelectionFlag, selection = self.selectOption( placeHolder, pageNavDict) if not invalidSelectionFlag: if selection in pageNavDict: if selection == 'B': state = 5 if selection == 'M': newAmount = input('Enter New Quotation Amount: ') if newAmount.isdigit(): confirmation = input( 'Confirm Modification Request(Y/N): ') if confirmation.isalpha(): if confirmation.lower() == 'y': #create object of quotations Quotation.changeAmount( optionDisplay[0], newAmount) elif confirmation.lower() == 'n': print('Taking back to previous menu') time.sleep(1) state = 5 else: print('Please enter a valid value[float only]') selection = index time.sleep(1) elif selection == 'A': confirmation = input( 'Confirm Accept Request(Y/N): ') if confirmation.isalpha(): if confirmation.lower() == 'y': #create object of quotations Quotation.changeStatus( optionDisplay[0], 'Approved') elif confirmation.lower() == 'n': print('Taking back to previous menu') time.sleep(1) state = 5 elif selection == 'R': confirmation = input( 'Confirm Reject Request(Y/N): ') if confirmation.isalpha(): if confirmation.lower() == 'y': #create object of quotations Quotation.changeStatus( optionDisplay[0], 'Rejected') elif confirmation.lower() == 'n': print('Taking back to previous menu') time.sleep(1) state = 5 else: state = self.navOptions(selection, state) else: print('Invalid selection, Please input again') state = 5 while state == 7: optionDisplay = Booking.listOwnerBookings(userObj.getRowId()) pageName = 'Completed Bookings' userName = userObj.getFirstName() pageNavDict = {'B': 'Go Back', 'O': 'Logout', 'E': 'Exit'} displayDict = { 'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'state': state } # tableHeader = self.displayPage(displayDict) placeHolder = dict() invalidSelectionFlag, selection = self.selectOption( placeHolder, pageNavDict) if not invalidSelectionFlag: if selection in pageNavDict: if selection == 'B': state = 2 else: state = self.navOptions(selection, state) else: print('Invalid selection, Please input again') while state == 8: optionDisplay = Payment.listOwnerPaymentRequests( userObj.getRowId()) pageName = 'Requested Payments Page' userName = userObj.getFirstName() pageNavDict = {'O': 'Logout', 'E': 'Exit', 'B': 'Back'} headerDisplay = 'Select ID to accept/reject Payment' displayDict = { 'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'headerDisplay': headerDisplay, 'state': state } self.displayPage(displayDict) #navPageDict = {'O': 'Logout', 'E': 'Exit', 'B': 'Back'} #displayPage('Requested Quotations Page', userObj.getFirstName(), quotationList, navPageDict, state) invalidSelectionFlag, selection = self.selectOption( optionDisplay, pageNavDict) if not invalidSelectionFlag: if selection == 'B': state = 2 elif selection in pageNavDict: state = self.navOptions(selection, state) else: # take to next state to display hall listing state = 9 else: print('Invalid selection, Please input again') while state == 9: index = int(selection) optionDisplay = Payment.viewPaymentDetails(index) pageName = 'Payments Details Page' userName = userObj.getFirstName() if (optionDisplay[4] == 'Pending'): pageNavDict = { 'A': 'Accept', 'R': 'Reject', 'B': 'Go Back', 'O': 'Logout', 'E': 'Exit' } else: pageNavDict = {'B': 'Go Back', 'O': 'Logout', 'E': 'Exit'} displayDict = { 'pageName': pageName, 'userName': userName, 'optionDisplay': optionDisplay, 'pageNavDict': pageNavDict, 'state': state } self.displayPage(displayDict) #displayPage('Quotation Details', userObj.getFirstName(), quotationDetails, navPageDict, state) #placeholder dictionary QuotationPage = dict() invalidSelectionFlag, selection = self.selectOption( optionDisplay, pageNavDict) if not invalidSelectionFlag: if selection in pageNavDict: if selection == 'B': state = 8 elif selection == 'A': confirmation = input( 'Confirm Accept Request(Y/N): ') if confirmation.isalpha(): if confirmation.lower() == 'y': #create object of quotations Payment.changeStatus( optionDisplay[0], 'Approved') Booking.changeStatus( optionDisplay[5], 'Confirmed') elif confirmation.lower() == 'n': print('Taking back to previous menu') time.sleep(1) state = 8 elif selection == 'R': confirmation = input( 'Confirm Reject Request(Y/N): ') if confirmation.isalpha(): if confirmation.lower() == 'y': #create object of quotations Payment.changeStatus( optionDisplay[0], 'Rejected') Booking.changeStatus( optionDisplay[5], 'Declined') elif confirmation.lower() == 'n': print('Taking back to previous menu') time.sleep(1) state = 8 else: state = self.navOptions(selection, state) else: print('Invalid selection, Please input again') self.state = state
def hsgt_top_analysis(): """ 分析沪深股通 top成交 策略 参数:买入资金比例、买入资金量、沪深股通资金流入、止盈比例 """ #days = 630 days = 120 q = Quotation() hsgt_his = q.get_hsgt_his(days + 100, 1, 60 * 6) jme_statistics = {} jme_count = {} ratio_statistics = {} ratio_count = {} change_statistics = {} change_count = {} statistics = 0 count = 0 profit_count = {} stock_statistic = {} days = q.get_trade_date(days) days = list(reversed(days)) for i,day in enumerate(days): if i + 2 >= len(days): break next_day = days[i + 1] next_2_day = days[i + 2] print(('\n' + next_day)) #资金流入 zjlr = 0 day_zjlr = day if day_zjlr in hsgt_his['zjlr']: zjlr = hsgt_his['zjlr'][day_zjlr] print(zjlr) #if zjlr < 0: # continue d = q.get_hsgt_top(day, 60 * 24 * 30) if d.empty: continue #按资金量排名 d = d.sort_index(by='jme', ascending=False) #d = d.sort_index(by='ratio', ascending=False) #d = d.head(1) for l in d.iterrows(): #买入比例 #if l[1]['ratio'] < 0.5: # continue #if l[1]['jme'] < 0: # continue price = q.get_h_data(l[1]['code'], 60 * 24 *30) if next_day not in price['open'] or next_2_day not in price['high']: continue buy_price = price['open'][next_day] #buy_price = price['high'][next_day] high_price = price['high'][next_2_day] high_profit = (high_price - buy_price)/buy_price close_price = price['close'][next_2_day] close_profit = (close_price - buy_price)/buy_price #止盈比例 profit_percent = 0.02 if high_profit > profit_percent: sell_price = buy_price * (1 + profit_percent) profit = profit_percent else: sell_price = close_price profit = close_profit sell_price = close_price profit = (close_price - buy_price)/buy_price #if profit < 0.00136: # continue print(('\n%s\t%s\t%f\t%f\t%f\t%f\t%f\t%f\t%d\t%f\t%f\t%f' % (l[1]['code'], l[1]['name'].encode('utf-8'), l[1]['change'], l[1]['jme'], l[1]['mrje'], l[1]['mcje'], l[1]['cjje'], l[1]['ratio'], l[1]['market'], buy_price, sell_price, profit))) jme_key = int(l[1]['jme']/10000000) if jme_key > 20 or jme_key < -20: jme_key = int(jme_key/10) * 10 if jme_key not in jme_statistics: jme_statistics[jme_key] = 0 jme_count[jme_key] = 0 #jme_statistics[jme_key] += profit if profit >= 0.00136: jme_statistics[jme_key] += 1 jme_count[jme_key] += 1 ratio_key = int(l[1]['ratio']*100) if ratio_key < 70: ratio_key = int(ratio_key/10) * 10 if ratio_key not in ratio_statistics: ratio_statistics[ratio_key] = 0 ratio_count[ratio_key] = 0 #ratio_statistics[ratio_key] += profit if profit >= 0.00136: ratio_statistics[ratio_key] += 1 ratio_count[ratio_key] += 1 change_key = int(l[1]['change']*10) if change_key > 20 or change_key < -20: change_key = int(change_key/10) * 10 if change_key not in change_statistics: change_statistics[change_key] = 0 change_count[change_key] = 0 #change_statistics['change_key'] += profit if profit >= 0.00136: change_statistics[change_key] += 1 change_count[change_key] += 1 profit_key = int(profit * 1000) if profit_key > 20 or profit_key < -20: profit_key = int(profit_key/10)*10 if profit_key not in profit_count: profit_count[profit_key] = 0 profit_count[profit_key] += 1 stock_key = l[1]['name'] if stock_key not in stock_statistics: stock_statistics[stock_key] = [] statistics += profit count += 1 # 只取第一个 #break print('\njme:\n') keys = list(jme_statistics.keys()) keys.sort() for k in keys: print((str(k) + '\t' + str(jme_count[k]) + '\t' + str(float(jme_statistics[k])/jme_count[k]))) print('\nratio:\n') keys = list(ratio_statistics.keys()) keys.sort() for k in keys: print((str(k) + '\t' + str(ratio_count[k]) + '\t' + str(float(ratio_statistics[k])/ratio_count[k]))) print('\nchange:\n') keys = list(change_statistics.keys()) keys.sort() for k in keys: print((str(k) + '\t' + str(change_count[k]) + '\t' + str(float(change_statistics[k])/change_count[k]))) print('\n=================') win = 0 for k,v in list(profit_count.items()): if k >= 1: win = win + v print('\ncount:') print(count) print('\nwin:') print((float(win)/count)) print('\naverage:') print((statistics/count)) print('\ntotal:') print(statistics) print('\n=================') keys = list(profit_count.keys()) keys.sort() for k in keys: print((str(k) + '\t' + str(profit_count[k]))) return
def test_get_hgt_capital(self): q = Quotation() d = q.get_hgt_capital() self.assertTrue(isinstance(d, float))
def execute(self, job): q = Quotation() hgt = q.get_hgt_capital() hgt_estimate = estimate_to_close(hgt) #沪港通指标 sell = 0 if hgt < self.HGT_LIM: sell = 1 if get_exchange_time( ) > 30 * 60 and hgt_estimate < self.HGT_ESTIMATE_LIM: sell = 1 if hgt < self.HGT_KEEP_LIM: sell = 2 if get_exchange_time( ) > 30 * 60 and hgt_estimate < self.HGT_KEEP_ESTIMATE_LIM: sell = 2 if sell == 0: job.status = 0 job.result.clear() return 0 if sell != 0: job.status = 1 t = Trader.get_instance(job['trader']) position = t.position() codes = [] for i, v in enumerate(job.result): codes.append(v.code) quotes = q.get_realtime_quotes(codes) temp_result = copy.copy(job.result) job.result.clear() for i, v in enumerate(temp_result): #找到该股的持仓数据 v_position = '' for p in position: if p.stock_code == v.code: v_position = p #没有持仓 if v_position == '': continue #盈利卖出 if sell == 1: v.price = max( quotes[v.code].buy, round( v_position.keep_cost_price * (1 + self.INCOME_RATION_LIM), 2)) #保本卖出 elif sell == 2: v.price = v_position.keep_cost_price #设置卖出参数 v.amount = v_position.enable_amount job.result.append(v) return 0
def test_get_one_realtime_quotes(self): q = Quotation() d = q.get_one_realtime_quotes('131800') self.assertIn('131800', d) self.assertEqual(d['131800'].symbol, 'sz131800') self.assertEqual(d['131800'].code, '131800')
def test_get_today_shibor_ON(self): q = Quotation() d = q.get_today_shibor_ON self.assertTrue(d > 0)
def test_get_stock_basics(self): q = Quotation() d = q.get_stock_basics() self.assertIn('code', d) self.assertGreater(len(d['code']), 1000)
def execute(self, job): t = Trader.get_instance(job['trader']) balance = t.balance() enable_balance = balance[0].enable_balance q = Quotation() quote = q.get_realtime_quotes([self.GC001, self.R001]) #for (k,v) in quote.items(): # string = v.__str__() # print string.encode('utf-8') #job.result.invest = [] job.result.clear() if quote[self.GC001].buy > quote[self.R001].buy and enable_balance >= self.GC001_UNIT * self.HAND: amount=int(enable_balance/self.HAND/self.GC001_UNIT)*self.GC001_UNIT #invest = Invest({'name':'GC001', 'code':self.GC001, 'amount':amount, 'price':quote[self.GC001].buy}) invest = {'name':'GC001', 'code':self.GC001, 'amount':amount, 'price':quote[self.GC001].buy} job.result.append(invest) enable_balance = enable_balance - amount * self.HAND quote = q.get_realtime_quotes([self.GC001, self.R001]) amount=int(enable_balance/self.HAND/self.R001_UNIT)*self.R001_UNIT #invest = Invest({'name':'R001', 'code':self.R001, 'amount':amount, 'price':quote[self.R001].buy}) invest = {'name':'R001', 'code':self.R001, 'amount':amount, 'price':quote[self.R001].buy} job.result.append(invest) #q = Quotation() #quote = q.get_realtime_quotes([self.GC001, self.R001]) #for (k,v) in quote.items(): # string = v.__str__() # print string.encode('utf-8') #if quote[self.GC001].buy > quote[self.R001].buy and enable_balance >= self.GC001_UNIT * self.HAND: # amount=int(enable_balance/self.HAND/self.GC001_UNIT)*self.GC001_UNIT # ret = t.sell(self.GC001, price=quote[self.GC001].buy, amount=int(enable_balance/self.HAND/self.GC001_UNIT)*self.GC001_UNIT) # job.notice(str(ret)) # job.trade(str(ret)) ##不要过于频繁操作 #time.sleep(2) #balance = t.balance() #enable_balance = balance[0].enable_balance #quote = q.get_realtime_quotes([self.GC001, self.R001]) #amount=int(enable_balance/self.HAND/self.R001_UNIT)*self.R001_UNIT #ret = t.sell(self.R001, price=quote[self.R001].buy, amount=amount) #job.notice(str(ret)) #job.trade(str(ret)) #t = Trader.get_instance(job['trader']) #d = t.position() ##d = t.entrust() ##d = t.buy('601288', price=3.1, amount=100) ##d = t.sell('601288', price=3.5, amount=100) ##d = t.entrust() ##d = t.check_available_cancels() ##d = t.cancel_all_entrust() ##d = t.cancel_entrust('500', '601288') ##d = t.get_deal('2017-04-11') #job.notice(str(d)) #job.trade(str(d)) return 0