# Bitcoin-Payable Black-Scholes Server

## Overview

In this tutorial we are going to show you how to use 21 to earn bitcoin by selling an endpoint that returns the theoretical price of an option derived by the Black-Scholes formula. The Black-Scholes formula is just one of many standard financial calculations, which range from relatively straight-forward to much more complex, computationally intense calculations. As is the case with performing general calculations on a remote server, outsourcing these financial calculations can reduce the burden of owning and operating computing hardware and convert large, upfront capital expenditures into much smaller, pay-as-you-go operating expenditures. Additionally, providing endpoints for a large array of standard financial calculations can allow organizations to more efficiently develop and enhance their financial models.

## Prerequisites

You will need the following first:

- A 21 Bitcoin Computer or 21
- The latest version of the 21 software, obtained by running
`21 update`

- Do the Introduction to 21 tutorial

If you have these prerequisites, you’re ready to go. Let's get started!

## Black-Scholes background

The Black-Scholes formula computes the theoretical price of a “European-style” option (i.e., an option that may be exercised only at the expiration date of that option). The five main inputs to the Black-Scholes formula are as follows:

- Current stock price
- Strike price of the option
- Time to expiration of the option (for the code below, 0.25 = a quarter of a year)
- Risk-free interest rate (for the code below, 0.03 = 3% risk free rate)
- Volatility of the stock (for the code below, 0.40 = 40% volatility)

In addition to calculating the theoretical price of the option, the Black-Scholes formula also derives a number of figures that are referred to as the “Greeks,” which show the sensitivity of the option price to several variables:

**Delta:**change in option price relative to a change in stock price**Gamma:**change in option’s Delta relative to a change in stock price**Theta:**change in option price relative to a change in time-to-expiration**Vega:**change in option price relative to a change in stock price volatility**Rho:**change in option price relative to a change in risk-free rate interest rate

## Hosting a Bitcoin-payable Black-Scholes server

The first step is to install SciPy, which is required to support some of the statistical components of the code.

```
sudo pip3 install scipy numpy
```

Next, create a folder to house your project:

```
mkdir black-scholes-server && cd black-scholes-server
```

The next step is to use a text editor to create a file called
`black-scholes-server.py`

in the `black-scholes-server`

directory, and
fill it with the following code:

```
import json
from flask import Flask, request
from two1.wallet import Wallet
from two1.bitserv.flask import Payment
from scipy.stats import norm
from math import log, sqrt, exp
app = Flask(__name__)
wallet = Wallet()
payment = Payment(app, wallet)
@app.route('/black-scholes')
@payment.required(10)
def BlackScholes():
data = {}
S = float(request.args.get('price'))
K = float(request.args.get('strike'))
T = float(request.args.get('time'))
R = float(request.args.get('rate'))
V = float(request.args.get('vol'))
d1 = (log(float(S)/K)+(R+V*V/2.)*T)/(V*sqrt(T))
d2 = d1-V*sqrt(T)
data['cPrice'] = S*norm.cdf(d1)-K*exp(-R*T)*norm.cdf(d2)
data['pPrice'] = K*exp(-R*T)-S+data['cPrice']
data['cDelta'] = norm.cdf(d1)
data['cGamma'] = norm.pdf(d1)/(S*V*sqrt(T))
data['cTheta'] = (-(S*V*norm.pdf(d1))/(2*sqrt(T))-R*K*exp(-R*T)*norm.cdf(d2))/365
data['cVega'] = S*sqrt(T)*norm.pdf(d1)/100
data['cRho'] = K*T*exp(-R*T)*norm.cdf(d2)/100
data['pDelta'] = data['cDelta']-1
data['pGamma'] = data['cGamma']
data['pTheta'] = (-(S*V*norm.pdf(d1))/(2*sqrt(T))+R*K*exp(-R*T)*norm.cdf(-d2))/365
data['pVega'] = data['cVega']
data['pRho'] = -K*T*exp(-R*T)*norm.cdf(-d2)/100
return json.dumps(data)
if __name__ == '__main__':
app.run(host='::', port=5000)
```

Finally, save the file, close it, and then start the server with the following command:

```
python3 black-scholes-server.py
```

Your bitcoin-powered Black Scholes Server endpoint should be up and running! It can be tested by running the following command:

```
21 buy 'http://[::1]/black-scholes?price=35&strike=40&time=0.25&rate=0.03&vol=0.4'
```

The output returned to your terminal should look similar to the following:

```
{
"cDelta": 0.29800155361035174,
"cGamma": 0.04951983983139014,
"cPrice": 1.1937025256188676,
"cRho": 0.02309087962685861,
"cTheta": -0.014054890024653524,
"cVega": 0.06066180379345292,
"pDelta": -0.7019984463896483,
"pGamma": 0.04951983983139014,
"pPrice": 5.894824718384406,
"pRho": -0.07616192585505524,
"pTheta": -0.010791784091001563,
"pVega": 0.06066180379345292
}
```

The format of the returned JSON data starts with either a "c" or "p" to denote "call" or "put" and then lists what the data item is (e.g., "cPrice" = the implied price of a call option, "pTheta" = implied Theta for a put option).

Congratulations, you just created and tested your Bitcoin-payable Black-Scholes endpoint!

## Next steps

You just learned how to build a basic financial calculator that someone can pay for in Bitcoin. Given these fundamentals, you can extend the code to build more complex financial models. Here are some ideas on what to build next:

Enhance this basic Black-Scholes formula to take into account dividend payments

Enhance this basic Black-Scholes formula to calculate “American-style” options (i.e., options that can be exercised at any time prior to and including the expiration date)

Build other simple financial calculations (e.g., discounted cash flow, internal rate of return, weighted-average cost of capital, etc.)

Build more complex financial calculations (e.g., Monte Carlo simulations, detailed back-testing, machine learning prediction models, etc.)

## How to send your Bitcoin to the Blockchain

Just as a reminder, you can send bitcoin mined or earned in your
21.co balance to the blockchain at any time by running ```
21
flush
```

. A transaction will be created within 10 minutes,
and you can view the transaction id with `21 log`

.
Once the transaction has been confirmed, you can check the
balance in your bitcoin wallet from the command line with
`wallet balance`

, and you can send bitcoin from your
wallet to another address with ```
wallet sendto
$BITCOIN_ADDRESS --satoshis $SATOSHI_AMOUNT --use-unconfirmed
```

.
The --satoshis flag allows you to specify the amount in satoshis;
without it the sendto amount is in BTC, but this behavior is
deprecated and will be removed soon. The
`--use-unconfirmed`

flag ensures that you can send
even if you have unconfirmed transactions in your wallet.

## Ready to sell your endpoint? Go to slack.21.co

Ready to try out your bitcoin-payable server in the wild? Or simply want to browse and purchase from other bitcoin-enabled servers? Head over to the 21 Developer Community at slack.21.co to join the bitcoin machine-payable marketplace hosted on the 21 peer-to-peer network.