Skip to content

mimaowang/SFI-ASM-Mesa

Repository files navigation

SFI-ASM-Mesa

Python 3.10+ Mesa 3.5+ Solara License: MIT

An interactive, browser-based implementation of the Santa Fe Institute Artificial Stock Market (SFI-ASM) built with Mesa 3.x and Solara. It is designed for teaching and exploratory research: a population of heterogeneous agents evolves trading rules through a genetic algorithm and social learning, producing emergent price bubbles and crashes relative to a slowly drifting fundamental value.

Status: educational / research prototype. The model deliberately simplifies several features of the original SFI-ASM (no order book, no explicit wealth accounting, no full GA crossover) so that the core mechanism—endogenous expectation formation and boom-bust dynamics—remains transparent and easy to visualize.

What makes this release useful: double-click starter.exe (Windows) and the interactive dashboard opens in your browser—no command-line knowledge required. The live visualizations make it easy to see how bubbles and crashes emerge from evolving trader rules.

At a glance

What it is A browser-based, interactive reproduction of the classic Santa Fe Institute Artificial Stock Market (SFI-ASM), built with Mesa 3.x and Solara.
Core idea Heterogeneous agents evolve trading rules through a genetic algorithm and social learning, producing emergent price bubbles and crashes.
Why use it Zero-config launch: double-click starter.exe and watch the dynamics in your browser—no command-line experience needed.
Best for Teaching, exploratory research, and getting an intuitive feel for how endogenous expectations create boom–bust cycles.

SFI-ASM-Mesa UI screenshot

What you will see

  • Chartist agents (green/red squares) hold a small set of condition-action forecasting rules of the form “if the last K returns looked like pattern X, predict next-period return Y”. Rules are rewarded when they predict the correct direction and penalized for magnitude errors; high-fitness rules survive, mutate, and spread through imitation.
  • Fundamentalist agents (blue circles) trade against deviations from fundamental value, pushing the price back toward the gray fundamental line.
  • When chartist rules reinforce each other, a directional consensus emerges, the price departs from fundamentals, and a bubble forms. When the deviation becomes large enough or rules switch sign, the bubble deflates.

About this implementation

This repository is a simplified academic reproduction of the Santa Fe Institute Artificial Stock Market. It is intended for teaching, exploration, and as a starting point for further research—not as a faithful replication of every detail in the original model.

  • Core simplifications: no limit-order book, no explicit budget/wealth accounting, no full genetic-algorithm crossover, and a reduced rule grammar.
  • The code prioritizes clarity and visual feedback over matching every published calibration.
  • Results are not guaranteed to be quantitatively identical to the original SFI-ASM papers.

If you need a full replication, see the references below (especially Ehrentreich, 2007) and the original source code archives.

Features

  • Modern, responsive Solara web UI with bilingual support (English / 中文).
  • Real-time spatial visualization of agents plus five synchronized Matplotlib charts:
    • Price vs. fundamental value
    • Bubble index
    • Bull/bear rule fitness
    • Bull ratio
    • Chartist ratio
  • Interactive parameter panel: change market composition, learning speed, price impact, noise, and fragility on the fly.
  • Reproducible simulation runs via Mesa’s seeded random-number generator.
  • Modular code structure separating model, visualization, and internationalization.

Quick start

One-click launch (Windows)

  1. Install Python 3.10+ and the dependencies:

    pip install -r requirements.txt
  2. Double-click starter.exe in the project root. The launcher starts the Solara server and opens the dashboard in your default browser automatically.

    Note: starter.exe is a small PyInstaller wrapper; it does not bundle Python itself, so the dependencies must be installed first.

    Windows may show a "Windows protected your PC" or "Unknown publisher" warning the first time you run an unsigned executable. Click More infoRun anyway if you trust the source.

Run from the terminal

If you prefer the command line, or you are on macOS / Linux:

# Install dependencies
pip install -r requirements.txt

# Start the interactive dashboard
solara run app.py --host=127.0.0.1 --port=8765

Then open http://127.0.0.1:8765 in your browser.

You can also use the cross-platform graphical launcher:

python launch.py

Rebuilding the Windows launcher

If you modify launch.py, rebuild starter.exe with PyInstaller:

pip install pyinstaller
pyinstaller --onefile --noconsole --name starter launch.py
# Then copy dist/starter.exe to the project root
cp dist/starter.exe starter.exe

Project structure

SFI-ASM-Mesa-v1.1-release/
├── app.py                  # Solara entry point
├── launch.py               # Cross-platform tkinter launcher (source)
├── starter.exe             # Pre-built Windows one-click launcher
├── requirements.txt        # Python dependencies
├── README.md               # This file
├── LICENSE                 # MIT license
├── CITATION.cff            # Citation metadata
├── CHANGELOG.md            # Version history
├── .gitignore              # Git ignore rules
├── src/
│   ├── __init__.py
│   ├── model.py            # TraderAgent, TradingRule, SFIMarketModel
│   ├── visualization.py    # Solara UI, charts, agent portrayal
│   └── i18n.py             # English / Chinese translations
├── tests/
│   ├── __init__.py
│   └── test_model.py       # Smoke tests for the model
└── assets/
    └── screenshot.png      # UI screenshot for the README

Model overview

The model follows the simplified SFI-ASM narrative introduced by Arthur et al. (1997) and surveyed by LeBaron (2002, 2006):

  1. Each chartist agent carries n_rules_per_agent forecasting rules. A rule’s condition is a binary string over the last memory_length price-return signs; its action is a predicted return bounded by max_prediction.
  2. At every step, each chartist matches the current market pattern against its rule set and trades in the direction predicted by its fittest matching rule. Fundamentalists trade against mispricing.
  3. Net aggregate demand is converted into a price return via price_impact. Market noise scales with market_fragility and the absolute net demand, amplifying volatility when agents agree.
  4. Every evolution_interval steps, chartists run a small genetic algorithm: the elite rule survives, the rest are mutated copies of tournament-selected parents. With probability learning_rate, a chartist also replaces its worst rule with a high-fitness rule sampled from the population.
  5. Rule fitness is updated as an exponential moving average of directional accuracy minus a magnitude penalty.

Parameters

Parameter Description Default
N Number of agents 100
chartist_ratio Fraction of agents initialized as chartists 0.8
n_rules_per_agent Number of forecasting rules per chartist 6
memory_length Length of the binary return pattern used by rules 3
max_prediction Maximum absolute return predicted by a rule 0.08
mutation_rate Probability of bit-flip / prediction jitter in the GA 0.15
evolution_interval Steps between GA and social-learning updates 5
learning_rate Per-step probability of copying a peer’s high-fitness rule 0.1
price_impact Scaling of net demand into price returns 4.0
sentiment_factor Steepness of the prediction → position mapping 40.0
fundamentalist_strength Strength at which fundamentalists pull price to value 5.0
noise_level Baseline standard deviation of the price shock 0.005
market_fragility Noise amplification factor when agents agree 1.5
fundamental_drift Standard deviation of the random walk in fundamental value 0.001

Suggested experiments

  • Create a bubble: raise chartist_ratio above 0.9 and lower fundamentalist_strength. Watch the price line diverge from the gray fundamental line.
  • Stabilize the market: lower chartist_ratio below 0.3 so fundamentalists dominate. The price tracks fundamentals closely.
  • Trigger a crash: raise market_fragility and wait for a period of strong consensus; small shocks are amplified into sharp corrections.

References

  • Arthur, W. B., Holland, J. H., LeBaron, B., Palmer, R. G., & Tayler, P. (1997). Asset pricing under endogenous expectations in an artificial stock market. In W. B. Arthur, S. N. Durlauf, & D. A. Lane (Eds.), The Economy as an Evolving Complex System II (pp. 15–44). Addison-Wesley.
  • LeBaron, B. (2002). Building the Santa Fe artificial stock market. Physica A: Statistical Mechanics and its Applications, 335(1–2), 1–16. https://doi.org/10.1016/S0378-4371(02)00482-6
  • LeBaron, B. (2006). Agent-based computational finance. In L. Tesfatsion & K. L. Judd (Eds.), Handbook of Computational Economics (Vol. 2, pp. 1187–1233). Elsevier. https://doi.org/10.1016/S1574-0021(05)02024-1
  • Ehrentreich, N. (2007). Agent-based modeling: The Santa Fe Institute artificial stock market model revisited (Vol. 602). Springer. https://doi.org/10.1007/978-3-540-73113-2
  • Kazil, J., Masad, D., & Crooks, A. (2020). Utilizing Python for agent-based modeling: The Mesa framework. In R. Thomson, C. Dancy, A. Hyder, & H. Bisgin (Eds.), Social, Cultural, and Behavioral Modeling (pp. 308–317). Springer. https://doi.org/10.1007/978-3-030-61255-9_30

License

This project is released under the MIT License.

Citation

If you use this model in your research or teaching, please cite it as:

@software{sfi_asm_mesa,
  title = {SFI-ASM-Mesa: An Agent-Based Model of Market Bubbles and Strategy Evolution},
  year = {2026},
  url = {https://github.com/mimaowang/SFI-ASM-Mesa}
}

Or use the metadata provided in CITATION.cff.

About

An interactive browser-based reproduction of the Santa Fe Institute Artificial Stock Market (SFI-ASM) built with Mesa and Solara.

Resources

License

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages