Esempio n. 1
0
    def simulate(self):
        "Simulate a round of trading between the agents(Pops) at this Market"
        pops_grouped = groupby(self.pops, lambda x: x.pop_type)
        # print(', '.join(["{}: {}".format(pop_type.title, len(list(pops))) for pop_type, pops in pops_grouped]))

        for pop in self.location.pops:
            # print("\nPop {} ({}):".format(pop.pop_type.title, pop.id))
            # print("Inventory: {}".format(pop.inventory.display()))

            # perform each Pop's production
            pop.money_yesterday = pop.money
            pop.perform_production()

            # for each good, check to see if the Pop needs to buy or sell
            for good in Good.all():
                pop.generate_orders(good)

        for good in Good.all():
            self.resolve_orders(good)

        # resolve all offers for each Good
        for pop in self.location.pops:
            if pop.money < 0:
                # change to the most profitable pop type
                # unless there's an underserved market
                self.decide_new_pop_type(pop)
Esempio n. 2
0
    def simulate(self):
        "Simulate a round of trading between the agents(Pops) at this Market"
        pops_grouped = groupby(self.pops, lambda x: x.pop_job)
        # print(', '.join(["{}: {}".format(pop_job.title, len(list(pops))) for pop_job, pops in pops_grouped]))

        with Timer('\tfor all pop generate orders'):
            for pop in self.location.pops:
                # print("\nPop {} ({}):".format(pop.pop_job.title, pop.id))
                # print("Inventory: {}".format(pop.inventory.display()))

                # perform each Pop's production
                pop.money_yesterday = pop.money
                pop.perform_logic()

                # for each good, check to see if the Pop needs to buy or sell
                for good in Good.all():
                    pop.generate_orders(good)

        with Timer("\tresolve orders"):
            for good in Good.all():
                self.resolve_orders(good)

        # resolve all offers for each Good
        with Timer("\tdecide new pop job"):
            for pop in self.location.pops:
                if pop.money < 0:
                    # change to the most profitable pop type
                    # unless there's an underserved market
                    self.decide_new_pop_job(pop)
                else:
                    # TODO: If money is declining recently, and about to be bankrupt,
                    # then switch to a new job
                    pass
Esempio n. 3
0
    def simulate(self):
        "Simulate a round of trading between the agents(Pops) at this Market"
        pops_grouped = groupby(self.pops, lambda x: x.pop_type)
        # print(', '.join(["{}: {}".format(pop_type.title, len(list(pops))) for pop_type, pops in pops_grouped]))


        for pop in self.location.pops:
            # print("\nPop {} ({}):".format(pop.pop_type.title, pop.id))
            # print("Inventory: {}".format(pop.inventory.display()))

            # perform each Pop's production
            pop.money_yesterday = pop.money
            pop.perform_production()

            # for each good, check to see if the Pop needs to buy or sell
            for good in Good.all():
                pop.generate_orders(good)

        for good in Good.all():
            self.resolve_orders(good)

        # resolve all offers for each Good
        for pop in self.location.pops:
            if pop.money < 0:
                # change to the most profitable pop type
                # unless there's an underserved market
                self.decide_new_pop_type(pop)
Esempio n. 4
0
    def most_demanded_good(self, minimum=1.5, day_range=10):
        """
        Get the good with the highest demand/supply ratio over time
        minimum (float)     the minimum demand/supply ratio to consider an opportunity
        day_range (int)     number of rounds to look back
        """
        best_good = None
        best_ratio = float('-inf')
        for good in Good.all():
            sells = self.history.sell_orders.average(good, day_range=day_range)
            buys = self.history.buy_orders.average(good, day_range=day_range)

            if buys > 0 and sells > 0:  # if this Good is traded in this Market

                if sells == 0 and buys > 0:
                    # make a fake supply of 0.5 for each unit to avoid
                    # an infinite ratio of supply to demand
                    sells = 0.5

                ratio = buys / sells

                if ratio > minimum and ratio > best_ratio:
                    best_ratio = ratio
                    best_good = good

        return best_good
Esempio n. 5
0
    def most_demanded_good(self, minimum=1.5, day_range=10):
        """
        Get the good with the highest demand/supply ratio over time
        minimum (float)     the minimum demand/supply ratio to consider an opportunity
        day_range (int)     number of rounds to look back
        """
        best_good = None
        best_ratio = float('-inf')
        for good in Good.all():
            sells = self.history.sell_orders.average(good, day_range=day_range)
            buys = self.history.buy_orders.average(good, day_range=day_range)

            if buys > 0 and sells > 0: # if this Good is traded in this Market

                if sells == 0 and buys > 0:
                    # make a fake supply of 0.5 for each unit to avoid
                    # an infinite ratio of supply to demand
                    sells = 0.5

                ratio = buys / sells

                if ratio > minimum and ratio > best_ratio:
                    best_ratio = ratio
                    best_good = good

        return best_good
Esempio n. 6
0
 def export(self):
     "Export the Market data as it currently exists"
     orders_for = lambda l, g: [o.export() for o in l[g]]
     return {
         'history': [{
             'good': good.ref(),
             'data': self.history.export(good, 1)
         } for good in Good.all()]
     }
Esempio n. 7
0
    def __init__(self, province, pop_type, population):
        """
        Creates a new Pop.
        manager  (Historia)
        province (SecondaryDivision)
        culture  (Culture)
        religion (Religion)
        language (Language)
        job      (Job)
        """
        self.bankrupt_times = 0
        self.province = province
        self.id = unique_id('po')

        self.population = population
        self.population_yesterday = 0

        self.pop_type = pop_type

        # ECONOMY
        self.money = 10
        self.money_yesterday = 0
        self.bankrupt = False

        # set inventory and ideal amounts
        self.inventory = Inventory(150)
        for item in self.pop_type.start_inventory:
            self.inventory.add(item['good'], item['amount'])

        self.update_ideal_inventory()

        # a dictionary of Goods to PriceRanges
        # represents the price range the agent considers valid for each Good
        self.price_belief = {}

        # a dictionary of Goods to price list
        # represents the prices of the good that the Pop has observed
        # during the time they have been trading
        self.observed_trading_range = {}

        self.successful_trades = 0
        self.failed_trades = 0


        # make some fake initial data
        for good in Good.all():
            avg_price = self.market.avg_historial_price(good, 15)
            # fake trades
            self.observed_trading_range[good] = [
                avg_price * 0.5,
                avg_price * 1.5
            ]
            # generate fake price belief
            self.price_belief[good] = PriceRange(avg_price * 0.5, avg_price * 1.5)
Esempio n. 8
0
    def __init__(self, province, pop_type, population):
        """
        Creates a new Pop.
        manager  (Historia)
        province (SecondaryDivision)
        culture  (Culture)
        religion (Religion)
        language (Language)
        job      (Job)
        """
        self.bankrupt_times = 0
        self.province = province
        self.id = unique_id('po')

        self.population = population
        self.population_yesterday = 0

        self.pop_type = pop_type

        # ECONOMY
        self.money = 10
        self.money_yesterday = 0
        self.bankrupt = False

        # set inventory and ideal amounts
        self.inventory = Inventory(150)
        for item in self.pop_type.start_inventory:
            self.inventory.add(item['good'], item['amount'])

        self.update_ideal_inventory()

        # a dictionary of Goods to PriceRanges
        # represents the price range the agent considers valid for each Good
        self.price_belief = {}

        # a dictionary of Goods to price list
        # represents the prices of the good that the Pop has observed
        # during the time they have been trading
        self.observed_trading_range = {}

        self.successful_trades = 0
        self.failed_trades = 0

        # make some fake initial data
        for good in Good.all():
            avg_price = self.market.avg_historial_price(good, 15)
            # fake trades
            self.observed_trading_range[good] = [
                avg_price * 0.5, avg_price * 1.5
            ]
            # generate fake price belief
            self.price_belief[good] = PriceRange(avg_price * 0.5,
                                                 avg_price * 1.5)
Esempio n. 9
0
    def most_costly_good(self, day_range, exclude=None):
        """
        Returns the good that has the highest average price over the given range of time
        range (int)           how many days to look back
        exclude (list[Good])  goods to exclude
        """
        best_good = None
        best_price = float('inf')

        for good in Good.all():
            if exclude is None or good in exclude:
                price = self.history.prices.average(good, day_range=day_range)

                if price > best_price:
                    best_price = price
                    best_good = good

        return best_good
Esempio n. 10
0
    def most_costly_good(self, day_range, exclude=None):
        """
        Returns the good that has the highest average price over the given range of time
        range (int)           how many days to look back
        exclude (list[Good])  goods to exclude
        """
        best_good = None
        best_price = float('inf')

        for good in Good.all():
            if exclude is None or good in exclude:
                price = self.history.prices.average(good, day_range=day_range)

                if price > best_price:
                    best_price = price
                    best_good = good

        return best_good
Esempio n. 11
0
    def most_cheap_good(self, day_range=10, exclude=None):
        """
        Returns the good that has the lowest average price over the given range of time
        range (int)           how many days to look back
        exclude (list[Good])  goods to exclude
        """
        best_good = None
        best_price = float('inf')

        for good in Good.all():
            if exclude is None or good not in exclude:
                price = self.mean_price(good)

                if price < best_price:
                    best_price = price
                    best_good = good

        return best_good
Esempio n. 12
0
    def goods_demand_ratio(self, day_range=10):
        """
        Get the good with the lowest demand/supply ratio over time
        day_range (int)     number of rounds to look back
        """
        demand_list = {}
        for good in Good.all():
            sells = self.history.sell_orders.average(good, day_range=day_range)
            buys = self.history.buy_orders.average(good, day_range=day_range)

            if buys > 0 or sells > 0: # if this Good is traded in this Market

                if sells == 0 and buys > 0:
                    # make a fake supply of 0.5 for each unit to avoid
                    # an infinite ratio of supply to demand
                    sells = 0.5

                ratio = buys / sells

                demand_list[good] = ratio
        return demand_list
Esempio n. 13
0
    def __init__(self, manager, location):
        self.manager = manager
        self.location = location

        # dictionary of list of orders by Good
        # stores the current buy and sell orders this market is processing
        self.buy_orders = {}
        self.sell_orders = {}

        # stores historical economic data for past transactions
        self.history = TradeHistory()

        # fill the trade history with a bunch of fake data
        for good in Good.all():
            self.history.register(good)
            self.history.prices.add(good, 1.0)
            self.history.buy_orders.add(good, 1.0)
            self.history.sell_orders.add(good, 1.0)
            self.history.trades.add(good, 1.0)
            self.buy_orders[good] = []
            self.sell_orders[good] = []

        for pop_type in PopType.all():
            self.history.profit.register(pop_type)
Esempio n. 14
0
    def __init__(self, manager, location):
        self.manager = manager
        self.location = location

        # dictionary of list of orders by Good
        # stores the current buy and sell orders this market is processing
        self.buy_orders = {}
        self.sell_orders = {}

        # stores historical economic data for past transactions
        self.history = TradeHistory()

        # fill the trade history with a bunch of fake data
        for good in Good.all():
            self.history.register(good)
            self.history.prices.add(good, 1.0)
            self.history.buy_orders.add(good, 1.0)
            self.history.sell_orders.add(good, 1.0)
            self.history.trades.add(good, 1.0)
            self.buy_orders[good] = []
            self.sell_orders[good] = []

        for pop_type in PopType.all():
            self.history.profit.register(pop_type)
Esempio n. 15
0
 def export(self):
     "Export the Market data as it currently exists"
     orders_for = lambda l, g: [o.export() for o in l[g]]
     return {
         'history': [{'good': good.ref(), 'data': self.history.export(good, 1)} for good in Good.all()]
     }
Esempio n. 16
0
 def export(self):
     "Export the Market data as it currently exists"
     orders_for = lambda l, g: [o.export() for o in l[g]]
     return {
         'history': [{'good': good.ref(), 'data': self.history.export(good, 1)} for good in Good.all()],
         'most_demanded_good': self.most_demanded_good(),
         'most_profitable_pop_job': self.most_profitable_pop_job(),
         'most_expensive_good': self.most_costly_good(exclude=[Good.fish])
     }