-
Option Payoffs 4
-
Lecture1.1
-
Lecture1.2
-
Lecture1.3
-
Lecture1.4
-
-
Binomial Model 8
-
Lecture2.1
-
Lecture2.2
-
Lecture2.3
-
Lecture2.4
-
Lecture2.5
-
Lecture2.6
-
Lecture2.7
-
Lecture2.8
-
-
Black-Scholes 6
-
Lecture3.1
-
Lecture3.2
-
Lecture3.3
-
Lecture3.4
-
Lecture3.5
-
Lecture3.6
-
-
Monte Carlo Simulations 3
-
Lecture4.1
-
Lecture4.2
-
Lecture4.3
-
NetworkX Introduction
The library networkx will allow us to visualize the binomial trees we are going to build in the lecture. Let’s begin with a review of some basic functionality.
The first step is to create a graph, which can be done as so:
import matplotlib.pyplot as plt
import networkx as nx
#Basic graphing with networkx
#Create a graph
G = nx.Graph()
When we use add_nodes_from and pass a list we create specific nodes. The following will add three nodes 1, 2 and 3.
#Add three nodes: 1, 2, 3
G.add_nodes_from([1,2,3])
The function add_edge takes a starting node and ending node to connect an edge between. The following will connect node 1 to node 2 and node 1 to node 3.
#Add an edge from 1 to 2
G.add_edge(1, 2)
#Add an edge from 1 to 3
G.add_edge(1, 3)
Finally, we will call the draw function but add two optional parameters. Setting with_labels to True will make sure each node is labeled, and we can also set the font weight to bold with font_weight=’bold’. The following combined with plt.show() displays our network.
#Draw the graph with labels
nx.draw(G, with_labels=True, font_weight='bold')
plt.show()
A graph can also take as an optional parameter a dictionary which specifies for each node where it should be placed. For example, if we want node 1 to be at the x position 1 and the y position 2, we would have the key 1 have a value of (1,2). Notice how we build a dictionary for all the positions of the three nodes and then pass it as pos.
#Create a dictionary which maps each node to a position in the graph
pos = {1: (0, 0),
2: (1, 1),
3: (1, -1)}
#Create our graph again
G = nx.Graph()
G.add_nodes_from([1,2,3])
G.add_edge(1, 2)
G.add_edge(1, 3)
#Draw the graph but pass in the positions this time
nx.draw(G, pos=pos, with_labels=True, font_weight='bold')
plt.show()
The nodes do not need to be integers, they could instead be strings. For example, we will describe each node with a label for time and the value of a stock in these lectures. Below is the code that makes a simple tree where at time 0 the stock is $100, and then in time 1 there are two paths, one to $90 and one to $110.
#Repeat this but change the nodes to be the following labels
pos = {"T=0-$100": (0, 0),
"T=1-$110": (1, 1),
"T=1-$90": (1, -1)}
G = nx.Graph()
G.add_nodes_from(["T=0-$100", "T=1-$110", "T=1-$90"])
G.add_edge("T=0-$100", "T=1-$110")
G.add_edge("T=0-$100", "T=1-$90")
plt.rcParams["figure.figsize"] = (15,10)
nx.draw(G, pos=pos, with_labels=True, font_weight='bold', font_size=15)
plt.show()