def start(self): # start_time = time.time() seed = 14 # seed = np.random.randint(100) deal1 = Deal(seed=seed, cards_each=4, first_turn='S') print("Seed =", seed) displayer.print_hands(deal1.current_hands) print("Trumps:", deal1.trumps) # deal1.play_card('W', deal1.current_hands['W'][0]) # print("Lead of", deal1.lead) player = deal1.play_order[deal1.current_turn_index] # start_time = time.time() all_layouts = simulator.find_layouts(deal1, player, on_lead=False) print(f"{len(all_layouts)} possible layouts") # print(f"Time Taken = {time.time() - start_time}") # displayer.print_hands(all_layouts[0]) start_time = time.time() df = self.sds(all_layouts, deal1) mean_df = df.mean() print(mean_df) print(f"Time Taken = {time.time() - start_time}") sys.exit(1) all_args = [[i] + [deal1] for i in all_layouts[:10000]] start_time = time.time() with Pool() as pool: results = pool.starmap(self.sds_multiprocess, all_args) df = pd.DataFrame(results) print(df.head()) print(df.mean()) print(f"Time Taken = {time.time() - start_time}") sys.exit(1) result_list = [] for layout in all_layouts[:1000]: d = Deal(hands=layout, current_turn_index=deal1.current_turn_index, current_trick=deal1.current_trick.copy()) dds = DDS(d) # displayer.print_hands(d.original_hands) # displayer.print_deal_info(d) utility_dict = dds.get_decision() # print(utility_dict) result_list.append(utility_dict.copy()) df = pd.DataFrame(result_list) print(df.mean()) print(f"Time Taken = {time.time() - start_time}") sys.exit(1)
def play_game(self): dealer_seat = 0 for _ in range(self.num_orbits): for i, player in enumerate(self.players): if player.chips == 0: player.chips = self.stack_size self.rebuys[i] += 1 self.display_player_stats() deal = Deal(self.players, dealer_seat=dealer_seat, debug_level=self.debug_level) deal.play_round() dealer_seat = (dealer_seat + 1) % len(self.players) self.round_number += 1
def test_create_deal_random_and_defined(): # This uses the create_deal function to test random and defined inputs for a deal d_random = Deal(seed=0) create_deal(d_random) deal = { 'N': set(['C14', 'C13', 'C12', 'C11']), 'E': set(['S14', 'S13', 'H12', 'H11']), 'S': set(['D14', 'D13', 'H14', 'H13']), 'W': set(['D12', 'D11', 'S12', 'S11']) } d_defined = Deal(deal=deal) create_deal(d_defined)
def test_play_to_all_leaves(): d = Deal(seed=0) d.make_lead() # print(d.original_hands) disp = Displayer() dec = Decisions() sim = Simulator() e = GameEngine(disp, dec, sim) e.play_to_all_leaves(d) assert_equal(d.trick_no, 5) assert_equal(d.card_no, 17) assert_equal(d.current_trick, []) # we save this number from a previous run. Good to check we always traverse the whole tree assert_equal(d.leaf_nodes, 832)
def test_make_lead_and_play_card(): deal = { 'N': set(['C14', 'C13', 'C12', 'C11']), 'E': set(['S14', 'S13', 'H12', 'H11']), 'S': set(['D14', 'D13', 'H14', 'H13']), 'W': set(['D12', 'D11', 'S12', 'S11']) } d = Deal(deal=deal) # This function also runs the play_card function d.make_lead() assert (d.lead in d.original_hands['W']) d.current_hands['W'].add(d.lead) assert_equal(d.original_hands, d.current_hands) assert_equal(d.card_no, 2)
def reset(self): # North and South """ :param reshuffle: whether reshuffle the hands for the predeal seats :return: deal """ if len(self.scores_dicts) == 0: raise Exception("Please set the data in adavance") self.bidding_history = np.zeros(36, dtype=np.uint8) # 1C 1D 1H 1S 1N ... 7N (PASS - not considered) self.max_bid = -1 self.n_pass = 0 self.turn = self.bidding_seats[0] # the first one. self.done = False self.strain_declarer = {0: {}, 1: {}} self.group_declarer = -1 idx = self.loading_data_order[self.loading_count] predeal, self.rewards_table = self.pre_deals_dicts[idx], self.scores_dicts[idx] self.loading_count += 1 self.one_hot_deal = np.zeros((len(Seat), len(FULL_DECK)), dtype=np.uint8) for seat, hands in predeal.items(): self.one_hot_deal[seat] = one_hot_holding(hands) # one hot cards # update the deal self.deal = Deal.prepare(predeal) if self.loading_count >= len(self.loading_data_order): # reshuffle the indices self.loading_count = 0 self.loading_data_order = random.sample(list(np.arange(len(self.pre_deals_dicts))), len(self.pre_deals_dicts)) self.traverse_flag = True if self.debug: convert_hands2string(self.deal) # if not allocated, zero vector is returned. return (self.one_hot_deal[self.turn], self.bidding_history), {"turn": Seat[self.turn], "max_bid": self.max_bid, "traverse": self.traverse_flag}
def main(): groupon = pygroupon.Groupon(os.environ["GROUPON_CLIENT_ID"]) groupon_json = groupon.get_deals() well_reviewed_deals = [] for deal_json in groupon_json['deals']: merchant = deal_json['merchant'] name = deal_json['merchant']['name'] ascii_name = convert_to_ascii(name) ratings = [d for d in merchant.get('ratings', []) if d.get('linkText', None) == 'Yelp'] if len(ratings) == 1: ratings = ratings[0] else: ratings = {} #groupon_yelp_url = ratings.get('url', None) score = float(ratings.get('rating', 0)) if score < FILTER_CUTOFF: continue yelp_json = search_script.get_rating(ascii_name) if yelp_json is None: #do not add with no yelp data continue #yelp_url = yelp_json.get('url', None) #if groupon_yelp_url != yelp_url: # print 'no match' # print 'groupon: ', groupon_yelp_url # print 'yelp: ', yelp_url # continue deal = Deal.from_json(yelp_json, deal_json) #if score >= FILTER_CUTOFF: if deal.yelp_score >= FILTER_CUTOFF: print 'added: ', name well_reviewed_deals.append(deal) os.chdir(CURRENT_DIR) with open('all_deals', 'wb') as f: cPickle.dump(well_reviewed_deals, f)
def run_dds(self): # deal1 = {'N': ['C14', 'C13', 'C12', 'C11'], 'E': ['S14', 'S13', 'H12', 'H13'], # 'S': ['D14', 'D11', 'H14', 'H11'], 'W': ['D12', 'D13', 'S12', 'S11']} # displayer.print_hands(deal1) # d = Deal(hands=deal1, current_trick=current_trick) # dds = DDS(d) # start_time = time.time() # utility_dict = dds.get_decision() # print(utility_dict) # # print(f"DDS says playing {decision} will bring {utility} tricks") # print(f"Time Taken = {time.time() - start_time}") # sys.exit(1) start_time = time.time() # Let south start this hand for i in range(0, 800): # seed = np.random.randint(1000) d = Deal(seed=i, cards_each=4, current_turn_index=3, trumps=None) dds = DDS(d) # displayer.print_hands(d.original_hands) # print("Trumps:", d.trumps) # utility_dict = dds.get_utilities() move = dds.get_move() # print(move) # print(utility_dict) print(f"Time Taken = {time.time() - start_time}")
def test_find_all_layouts_and_run_sims(): deal = { 'N': set(['C14', 'C13', 'C12', 'C11']), 'E': set(['S14', 'S13', 'H12', 'H11']), 'S': set(['D14', 'D13', 'H14', 'H13']), 'W': set(['D12', 'D11', 'S12', 'S11']) } d = Deal(deal=deal) sim = Simulator() dec = Decisions() disp = Displayer() e = GameEngine(disp, dec, sim) d.make_lead('D12') layouts = sim.find_layouts(d) # This should be the case because west has played a card already and north/south haven't assert (len(layouts[2]) > len(layouts[0]))
def run_sims_position(self, player_layouts, lead): """ For each player (NS combined), we play out the full game tree for every possible combination of hands that their opponents may have after the lead """ all_sims = [] for position_layouts in player_layouts: simulations = {} for full_hands in position_layouts: new_deal = Deal(deal=full_hands) new_deal.make_lead(lead) simulations.update(self.play_to_all_leaves(new_deal)) all_sims.append(simulations) return all_sims
def sds_multiprocess(self, layout, deal): d = Deal(hands=layout, current_turn_index=deal.current_turn_index, current_trick=deal.current_trick.copy(), trumps=deal.trumps) dds = DDS(d) # displayer.print_hands(d.original_hands) # displayer.print_deal_info(d) utility_dict = dds.get_utilities() return utility_dict
def test_play_to_leaf_with_sims(): d = Deal(seed=0) disp = Displayer() dec = Decisions() sim = Simulator() e = GameEngine(disp, dec, sim) sims = sim.load_sims(0) d = e.play_to_leaf(d, sims, random=False) assert_equal(d.full_history[0][1], d.trick_tally)
def insert_buy(self, quantity, price): """ Insert buy order in the order book and execute orders if it's possible. :param quantity: int The amount to buy :param price: double The unit price to buy :return: None """ buy_order = Order(quantity, price, type_of_order='buy') if quantity != 0: self._buy_orders.append(buy_order) self._buy_orders.sort() self._buy_orders.reverse() print('--- Insert {order} on {book}'.format( order=buy_order.__str__(), book=self._name)) while len(self._sell_orders) != 0 and self._sell_orders[0].get_price( ) <= buy_order.get_price() and buy_order.get_qty() > 0: # Case quantity sell order > first buy order in our book if buy_order.get_qty() > self._sell_orders[0].get_qty(): deal = Deal(self._sell_orders[0].get_qty(), self._sell_orders[0].get_price(), self._name) self._execute_deals.append(deal) new_qty = buy_order.get_qty() - self._sell_orders[0].get_qty() # Fill the first buy order self._sell_orders.remove(self._sell_orders[0]) buy_order.set_qty(new_qty) print(deal.__str__()) # Case quantity sell order < first buy order in our book else: deal = Deal(buy_order.get_qty(), self._sell_orders[0].get_price(), self._name) self._execute_deals.append(deal) # Update of the new quantity self._sell_orders[0].set_qty(self._sell_orders[0].get_qty() - buy_order.get_qty()) buy_order.set_qty(0) self._buy_orders.remove(self._buy_orders[0]) if self._sell_orders[0].get_qty() == 0: self._sell_orders.remove(self._sell_orders[0]) print(deal.__str__()) print(self.get_status()) return None
def get_deals(): deals = [] csv_file = Settings.getSetting('DEALS_FILE') with open(csv_file, 'r', newline='') as csv: deals_dict = Deal.dict_from_csv(csv) for deal in deals_dict.values(): deals.append({ 'date': deal.date.isoformat(), 'name': deal.name, 'price': deal.price, 'savings': deal.savings, 'description': deal.description, }) return render_template('deals.html', deals=deals)
def _get_deals(): url = Settings.getSetting('SCRAPE_URL') deals = [] with request.urlopen(url) as response: doc = BeautifulSoup(response, 'html.parser') table = doc.select_one('table.shopItems') for td in table.find_all('td'): shop_item_base = td.select_one('.shopItemBase') name = shop_item_base.select_one('.name').get_text() price = shop_item_base.select_one('.price').get_text() savings_div = shop_item_base.select_one('.savings') savings = savings_div.select_one('.value').get_text() description = shop_item_base.select_one( '.description').get_text().strip() deals.append(Deal(date.today(), name, price, savings, description)) return deals
def test_play_to_leaf(): deal = { 'N': set(['C14', 'C13', 'C12', 'C11']), 'E': set(['S14', 'S13', 'H12', 'H11']), 'S': set(['D14', 'D13', 'H14', 'H13']), 'W': set(['D12', 'D11', 'S12', 'S11']) } d = Deal(deal=deal) disp = Displayer() dec = Decisions() sim = Simulator() e = GameEngine(disp, dec, sim) e.play_to_leaf(d) assert_equal(d.trick_no, 5) assert_equal(d.card_no, 17) assert_equal(d.current_trick, []) assert_equal(d.leaf_nodes, 1)
def test_complete_trick(): deal = { 'N': set(['C14', 'C13', 'C12', 'C11']), 'E': set(['S14', 'S13', 'H12', 'H11']), 'S': set(['D14', 'D13', 'H14', 'H13']), 'W': set(['D12', 'D11', 'S12', 'S11']) } d = Deal(deal=deal) # This function also runs the play_card function d.play_card('W', 'S12') d.play_card('N', 'C14') d.play_card('E', 'S14') d.play_card('S', 'H13') d.complete_trick() # East won the trick assert_equal('E', d.play_order[d.current_turn_index]) assert_equal(d.trick_tally, 0) assert_equal(d.card_no, 5) assert_equal(d.current_trick, [])
def from_identifier(self, identifier): components = identifier.split("-") if len(components) == 2: (board_number_string, deal_and_history_identifier) = components if ':' in deal_and_history_identifier: deal_identifier, call_history_identifier = deal_and_history_identifier.split(':') # We have to do a bit of a dance to convert from the board url system that # the JS code uses to the one the python uses. call_history = CallHistory.from_board_number_and_calls_string(int(board_number_string), call_history_identifier) else: deal_identifier = deal_and_history_identifier call_history = CallHistory.empty_for_board_number(int(board_number_string)) else: (board_number_string, deal_identifier, call_history_identifier) = components call_history = CallHistory.from_identifier(call_history_identifier) board_number = int(board_number_string) deal = Deal.from_identifier(deal_identifier) return Board(number=board_number, deal=deal, call_history=call_history)
def test_generate_possible_layouts(): d = Deal(seed=0) disp = Displayer() dec = Decisions() sim = Simulator() e = GameEngine(disp, dec, sim) layouts = sim.generate_layouts('NS', set(['D12', 'D11', 'S12', 'S11']), set(['C14', 'C13', 'C12', 'C11']), d.all_cards, lead=set([])) assert_equal(len(layouts), scipy.special.comb(8, 4)) my_layout = { 'N': set(['C14', 'C13', 'C12', 'C11']), 'E': set(['S14', 'S13', 'H12', 'H11']), 'S': set(['D12', 'D11', 'S12', 'S11']), 'W': set(['D14', 'D13', 'H14', 'H13']) }
def evaluate_new_sample(self, predeal_seats=None, declarer=None): # North and South """ :param predeal_seats: if not None, allocate cards to those seats. e.g. [0, 1] stands for North and East :param reshuffle: whether reshuffle the hands for the predeal seats :return: deal """ if predeal_seats is None: predeal_seats = self.bidding_seats predeal = {} random.shuffle(self.cards) i = 0 self.one_hot_deal = np.zeros((len(Seat), len(FULL_DECK)), dtype=np.uint8) for seat in sorted(predeal_seats): predeal[seat] = self.cards[i:i + len(Rank)] self.one_hot_deal[seat] = one_hot_holding( predeal[seat]) # one hot cards i += len(Rank) # shift the index self.deal = Deal.prepare(predeal) if self.debug: convert_hands2string(self.deal) rewards_dict = {} if declarer is not None: rewards = self.score_fn(dealer=self.deal, declarer=declarer, tries=self.nmc, mode=self.score_mode) rewards_dict[declarer] = rewards else: for s in self.bidding_seats: rewards = self.score_fn(dealer=self.deal, declarer=s, tries=self.nmc, mode=self.score_mode) rewards_dict[s] = rewards return predeal, rewards_dict, self.one_hot_deal[self.bidding_seats]
def reset(self, predeal_seats=None, reshuffle=True): # North and South """ :param predeal_seats: if not None, allocate cards to those seats. e.g. [0, 1] stands for North and East :param reshuffle: whether reshuffle the hands for the predeal seats :return: deal """ self.bidding_history = np.zeros( 36, dtype=np.uint8) # 1C 1D 1H 1S 1N ... 7N (PASS - not considered) self.max_bid = -1 self.n_pass = 0 self.turn = self.bidding_seats[0] # the first one. self.done = False self.strain_declarer = {0: {}, 1: {}} self.group_declarer = -1 if predeal_seats is None: predeal_seats = self.bidding_seats predeal = {} random.shuffle(self.cards) if reshuffle: # generate new hands for predeal seats. i = 0 self.one_hot_deal = np.zeros((len(Seat), len(FULL_DECK)), dtype=np.uint8) for seat in sorted(predeal_seats): predeal[seat] = self.cards[i:i + len(Rank)] self.one_hot_deal[seat] = one_hot_holding( predeal[seat]) # one hot cards i += len(Rank) # shift the index self.deal = Deal.prepare(predeal) if self.debug: convert_hands2string(self.deal) # if not allocated, zero vector is returned. return (self.one_hot_deal[self.turn], self.bidding_history), { "turn": Seat[self.turn], "max_bid": self.max_bid }
def sds(self, layouts, deal): """ This runs a dds for every possible layout as viewed from the current player. And then aggregates the results by taking the mean number of tricks for each card """ results_list = [] for layout in layouts: d = Deal(hands=layout, current_turn_index=deal.current_turn_index, current_trick=deal.current_trick.copy(), trumps=deal.trumps) dds = DDS(d) # displayer.print_hands(d.original_hands) # displayer.print_deal_info(d) utility_dict = dds.get_utilities() # print(utility_dict) results_list.append(utility_dict.copy()) df = pd.DataFrame(results_list) return df
def step(self, action): """ :param action: bid action :param tries: MC tries. :return: state, reward, done """ if self.done: raise Exception("No more actions can be taken") if action < 0 or action > 35: raise Exception("illegal action") if action == 35: # PASS self.bidding_history[action] = 1 # PASS self.n_pass += 1 else: if action <= self.max_bid: raise Exception("illegal bidding.") self.bidding_history[action] = 1 self.bidding_history[-1] = 0 # reset PASS self.n_pass = 0 self.max_bid = action strain = convert_action2strain(action) group = Seat2Group[self.turn] if self.strain_declarer[group].get(strain, '') == '': self.strain_declarer[group][strain] = self.turn # which one self.group_declarer = group # which group self.turn = (self.turn + 1) % len(Seat) # loop while True: # move to the participant if self.turn not in self.bidding_seats: self.turn = (self.turn + 1) % len(Seat) self.n_pass += 1 else: break hand = self.one_hot_deal[self.turn] reward = 0 # state is the next bidding player's state if self.n_pass >= 3 or self.max_bid == 34: if self.max_bid < 0: raise Exception("illegal bidding") # extract the declarer, strain , level strain = convert_action2strain(self.max_bid) level = convert_action2level(self.max_bid) # single thread # reward = np.mean(Deal.score_st(dealer=self.deal, level=level, strain=strain, declarer=declarer, tries=self.nmc, mode=self.score_mode)) # parallel threads # np.mean is moved to score declarer = self.strain_declarer[self.group_declarer][ strain] # thise group's first declarer reward = Deal.score(dealer=self.deal, level=level, strain=strain, declarer=declarer, tries=self.nmc, mode=self.score_mode) self.done = True state = (hand, self.bidding_history) info = {"turn": Seat[self.turn], "max_bid": self.max_bid} if self.debug: log_state(state, reward, self.done, info) return state, reward, self.done, info
def __init__(self, number=None, deal=None, call_history=None): self.number = number or 1 self.deal = deal or Deal.random() self.call_history = call_history or CallHistory.empty_for_board_number(number)
from deal import Deal from product import Product beanName = "Canned Beans" beanCost = 2 beanQuantity = 10 beansOnSale = True buyThreeGetOneFreeDealOnBeans = Deal() cannedBeans = Product(beanName, beanCost, beanQuantity, beansOnSale) buyThreeGetOneFreeDealOnBeans.dealPrice = cannedBeans.price * 3 buyThreeGetOneFreeDealOnBeans.maxQuantity = 4 cannedBeans.deal = buyThreeGetOneFreeDealOnBeans def calculateCostAfterDeal(item): if (item.quantity <= item.deal.maxQuantity): return (item.deal.dealPrice * item.quantity) else: totalCostForItemsThatDoNotQualifyForDeal = item.price * ( item.quantity - item.deal.maxQuantity) total = totalCostForItemsThatDoNotQualifyForDeal + item.deal.dealPrice return (total) def calculateCost(item): if (item.onSale): return (calculateCostAfterDeal(item)) else: return (item.price * item.quantity)
def test_random(self): # Just make sure the random code path does not assert, and returns something non-None. self.assertTrue(bool(Deal.random()))
def run_example(self): # Read in our example and import it as a module module_name = 'Examples.' + sys.argv[1] example = importlib.import_module(module_name, package=None) outfile_name = 'Examples/' + sys.argv[1] + '_output.txt' try: trumps = example.trumps except AttributeError: trumps = None try: first_turn = example.first_turn except AttributeError: first_turn = 'W' try: current_trick = example.current_trick except AttributeError: current_trick = None if hasattr(example, 'hands'): deal = Deal(hands=example.hands, trumps=example.trumps, first_turn=example.first_turn, current_trick=example.current_trick) else: # Probably want a random hand instead of a defined hand deal = Deal(seed=example.seed, cards_each=example.cards_each, trumps=example.trumps, first_turn=example.first_turn) # Note: make this write to output instead displayer.print_hands(deal.current_hands, outfile_name) # displayer.print_hands(deal.current_hands) outfile = open(outfile_name, 'a') outfile.write(f"Trumps: {deal.trumps}\n") outfile.write(f"Current trick: {deal.current_trick}\n") outfile.write(f"{first_turn}'s turn\n") # print("Trumps:", deal.trumps) player = deal.play_order[deal.current_turn_index] start_time = time.time() all_layouts = simulator.find_layouts(deal, player, on_lead=False) outfile.write(f"{len(all_layouts)} possible layouts\n\n") # print(f"{len(all_layouts)} possible layouts") if hasattr(example, 'multiprocessing') and example.multiprocessing: # if example.multiprocessing: all_args = [[i] + [deal] for i in all_layouts] start_time = time.time() with Pool() as pool: results = pool.starmap(self.sds_multiprocess, all_args) df = pd.DataFrame(results) else: df = self.sds(all_layouts, deal) # print(df.mean()) # print(type(df.mean())) df.mean().to_csv(outfile, sep=' ') outfile.write(f"\nTime Taken = {time.time() - start_time}\n") # print(f"Time Taken = {time.time() - start_time}") outfile.close() sys.exit(1)
def deal_init(): ######## #Clean player frame from the hit cards: Deal.clean_table(frames = [player_cards_frame,dealer_cards_frame,deal_results_frame]) ######## ######## #Initialize Card Instances so this way i will have a new deck each time deal is pressed cards_instances = [] for card in collect_cards(): cards_instances.append(Card(name = card)) # (Card instance) print(f'{card} added to deck') ######## #Initialize Game: game = Deal( deck = cards_instances, master = root, player_cards_frame = player_cards_frame, player_game_options_frame = player_game_options_frame, player_card1_label = player_card1_label, player_card2_label = player_card2_label, dealer_card1_label = dealer_card1_label, dealer_card2_label = dealer_card2_label, player_score_label = player_score_label, dealer_score_label = dealer_score_label, dealer_cards_frame = dealer_cards_frame, deal_results_frame = deal_results_frame, player_busted_message = player_busted_message, dealer_busted_message = dealer_busted_message, split = split ) # Starting operations in real game: #deal player: game.deal_player() #deal for dealer: #handle all dealt cards for dealer for here so we can keep one undisplayed dealer_1 = game.get_card(dealer_card1_label, is_player = False) dealer_2 = game.get_card(dealer_card2_label, is_player = False, display=False) #fill the score board: game.set_scoreboard() #See if split should be disabled or enabled: game.set_split_button_state() #Set the Buttons click function <Button-1> Stand for left click hit.bind('<Button-1>', lambda event: game.hit(dealer_2)) stand.bind('<Button-1>', lambda event: game.finish_player_turn(dealer_2))
def buying_3(self, first_buy, second_buy, third_buy): global running_box # 支撑线压力线,波谷波峰数据集,变异系数,支撑点压力点,以及原因的获取 # df_s, cv_s, price_s = self.support_line() e_support, reason_s = self.support_dot() # df_p, cv_p, price_p = self.pressure_line() e_pressure, reason_p = self.pressure_dot() obj1 = Deal(self.stock_id) price_buy = 0 price_sell = 0 cash = 0 num = 0 if self.df.high[0] < self.ave_price_60[0]: # 上 if self.df.low[0] >= first_buy: tik_tok = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) waiting_box = pd.read_csv( 'C:/Users/liquan/PycharmProjects/live/DEAL/waiting_box.csv' ) waiting_detail = pd.DataFrame( [[tik_tok, self.stock_id, num, price_buy, price_sell]], columns=[ 'drop_time', 'stock_id', 'num', 'price_buy', 'price_sell' ], index=[0]) waiting_box = pd.concat([waiting_box, waiting_detail], axis=0) waiting_box.to_csv('waiting_box.csv', encoding='utf-8', index_label=False, mode='w') # 中 elif self.df.low[0] <= first_buy <= self.df.high[0]: price_buy = first_buy price_sell = 0 cash = obj1.pocket() num = math.floor(cash / (price_buy * 300)) * 100 if num >= 100: print 'situation3_1' return price_buy, price_sell, cash, num # 中下 elif (self.df.high[0] <= first_buy) and (self.df.low[0] >= second_buy): tik_tok = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) second_buy_box = pd.read_csv( 'C:/Users/liquan/PycharmProjects/live/DEAL/second_buy_box.csv' ) waiting_detail = pd.DataFrame( [[tik_tok, self.stock_id, num, second_buy, price_sell]], columns=[ 'drop_time', 'stock_id', 'num', 'price_buy', 'price_sell' ], index=[0]) second_buy_box = pd.concat([second_buy_box, waiting_detail], axis=0) second_buy_box.to_csv('second_buy_box.csv', encoding='utf-8', index_label=False, mode='w') # 中 elif self.df.low[0] <= second_buy <= self.df.high[0]: price_buy = first_buy price_sell = 0 cash = obj1.pocket() num = math.floor(cash / (price_buy * 300)) * 100 if num >= 100: print 'situation3_2' return price_buy, price_sell, cash, num # 中下 elif (self.df.high[0] <= second_buy) and (self.df.low[0] >= third_buy): tik_tok = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) second_buy_box = pd.read_csv( 'C:/Users/liquan/PycharmProjects/live/DEAL/second_buy_box.csv' ) waiting_detail = pd.DataFrame( [[tik_tok, self.stock_id, num, second_buy, price_sell]], columns=[ 'drop_time', 'stock_id', 'num', 'price_buy', 'price_sell' ], index=[0]) second_buy_box = pd.concat([second_buy_box, waiting_detail], axis=0) second_buy_box.to_csv('second_buy_box.csv', encoding='utf-8', index_label=False, mode='w') # 中 elif self.df.low[0] <= third_buy <= self.df.high[0]: price_buy = first_buy price_sell = 0 cash = obj1.pocket() num = math.floor(cash / (price_buy * 300)) * 100 if num >= 100: print 'situation3_3' return price_buy, price_sell, cash, num # 下 else: research_box = pd.read_csv( 'C:/Users/liquan/PycharmProjects/live/DEAL/research_box.csv' ) tik_tok = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) stock_id = self.stock_id explain = 'situation1_2' research_detail = pd.DataFrame( [[tik_tok, stock_id, explain]], columns=['drop_time', 'stock_id', 'explain'], index=[0]) research_box = pd.concat([research_box, research_detail], axis=0) research_box.to_csv('research_box.csv', encoding='utf-8', index_label=False, mode='a') else: waiting_box = pd.read_csv( 'C:/Users/liquan/PycharmProjects/live/DEAL/waiting_box.csv') price_buy = waiting_box.loc[waiting_box.stock_id == self.stock_id, 'price_buy'][0] # whatever cv_p == 1 or not ,跳空位必须在e_pressure下 # 跳空保存 if (self.df.low[0] > self.ave_price_5[0]) and (self.df.high[0] < e_pressure): price_buy = self.ave_price_5[0] price_sell = 0 # num是无需在意的值 num = 0 tik_tok = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) waiting_box = pd.read_csv( 'C:/Users/liquan/PycharmProjects/live/DEAL/waiting_box.csv' ) waiting_detail = pd.DataFrame( [[tik_tok, self.stock_id, num, price_buy, price_sell]], columns=[ 'drop_time', 'stock_id', 'num', 'price_buy', 'price_sell' ], index=[0]) waiting_box = pd.concat([waiting_box, waiting_detail], axis=0) waiting_box.to_csv('waiting_box.csv', encoding='utf-8', index_label=False, mode='w') # 中 elif (self.df.low[0] <= price_buy <= self.df.high[0]) and (self.df.high[0] < e_pressure): cash = obj1.pocket() / 5 num = math.floor(cash / (price_buy * 100)) * 100 if num >= 100: print 'situation3_4' return price_buy, price_sell, cash, num return price_buy, price_sell, cash, num
def test_identifier(self): deal = Deal.from_string("23456789TJQKA... .23456789TJQKA.. ..23456789TJQKA. ...23456789TJQKA") self.assertEquals(deal.identifier(), '0000001555555aaaaaabffffff') self.assertEquals(deal.pretty_one_line(), Deal.from_identifier(deal.identifier()).pretty_one_line())
def selling_3(self, first_sell_up, second_sell_up, third_sell_up, first_sell_down): global running_box # 支撑线压力线,波谷波峰数据集,变异系数,支撑点压力点,以及原因的获取 # df_s, cv_s, price_s = self.support_line() e_support, reason_s = self.support_dot() # df_p, cv_p, price_p = self.pressure_line() e_pressure, reason_p = self.pressure_dot() obj1 = Deal(self.stock_id) price_buy = 0 price_sell = 0 cash = 0 num = 0 # 涨停止盈 if self.df.low[0] <= self.df.close[1] * 1.09 <= self.df.high[0]: price_buy = 0 price_sell = self.df.close[1] * 1.09 num0 = list(running_box.loc[running_box.stock_id == self.stock_id, 'bought_num'])[0] / 5 num = math.floor(num0 * 100) * 100 commission_buy, commission_sell = obj1.order_cost( num, price_sell, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) cash = num * price_sell - commission_sell if num >= 200: print 'situation3_5' return price_buy, price_sell, cash, num else: num = 200 commission_buy, commission_sell = obj1.order_cost( num, price_sell, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) cash = num * price_sell - commission_sell print 'situation3_6' return price_buy, price_sell, cash, num # 长上影线止盈 close_ave5 = create_data.ave_data_create(self.df.close, 5) open_ave5 = create_data.ave_data_create(self.df.open, 5) high_ave5 = create_data.ave_data_create(self.df.high, 5) low_ave5 = create_data.ave_data_create(self.df.low, 5) if ((self.df.high[0] - max(self.df.close[0], self.df.open[0])) / (self.df.high[0] - self.df.low[0]) >= 0.5) or \ ((high_ave5[0] - max(open_ave5[0], close_ave5[0])) / (high_ave5[0] - low_ave5[0]) >= 0.5): if self.df.volume[0] > self.df.volums[0:5].mean(): price_buy = 0 price_sell = self.df.close[0] num0 = list( running_box.loc[running_box.stock_id == self.stock_id, 'bought_num'])[0] / 5 num = math.floor(num0 * 100) * 100 commission_buy, commission_sell = obj1.order_cost( num, price_sell, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) cash = num * price_sell - commission_sell if num >= 200: print 'situation3_7' return price_buy, price_sell, cash, num else: num = 200 commission_buy, commission_sell = obj1.order_cost( num, price_sell, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) cash = num * price_sell - commission_sell print 'situation3_8' return price_buy, price_sell, cash, num if self.df.high[0] < self.ave_price_60[0]: price_sell = min(e_support, first_sell_down) * 0.99 # 支撑位止损 if self.df.close[0] <= price_sell: num = list( running_box.loc[running_box.stock_id == self.stock_id, 'bought_num'])[0] commission_buy, commission_sell = obj1.order_cost( num, price_sell, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) cash = num * price_sell - commission_sell print 'situation3_9' return price_buy, price_sell, cash, num else: # 跳空止盈 if self.df.low[0] > self.ave_price_5[0]: price_buy = 0 price_sell = self.df.close[0] num0 = list( running_box.loc[running_box.stock_id == self.stock_id, 'bought_num'])[0] / 5 num = math.floor(num0 * 100) * 100 commission_buy, commission_sell = obj1.order_cost( num, price_sell, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) cash = num * price_sell - commission_sell if num >= 200: print 'situation3_10' return price_buy, price_sell, cash, num else: num = 200 commission_buy, commission_sell = obj1.order_cost( num, price_sell, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) cash = num * price_sell - commission_sell print 'situation3_11' return price_buy, price_sell, cash, num # 超过压力位止盈 # 对于cv_p没做限定,如果存在负角度的压力线,是否会低于60日线,已改pressure角度0到30 elif self.df.low[0] <= first_sell_up <= self.df.high[0]: price_buy = 0 price_sell = self.df.close[0] num0 = list( running_box.loc[running_box.stock_id == self.stock_id, 'bought_num'])[0] / 5 num = math.floor(num0 * 100) * 100 commission_buy, commission_sell = obj1.order_cost( num, price_sell, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) cash = num * price_sell - commission_sell if num >= 200: print 'situation3_12' return price_buy, price_sell, cash, num else: num = 200 commission_buy, commission_sell = obj1.order_cost( num, price_sell, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) cash = num * price_sell - commission_sell print 'situation3_13' return price_buy, price_sell, cash, num elif self.df.low[0] <= second_sell_up <= self.df.high[0]: price_buy = 0 price_sell = self.df.close[0] num0 = list( running_box.loc[running_box.stock_id == self.stock_id, 'bought_num'])[0] / 5 num = math.floor(num0 * 100) * 100 commission_buy, commission_sell = obj1.order_cost( num, price_sell, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) cash = num * price_sell - commission_sell if num >= 200: print 'situation3_14' return price_buy, price_sell, cash, num else: num = 200 commission_buy, commission_sell = obj1.order_cost( num, price_sell, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) cash = num * price_sell - commission_sell print 'situation3_15' return price_buy, price_sell, cash, num elif self.df.low[0] <= third_sell_up <= self.df.high[0]: price_buy = 0 price_sell = self.df.close[0] num0 = list( running_box.loc[running_box.stock_id == self.stock_id, 'bought_num'])[0] / 5 num = math.floor(num0 * 100) * 100 commission_buy, commission_sell = obj1.order_cost( num, price_sell, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) cash = num * price_sell - commission_sell if num >= 200: print 'situation3_16' return price_buy, price_sell, cash, num else: num = 200 commission_buy, commission_sell = obj1.order_cost( num, price_sell, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5) cash = num * price_sell - commission_sell print 'situation3_17' return price_buy, price_sell, cash, num return price_buy, price_sell, cash, num
from deal import Deal import time start = time.time() # Strain 0: "C", 1: "D", 2: "H", 3: "S", 4: "N" # Suit 0: "S", 1: "H", 2: "D", 3: "C" predeal = {0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]} deal1 = Deal.prepare(predeal) Deal.score(dealer=deal1, level=5, strain=0, declarer=3, tries=100) print("%.2f seconds elapsed" % (time.time()-start))
def _get_existing_deals_dict(): deals_dict = {} csv_file = Settings.getSetting('DEALS_FILE') with open(csv_file, 'r', newline='') as csv: deals_dict = Deal.dict_from_csv(csv) return deals_dict