def __init__(self, agent, generator): """ Backtest evaluates a trading agent based on a data generator instance that yields events based on a set of sources. :param agent: Agent, trading agent instance :param generator Generator, data generator instance """ # from arguments self.agent = agent self.generator = generator # data updated chunk-wise by the generator self.sources = None self.monitor = None # identify symbols as market_ids symbols = set(source_id.split(".")[0] for source_id in self.generator.sources ) # setup market instances for market_id in symbols: Market(market_id) # access market instances self.markets = Market.instances
def main(): # Parse Input if len(sys.argv) != 2: print('Usage: python main.py <path-to-data>') return data_dir = sys.argv[1] # Load Data trade_dates, market_data = data.load_data(data_dir) market = Market(market_data) trade_dates = _find_range(trade_dates) # Output Starting Conditions print(f'Starting cash: ${STARTING_CASH:,.2f}') print(f'Monthly cash: ${MONTHLY_CASH:,.2f}') print(f'Trading Start: {trade_dates[0]}') print(f'Trading End: {trade_dates[-1]}') print('') print('Strategies:') for strat in STRATEGIES: print(f' {strat.name()}') print('') # Run Backtest for trade_date in trade_dates: market.set_date(trade_date) for strat in STRATEGIES: strat.notify_day(trade_date, market) # Output Results for strat in STRATEGIES: name = strat.name() result = strat.total_balance(market) contribs = strat.total_contributions() print(f'{name} ended with ${result:,.2f} from ${contribs:,.2f} in contributions')
def get_offers(): response = requests.get( "https://www.edeka.de/eh/service/eh/ods/offers?marketId=8001350&limit=89899" ) jsonData = json.loads(response.text) market = Market("edeka") market.valid_from = datetime.utcfromtimestamp(jsonData['gueltig_von'] / 1000) market.valid_until = datetime.utcfromtimestamp(jsonData['gueltig_bis'] / 1000) for jsonArticle in jsonData['docs']: article = Article() article.label = jsonArticle['titel'] article.price = jsonArticle['preis'] article.url = jsonArticle['bild_app'] result = re.search('\((.*)\)', jsonArticle['beschreibung']) if result != None: unit = result.group(1).split('=') article.unit = unit[0] article.price_unit = unit[1] market.articles.append(article) return market
def __init__(self, ob_ctx): self.shutdown_mutex = Lock() self.ob_ctx = ob_ctx db = Obdb(ob_ctx.db_path, ob_ctx.disable_sqlite_crypt) self.transport = CryptoTransportLayer(ob_ctx, db) self.market = Market(self.transport, db) self.upnp_mapper = None Thread(target=reactor.run, args=(False, )).start() peers = ob_ctx.seeds if not ob_ctx.seed_mode else [] self.transport.join_network(peers) handlers = [(r"/", MainHandler), (r"/main", MainHandler), (r"/html/(.*)", OpenBazaarStaticHandler, { 'path': './html' }), (r"/ws", WebSocketHandler, dict(transport=self.transport, market_application=self, db=db))] # TODO: Move debug settings to configuration location settings = dict(debug=True) super(MarketApplication, self).__init__(handlers, **settings)
def market(): player = game.get_player() techlevels = game.get_techlevels() is_winning_region = game.get_universe().get_winningitem_region( ) == game.get_universe().get_currentregion() #admin cheats :) print("ADMIN CHEATS") print(game.get_universe().get_winningitem_region().get_name()) print(game.get_universe().get_currentregion().get_name()) print(is_winning_region) market = Market(techlevels.index(request.form['techlevel']), player.get_merchant_skills(), player.get_name(), is_winning_region) game.set_market(market) print(player.get_inventory()) empty_inventory = False if player.get_inventory() == {}: empty_inventory = True return render_template('market.html', market=json.dumps(market.intoarrayjsonform()), techlevel=request.form['techlevel'], credits=player.get_credits(), inventory=json.dumps( player.get_inventory_array_json()), inventory_status=empty_inventory)
def predict_2017(cls): from market import Market import helpers from dateutil import parser forecaster = TemperatureForecastModel('/home/hngo/PycharmProjects/volttron-applications/pnnl/TNSAgent/campus_config') # Create market with some time intervals mkt = Market() analysis_time = parser.parse("2017-01-01 00:00:00") mkt.marketClearingTime = analysis_time mkt.nextMarketClearingTime = mkt.marketClearingTime + mkt.marketClearingInterval # Control steps using horizon mkt.futureHorizon = timedelta(days=365) mkt.check_intervals(analysis_time) # set time intervals forecaster.update_information(mkt) # schedule powers predictor = OpenLoopPnnlLoadPredictor(forecaster) predictor.schedule_power(mkt) powers = [(x.timeInterval.startTime, x.value) for x in predictor.scheduledPowers] total_power = sum([s[1] for s in powers]) print(powers) print(total_power)
def testMarketTransaction(): market, fred, carl = setUpMarket() patron = Chef("patrano") platesOnMarket = market.get_plates_for_sale() market.buy(patron, platesOnMarket[0]) printMarket(market) assert (patron.cart.get_order()[0].name == "Wings") assert (len(fred.kitch.patron_orders) == 1) assert (len(carl.kitch.patron_orders) == 0) chef1 = Chef() chef2 = Chef() chef1.name = "Carl" chef2.name = "Fred" chef1.add_plate(plate_name="Wings") chef1.add_plate(plate_name="Tacos") chef2.add_plate(plate_name="Boneless Wings") chef2.add_plate(plate_name="Burritos") chef1.kitch.get_plate("Wings").add_item(Item(name="wing", price=2.50)) chef1.kitch.get_plate("Wings").add_item(Item(name="wing2", price=2.50)) chef1.kitch.get_plate("Tacos").add_item(Item(name="wing", price=2.50)) chef2.kitch.get_plate("Boneless Wings").add_item( Item(name="beans", price=2.50)) chef2.kitch.get_plate("Boneless Wings").add_item( Item(name="cheese", price=2.50)) chef2.kitch.get_plate("Burritos").add_item(Item(name="cheese", price=2.50)) market = Market() market.offer(chef1, chef1.get_plate("Wings")) market.offer(chef1, chef1.get_plate("Tacos")) market.offer(chef2, chef2.get_plate("Boneless Wings")) market.offer(chef2, chef2.get_plate("Burritos")) return market, chef1, chef2
def change2market(self): self.buildings = Market(world=self.world, village=self.village, root=self.f_screen, resources=self.resources, row_i=3, column_i=1)
def __init__(self, store_file, my_market_ip, my_market_port, my_node_port, my_node_file, seed_uri, market_id): self.transport = CryptoTransportLayer(my_market_ip, my_market_port, market_id, store_file) self.transport.join_network(seed_uri) data_store = SQLiteDataStore( ) # creates in-memory database, should be persistent known_nodes = self.known_entangled_nodes(my_node_file, seed_uri, my_node_port) # initializes node with specified port and an in-memory SQLite database self.node = entangled.node.EntangledNode(udpPort=my_node_port, dataStore=data_store) self.node.joinNetwork(known_nodes) self.market = Market(self.transport, self.node, store_file) handlers = [(r"/", MainHandler), (r"/main", MainHandler), (r"/html/(.*)", tornado.web.StaticFileHandler, { 'path': './html' }), (r"/ws", WebSocketHandler, dict(transport=self.transport, node=self.market))] # TODO: Move debug settings to configuration location settings = dict(debug=True) tornado.web.Application.__init__(self, handlers, **settings)
def test_market(n, m, t, partial, writer): market = Market(n, m, t, partial) serialDictatorship.serial_dictatorship(market) serial_happy = evaluation.happy(market) serial_percent_served = evaluation.percent_served(market) serial_avg_time = evaluation.average_time(market) market.reset() serialDictatorship.modified_serial_dictatorship(market) mod_happy = evaluation.happy(market) mod_percent_served = evaluation.percent_served(market) mod_avg_time = evaluation.average_time(market) market.reset() minLocations.minimize_locations(market) min_loc_happy = evaluation.happy(market) min_loc_percent_served = evaluation.percent_served(market) min_loc_avg_time = evaluation.average_time(market) row = [ n, m, t, partial, serial_happy, serial_percent_served, serial_avg_time, mod_happy, mod_percent_served, mod_avg_time, min_loc_happy, min_loc_percent_served, min_loc_avg_time ] writer.writerow(row)
def market_init(self, product): # usd_acc = self.binance_accounts['USD'] # crypto_acc = self.binance_accounts.get(product['base_currency']) # if (usd_acc == None or crypto_acc == None): # log.error ("No account available for product: %s"%(product['id'])) # return None #Setup the initial params # log.debug ("product: %s"%product) market = Market(product=product, exchange=self) market.fund.set_initial_value(Decimal(0)) #usd_acc['available'])) market.fund.set_hold_value(Decimal(0)) #usd_acc['hold'])) market.fund.set_fund_liquidity_percent(10) #### Limit the fund to 10% market.fund.set_max_per_buy_fund_value(100) market.asset.set_initial_size(Decimal(0)) #crypto_acc['available'])) market.asset.set_hold_size(0) #Decimal(crypto_acc['hold'])) ## Feed Cb market.consume_feed = self._binance_consume_feed ## Init Exchange specific private state variables market.O = market.H = market.L = market.C = market.V = 0 market.candle_interval = self.candle_interval log.info("Market init complete: %s" % (product['id'])) #set whether primary or secondary market.primary = self.primary return market
def main(argv): """ runtime entrypoint """ try: args = extract_args(argv) timestamp = datetime.now() print('*** model-goals ***') print(' model run time: {}'.format(timestamp)) print(' goals file: {}'.format(args[0])) print(' site file: {}'.format(args[1])) print(' exchange file: {}'.format(args[2])) print(' exchange id: {}'.format(args[3])) goals = load_yaml(args[0]) sites = load_yaml(args[1]) exchange = Market(load_yaml(args[2]), args[3]) report.start() report.output_general('Starting State') print_state(sites, exchange) report.end() consumption = execute_goals(goals, sites, exchange) report.newline() report.start() summary = consumption.summarize_inventory(exchange) report.output_value_table(summary['inventory'], "Consumption for all Goals") report.end() report.newline() print(output.getvalue()) return 0 except Exception: traceback.print_exc() return 100
def trade_a_priced(self, environment, time): # We find the market price of A shares # given supply and demand of the agents # and tolerance of error, resolution of search # and amplification factor for exponential search suppliers = [] for agent in environment.firms: if agent.domicile == 0: # print agent.get_account("number_of_shares"), agent.identifier suppliers.append([agent, agent.supply_of_shares]) # And the list of buyers and their demand functions buyers = [] for agent in environment.funds: buyers.append([agent, agent.demand_a]) price_dummy = 75 from market import Market # Put the appropriate settings, i.e. desired identifier market = Market("market") price = market.tatonnement(suppliers, buyers, price_dummy, 0.001, 0.01, 1.1) environment.variable_parameters["price_of_a"] = price # print price # now we use rationing to find the actual transactions between agents for_rationing = [] for firm in environment.firms: if firm.domicile == 0: for_rationing.append([firm, firm.supply_of_shares(price)]) for fund in environment.funds: for_rationing.append([fund, -fund.demand_a(price)]) # And we find the rationing, ie the amounts # of shares sold between pairs of agents rationed = market.rationing_proportional(for_rationing)
def __init__(self, access_token=''): self.Account = Account(access_token=access_token) self.Apps = Apps(access_token=access_token) self.Audio = Audio(access_token=access_token) self.Auth = Auth(access_token=access_token) self.Board = Board(access_token=access_token) self.Database = Database(access_token=access_token) self.Docs = Docs(access_token=access_token) self.Other = Other(access_token=access_token) self.Fave = Fave(access_token=access_token) self.Friends = Friends(access_token=access_token) self.Gifts = Gifts(access_token=access_token) self.Groups = Groups(access_token=access_token) self.Likes = Likes(access_token=access_token) self.Market = Market(access_token=access_token) self.Messages = Messages(access_token=access_token) self.Newsfeed = Newsfeed(access_token=access_token) self.Notes = Notes(access_token=access_token) self.Notifications = Notifications(access_token=access_token) self.Pages = Pages(access_token=access_token) self.Photos = Photos(access_token=access_token) self.Places = Places(access_token=access_token) self.Polls = Polls(access_token=access_token) self.Search = Search(access_token=access_token) self.Stats = Stats(access_token=access_token) self.Status = Status(access_token=access_token) self.Storage = Storage(access_token=access_token) self.Users = Users(access_token=access_token) self.Utils = Utils(access_token=access_token) self.Video = Video(access_token=access_token) self.Wall = Wall(access_token=access_token) self.Widgets = Widgets(access_token=access_token)
def run(args): market = Market(args.market) with Inventory(args.inventory) as inventory: items = [{ "name": item["name"], "count": item["count"], "market": market.item(item["name"]) } for item in inventory.get_items()] for item in items: if not item["market"]["ducats"]: item["market"]["ducats"] = 0 if args.ducats: items = sorted(items, key=lambda a: -a["market"]["ducats"] / a["market"][ "stats"][-1]["median"]) elif args.plats: items = sorted(items, key=lambda a: -a["market"]["stats"][-1]["median"]) else: items = sorted(items, key=lambda a: a["name"]) print(f'{"Ducats/Price":>60} {"Volume":>9} {"Price":>9}') for item in items: label = f'{item["count"]}x {item["name"].replace("_", " ").title()}' market_stats = item["market"]["stats"][-1] ducats = item["market"]["ducats"] / market_stats["median"] print( f'{label:50} {ducats:9.2f} {market_stats["volume"]:9} {market_stats["median"]:9.2f}' )
def createmarket(numagents=15): agents = [] market = Market() initbaseprices(market.marketprices) for x in range(numagents): agents.append(makerandomagent(market)) market.addagent(agents[-1]) return agents, market
def init(self): self.citizens = [] for i in range(self.default_population): self.citizens.append(Citizen(self, self.data_path)) self.market = Market(self.data_path) self.day = 0
def get_offers(): market = Market("aldi") now = datetime.datetime.now() dates = [['mo', now - datetime.timedelta(days=now.weekday())], ['do', next_day(now, 3)], ['fr', next_day(now, 4)], ['mo', next_day(now, 0)]] types = ['angebote', 'aktion'] for type in types: for obj in dates: url = 'https://www.aldi-nord.de/angebote/' + type + '-' + obj[ 0] + '-' + '{:02d}'.format(obj[1].day) + '-' + '{:02d}'.format( obj[1].month) + '.html' #print url raw_html = simple_get(url) if raw_html is None: continue html = BeautifulSoup(raw_html, 'html.parser') for div in html.select('div'): #label if 'mod-article-tile' in div.get('class'): article = Article() article.date = format(obj[1], "%Y-%m-%d") # title h4 = div.select('h4') for tag in h4: article.label = tag.getText() # price span = div.select('span') for sp in span: if sp.get('class' ) is not None and 'price__main' in sp.get( 'class'): article.price = float(sp.getText().replace( '*', '').lstrip('\n').rstrip('\n')) if sp.get('class' ) is not None and 'price__base' in sp.get( 'class'): article.price_unit = sp.getText().replace( '(', '').replace(')', '').replace(' ', '') splitted_unit = article.price_unit.split('=') article.price_unit = splitted_unit[1] article.unit = splitted_unit[0] #url a = div.select('a') for href in a: if (href.get('class') is not None and 'mod-article-tile__action' in href.get('class')): article.url = 'https://www.aldi-nord.de/' + href.get( 'href') market.articles.append(article) return market
def main(): model = Market(2, 2) agent0 = model.schedule.agents[0] agent1 = model.schedule.agents[1] agent0.u_params = np.array([1 / 2, 1 / 2]) agent1.u_params = np.array([1 / 2, 1 / 2]) agent0.ppf = np.array([4, 1]) agent1.ppf = np.array([1, 4]) return model
def get_offers(): market = Market('rewe') types = [ None, 'fruehstueck', 'topangebote', 'obst-und-gemuese', 'frisch-und-kuehlung', 'tiefkuehl', 'kochen-und-backen', 'suessigkeiten', 'getraenke', 'drogerie', 'sonstige-angebote' ] labels = [] for type in types: type = type + '/' if type != None else '' url = 'https://www.rewe.de/angebote/1931138/' + type + 'berlin/rewe-clayallee-336' raw_html = simple_get(url) if raw_html is None: continue html = BeautifulSoup(raw_html, 'html.parser') for div in html.select('div'): if div.get('class') is not None and 'drm-item-card' in div.get( 'class'): article = Article() #label for innerdiv in div.select('p'): if innerdiv.get( 'class' ) is not None and 'headline' in innerdiv.get('class'): article.label = innerdiv.getText() # price for innerdiv in div.select('div'): if innerdiv.get( 'class' ) is not None and 'price-euro' in innerdiv.get('class'): article.price = innerdiv.getText() elif innerdiv.get( 'class' ) is not None and 'price-cent' in innerdiv.get('class'): article.price += innerdiv.getText() if article.price is not None: article.price = float(article.price.replace(',', '.')) text_description = div.select('.text-description') if len(text_description) > 0: for p in text_description[0].select('p'): if '=' in p.getText(): article.price_unit = p.getText().replace( '(', '').replace(')', '').replace(' ', '') splitted_unit = article.price_unit.split('=') article.price_unit = splitted_unit[1] article.unit = splitted_unit[0] if article.label != None and article.label not in labels: market.articles.append(article) labels.append(article.label) return market
def test_new_pricelevel(self): """ Add new bid and ask orders and checks price-time priority """ market = Market() bidprice = np.random.uniform(0.0001, 100000) o1 = namedtuple('Order', 'is_buy, qty, price') o1 = o1(is_buy=True, qty=10, price=bidprice) o2 = namedtuple('Order', 'is_buy, qty, price') o2 = o2(is_buy=True, qty=5, price=bidprice) o3 = namedtuple('Order', 'is_buy, qty, price') o3 = o3(is_buy=True, qty=7, price=bidprice) # Check price level creation, heads and tails, uid & order active o1uid = market.send(*o1) self.assertIn(o1.price, market._bids.book.keys()) self.assertEqual(market._bids.best.price, o1.price) self.assertEqual(market._bids.best.head.uid, o1uid) self.assertEqual(market._bids.best.tail.uid, o1uid) self.assertEqual(market._orders[o1uid].uid, o1uid) self.assertEqual(market.get(o1uid)['active'], True) o2uid = market.send(*o2) self.assertEqual(market._bids.best.price, bidprice) # Check time priority inside PriceLevel self.assertEqual(market._bids.best.head.uid, o1uid) o3uid = market.send(*o3) self.assertEqual(market._bids.best.head.uid, o1uid) self.assertEqual(market._bids.best.head.next.uid, o2uid) self.assertEqual(market._bids.best.tail.uid, o3uid) # Check list of orders ### SAME FOR ASKS askprice = bidprice + 0.0001 o4 = namedtuple('Order', 'is_buy, qty, price') o4 = o4(is_buy=False, qty=10, price=askprice) o5 = namedtuple('Order', 'is_buy, qty, price') o5 = o5(is_buy=False, qty=5, price=askprice) o6 = namedtuple('Order', 'is_buy, qty, price') o6 = o6(is_buy=False, qty=7, price=askprice) # Check price level creation, heads and tails o4uid = market.send(*o4) self.assertIn(askprice, market._asks.book.keys()) self.assertEqual(market._asks.best.price, o4.price) self.assertEqual(market._asks.best.head.uid, o4uid) self.assertEqual(market._asks.best.tail.uid, o4uid) self.assertEqual(market._orders[o4uid].uid, o4uid) o5uid = market.send(*o5) # Check time priority inside PriceLevel self.assertIs(market._asks.best.head.uid, o4uid) o6uid = market.send(*o6) self.assertEqual(market._asks.best.head.uid, o4uid) self.assertEqual(market._asks.best.head.next.uid, o5uid) self.assertEqual(market._asks.best.tail.uid, o6uid)
def main(argv): """ runtime entrypoint """ try: args = extract_args(argv) inventory = Inventory(load_yaml(args[0])) exchanges = load_yaml(args[1]) outfile = open(args[2], "w") ica_market = Market(exchanges, "IC1") ncc_market = Market(exchanges, "NC1") cis_market = Market(exchanges, "CI1") inventory.output_summary("List Cost (ICA)", ica_market, outfile) inventory.output_summary("List Cost (NCC)", ncc_market, outfile) inventory.output_summary("List Cost (CIS)", cis_market, outfile) except Exception as err: print(err) return 100
def test_add_ais(self): market = Market() self.assertEqual(len(market.ais), 0) ais = [AI(market.basic), AI(market.basic)] market.add_ais(ais) self.assertEqual(len(market.ais), 2) ai = AI(market.basic) market.add_ais(ai) self.assertEqual(len(market.ais), 3) self.assertIn(ai, market.ais)
def evaluate_strategy(self, strategy, mode=None): for dp in self.dp_timeslots: # Run a market sequence with all the bids of the corresponding dp strdp = str(dp) if dp>9 else "0"+str(dp) bid_file_tag = "dp" + strdp + "d1" customer_bid_file_tag = "dp" + strdp + "d1cc" delivery_product = self.initiate_dps([dp])[0] market = Market(delivery_product, bid_file_tag, customer_bid_file_tag, printing_mode=False) market.main() return 0
def main_menu(session, base_url): """ Provides the different options for the sample application: Market Quotes, Account List :param session: authenticated session """ market = Market(session, base_url) accounts = Accounts(session, base_url) order = Order(session, {}, base_url) # ret = market.quoteCommon("vsat") # print ("MARKET FOR VST", ret) accountsObj = accounts.printPorfolio(PERCENT) accountsList = accountsObj['acct'] accountsPort = accountsObj['port'] ordersAcct = {} for account in accountsList: ordersAcct[account['accountId']] = order.viewOpenOrder(account, False) checkAccountOrder(accountsPort, ordersAcct) menu_items = {"1": "Market Quotes", "2": "Account List", "3": "Place File order", "4": "Cancel all open orders", "5": "Cancel ALL orders and redo on current price", "6": "redo diff orders", "7": "Exit"} while True: print("") options = menu_items.keys() for entry in options: print(entry + ")\t" + menu_items[entry]) selection = input("Please select an option: ") if selection == "1": market.quotes() elif selection == "2": accounts.account_list() elif selection == "3": order.readCSV(False) elif selection == "4": for account in accountsList: order.viewOpenOrder(account, True) elif selection == "5": for account in accountsList: order.viewOpenOrder(account, True) order.readCSV(True) elif selection == "6": order.dodiff() elif selection == "7": break else: print("Unknown Option Selected!")
def __init__(self): super(StockSimApp, self).__init__() self.market = Market() self.ais = generate_ai() self.market.add_ais(self.ais) for each in self.market.ais: each.market = copy(self.market.basic) self.user = User(self.market) self.current_company = "AAPL" self.current_price = str(float(self.market.basic["AAPL"][-1])) self.generate_graph(self.current_company)
def test_get_basic(self): market = Market() self.assertIn("AAPL", market.basic.keys()) self.assertIn("AMD", market.basic.keys()) self.assertIn("AMZN", market.basic.keys()) self.assertIn("INTC", market.basic.keys()) self.assertIn("MSFT", market.basic.keys()) self.assertIn("CSCO", market.basic.keys()) self.assertIn("GPRO", market.basic.keys()) self.assertIn("NVDA", market.basic.keys()) self.assertEqual(len(market.basic["AAPL"]), 30)
def testSamePlateOffer(): carl = Chef("carl") fred = Chef("fred") carl.kitch.add_plate(plate_name="Wings") carl.kitch.add_plate(plate_name="Tacos") fred.kitch.add_plate(plate_name="Wings") fred.kitch.add_plate(plate_name="Tacos") market = Market() market.offer(carl, carl.kitch.get_plate("Wings")) market.offer(fred, fred.kitch.get_plate("Wings")) assert (market.itemsOnMarket[carl][0].name == "Wings") assert (market.itemsOnMarket[fred][0].name == "Wings")
def test_get_stored_market_names__contains_files(self, mock_os): market = Market('market') DummyFile('a') filename_list = ['a', 'b', 'c', 'd'] dummyfile_list = [ DummyFile('a'), DummyFile('b'), DummyFile('c'), DummyFile('d') ] iterator_filelist = iter(dummyfile_list) mock_os.scandir.return_value = iterator_filelist self.assertEqual(market.get_stored_market_names(), filename_list)
def __init__(self, interval="day", market_wrapper: Market = None, verbose=False): self._data = pd.DataFrame() self._tickers = [] self._etfs = None self.market = Market() if market_wrapper is None else market_wrapper self.interval = interval self.data_file = MAIN_FOLDER / f"ETFs_history_i={interval}.csv" self.tickers_file = MAIN_FOLDER / f"tickers_i={interval}.dat" self.verbose = verbose # Update self._load_data()