Skip to content

Instantly share code, notes, and snippets.

@jmarhee
Created March 21, 2023 18:47
Show Gist options
  • Save jmarhee/0464e1298edd8b95bf81fd6b560ad053 to your computer and use it in GitHub Desktop.
Save jmarhee/0464e1298edd8b95bf81fd6b560ad053 to your computer and use it in GitHub Desktop.

NashPy Quickstart for Python Programmers

nashpy is a Python library for computing equilibria in game theory. It provides tools for computing Nash equilibria, correlated equilibria, and other solution concepts in both cooperative and non-cooperative games.

This quickstart document will cover the basics of using nashpy to solve simple two-player games.

Installation

To install nashpy, you can use pip:

pip install nashpy

Creating a Game

In nashpy, a game is represented as a matrix. For example, consider the following two-player game:

        L   R
    T  2,2 0,4
    B  4,0 1,1

We can represent this game as a NumPy array in nashpy as follows:

import numpy as np
import nashpy as nash

game_matrix = np.array([[2, 0], [4, 1]]), np.array([[2, 4], [0, 1]]))
game = nash.Game(game_matrix)

Here, we first create two matrices (one for each player's payoff) and then create a nash.Game object with these matrices.

Computing Equilibria

Once we have created a game, we can compute various equilibria using nashpy. For example, we can compute the Nash Equilibrium of the game as follows:

nash_eqs = game.support_enumeration()
for eq in nash_eqs:
    print(eq)

This will output the following:

(array([0.33333333, 0.66666667]), array([0.4, 0.6]))
(array([0.33333333, 0.66666667]), array([0.4, 0.6]))

The output shows two Nash equilibria of the game, where the first array represents Player 1's strategy and the second array represents Player 2's strategy.

We can also compute other solution concepts, such as correlated equilibria, using nashpy. For example:

corr_eqs = game.support_correlated_equilibria()
for eq in corr_eqs:
    print(eq)

This will output the following:

[[0.25 0.  ]
 [0.   0.25]
 [0.25 0.  ]
 [0.   0.25]]

This output represents a correlated equilibrium of the game, where the matrix represents a probability distribution over each player's strategies.

Conclusion

This quickstart document has covered the basics of using nashpy to solve simple two-player games. nashpy provides many more tools for solving games, including support for larger games, mixed strategies, and various solution concepts. For more information, you can refer to the nashpy documentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment