烟台建设集团网站,上海企业网站制作多少钱,哈尔滨网络公司有哪些,江苏城乡与住房建设部网站传统期权二叉树的算法都是基于数组的#xff0c;对于没有编程基础的人来说非常不直观。二叉树是一种特殊的图#xff0c;可以用python networkx这个图算法库实现#xff0c;这个库不仅包含常用的图算法#xff0c;还包含简单的绘图功能#xff0c;非常适合研究分析使用。 …传统期权二叉树的算法都是基于数组的对于没有编程基础的人来说非常不直观。二叉树是一种特殊的图可以用python networkx这个图算法库实现这个库不仅包含常用的图算法还包含简单的绘图功能非常适合研究分析使用。
def binarytree_europtionfull(S,K,r,q,sigma,t,steps,op_type):unp.exp(sigma*np.sqrt(t/steps))d1/uP(np.exp((r-q)*t/steps)-d)/(u-d)#二叉完全树 Gnx.full_rary_tree(2,2**(steps1)-1)G.nodes[0][price]S#正推过程for (parent,children) in nx.bfs_successors(G,0):#print(parent,children)G.nodes[children[0]][price]G.nodes[parent][price]*d;G.nodes[children[1]][price]G.nodes[parent][price]*u;#对最后一天到期日计算所有情况下的payofffor i in nx.descendants_at_distance(G,0,steps):G.nodes[i][opt_val]np.maximum(G.nodes[i][price]-K,0)#倒推过程for (parent,children) in reversed(list(nx.bfs_successors(G,0))):G.nodes[parent][opt_val]((1-P)*G.nodes[children[0]][opt_val](P)*G.nodes[children[1]][opt_val])*np.exp(-r*t/steps) #print(node)datG.nodes.data()#生成图形显示可注释掉。pos graphviz_layout(G, progdot)nx.draw(G, pos, labels{k:price: %.2f\n opt_val:%.2f%(v[price],v[opt_val]) for (k,v) in dat},with_labelsTrue)plt.show()return G.nodes[0][opt_val] 直接用二叉树空间复杂度为呈指数增长。我们注意到对于中间的节点其实有一些是相等的因为对于一支标的价格S*u*dS*d*u所以我们可以将这些节点合并这就是网格模式。
def binarytree_europtionLattice(S,K,r,q,sigma,t,steps,op_type):unp.exp(sigma*np.sqrt(t/steps))d1/uP(np.exp((r-q)*t/steps)-d)/(u-d)G nx.Graph()G.add_node(0)G.nodes[0][price]Scnt0for i in range(steps):for j in range(i1):#print(j,i,cnt,cnti1,cnti2)G.add_edge(cnt,cnti1)G.add_edge(cnt,cnti2)cnt1#正推过程for (parent,children) in nx.bfs_successors(G,0):if len(children)2:G.nodes[children[0]][price]G.nodes[parent][price]*d;G.nodes[children[-1]][price]G.nodes[parent][price]*u;#对最后一天到期日计算所有情况下的payofffor i in nx.descendants_at_distance(G,0,steps):G.nodes[i][opt_val]np.maximum(G.nodes[i][price]-K,0)#倒推过程for (parent,children) in reversed(list(nx.bfs_successors(G,0))):G.nodes[parent][opt_val]((1-P)*G.nodes[children[-1]-1][opt_val](P)*G.nodes[children[-1]][opt_val])*np.exp(-r*t/steps) #生成图形显示可注释掉。pos graphviz_layout(G, progdot)nx.draw(G, pos, labels{k:price: %.2f\n opt_val:%.2f%(v[price],v[opt_val]) for (k,v) in dat},with_labelsTrue)plt.show()return G.nodes[0][opt_val]