# NAIF Usage Examples

Authors: Mikhail Anufriev Giulio Bottazzi , August 31, 2007 0.7 GPL

# Some simple examples

## Example 1. Single trend-following agent

We start with a simple example with a single agent operating in the market. Look at the file test01.cfg distributed together with naif source. You will find the following line:

```x=.5,w=1,f=.5+.1*ret1
```

This line defines a "trend-follower" type of agent: if the price of the asset remains fixed, that is the return is zero (ret1=0), he invest half of his wealth in the risky security. If the return is positive this share increases, if the return is negative the share decreases. Now consider the following command:

```naif -O r -t 40 -D mean=.02 -r .01 < test01.cfg
```

It will print the returns history (-O r) for 40 time steps (-t 40) of a market where the risky asset has constant yield equal to .02 (-D mean=.02) and the riskless asset gives return equal to .01 (-r .01). The market is populated by the agent defined above. Compare the result with the one obtained when a noise component is introduced in the risky yield:

```naif -O r -t 40 -D type=1,mean=.02,stdev=.02 -r .01 < test01.cfg
```

Both time series of the price return are reported below

It is interesting to see what happens in the EMC (Equilibrium Market Curve) plane defined by the price return and the agent's investment share. To draw the trajectory one can use the command:

```naif -O rx -t 40 -R mean=1 -D mean=.02 -r .01 < test01.cfg
```

In this case we additionally specify the initial return (-R mean=1) to visualize fluctuations better, and print return and investment share (-O rx), columnwise. The whole gnuplot code is given by:

```rf=.01
y=.02

set grid
set xlabel "Price Return"
set ylabel "Investment Share"

plot [-.5:.4][0.2:.8]\
.5+.1*x                                                          w l lt 2 lw 3 title "investment function",\
(x-rf)/(x+y-rf)                                                  w l lt 1 lw 5 title "EMC",\
"< ./naif -O rx -t 40 -R mean=1 -D mean=.02 -r .01 < test01.cfg" w lp lt 4 pt 6 ps 1 notitle
```

Here we add the equations for the investment function and for the EMC which depends on the risk-free interest rate (rf=.01), yield (y=.02) and return (x). We get the following plot as a result.

As you can see, the system converges to a stable fixed point, which is the intersection of the investment function and the EMC. This is expected.

## Example 2. Two fundamentalists generate multiple equilibria

Consider now the case of a couple of agents with constant investment shares. They are defined in test02_1.cfg:

```x=.5,w=1,f=0.5
x=.8,w=.7,f=-0.5
```

Market with two constant investment functions, f=0.5 and f=-0.5, has two stable equilibria. In one of them there is no equity premium, so that price return r=-y + r_f, where y is the average yield and r_f is the riskless return. Both agents are surviving in this equilibrium. In the second equilibrium only the first agent survives and price return is determined through the EMC. We set the average yield to .02 and riskless return to .01. The following command generates the return trajectory over 200 periods in this case:

```naif -O r -t 200 -R mean=1 -D mean=.02 -r .01 < test02_1.cfg
```

The trajectory converges to the first, no-equity-premium equilibrium with return -.01.

Now we change initial conditions, in this case the wealth distribution among two agents and use the same command as above but with another configuration file:

```naif -O r -t 200 -R mean=1 -D mean=.02 -r .01 < test02_2.cfg
```

In the file test02_2.cfg the agents are defined as follows:

```x=.5,w=1,f=0.5
x=.8,w=.1,f=-0.5
```

so that the first agent has even higher relative initial wealth share. It turns out, that in this case the trajectory converges to the equilibrium with risk premium where the first agent survives. Both trajectories are shown below as thick curves.

In addition, in the same plot we show noisy versions of both trajectories generated by:

```naif -O r -t 200 -R mean=1 -D type=1,mean=.02,stdev=0.01 -r .01 < test02_1.cfg
naif -O r -t 200 -R mean=1 -D type=1,mean=.02,stdev=0.01 -r .01 < test02_2.cfg
```

It is interesting that noisy trajectories represent mirror images of each other with respect to the line r_f = .01. The reason is that in the case of the constant investment functions, the noise of the return is completely generated by the noise on the yield, and proportional to the term <x^2>/<x(1-x)>. But this term is equal to -1 in the first equilibrium and +1 in the second.

The same situation with multiple equilibria can be illustrated in the phase diagram with the EMC. In this case on the vertical axes we will print the average investment share weighted by the agents' relative wealths. In the first, no-equity-premium equilibrium, the average choice must be zero, while in the second equilibrium the average choice is equal to the choice of the first, surviving agent.

It is important to keep in mind that the model gives stationary trajectories in terms of returns. Of course, the translation of these variables into the behavior of level variables (e.g. price) is straight-forward. In naif program one can print the evolution of different variables through the option -O. For example the lines:

```naif -O p -t 200 -R mean=1 -D type=1,mean=.02,stdev=0.01 -r .01 < test02_1.cfg
naif -O w -t 200 -R mean=1 -D type=1,mean=.02,stdev=0.01 -r .01 < test02_1.cfg
```

print in the standard output the evolution of price and the evolution of total wealth (i.e. cash plus risky assets multiplied by price), respectively. The lines:

```naif -O W -t 200 -R mean=1 -D type=1,mean=.02,stdev=0.01 -r .01 < test02_1.cfg
naif -O A -t 200 -R mean=1 -D type=1,mean=.02,stdev=0.01 -r .01 < test02_1.cfg
naif -O B -t 200 -R mean=1 -D type=1,mean=.02,stdev=0.01 -r .01 < test02_1.cfg
```

leads to the multiple columns output. It prints, respectively, the wealth share of different agents, the number of shares of the risky asset, and the amount of the risk-less asset (cash) belonging to every agent. For our example we get the following plots for different equilibria.

In the no-equity-premium the price converges to 0 due to the negative return, but the total wealth is growing with the risk-free rate.

Initially the first agent has larger wealth, but in equilibrium their wealth should be distributed in a way to guarantee zero average choice. Since their investment shares are 0.5 and -0.5, they have to have the same wealth shares. During the transition, in relative terms the first agent loses money by investing half of his wealth into unprofitable risky asset. Instead, the second agent gains the wealth, keeping negative (short) position in the risky asset.

Since the total wealth of every agent is increasing, both of them change the absolute level of investment into the risky asset. The first agent borrows more and more shares from the second. The total sum of the possessions is always equal to 1, which is the (normalized) number of the risky asset's shares available in the market.

Generally, the amount of the riskless asset is growing when agents get the risk-free interest and the dividend per share of the riskless asset. In this case, the second agent has to pay the dividends to the first one, but with larger flow from the risk-free investment she is actually getting more money.

### Equilibrium with one survivor

In this equilibrium the return is positive, so that the price is growing. Total wealth is growing with the same rate.

The first agent initially has larger wealth share and is able to get all the wealth.

The second agent is always short in the risky asset, but doing that she loses her wealth, and can afford lending less and less shares of the risky asset.

The second agent eventually loses her money.

## Example 3. Constant yield vs. growing dividend

In the first example, the trend-follower reacted only on the return value. Now we consider the agent who follows the trend of the TOTAL return, i.e. both of price return and dividend yield. In addition we assume that agent reacts positively on the high value of the last (i.e. just-realized) dividend yield. Such agent is defined in test03.cfg as follows:

```x=.1,w=1,f=.5+.1*(ret1+yld1)+yld0
```

The following two commands print the first 50 returns in such a market for cases with and without noise in the yield. Notice that apart from the price return, two initial yields are necessary for initialization of the simulation. They are generated by command "-Y mean=.02"

```naif -O r -t 50 -D type=1,mean=.02,stdev=0     -Y mean=.02 -r .01 < test03.cfg
naif -O r -t 50 -D type=1,mean=.02,stdev=0.001 -Y mean=.02 -r .01 < test03.cfg
```

We also generate the time series of the dividend yield in the same market by means of the following two commands:

```naif -O y -t 50 -D type=1,mean=.02,stdev=0     -Y mean=.02 -r .01 < test03.cfg
naif -O y -t 50 -D type=1,mean=.02,stdev=0.001 -Y mean=.02 -r .01 < test03.cfg
```

The generated trajectories are reported below

Notice that the picture is not qualitatively different from our first example. This is reasonable, since the assumption of the constant mean of the dividend yield leads to the (almost) the same investment strategy in equilibrium. (Since the investment functions has changed, the level of equilibrium return is different, of course.)

Now we modify the example and consider the same agent operating in the market where dividend is growing with constant rate. The new time series are generated by commands:

```naif -O r -t 2000 -D type=3,mean=.02,stdev=0    -Y mean=.02 -r .01 < test03.cfg
naif -O r -t 2000 -D type=3,mean=.02,stdev=0.02 -Y mean=.02 -r .01 < test03.cfg
naif -O y -t 2000 -D type=3,mean=.02,stdev=0    -Y mean=.02 -r .01 < test03.cfg
naif -O y -t 2000 -D type=3,mean=.02,stdev=0.02 -Y mean=.02 -r .01 < test03.cfg
```

We show resulting trajectories below

For this dividend structure it is known that when average growth rate of the dividend is larger than the risk-free interest rate, in the equilibrium the price return is equal to the average growth rate of the dividend. Instead, the yield is defined through the plot with the corresponding EMC. We show it below

In this case the convergence is monotonic, so that the points in the phase space moves very close to the investment function. The whole gnuplot code is given by:

```g=.02
rf=.01

plot [0.005:0.015]\
0.5+0.1*(g+x)+x        w l lt 2 lw 3 title "investment function",\
(g-rf)/(x+g-rf)        w l lt 1 lw 5 title "EMC",\
"< ./naif -O yx -t 300 -D type=3,mean=.02,stdev=0 -Y mean=.02 -r .01 < test03.cfg" w lp lt 4 pt 6 lw 1 title "yield, no noise, first 300 steps",\
"< ./naif -O yx -T 600 -t 50 -D type=3,mean=.02,stdev=0 -Y mean=.02 -r .01 < test03.cfg" w lp lt 4 pt 6 ps 2 lw 1 title "yield, no noise, after 600 steps"
```

# More advanced examples

## Example 4. Mean-variance optimizer with truncated investment function

In all examples so far, the agents could have any investment share, positive or negative. Now we consider the situation typical for the so-called Levy-Levy-Solomon (LLS) microscopic simulation model. The agents there predict the next total return as average of L past returns and, furthermore, are not allowed to have short positions. The last requirement confines the investment functions between, say, 0.01 and 0.99. For example, an agent with memory span L=5 is defined in test04_1.cfg as follows:

```x=.1,w=1,f=.5*(cwr1_5+cwy1_5),l=0.01,u=0.99
```

One can compare the price series generated in the market by such an agent, with the ones generated by similar agents having memory spans L=10 and L=15. They are defined in test04_2.cfg and test04_3.cfg, respectivelys:

```x=.1,w=1,f=.5*(cwr1_10+cwy1_10),l=0.01,u=0.99
```

and:

```x=.1,w=1,f=.5*(cwr1_15+cwy1_15),l=0.01,u=0.99
```

The commands:

```naif -O p -D type=3,mean=0.04,stdev=0 -Y mean=.02 -T 0 -t 400 -r 0 < test04_1.cfg
naif -O p -D type=3,mean=0.04,stdev=0 -Y mean=.02 -T 0 -t 400 -r 0 < test04_2.cfg
naif -O p -D type=3,mean=0.04,stdev=0 -Y mean=.02 -T 0 -t 400 -r 0 < test04_3.cfg
```

generate the following PRICE trajectories

To explain this dynamics, notice that the risk free interest rate was set to 0, which is less than the averare growth rate of the dividend (0.04). Therefore the price return in the unique stable equilibrium must be equal to 0.04, while the dividend yield is defined through the EMC. Apparently, only for the agent with long memory L=15, this equilibrium is stable.

### Long memory

Let us then, first, analyze this case: L=15. On the phase space of the EMC the dynamics looks as in the next diagram, generated with code:

```set xlabel "Dividend Yield"
set ylabel "Investment Share"
g=0.04
rf=0

plot [:][0:0.4]\
(g-rf)/(x+g-rf)        w l lt 1 lw 5 title "  EMC",\
0.5*(g+x)              w l lt 2 lw 3 title "  investment function",\
"< ./naif -O yx -T 150 -t 30 -D type=3,mean=.04,stdev=0 -r 0 < test04_3.cfg" w lp lt 4 pt 6 ps 1 lw 1 title "  30 steps after 150 transitory",\
"< ./naif -O yx -T 180 -t 30 -D type=3,mean=.04,stdev=0 -r 0 < test04_3.cfg" w lp lt 4 pt 6 ps 2 lw 1 title "  next 30 steps"
```

The convergence to the stable fixed point can be also seen on the time series:

The last plot is generated with the multiplot command in the gnuplot:

```reset
set key horizontal left top
set grid y

set size 1,1

set multiplot

set size 1,0.25
set origin 0.0,0.0

set bmargin 2
set tmargin 0.5
set lmargin 5
set rmargin 2

set ylabel "Price"
set logscale y
plot [:]\
"< ./naif -O p -T 100 -t 200 -D type=3,mean=.04,stdev=0 -Y mean=.02 -r 0 < test04_3.cfg" w l lt 1 lw 2 notitle
unset logscale y

set bmargin 0.5
set format x ""
set xlabel ""
set origin 0.0,0.25
set ylabel "Return" offset -1
plot [:]\
"< ./naif -O r -T 100 -t 200 -D type=3,mean=.04,stdev=0 -Y mean=.02 -r 0 < test04_3.cfg" w l lt 2 lw 2 notitle

set origin 0.0,0.5
set ylabel "Yield" offset -1
plot [:]\
"< ./naif -O y -T 100 -t 200 -D type=3,mean=.04,stdev=0 -Y mean=.02 -r 0 < test04_3.cfg" w l lt 3 lw 2 notitle

set origin 0.0,0.75
set ylabel "Share" offset 1
plot [:]\
"< ./naif -O x -T 100 -t 200 -D type=3,mean=.04,stdev=0 -Y mean=.02 -r 0 < test04_3.cfg" w l lt 4 lw 2 notitle

unset multiplot
```

Let us have a closer look on the typical quasi-cyclical phase of the transitory pattern. Take a zoomed version of the previous plot between time steps 20 and 46.

In the beginning the agent invests only 25% of his wealth to the risky asset. This is quite low quantity, so that the price return is low. Furthermore, it is negative, so that the price falls down. The falling price contributes to the growing yield, but this positive contribution to the agent's wealth is not enough to overcome the losses due to the price fall. The total return decreases and the investment function dictates to the agent to invest even less.

But the investment share is bounded from below. When the minimum level 0.01 is reached (at period 5 on the graph), the price is on its lowest but the dividend is still growing. Therefore, the dividend yield will be extremely high next period. High yield has two important effects. First, it contributes to the agents' wealth and, through the demand effect, brings return back to the positive level. Second, it also changed the agent's investment behavior.

Now the boom period starts. The investment share and prices are growing, the return is positive, but the dividend yield falls down. Nevertheless, the economy time series looks stationary and it seems that nothing can stop the boom. But over another 15 periods the agent suddenly becomes less optimistic in his investments. Why does it happen? Because the agent forgot the periods 4-8, which were characterized by very high yield and return. The investment share starts to fall and the cycle repeats it again.

As we have seen, in this example, the dynamics come to the rest point. High memory span implies that the rare periods of high return changes get small weight in the agents' memory. This effect, together with relatively flatness of the investment function, explains the stability of dynamics.

### Short memory

Consider now the case with short memory span, L=5. The dynamics is unstable in this case, and the typical cycle looks as follows.

The qualitative story is similar to the one previously told. Periods 1-6 are related to the boom. The investment share is on its highest level, therefore the price is high, therefore the dividend yield is low. At some point the boom comes to the end. We can see, that as in the previous example, the reason is that some high values of return and yield were forgotten by the agent.

In contrast with the previous example, the change is drammatic now: the agent immediately switches to the lowest possible investment share. The price falls down and the next period yield increases. This increase in the dividend yield pushes us the investment share and, afterwards, the prices. After two periods the agent again invests the maximum, the return jumps up and then immediately falls down, reacting, respectively, on the high increase of the investment share and the stabilization of it on the 0.99 level.

Now the time of relative stability starts. The agent, however, still remembers a period of high total return (when the yield was high), two other periods of huge return (the yield was low already, but prices grew very fast), and also one period of huge crash. One after another, these periods leave the agent's memory, and when only the last period remains, the investment share falls down. The story repeats again.

### Moderate memory

The moderate memory case, L=10, is somewhere in between the previous two, as we can see below. Sometimes the yield generated by the low prices is high enough to trigger very strong (maximum) investment behavior, but sometimes it is not and the investment shares grows to the moderate level.

It is important to keep in mind that all the simulations we showed so far were competely deterministic. Some of the qualitative features of the system became clear. We can see that the crashes happen periodically and that the length of the period is related to the memory span of the agent. However, the seemingly unpredictable sizes of the booms and crashes on the last plot suggest that the system is chaotic or close to being chaotic.

We also observed some asymmetry in the time series, in the sense that the agents typically spend more time in the regime of the large investmet shares with low price returns. This is puzzling, since in the original contribution of Levy and Levy (1994), for example, one did not observe such an asymmetry. Compare also the last simulations with the same time series in the first few periods.

It seems that the symmetric situation (with equally long bear and bull market regimes) is typical only for transitory period, during which the price did not yet developed its trend. When the price starts to grow, its return becomes typically positive which contributes to the positive "bias" of the agent in the investment behavior.

### Co-existence of different attractors

The simulations so-far suggest that the fixed point is unstable for the agent with moderate memory, L=10. This is not the case, however. It turns out that the point is actually stable, but it co-exists with the stable quasi-cycle which we observed so far. Consider the following commands:

```naif < test04_2.cfg -O p -D type=3,mean=0.04,stdev=0 -Y mean=0.02 -T 0 -t 400 -r 0
naif < test04_2.cfg -O p -D type=3,mean=0.04,stdev=0 -Y mean=0.12 -T 0 -t 400 -r 0
```

The only difference is in the initial return time series submitted to the program. In the first case, it consists of 10 returns equal to 0.02, while in the second case it consists of 10 returns equal to 0.12. The resulting time series are quite different, however.

### Role of noise

The previous finding stresses also the role of noise, which can switch the system from one attractor to another. Let us simulate the same three time series as in the first figure of this Section, but now assume that the dividend grows with a random rate. The following commands have been used:

```naif < test04_1.cfg -O p -D type=3,mean=0.04,stdev=0.05 -Y mean=.02 -T 0 -t 400 -r 0
naif < test04_2.cfg -O p -D type=3,mean=0.04,stdev=0.05 -Y mean=.02 -T 0 -t 400 -r 0
naif < test04_3.cfg -O p -D type=3,mean=0.04,stdev=0.05 -Y mean=.02 -T 0 -t 400 -r 0
```

and the resulting dynamics are shown below.

The time series with moderate memory L=10 is now stable (even if it is volatile due to noise added to the dividend growth rate).

## Example 5. Two mean-variance optimizers with truncated investment functions

In our previous example the agent with memory span L=15 generated stable dynamics. Let us suppose that another agent enters such a market. She has the same memory span but smaller risk aversion. This situation is described in test05_1.cfg as:

```x=.1,w=1,f=.5*(cwr1_15+cwy1_15),l=0.01,u=0.99
x=.1,w=1,f=3*(cwr1_15+cwy1_15),l=0.01,u=0.99
```

The situation in the market can be illustrated by means of the EMC as follows.

The lower equilibrium (generated by the 1st agent) is now unstable, but the new equilibrium (generated by the 2nd agent) is not necessary stable. It suggests that the invasion of the market should be successful, i.e. the second agent (with smaller risk aversion) will be able to survive in the long run. Whether she will dominate the market or not will depend on the stability of her, new equilibrium.

It turns out that her memory span, L_2=15, is too small to generate stable equilibrium. As a comparison, let us consider the following configurations (test05_2.cfg, test05_3.cfg and test05_4.cfg) where this agent has memory spans L=20:

```x=.1,w=1,f=.5*(cwr1_15+cwy1_15),l=0.01,u=0.99
x=.1,w=1,f=3*(cwr1_20+cwy1_20),l=0.01,u=0.99
```

L=30:

```x=.1,w=1,f=.5*(cwr1_15+cwy1_15),l=0.01,u=0.99
x=.1,w=1,f=3*(cwr1_30+cwy1_30),l=0.01,u=0.99
```

and L=40:

```x=.1,w=1,f=.5*(cwr1_15+cwy1_15),l=0.01,u=0.99
x=.1,w=1,f=3*(cwr1_40+cwy1_40),l=0.01,u=0.99
```

With commands:

```naif -O p -D type=3,mean=0.04,stdev=0.05 -T 0 -t 500 -r 0 < test05_1.cfg
naif -O p -D type=3,mean=0.04,stdev=0.05 -T 0 -t 500 -r 0 < test05_2.cfg
naif -O p -D type=3,mean=0.04,stdev=0.05 -T 0 -t 500 -r 0 < test05_3.cfg
naif -O p -D type=3,mean=0.04,stdev=0.05 -T 0 -t 500 -r 0 < test05_4.cfg
```

one obtaines the following time series

When the second agent has the memory span equal to 15 or 20, the dynamics is unstable and investment shares switch between maximum and minimum levels, leading to large price fluctuations. When her memory span is equal to 30, the dynamics (as we confirm below) slowly converges to the stable fixed point. When the memory span is 40, the stable fixed point is reached already after 200 time steps.

To see the evolution of the wealth shares in all the four cases, use the commands:

```naif -O X -D type=3,mean=0.04,stdev=0.05 -T 0 -t 500 -r 0 < test05_1.cfg
naif -O X -D type=3,mean=0.04,stdev=0.05 -T 0 -t 500 -r 0 < test05_2.cfg
naif -O X -D type=3,mean=0.04,stdev=0.05 -T 0 -t 500 -r 0 < test05_3.cfg
naif -O X -D type=3,mean=0.04,stdev=0.05 -T 0 -t 500 -r 0 < test05_4.cfg
```

The following plot is obtained from the SECOND column of the output. It shows, therefore, the wealth share of the agent with smaller risk aversion.

In those cases, when the equilibrium is unstable both agents co-exist in the market in the long-run. Instead, for L_2=30 and L_2=40, the second agent manages to wipe the first agent out of the market.

Finally, we show the time series for investment share, dividend yield, return and price after 1000 transitory steps for all four simulations. The case of L_2=30 and L_2=40 coincide.

## Example 7. Dynamics close to instability

Numerical simulations of NAIF program help to understand better the nature of bifurcations leading to instability of the system.

### Losing stability through the Neimark-Sacker bifurcation with increasing investment function

The most common way of losing stability is through the Neimark-Sacker bifurcation (when two complex multipliers cross the unit circle). In test07_1.cfg we define the agent as:

```x=0.05,w=1,f=0.05+0.0474*ret1
```

Consider the case of constant yield (equal to 0.02) with riskfree interest rate 0. Under these economic conditions, the investment function above leads to the equilibrium return 0.001054. This point is stable, but it is very close to the stability border. Indeed, the two complex conjugated multipliers have modulus 0.99847. We also consider specification in test07_2.cfg:

```x=0.05,w=1,f=0.05+0.0475*ret1
```

which also leads to the stable point with modulus of roots 0.99953. (The small change of investment function leads also to small shift in the fixed point.) Finally, in test07_3.cfg we define:

```x=0.05,w=1,f=0.05+0.0476*ret1
```

This investment function leads to unstable equilibrium with modulus of multipliers equal to 1.00058.

In order to guarantee that initial point belongs to the basin of attractor, we carefully specify initial conditions both in the config file (x=0.05) and in the command line (-R mean=0.001) using the command:

```naif -O r -T 10000 -t 100 -D mean=.02 -R mean=0.001 -r 0 < test07_2.cfg
```

The next plot shows how the dynamics in the first two (stable) cases look like after a long transitory period.

In the unstable case the oscillating dynamics is diverging and never settles down to the periodic or quasi-periodic attractor:

It suggests that in this case the NS bifurcation is subcritical (i.e. before bifrcation the unstable quasi-periodic solution coexists with stable fixed point)

Similar scenario can be observed in the case when agent has the same investment function, but consideres the average of last two observations. It leads to the stabilization of the same fixed point (for given slope), but for larger slopes the system again undergoes subcritical Neimark-Sacker bifurcation. The next two plots use files test07_4.cfg:

```x=0.05,w=1,f=0.05+0.067*cwr1_2
```

and test07_5.cfg:

```x=0.05,w=1,f=0.05+0.0675*cwr1_2
```

### Losing stability through the Neimark-Sacker bifurcation with decreasing investment function

Interesting example of NS bifurcation happens when agent's investment function is decreasing. If the memory span of such agent is odd, say 1, then the flip bifrucation takes place. (This situation we consider in the next Section.) But when the memory span is even, as 2 or 4, then the typical bifurcation is again Neimark-Sacker. In file test07_6.cfg we consider:

```x=0.4932,w=1,f=0.5-0.349*cwr1_2
```

and compare it with agent in test07_7.cfg:

```x=0.4932,w=1,f=0.5-0.35*cwr1_2
```

In both cases agents have decreasing function of average of past 2 returns. In the former case two complex multipliers have modulus equal to 0.999564, while in the latter case, the modulus are 1.00071. Therefore, commands:

```naif -O r -T 10000 -t 50 -D mean=.02 -R mean=0.01946 -r 0 < test07_6.cfg
naif -O r -T 10000 -t 50 -D mean=.02 -R mean=0.01946 -r 0 < test07_7.cfg
```

should generate stable and unstable trajectories, respectively. The next plot shows the result

Now the system gets to the quiasi-periodic trajectory immediately after the Neimark-Sacker bifurcation. Thus, in this case the bifurcation seems to be supercritical.

### Losing stability through the flip bifurcation with decreasing investment function

Occasionally the system loses its stability through the flip bifurcation. Analysis shows that it can happen, for example, when agent with decreasing investment function and odd memory span crosses the EMC too steeply. Consider two configuration files test07_8.cfg and test07_9.cfg given as below:

```x=0.497,w=1,f=0.5-0.123*ret1
```

and:

```x=0.497,w=1,f=0.5-0.124*ret1
```

Numerical computations give multipliers -0.995829, 0.494072 in the former case and multipliers -1.00124, 0.4954 in the latter. Obviously, the fixed point undergoes the flip bifurcation.

Indeed, the plot shows that after stability the dynamics start to diverge being close to 2 cycle. Moreover, the oscillating trajectory is continuing to diverge, suggesting that the flip bifurcation is subcritical.

## Example 8. Non-trivial Transitions between Different Equilibria

Even when the attractor of the dynamics is clear, the transitory dynamics can be non-trivial and rather long. Consider the situation described in test08_1.cfg as:

```x=0.1,w=.1,f=0.1
x=-0.1,w=-1,f=-0.1
```

This example is analogous to Example 2 we considered above. There are three equilibria in the market, stable no-equity-premium equilibrium with two survivors, stable equilibrium where only first agent survives, and unstable equilibrium where only the second agent survives. We take 0 risk free interest rate and with the help of command:

```naif -O r -t 2000 -D mean=.02 -r 0 < test08_1.cfg
```

observe long transitory from the unstable equilibrium with second survivor to the stable equilibrium with first survivor. In all the following plots the total length of simulation is 2000 periods.

The strange feature of the transitory dynamics is that while the price return smoothly evolves from the negative level in the unstable equilibrium to the positive level in the stable one, the average investment share has a point of discontinuity.

To understand this transition, notice that the initialization of agents in test08_1.cfg gives the second agent negative initial wealth (which is interpreted as debt in this case) and also negative investment share (which implies normal, positive position in the risky asset). Thus, overall she starts with positive number of shares of the risky asset and with big negative amount of cash. Furthermore, the total initial wealth equal to sum of 0.1 and -1 is also negative.

The initial conditions then imply that price starts to fall down, but that the wealth grows due to the positive dividend yield. At some point wealth reaches level 0. At this moment we observe discontinuity: positive wealth of the first agent immediately translates to the positive wealth share, while it was always negative before. The opposite happens with the wealth of the second agent. Then, the wealth continues to grow with asymptotical growth rate equal to the equilibrium rate of return.

The price return was negative in the beginning, so the price falled. Instead, the wealth, which is initially negative, grew because of the high dividend yield. When wealth undergoes transition from positive to negative, the price return also becomes positive and price starts to grow.

Wealth of the first agent is always positive and growing. Until the total wealth is negative, it translates to the negative decreasing wealth share. Then it becomes positive and it reaches 1 when the second agent disappears from the market.

First agent has very good timing. His share of the risky asset grows as the return for the asset grows.

Second agent starts with negative cash. She improves her position by selling short the risky asset, which is, however, better than the riskless in average.

# Generating many similar agents

Using the syntax : in the configuration file it is possible to generate multiple copy of the same agent. Sometimes, however, it is useful to generate many agents who are variation with respect a single baseline model. This can be easily achieved using the ability of the Unix zsh to manipulate arithmetic expressions. For instance consider the agent description:

```x=.5,w=1,f=.5+.1*ret1
```

in test01.cgf. One can generate many similar agents with the following simple script:

```setopt INTERACTIVE_COMMENTS

for i in {1..100}; do
# generate uniform r.v. in [0,1)
eps=\$(( RANDOM/32767.0 ));
# scale the r.v.
eps=\$(( .1+.01*eps));
# generate the investment function
echo "x=.1,w=1,f=.5+\$eps*ret1";
done > file.cfg
```

then file.cfg contains the definition of 100 slightly different traders. Notice that this script does not work in bash, since this shell only perform integer operations.

** This file is produced with a command
rst2html.py --stylesheet=naif.css README.examples naif_examples.html