%matplotlib inline
import random as rnd
import pandas as pd
import time

# measure how long it takes to run the script
startit = time.time()

class Seller():
    def __init__(self,name):
        self.name = name
        self.wta = []

    # the supplier has n quantities that they can sell
    # they may be willing to sell this quantity anywhere from a lower price of l
    # to a higher price of u
    def set_quantity(self,n,l,u):
        wta = []
        for i in range(n):
            p = rnd.uniform(l,u)
            self.wta.append(p)

    def get_name(self):
        return self.name
    
    def get_asks(self):
        return self.wta


class Buyer():
    
    def __init__(self, name):
        self.wtp = []
        self.name = name
        
    # the supplier has n quantities that they can buy
    # they may be willing to sell this quantity anywhere from a lower price of l
    # to a higher price of u
    def set_quantity(self,n,l,u):
        for i in range(n):
            p = rnd.uniform(l,u)
            self.wtp.append(p)
     
    def get_name(self):
        return self.name
    
    # return list of willingness to pay
    def get_bids(self):
        return self.wtp


class Book():
    ledger = pd.DataFrame(columns = ("role","name","price","cleared"))

    
    def set_asks(self,seller_list):
        # ask each seller their name
        # ask each seller their willingness
        # for each willingness append the data frame
        for seller in seller_list:
            seller_name = seller.get_name()
            seller_price = seller.get_asks()
            for price in seller_price:
                self.ledger=self.ledger.append({"role":"seller","name":seller_name,"price":price,"cleared":"in process"},
                                               ignore_index=True)

    def set_bids(self,buyer_list):
        # ask each seller their name
        # ask each seller their willingness
        # for each willingness append the data frame
        for buyer in buyer_list:
            buyer_name = buyer.get_name()
            buyer_price = buyer.get_bids()
            for price in buyer_price:
                self.ledger=self.ledger.append({"role":"buyer","name":buyer_name,"price":price,"cleared":"in process"},
                                               ignore_index=True)

    def update_ledger(self,ledger):
        self.ledger = ledger
        
    def get_ledger(self):
        return self.ledger
    
        
class Market():
    count = 0
    last_price = ''
    book = Book()
    b = []
    s = []
    ledger = ''
    
    #def __init__(self):

    def add_buyer(self,buyer):
        self.b.append(buyer)
        
    def add_seller(self,seller):
        self.s.append(seller)
    
    def set_book(self):
        self.book.set_bids(self.b)
        self.book.set_asks(self.s)
    
    def get_ledger(self):
        self.ledger = self.book.get_ledger()
        return self.ledger
    
    def get_bids(self):
        # this is a data frame
        ledger = self.book.get_ledger()
        rows= ledger.loc[ledger['role'] == 'buyer']
        # this is a series
        prices=rows['price']
        # this is a list
        bids = prices.tolist()
        return bids
    
    def get_asks(self):
        # this is a data frame
        ledger = self.book.get_ledger()
        rows = ledger.loc[ledger['role'] == 'seller']
        # this is a series
        prices=rows['price']
        # this is a list
        asks = prices.tolist()
        return asks
    
    # return the price at which the market clears
    # this fails because there are more buyers then sellers
    
    def get_clearing_price(self):
        # buyer makes a bid starting with the buyer which wants it most
        b = self.get_bids()
        s = self.get_asks()
        # highest to lowest
        self.b=sorted(b, reverse=True)
        # lowest to highest
        self.s=sorted(s, reverse=False)
        
        # find out whether there are more buyers or sellers
        # then drop the excess buyers or sellers; they won't compete
        n = len(b)
        m = len(s)
        
        # there are more sellers than buyers
        # drop off the highest priced sellers 
        if (m > n):
            s = s[0:n]
            matcher = n
        # There are more buyers than sellers
        # drop off the lowest bidding buyers 
        else:
            b = b[0:m]
            matcher = m
        
        # It's possible that not all items sold actually clear the market here
        for i in range(matcher):
            if (self.b[i] > self.s[i]):
                self.count +=1
                self.last_price = self.b[i]
                
        return self.last_price
    
    # TODO: Annotate the ledger
    def annotate_ledger(self,clearing_price):
        ledger = self.book.get_ledger()
        for index, row in ledger.iterrows():
            if (row['role'] == 'seller'):
                if (row['price'] < clearing_price):
                    ledger.ix[index,'cleared'] = 'True'
                else:
                    ledger.ix[index,'cleared'] = 'False'
            else:
                if (row['price'] > clearing_price):
                    ledger.ix[index,'cleared'] = 'True'
                else:
                    ledger.ix[index,'cleared'] = 'False'  
                    
        self.book.update_ledger(ledger)
    
    def get_units_cleared(self):
        return self.count
        
        

"""
Explanation: Matching Market
This simple model consists of a buyer, a supplier, and a market. 
The buyer represents a group of customers whose willingness to pay for a single unit of the good is captured by a vector of prices wta. You can initiate the buyer with a set_quantity function which randomly assigns the willingness to pay according to your specifications. You may ask for these willingness to pay quantities with a getbid function. 
The supplier is similiar, but instead the supplier is willing to be paid to sell a unit of technology. The supplier for instance may have non-zero variable costs that make them unwilling to produce the good unless they receive a specified price. Similarly the supplier has a  get_ask function which returns a list of desired prices. 
The willingness to pay or sell are set randomly using uniform random distributions. The resultant lists of bids are effectively a demand curve. Likewise the list of asks is effectively a supply curve. A more complex determination of bids and asks is possible, for instance using time of year to vary the quantities being demanded. 
New in version 3

Multiple buyers and sellers can be added
the model is ran with consumer data of 2010 (CBS Statline). The dictionary creates new buyers and sellers in every time step. - Fixed initialisation of the buyer to reduce runtime, further improvements will be done in version 4.

Microeconomic Foundations
The market assumes the presence of an auctioneer which will create a book, which seeks to match the bids and the asks as much as possible. If the auctioneer is neutral, then it is incentive compatible for the buyer and the supplier to truthfully announce their bids and asks. The auctioneer will find a single price which clears as much of the market as possible. Clearing the market means that as many willing swaps happens as possible. You may ask the market object at what price the market clears with the get_clearing_price function. You may also ask the market how many units were exchanged with the get_units_cleared function.
Agent-Based Objects
The following section presents three objects which can be used to make an agent-based model of an efficient, two-sided market.
End of explanation
"""


# Test the Book
ledger = pd.DataFrame(columns = ("role","name","price","cleared"))
ledger=ledger.append({"role":"seller","name":"gas","price":24,"cleared":"in process"},ignore_index=True)
ledger=ledger.append({"role":"buyer","name":"gas","price":25,"cleared":"in process"},ignore_index=True)
#df.append({'foo':1, 'bar':2}, ignore_index=True)
rows=ledger.loc[ledger['role'] == 'seller']
print(rows['price'].tolist())


for index, row in ledger.iterrows():
    if (row['role'] == 'seller'):
        print("yes","index")
        ledger.ix[index,'cleared']='True'
        row['cleared']='True'
    else:
        print("No change")
print()
print(ledger)


"""
Explanation: Test DataFrame Appending
End of explanation
"""


hist_book = []

# example of how the god info will look like:
god_info = {
            '3000': {'home': (100, 0, 10), 'industry': (50, 0, 10), 'electricity': (75, 0, 10)},
            '3001': {'home': (90, 0, 10), 'industry': (40, 0, 10), 'electricity': (60, 0, 10)}
            }

df = pd.read_csv('2010cbstestrun.csv', header=0, index_col=0)
df = df.transpose()

# build the god info from the CSV file, overwrite the example
god_info = {'%s' %x:{'elec':(y,0,10),'indu':(z,0,10),'home':(u,0,10)} 
            for x,y,z,u in zip(df.index,df['elec'],df['indu'],df['home'])}

for year in god_info:
    print('####################################')
    # make a supplier and get the asks
    supplier = Seller("Natural Gas")
    supplier.set_quantity(100,0,10)
    
    book = Book()
    book.set_asks([supplier])
    
    # make a buyer and get the bids
    buyerinfo = god_info[year]
    
    buyer_dict = {}
    for name in buyerinfo:
        buyer_dict[name] = Buyer('%s' % name)
    
    for i in buyer_dict:
        buyer_dict[i].set_quantity(*buyerinfo[i])
    book.set_bids([buy for buy in buyer_dict.values()])
    ledger = book.get_ledger()
    
    gas_market = Market()
    gas_market.add_seller(supplier)
    for buy in buyer_dict.values():
        gas_market.add_buyer(buy)
    gas_market.set_book()
    asks = gas_market.get_asks()
    #print(asks)
    
    clearing = gas_market.get_clearing_price()
    gas_market.annotate_ledger(clearing)
    new_ledger = gas_market.get_ledger()
    
    #save current market state
    print(year)
    hist_book.append([year, clearing])


pd.DataFrame.head(new_ledger)
print(hist_book)

"""
Explanation: Example Market
In the following code example we use the buyer and supplier objects to create a market. At the market a single price is announced which causes as many units of goods to be swapped as possible. The buyers and sellers stop trading when it is no longer in their own interest to continue.
End of explanation
"""


# timeit

stopit = time.time()

print('it took us %s seconds to get to this conclusion' % (stopit-startit))

"""
Explanation: Operations Research Formulation
The market can also be formulated as a very simple linear program or linear complementarity problem. It is clearer and easier to implement this market clearing mechanism with agents. One merit of the agent-based approach is that we don't need linear or linearizeable supply and demand function. 
The auctioneer is effectively following a very simple linear program subject to constraints on units sold. The auctioneer is, in the primal model, maximizing the consumer utility received by customers, with respect to the price being paid, subject to a fixed supply curve. On the dual side the auctioneer is minimizing the cost of production for the supplier, with respect to quantity sold, subject to a fixed demand curve. It is the presumed neutrality of the auctioneer which justifies the honest statement of supply and demand. 
An alternative formulation is a linear complementarity problem. Here the presence of an optimal space of trades ensures that there is a Pareto optimal front of possible trades. The perfect opposition of interests in dividing the consumer and producer surplus means that this is a zero sum game. Furthermore the solution to this zero-sum game maximizes societal welfare and is therefore the Hicks optimal solution.
Next Steps
A possible addition of this model would be to have a weekly varying demand of customers, for instance caused by the use of natural gas as a heating agent. This would require the bids and asks to be time varying, and for the market to be run over successive time periods. A second addition would be to create transport costs, or enable intermediate goods to be produced. This would need a more elaborate market operator.  Another possible addition would be to add a profit maximizing broker. This may require adding belief, fictitious play, or message passing. 
The object-orientation of the models will probably need to be further rationalized. Right now the market requires very particular ordering of calls to function correctly.
End of explanation
"""


