29 Eylül 2012 Cumartesi

Supply, Demand and Market Microstructure

To contact us Click HERE
Today we are going to make an agent-based simulation modelof Supply and Demand. Pretend we have a room full ofpeople. Some of them have apples, some do not. Some are hungry, someare not. All have money in their pockets with which they can buy andsell apples, if they so choose. What determines the price of apples?

Much of conventional economic theory rests on the assumption ofperfectly competitive markets populated by perfectly rationalparticipants. If we let the people in the room interact by anopen-outcry auction, theory suggests they will listen to the bid andask prices, figure out where the supply and demand curves cross, andtrade the equilibrium quantity of apples at the equilibriumprice. This assumption greatly simplifies the mathematics, so much sothat it underlies almost all economic theory. But is this model ofhuman behavior realistic? Let's try some experiments!

Let me describe the background a little more clearly. We areinterested here in what academics call market microstructure:the magic of how prices actually get established on the scale ofindividual transactions. The thing being traded could be a piece offruit, a gadget like an ipod, an hour of professional services, or 100shares of Apple Computer on the stock market. The key point is thatnot everyone wants these things equally badly: a hungry person wantsan apple, but a person who just ate might rather have cash, so theycan buy a gadget instead. Moreover, not everyone has the same startingposition (or endowment): some people start the game holding anapple, while others do not.

As a result of this lack of symmetry, some people may wish tomake trades with other people. In our simple example, you can trademoney for apples and vice versa, but in a general equilibriummodel you can trade in a whole variety of different goods(e.g. oranges, lemons) simultaneously. In our simple example, everyoneis in the same place at the same time, but again, in a generalequilibrium model you can even have different locations and differenttime periods; you can interpret differences in price over time asinterest rates, and develop all kinds of deep insights into the realeconomy.

When economists first started trying to analyze markets, roughly acentury ago, there were no computers to do simulations, so they neededto make simplifying assumptions to reduce the problem to simplealgebra. As with theorems in math, there are a lot of technicaldetails you can include in the assumptions, and mathematicaleconomists have studied how much you need to assume in order to provethat people will act a certain way. For example,the Arrow- Debreu - McKenzie model, which is at the heart of generalequilibrium models in economics, requires certain technicalassumptions (e.g. convexity) in order to prove the existence of aunique equilibrium.

For today, though, let's keep it simple. Imagine that each person hasa secret reservation price at which they are indifferentbetween having an apple and having cash. For a hungry person, thisreservation price is higher than for someone who just ate. For astarving person, for whom this apple is their last hope of not dying,the price is essentially infinite: they will never give away theirapple if they start with one, and they will give away all of theirstarting cash to obtain one if they do not have one. For someone whois not hungry at all and who hates the taste of apples, the price isessentially zero: they will sell their original apple, if they haveone, for any positive price, and will never spend any of their moneybuying one.

Call the people who start the game with an apple sellers, andthe others buyers. The names reflect what they could do,but not necessarily what they want to do, nor even whatthey will do.

Let's walk through a version of the conventional theory. Imagine weline up all the sellers in increasing order of reservationprice. Also, line up the buyers in decreasing order ofreservation price. Now we walk down the line, exchanging apples,until the seller wants more than the corresponding buyer willoffer. For example, suppose the reservation prices look like this:

BuyersSellers
10 0.2
9 0.5
8 1.5
7 2.5
6 4.5
5 8.5
4 16
3
2
1

Nothing requires the number of buyers and sellers to match exactly.Here there are ten players who start off with an apple (potentialsellers), and seven who do not (potential buyers).

The first seller has a reservation price of 0.2 dollars, andthe first buyer has a reservation price of 10 dollars. Clearly theywould both be willing to make a trade, at any price between twenty centsand ten dollars.

The second pair (9, 0.5) are also willing to trade, as are the (8,1.5) pair,the (7,2.5) pair and the (6,4.5) pair. But they are a lot more specificabout what price is acceptable: in order for all of these pairs totrade, the price of apples must be between 4.50 and 6 dollars.

The remaining sellers want $8.50 or more, while the remaining buyers want to pay $5or less, so no further pairs will trade, regardless of whatprice we pick.

You have probably seen a diagram of intersecting supply anddemand curves as a way of visualizing the equilibrium. Here is aversion showing the data in the table above, where the horizontal axisrepresents people and the vertical axis their reservation price. Thered dots are sellers, the blue dots are buyers, and the thin graylines show the equilibrium price and volume. The equilibrium price isanywhere between 4.5 and 6 dollars, but if we had lots more players,each with randomly chosen reservation prices, the dots would mergeinto a continuous curve with a unique equilibrium price.

Notice that the equilibrium price is determined by where the linescross, not by any sort of "average" reservation price: changing thelast seller's reservation price from 16 to 32 would have no impact onthe equilibrium price or quantity. Economists refer to this phenomenonusing the word marginal: not in the usual English senses of"at the side of" or "unimportant", but rather tomean "incrementally" or "at the tipping point". The "marginalplayer" is the one in the center of the diagram, where thelines cross, who is essentially indifferent to buying or selling atthe equilibrium price.

Why does the theory predict this particular outcome? Theconventional argument for the emergence of the equilibrium price underperfect competition goes like this. Should someone in the market shoutout "the price is 8 dollars", more sellers would be interested, butfewer buyers. Presumably some of the sellers (those with reservationprices less than 8) would lower their price in order to win back thebuyers. Similarly, should someone claim "the price is 2 dollars",additional buyers would come to the table, but sellers would walkaway. This would encourage those buyers with high reservation pricesto raise their offers. In both cases, prices far from equilibriumwould trigger supply-demand imbalances that would nudge the playersback toward the equilibrium price.

In many ways, this is a very convincing story. However, it isa bit abstract. Economists use it to model all kinds of real worldmarkets; yet not all markets resemble an open-outcry auction. When yougo to a supermarket in the United States to buy groceries, postedprices are not subject to negotiation (although this is not the casewith automobiles, nor is it always true in othercountries). Supermarkets do compete with each other, and do advertiseprices in local newspapers, and shoppers can (if they have a car andenough spare time) drive to multiple stores to compareprices. Shoppers' reservation prices do vary - some people clipcoupons to ensure the best possible price, while others are relativelyprice insensitive. However, prices fluctuate a lot from day to day andstore to store. Prices in other markets can be even wilder: just thinkof the huge gyrations in the stock market in the last few weeks.

It is hard to imagine that this is all based on purelyrational calculations or to see it as a stable equilibrium situation.In recent years, many economists have begun looking at alternativetheories (e.g. behavioral economics) that attempt tobetter describe how real people behave.

This brings us to today's question: how well does the conventionalmodel fit reality? Or, to be more precise, since we will be doingcomputer simulations rather than experiments with live humans, we wantto know:
  • Can we design simple agents that achieve the equilibrium theory predicts?
  • Can we design plausible agents that fail to achieve the theoretical equilibrium?

In other words, for today, we are not trying todevelop prescriptive rules for how agents, orpeople, should behave. Instead, we are interested in studyingvarious descriptive theories: if people (represented bysimulated agents) behave a certain way, what happens?

We could undoubtedly construct complicated models that incorporate agreat many features of real market places. However, thequestion today is whether we can construct extremely simplemodels that capture enough realism to make the results interesting;the hope is that the simplicity of the models will help us ininterpreting why they behave the way they do.

Both questions (arguing for and against the conventional theory) areinteresting, and both can be answered affirmatively. Let's see what we can find out by experimenting withsimulations.

As before, we willuse Python and PyGame to implement theagent-based model and visualize the results. These are free,high-quality, open-source, cross-platform software packages that youcan grab from the web and install in just a couple of minutes. SeeAnEvolving Ecosystem Game for details on how to download them. Oncethese are installed, go to the Start Menu, under Programs look forPython 3.2, and within that, click on IDLE. Again, the previous posthas more details on how to get started using Python. I also highlyrecommend reading a tutorial suchas Introductionto Computer Science Using Python and PyGame to help you getstarted with these powerful tools.

Let's start with a (hopefully) plausible model thatillustrates how the theory can fail if its assumptions are not met. Wewill leave it as a challenge to readers to try constructing a "Simple"model that does match the theory.

We need to decide how to model the agents, how they should interact, and howto visualize the progress of the simulation.

The model: Each agent will have a starting endowment of zero orone apples, and a secret reservation price. Each time step we choose arandom agent A who will interact with a second random agent B. If Ahas an apple, A will offer B an ask price, i.e. a price atwhich A would be willing to sell. If A does not have an apple, A willoffer B a bid price, i.e. a price at which A would be willingto buy. A chooses the price randomly, either above her reservationprice (if she is selling) or below (if she is buying). Either way, ifB can and is willing to trade at the specified price, they do so. The gameends after 500 such interactions.

Here is the code. We define an Agent class that keeps track of thenumber of apples the agent owns, as well as their reservation price.We create our agents to match the table of Buyers and Sellersshown above, so we can compare to the theoretical outcome describedearlier.

import pygameimport randomrandom.seed(123456)class Agent:    def interactWith(self, other):        if self.apple == 0 and other.apple == 1:             # maybe buy from other            bid = random.uniform(0, self.price)            trade(bid, self, other, bid >= other.price)        elif self.apple == 1 and other.apple == 0:             # maybe sell to other            ask = random.uniform(self.price, maxPrice)            trade(ask, other, self, ask <= other.price)    def __init__(self, initialApples, reservationPrice):        self.apple = initialApples        self.price = reservationPricedef trade(price, buyer, seller, success):    global iter    iter += 1    if success:        line(green, buyer.price, seller.price)        dot(green, price, 7)        buyer.apple += 1        seller.apple -= 1        print("price: ", round(price, 3),               " seller: ", seller.price,               " buyer: ", buyer.price)    else:        dot(gray, price)    dot(blue, buyer.price)    dot(red, seller.price)    pygame.display.flip()def dot(color, price, r=4):    pygame.draw.circle(screen, color, (getX(),getY(price)), r)def line(color, p0, p1):    x = getX()    pygame.draw.line(screen, color, (x,getY(p0)), (x,getY(p1)), 2)def getX():    return round(iter*W/(nIter+1.))def getY(price):    # note (0,0) is TOP left of window    return round(H - H*price/(maxPrice+1.))W = 800; H = 500; nIter = 500; maxPrice = 24# initialize graphics window:pygame.init()screen = pygame.display.set_mode([W, H])pygame.display.set_caption("Supply and Demand")white = [255, 255, 255]; gray = [128, 128, 128]red = [255, 0, 0]; blue = [0, 0, 255]green = [0, 200, 0]; yellow = [255, 255, 0]screen.fill(white)pygame.draw.rect(screen, yellow, (0,getY(6),W,getY(4.5)-getY(6)))pygame.display.flip()# initialize agents:seq = [] # one-dimensional list of Agentsfor p in [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]:    seq.append(Agent(0, p)) # buyersfor p in [0.2, 0.5, 1.5, 2.5, 4.5, 8.5, 16]:    seq.append(Agent(1, p)) # sellers# main loop:iter = 0done = Falseclock = pygame.time.Clock()N = len(seq)while done==False:    if iter <= nIter:        a = seq[random.randint(0,N-1)]        b = seq[random.randint(0,N-1)]        a.interactWith(b)    clock.tick(120)    for event in pygame.event.get():        if event.type == pygame.QUIT:            done = Truepygame.quit()

Only a few lines in this long code listing really matter forour purposes. The first section (the Agent "class") specifies howthey interact with each other, and how to initialize them. The two"for" loops just before the "main" loop create 17 Agents matching thetable of buyers and sellers. Inside the main loop, we randomly selectagents A and B for interaction.

All the rest is just for implementing the graphical visualization. Asthe simulation progresses, we use the PyGame graphics features todisplay what is happening. There are many ways we could try tovisualize the progress; for today, I have decided to plot timeincreasing horizontally, with price increasing vertically. Red dotsshow seller reservation prices, blue dots show buyer reservationprices. Gray dots show suggested transaction prices, which turngreen (and get connected to the corresponding red and blue dots with agreen line) if the offer is accepted. We also print thedetails of successful trades for reference. The horizontal yellow barshows the price range predicted by the theory, namely 4.5 to 6dollars.

Here is a typical run.

price:  0.77  seller:  0.5  buyer:  10price:  1.48  seller:  0.2  buyer:  4price:  7.161  seller:  2.5  buyer:  9price:  2.198  seller:  1.5  buyer:  2.5price:  5.897  seller:  4.5  buyer:  8price:  4.396  seller:  4  buyer:  4.5price:  4.94  seller:  2.5  buyer:  5price:  5.899  seller:  4.5  buyer:  7price:  5.202  seller:  5  buyer:  6

Initially (near the left side) there are buyers (bidding in blue)spread over the whole range below $10. There are also sellers (askingin red) from very low prices all the way up to $16. In some cases,such as the seller whose reservation price is $16, they stay red thewhole game. But other sellers, with low reservation prices, wind upselling early on, after which they become potential buyers. Thus as wemove to the right of the image, several initially red horizontaltrails eventually turn blue once a sale occurs. Similarly,some early buyers with high reservation prices become sellers (bluechanges to red) after an early transaction.

It is even possible for the same agent to be a buyer in onetransaction and a seller in another. I deliberately made all thereservation prices distinct so that we could use them to refer to theagents unambiguously. Looking for the ".5"'s in the list oftransactions, we see that Agent 2.5, Agent 4.5, Agent 4 and Agent 5all play both buyer and seller roles. Their reservation prices aretoward the middle of the pack, so they can pretty easily buy or selldepending on who else they are dealing with.

The final quarter of the graph has no green dots. Bythis point, all of the apples are in the hands of the people with thehighest reservation prices, so nothing further will happen. This isquite remarkable. Indeed, it illustrates why free markets are oftena very effective method for redistributing goods.

Did we match the theory? No. Of the 9 transactions, the firstfour prices are well outside the yellow band. The last 5 do occurwithin (or at least quite close to) the yellow band predicted by thetheory, so we might think we are at least "approaching" equilibrium astime goes on. However, if we try running it again with a differentrandom seed (12345), we get different results, due to different randomdice rolls:

price:  1.52  seller:  1.5  buyer:  8price:  4.639  seller:  2.5  buyer:  7price:  3.045  seller:  0.5  buyer:  4price:  1.88  seller:  0.2  buyer:  10price:  5.557  seller:  4.5  buyer:  6price:  8.998  seller:  4  buyer:  9

This time only 2 of 6 transactions fall within the predicted band, andthe last transaction of all is well outside it. We do see the samebasic pattern of trades moving apples from those who do notwant them much to those who want them very much; by half way into thesimulation, all of the apples are once again in the hands ofthe people with the highest reservation prices (all the red dots areabove all the blue dots).

Why don't all the prices fall inside the yellow band? Doesthis contradict the theory? No. Ken Arrow and the others proved amathematical theorem: that if agents behave in certain ways(perfectly rational perfect competition with convexutilities), then they will indeed reach the equilibrium price.The theory is not wrong; indeed its authors won a Nobel Prize for it.But our simulated agents are neither particularly rational (they donot attempt to look ahead, game the system, or even keep track of pastencounters) nor particularly competitive (they do not negotiate withmore than one opponent at a time, nor do they adjust price in responseto what they learn). The theory is not applicable to our littleexperiment, because our agents do not behave the way the theoryassumes.

This leads me to offer a fun challenge to readers: canyou devise an alternative simulation in which agents do actaccording to the theory, trading the predicted quantity of apples andonly doing so at prices inside the yellow band?

One ground rule: do not actually make the agents line up inorder of their reservation prices, in the manner we used to derive thesupply and demand curves at the beginning of this article. Theirreservation prices are private, not written on their foreheads for allto see, and real market places usually do not have a "supervisor" liningpeople up this way.

The goal is to keep the simulation as simple as possible,adding only the minimal amount of extra complexity needed to get theagents to act "properly". They do not need to actually performcomplicated "rational" calculations in their heads, they just needto act as if they knew what they were doing.

If you like, please do submit suggested solutions (or even justideas for what you would like to try, even if you do not code themyourself). You can enter them directly into the Comments box below, orGoogle-mail them to me (at the address described at the end of theWelcomepost) and I will collect them for a subsequent follow-up article.

I hope you enjoyed this discussion. As usual, please postquestions, comments and other suggestions, or G-mail me directly. Remember you cansign up for email alerts about new posts by entering your address inthe widget on the sidebar. Or follow@ingThruMath on Twitter toget a 'tweet' for each newpost. About the Blog has some additional pointers for newcomers, who mayalso want to look atthe Contents page for a complete list of previous articles. See younext time!

Hiç yorum yok:

Yorum Gönder