# 期权头寸计算

## 数据准备

``````optionData = pd.read_csv(u'期权头寸.csv', encoding='gbk', parse_dates = [3], dtype = {u'代码':str})
pd.options.display.float_format = '{:,.2f}'.format
print(optionData)

代码 方向  行权价       到期时间    头寸
0  000001  C 2.20 2015-02-19  1000
1  000002  C 2.10 2015-02-19  -500
2  000003  P 1.90 2015-03-19  1000
3  000004  P 1.80 2015-03-19  -500
``````

## 计算方法

``````def processOptionBook(optionData):

# 由于我们现在还无法获取市场数据，制作一些假的市场数据数据
# 例如波动率水平，利率水平
vol = 0.3 * np.random.random(len(optionData)) + 0.2
spot = 2.0
riskFree = 0.04
dividend = 0.0
evaluationDate = Date.todaysDate()

# 根据用户的输入计算期权的价格以及各种greeks
t2m = (optionData[u'到期时间'].apply(lambda x:Date(x.year,x.month,x.day)) - evaluationDate)/ 365.0
optionType = optionData[u'方向'].apply(lambda x: x=='C' and 1 or -1)
strike = optionData[u'行权价']

calculateResult = BSMPrice(optionType,strike,spot,riskFree,dividend, vol,t2m)

# 整理数据
calculateResult = calculateResult.multiply(optionData[u'头寸'].values, axis = 0)
calculateResult.index = optionData[u'代码']
portfolio = pd.DataFrame(dict(np.sum(calculateResult)), index = ['portfolio'])
calculateResult = calculateResult.append(portfolio)
calculateResult.index.name = u'代码'
calculateResult = calculateResult.reindex_axis(['price', 'delta', 'gamma', 'rho', 'theta', 'vega'], axis = 1)

return calculateResult
``````
``````res= processOptionBook(optionData)
print(res)

price   delta     gamma    rho   theta   vega

000001    27.36  222.15  1,317.92  26.27 -550.43 149.48
000002    -5.13  -94.07 -1,326.48 -11.53  116.11 -67.71
000003    24.81 -238.18  1,822.42 -70.03 -168.14 231.44
000004    -8.43   71.48   -514.95  21.15   82.48 -84.38
portfolio 38.62  -38.62  1,298.91 -34.13 -519.98 228.84
``````