# Python 代码

# 基本服务调用

# 示例1:简单调用

import requests
with open("E:\\AnalyticSolutionV2020-05\\Bachelier_getGreeksList.json", "r") as f:#设置Json文件存储路径,文件内容见API
    json_str = f.read()  #读取Json输入文件
params = {'params': json_str}#将输入问价赋值给远程调用的参数params
result = requests.post("http://bcopt.com/model", data=params)#通过远程微服务获取定价信息
print(result.json())#打印返回参数参数

# 示例2:解析返回值

import requests
#基础函数,通过远程微服务获取定价信息
def post_by_params(json_str):
    params = {'params': json_str}
    result = requests.post("http://bcopt.com/model", data=params)
    return result
#基础函数,解析返回信息中的价格序列
def parse_json_price(jsonStrBack):
    json_object = jsonStrBack.json()
    return json_object['Price']
#主函数
if __name__ == '__main__':
    with open("E:\\AnalyticSolutionV2020-05\\BlackScholes_getGreeksList.json", "r") as f:
        json_str = f.read()  # 读取文件
        print(json_str)
    str_re = post_by_params(json_str)
    print(str(str_re))
    print(str_re.json())
    print(parse_json_price(str_re))

# 示例3:封装库文件

封装,放入子文件夹:lib,命名myBCOptLib

import json
import lib.myBCOptLib as mylib
#构建Json文件
dict = {"version":"AnalyticSolution.V202005","model":"BlackScholes","function":"getGreeks"}
sub_dict_derivative= {"CallPut":1,"Strike":1919,"DeliveryYears":1,"ExpiryYears":1,"ID":1}
sub_dict_marketData= {"RateD":0.02,"Forward":1905,"Vol":0.06}
sub_dict_controlParameters= {"forwardDiff":19,"volDiff":0.01,"yearDiff":0.00274}
dict["derivative"] = sub_dict_derivative
dict["marketData"] = sub_dict_marketData
dict["controlParameters"] = sub_dict_controlParameters
test_json = json.dumps(dict)#放入Json文件
#print(test_json)
str_re = mylib.post_by_params_json(test_json)
print(str_re.text)#打印结果
dict["derivative"]["Strike"]=1955#update strike 更新行权价
test_json = json.dumps(dict)#放入Json文件
str_re = mylib.post_by_params_json(test_json)#再次调用
print(str_re.text)#打印结果

调用

import lib.myBCOptLib as mylib
str_re = mylib.post_by_params_fileURL("E:\\AnalyticSolutionV2020-05\\Bachelier_getGreeks.json")
print(str(str_re.json()))

# 示例4:程序构建Json

import json
import lib.myBCOptLib as mylib
#构建Json文件
dict = {"version":"AnalyticSolution.V202005","model":"BlackScholes","function":"getGreeks"}
sub_dict_derivative= {"CallPut":1,"Strike":1919,"DeliveryYears":1,"ExpiryYears":1,"ID":1}
sub_dict_marketData= {"RateD":0.02,"Forward":1905,"Vol":0.06}
sub_dict_controlParameters= {"forwardDiff":19,"volDiff":0.01,"yearDiff":0.00274}
dict["derivative"] = sub_dict_derivative
dict["marketData"] = sub_dict_marketData
dict["controlParameters"] = sub_dict_controlParameters
test_json = json.dumps(dict)#放入Json文件
#print(test_json)
str_re = mylib.post_by_params_json(test_json)
print(str_re.text)#打印结果
dict["derivative"]["Strike"]=1955#update strike 更新行权价
test_json = json.dumps(dict)#放入Json文件
str_re = mylib.post_by_params_json(test_json)#再次调用
print(str_re.text)#打印结果

# 应用分析

# 计算AU T+D的历史波动率

import numpy
import requests
from matplotlib import pyplot as plt

json_str='{ "version":"formula.V202001", "model":"historicalVol", "function":"getHisVol", "marketData": { "Spot":[377.4, 376.75, 377.68, 377.05, 375.46, 373.42, 375.32, 376.29, 373.25, 373.86, 372.68, 373.89, 373.21, 370.34, 366.5, 365.33, 362.03, 362.96, 365.87, 374.92, 377.93, 377.09, 376.86, 377.45, 380.23, 378.18, 377.64, 375.07, 376.25, 375.63, 374.77, 377.82, 378.09, 377.97, 379.73, 379.8, 377.27, 376.28, 376.22, 376.82, 375.28, 375.66, 374.38, 372.47, 370.73, 368.74, 366.45, 369.71, 370.55, 370.55, 371.89, 371.74, 371.51, 369.49, 369.91, 376.14, 380.22, 380.53, 387.13, 384.94, 385.86, 386.33, 383.55, 378.34, 387.34, 389.53, 392.67, 391.01, 389.62, 391.37, 392.72, 388.73, 391, 389.49, 389.43, 387.84, 387.91, 384.53, 380.03, 380.22, 379.87, 380.99, 380.95, 378.34, 374.62, 369.82, 372.45, 371.38, 372.55, 373.15, 374.32, 375.61, 373.75, 371.68, 374.73, 371.25, 367.25, 368.41, 366.06, 368.23, 371.22, 368.11, 367.56, 366.95, 367.08, 361.47, 356.27, 362.16, 365.45, 365.96, 365.95, 364.54, 364.99, 365, 364.49, 366.2, 364.46, 363.8, 361.96, 361.27, 363.37, 360.95, 356.11, 357.9, 355, 357.89, 361.48, 360.3, 364.4, 369.44, 374.13, 377.26, 377.53, 372.88, 370.13, 371.04, 382.06, 381.45, 376.92, 374.68, 379.45, 382.4, 387.97, 386.73, 384.7, 383.82, 384.98, 387.44, 386.31, 387.79, 387.15, 384.98, 384.6, 382.95, 385.31, 384.73, 386.16, 384.67, 384.47, 395.54, 397.02, 400.96, 399.56, 397.12, 392.18, 390.46, 391.68, 393.6, 390.89, 389.83, 389.46, 391.45, 394.41, 390.52, 386.63, 385.35, 381.14, 381.36, 381.44, 382.16, 385.94, 385.4, 381.24, 381.62, 380.18, 376.83, 370.42, 371.05, 378.64, 378.59, 378.63, 384.73, 391.67, 390.91, 391.49, 393.29, 394.63, 396.73, 395.23, 393.48, 394.24, 395.26, 408.04, 406.36, 401.99, 403.22, 400.91, 398.76, 396.43, 399.51, 404.33, 403.28, 400.9, 402.03, 404.09, 403.6, 402.2, 402.68, 403.03, 402.29, 401.88, 407.55, 408.01, 403.93, 404.28, 401.96, 398.07, 397.32, 396.82, 402.43, 406.36, 414.86, 413.02, 414.11, 415.54, 416.97, 416.02, 416.83, 416.33, 412.47, 413.16, 413.16, 413.61, 415.49, 421.16, 422.05, 419.52, 417.02, 415.73, 412.81, 414.68, 410.96, 414.32, 418.21, 427.59] }, "controlParameters": { "periodLen":30, "topN":100 } }'
params = {'params': json_str}#入参
result = requests.post("http://bcopt.com/model", data=params)#发送给远程服务
reJson=result.json()

yplot = numpy.array(reJson['hisVolList'])
xplot = range(0, len(yplot))
plt.plot(xplot, yplot, color='red', label='AU T+D hisVol' )
plt.title('hisVol')
plt.xlabel('days')
plt.ylabel('AU T+D hisVol')
plt.legend()
plt.show()

# ATM的Delta不等于50%

import requests
import numpy
import matplotlib.pyplot as plt
#基础函数,通过远程微服务获取定价信息
def post_by_params(json_str):
    params = {'params': json_str}
    result = requests.post("http://bcopt.com/model", data=params)#通过远程微服务获取定价信息
    return result
#基础函数,解析返回信息中的价格序列
def parse_json_delta(jsonStrBack):
    json_object = jsonStrBack.json()
    price = [0 for i in range(len(json_object['valueList']))]
    for i in range(0,len(json_object['valueList'])):
        price[i]=json_object['valueList'][i]['Delta']
    return price
#应用函数,分析价格伴随到期日增长的规律
def price_vanilla_spread_list_expiry_growth(xplot,strike,callPut,ED):
    json_str = '{version:"V20210101",model:"BS_EUR",function:"getPriceGreeks",parameterList:[ '
    for i in xplot:
        json_str =json_str +'{RD:0.022,RF:0.021,S:1710,F:1700,V:'+str(i)+',CP:'+str(callPut)+',K:'+str(strike)
        json_str = json_str +',TD:'+str(ED)+',ED:'+str(ED)+',ID:"comment"},'
    json_str = json_str +']} '
    str_re1=post_by_params(json_str)
    yplot = numpy.array(parse_json_delta(str_re1))
    return yplot
#应用函数,打印价格伴随到期日增长的规律
def print_vanilla_delta_growth():
    xplot = range(1, 500)#vol范围1-1000%
    call1Y = price_vanilla_spread_list_expiry_growth(xplot,1700, 1, 365)
    put1Y = price_vanilla_spread_list_expiry_growth(xplot,1700, -1, 365)
    call3Y = price_vanilla_spread_list_expiry_growth(xplot,1700, 1, 365*3)
    put3Y = price_vanilla_spread_list_expiry_growth(xplot,1700, -1, 365*3)
    plt.plot(xplot, call1Y, color='green', label='call1Y',)
    plt.plot(xplot, put1Y, color='red', label='put1Y')
    plt.plot(xplot, call3Y, color='green', label='call3Y',linestyle=':')
    plt.plot(xplot, put3Y, color='red', label='put3Y',linestyle=':')
    plt.title('delta moving as vol upside')
    plt.xlabel('vol')
    plt.ylabel('delta')
    plt.legend()
    plt.show()
#主函数
if __name__ == '__main__':
    print_vanilla_delta_growth()

# 相关系数对Quanto期权影响

import requests
import numpy as np
import matplotlib.pyplot as plt
#Corr如何影响Quanto期权价格、Greeks,以人民币报价
#函数:获取服务
def post_by_params(json_str):
    params = {'params': json_str}
    result = requests.post("http://bcopt.com/model", data=params)
    return result

#函数:构建脚本计算Price
def price(corr,year,VolFD1_ATM,VolFQ2_ATM,CallPut,Strike):
    json_str = '{ "version":"AnalyticSolution.V202005", "model":"VanillaQuanto", "function":"getGreeks2VolCorr", "derivative": { "CallPut":'+str(CallPut)+', "Strike":'+str(Strike)+', "QuantoFactor":6.5, "DeliveryYears":'+str(year)+', "ExpiryYears":'+str(year)+', "ID":1 }, "marketData": { "SpotFD":1900, "SpotDQ":6.5, "RateD":0.02, "RateF":0.02, "RateQ":0.02, "Forward":1905, "VolFD_SMILE":0.16, "VolFD1_ATM":'+str(VolFD1_ATM)+', "VolFQ2_ATM":'+str(VolFQ2_ATM)+',"Corr_FD_FQ": '
    json_str = json_str + str(corr)
    json_str = json_str +' }, "controlParameters": { "forwardDiff":19, "volDiff":0.01, "yearDiff":0.00274 } } '
    #print(json_str)
    jsonStrBack=post_by_params(json_str)
    json_object = jsonStrBack.json()
    return json_object['Price']

#函数:构建脚本计算Delta
def delta(corr,year,VolFD1_ATM,VolFQ2_ATM,CallPut,Strike):
    json_str = '{ "version":"AnalyticSolution.V202005", "model":"VanillaQuanto", "function":"getGreeks2VolCorr", "derivative": { "CallPut":'+str(CallPut)+', "Strike":'+str(Strike)+', "QuantoFactor":6.5, "DeliveryYears":'+str(year)+', "ExpiryYears":'+str(year)+', "ID":1 }, "marketData": { "SpotFD":1900, "SpotDQ":6.5, "RateD":0.02, "RateF":0.02, "RateQ":0.02, "Forward":1905, "VolFD_SMILE":0.16, "VolFD1_ATM":'+str(VolFD1_ATM)+', "VolFQ2_ATM":'+str(VolFQ2_ATM)+',"Corr_FD_FQ": '
    json_str = json_str + str(corr)
    json_str = json_str +' }, "controlParameters": { "forwardDiff":19, "volDiff":0.01, "yearDiff":0.00274 } } '
    #print(json_str)
    jsonStrBack=post_by_params(json_str)
    json_object = jsonStrBack.json()
    return json_object['Delta']

#函数:打印增长规律
def print_corr_growth():
    corr = np.arange(-1.00, 1.00, 0.1)
    yplot1m = [price(i,1/12,0.15,0.15,-1,1900) for i in corr]
    yplot6m = [price(i, 0.5,0.15,0.15,-1,1900) for i in corr]
    yplot12m = [price(i, 1,0.15,0.15,-1,1900) for i in corr]
    plt.subplot(1, 2, 1)
    plt.plot(corr, yplot1m, color='red', label='1Mon')
    plt.plot(corr, yplot6m, color='blue', label='6Mon')
    plt.plot(corr, yplot12m, color='green', label='12Mon')
    plt.title('XAUUSD call vanilla quanto cny price vs corr')
    plt.xlabel('corr')
    plt.ylabel('price')

    yplot1m = [delta(i,1/12,0.15,0.15,-1,1900) for i in corr]
    yplot6m = [delta(i, 0.5,0.15,0.15,-1,1900) for i in corr]
    yplot12m = [delta(i, 1,0.15,0.15,-1,1900) for i in corr]
    plt.subplot(1, 2, 2)
    plt.plot(corr, yplot1m, color='red', label='1Mon')
    plt.plot(corr, yplot6m, color='blue', label='6Mon')
    plt.plot(corr, yplot12m, color='green', label='12Mon')
    plt.title('XAUUSD call vanilla quanto cny delta vs corr')
    plt.xlabel('corr')
    plt.ylabel('delta')

    plt.legend()
    plt.show()
#主函数
if __name__ == '__main__':
    print_corr_growth()
上次更新: 2022/6/3 下午6:45:05