BitcoinPayable BlackScholes 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 BlackScholes formula. The BlackScholes formula is just one of many standard financial calculations, which range from relatively straightforward 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, payasyougo 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!
BlackScholes background
The BlackScholes formula computes the theoretical price of a “Europeanstyle” option (i.e., an option that may be exercised only at the expiration date of that option). The five main inputs to the BlackScholes 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)
 Riskfree 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 BlackScholes 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 timetoexpiration
 Vega: change in option price relative to a change in stock price volatility
 Rho: change in option price relative to a change in riskfree rate interest rate
Hosting a Bitcoinpayable BlackScholes 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 blackscholesserver && cd blackscholesserver
The next step is to use a text editor to create a file called
blackscholesserver.py
in the blackscholesserver
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('/blackscholes')
@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 = d1V*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 blackscholesserver.py
Your bitcoinpowered Black Scholes Server endpoint should be up and running! It can be tested by running the following command:
21 buy 'http://[::1]/blackscholes?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 Bitcoinpayable BlackScholes 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 BlackScholes formula to take into account dividend payments

Enhance this basic BlackScholes formula to calculate “Americanstyle” 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, weightedaverage cost of capital, etc.)

Build more complex financial calculations (e.g., Monte Carlo simulations, detailed backtesting, 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 useunconfirmed
.
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
useunconfirmed
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 bitcoinpayable server in the wild? Or simply want to browse and purchase from other bitcoinenabled servers? Head over to the 21 Developer Community at slack.21.co to join the bitcoin machinepayable marketplace hosted on the 21 peertopeer network.