siat 3.10.125__py3-none-any.whl → 3.10.127__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. siat/common.py +106 -2
  2. siat/exchange_bond_china.pickle +0 -0
  3. siat/fund_china.pickle +0 -0
  4. siat/stock.py +10 -2
  5. siat/stock_info.pickle +0 -0
  6. {siat-3.10.125.dist-info → siat-3.10.127.dist-info}/METADATA +235 -226
  7. siat-3.10.127.dist-info/RECORD +76 -0
  8. {siat-3.10.125.dist-info → siat-3.10.127.dist-info}/WHEEL +1 -1
  9. {siat-3.10.125.dist-info → siat-3.10.127.dist-info/licenses}/LICENSE +0 -0
  10. {siat-3.10.125.dist-info → siat-3.10.127.dist-info}/top_level.txt +0 -0
  11. siat/__init__ -20240701.py +0 -65
  12. siat/__init__.py.backup_20250214.py +0 -73
  13. siat/alpha_vantage_test.py +0 -24
  14. siat/assets_liquidity_test.py +0 -44
  15. siat/barrons_scraping_test.py +0 -276
  16. siat/beta_adjustment_test.py +0 -77
  17. siat/bond_test.py +0 -142
  18. siat/capm_beta_test.py +0 -49
  19. siat/cmat_commons.py +0 -961
  20. siat/compare_cross_test.py +0 -117
  21. siat/concepts_iwencai.py +0 -86
  22. siat/concepts_kpl.py +0 -93
  23. siat/cryptocurrency_test.py +0 -71
  24. siat/derivative.py +0 -1111
  25. siat/economy-20230125.py +0 -1206
  26. siat/economy_test.py +0 -360
  27. siat/esg_test.py +0 -63
  28. siat/fama_french_test.py +0 -115
  29. siat/financial_statements_test.py +0 -31
  30. siat/financials2 - /321/205/320/231/320/277/321/206/320/254/320/274.py" +0 -341
  31. siat/financials_china2_test.py +0 -67
  32. siat/financials_china2_test2.py +0 -88
  33. siat/financials_china2_test3.py +0 -87
  34. siat/financials_china_test.py +0 -475
  35. siat/financials_china_test2.py +0 -197
  36. siat/financials_china_test2_fin_indicator.py +0 -197
  37. siat/financials_test.py +0 -713
  38. siat/fred_test.py +0 -40
  39. siat/fund_china_test.py +0 -175
  40. siat/fund_test.py +0 -40
  41. siat/future_china_test.py +0 -37
  42. siat/global_index_test.py +0 -66
  43. siat/grafix_test.py +0 -112
  44. siat/holding_risk_test.py +0 -13
  45. siat/local_debug_test.py +0 -100
  46. siat/markowitz2-20240620.py +0 -2614
  47. siat/markowitz_ccb_test.py +0 -37
  48. siat/markowitz_ef_test.py +0 -136
  49. siat/markowitz_old.py +0 -871
  50. siat/markowitz_simple-20230709.py +0 -370
  51. siat/markowitz_test.py +0 -164
  52. siat/markowitz_test2.py +0 -69
  53. siat/ml_cases_example1.py +0 -60
  54. siat/option_china_test.py +0 -447
  55. siat/option_pricing_test.py +0 -81
  56. siat/option_sina_api_test.py +0 -112
  57. siat/proxy_test.py +0 -84
  58. siat/quandl_test.py +0 -39
  59. siat/risk_adjusted_return_test.py +0 -81
  60. siat/risk_evaluation_test.py +0 -96
  61. siat/risk_free_rate_test.py +0 -127
  62. siat/sector_china_test.py +0 -203
  63. siat/security_price.py +0 -831
  64. siat/security_prices_test.py +0 -310
  65. siat/security_trend2-20240620.py +0 -493
  66. siat/setup.py +0 -41
  67. siat/shenwan index history test.py +0 -41
  68. siat/stock_china_test.py +0 -38
  69. siat/stock_info_test.py +0 -189
  70. siat/stock_list_china_test.py +0 -33
  71. siat/stock_technical-20240620.py +0 -2736
  72. siat/stock_test.py +0 -487
  73. siat/temp.py +0 -36
  74. siat/test2_graphviz.py +0 -484
  75. siat/test_graphviz.py +0 -411
  76. siat/test_markowitz_simple.py +0 -198
  77. siat/test_markowitz_simple_revised.py +0 -215
  78. siat/test_markowitz_simple_revised2.py +0 -218
  79. siat/transaction_test.py +0 -436
  80. siat/translate-20230125.py +0 -2107
  81. siat/translate-20230206.py +0 -2109
  82. siat/translate-20230215.py +0 -2158
  83. siat/translate_20240606.py +0 -4206
  84. siat/translate_241003_keep.py +0 -4300
  85. siat/universal_test.py +0 -100
  86. siat/valuation_market_china_test.py +0 -36
  87. siat-3.10.125.dist-info/RECORD +0 -152
siat/test_graphviz.py DELETED
@@ -1,411 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- import os; os.chdir('S:/siat')
3
- from siat import *
4
- #==============================================================================
5
-
6
- from sklearn import tree # 导入树
7
- from sklearn.datasets import load_wine #红酒数据集
8
- from sklearn.model_selection import train_test_split #数据集的分割操作
9
-
10
- wine = load_wine() #加载数据集
11
-
12
- import pandas as pd #利用pandas将data与target拼接成数据表
13
- pd.concat([pd.DataFrame(wine.data),pd.DataFrame(wine.target)],axis=1)
14
-
15
- Xtrain,Xtest,Ytrain,Ytest = train_test_split(wine.data,wine.target,test_size=0.3) #将数据集划分为训练集和测试集
16
-
17
- clf = tree.DecisionTreeClassifier(criterion='entropy') #实例化一个决策分类树模型
18
- clf = clf.fit(Xtrain,Ytrain) #模型拟合
19
- score = clf.score(Xtest,Ytest) #返回预测的准确度accuracy
20
- feature_name = ['酒精','苹果酸','灰','灰的碱性','镁','总酚','类黄酮','非黄烷类酚类',
21
- '花青素','颜色强度','色调','od280/od315稀释葡萄酒','脯氨酸']
22
- import graphviz
23
- dot_data = tree.export_graphviz(clf
24
- ,out_file = None
25
- ,feature_names= feature_name
26
- ,class_names=["琴酒","雪莉","贝尔摩德"]
27
- ,filled=True
28
- ,rounded=True
29
-
30
- ) # 第一个参数为实例化的模型参数
31
- graph = graphviz.Source(dot_data) #绘制决策树
32
-
33
- graph.view()
34
-
35
- graph
36
-
37
-
38
-
39
- #==============================================================================
40
-
41
- import pandas as pd
42
- data1=pd.DataFrame([
43
-
44
- ['NaN','水果',0.339,'ROOT->水果',1],
45
- ['NaN','零食',0.225,'ROOT->零食',1],
46
-
47
- ['水果','柑果',3.241,'水果->柑果',2],
48
- ['水果','梨果',0.054,'水果->梨果',2],
49
-
50
- ['柑果','橙子',1.457,'柑果->橙子',3],
51
- ['柑果','橘子',0.237,'柑果->橘子',3],
52
- ['柑果','柚子',1.800,'柑果->柚子',3],
53
-
54
- ['柚子','葡萄柚',9.544,'柚子->沙田柚',4],
55
- ['橙子','甜橙',1.078,'橙子->甜橙',4],
56
- ['橙子','脐橙',1.656,'橙子->脐橙',4],
57
-
58
- ], columns=['pnode','node','gap','edge','lv'])
59
-
60
- from graphviz import Digraph
61
- # 实例化一个Digraph对象(有向图),name:生成的图片的图片名,format:生成的图片格式
62
- dot= Digraph(name="DuPont_Identity",format="svg")
63
-
64
- # 将所有列的数据都转成list格式
65
- node_list = data1['node'].tolist()
66
- gap_list=data1['gap'].tolist()
67
- edge_list=data1['edge'].tolist()
68
- lv_list=data1['lv'].tolist()
69
-
70
- # dot.node定义节点名称,name:这个节点对象的名称,label:节点名,color:画节点的线的颜色
71
- # fontname:防止字体乱码情况
72
- for i in range(len(node_list)):
73
- dot.node(name=edge_list[i].split('->')[1]+"_"+edge_list[i].split('->')[0],
74
- label=node_list[i]+'\n'+"Gap:{:.2f}K".format(gap_list[i]),
75
- shape='box',
76
- color="peachpuff",
77
- style = "filled",
78
- fontname="Microsoft YaHei")
79
-
80
- # add edges 1-4层
81
- for i in range(len(node_list)):
82
- target_list=edge_list[i].split('->')[1]+"|"+edge_list[i].split('->')[0]
83
- # add edge 第一层
84
- if lv_list[i]==1 and "ROOT" in target_list:
85
- dot.edge('Company',target_list)
86
- # add edge 第二层
87
- for j in range(len(node_list)):
88
- temp_list=edge_list[j].split('->')[1]+"|"+edge_list[j].split('->')[0]
89
- if lv_list[i]==2 and lv_list[j]==1 and (target_list.split("|")[1] == temp_list.split("|")[0]) :
90
- dot.edge(temp_list,target_list)
91
- # add edge 第三层
92
- if lv_list[i]==3 and lv_list[j]==2 and (target_list.split("|")[1] == temp_list.split("|")[0]):
93
- dot.edge(temp_list,target_list)
94
- # add edge 第四层
95
- if lv_list[i]==4 and lv_list[j]==3 and (target_list.split("|")[1] == temp_list.split("|")[0]):
96
- dot.edge(temp_list,target_list)
97
-
98
-
99
- # filename:图片的名称,若无filename,则使用Digraph对象的name,默认会有gv后缀
100
- # directory:图片保存的路径,默认是在当前路径下保存
101
- # dot.view(filename="水果零食业绩归因", directory="D:\MyTest")
102
- import graphviz
103
- g = graphviz.Source(dot) #绘制决策树
104
- g.view()
105
-
106
- g
107
-
108
-
109
- #==============================================================================
110
-
111
- import pandas as pd
112
- data1=pd.DataFrame([
113
-
114
- ['NaN','水果',-4.373,0.339,'ROOT->水果',1],
115
- ['NaN','零食',-3.492,0.225,'ROOT->零食',1],
116
-
117
- ['水果','柑果',-1.575,3.241,'水果->柑果',2],
118
- ['水果','梨果',-4.380,0.054,'水果->梨果',2],
119
-
120
- ['柑果','橙子',-3.025,1.457,'柑果->橙子',3],
121
- ['柑果','橘子',-5.707,0.237,'柑果->橘子',3],
122
- ['柑果','柚子',-6.765,1.800,'柑果->柚子',3],
123
-
124
- ['柚子','葡萄柚',-1.158,9.544,'柚子->沙田柚',4],
125
- ['橙子','甜橙',-1.170,1.078,'橙子->甜橙',4],
126
- ['橙子','脐橙',-1.640,1.656,'橙子->脐橙',4],
127
-
128
-
129
- ], columns=['pnode','node','gap','gap_rate','edge','lv'])
130
-
131
-
132
- # 实例化一个Digraph对象(有向图),name:生成的图片的图片名,format:生成的图片格式
133
- dot= Digraph(name="G",format="png")
134
-
135
- # 将所有列的数据都转成list格式
136
- node_list = data1['node'].tolist()
137
- gap_list=data1['gap'].tolist()
138
- gap_rate_list=data1['gap_rate'].tolist()
139
- edge_list=data1['edge'].tolist()
140
- lv_list=data1['lv'].tolist()
141
-
142
- # dot.node定义节点名称,name:这个节点对象的名称,label:节点名,color:画节点的线的颜色
143
- # fontname:防止字体乱码情况
144
- for i in range(len(node_list)):
145
- if gap_rate_list[i]>0.5:
146
- dot.node(name=edge_list[i].split('->')[1]+"|"+edge_list[i].split('->')[0],
147
- label=node_list[i]+'\n'+"Gap:{:.2f}K".format(gap_list[i]/1000),
148
- color="lightsalmon",
149
- style = "filled",
150
- fontname="Microsoft YaHei")
151
- else:
152
- dot.node(name=edge_list[i].split('->')[1]+"|"+edge_list[i].split('->')[0],
153
- label=node_list[i]+'\n'+"Gap:{:.2f}K".format(gap_list[i]/1000),
154
- color="peachpuff",
155
- style = "filled",
156
- fontname="Microsoft YaHei")
157
-
158
-
159
- # add edges 1-4层
160
- for i in range(len(node_list)):
161
- target_list=edge_list[i].split('->')[1]+"|"+edge_list[i].split('->')[0]
162
- # add edge 第一层
163
- if lv_list[i]==1 and "ROOT" in target_list:
164
- dot.edge('total_gap',target_list)
165
- # add edge 第二层
166
- for j in range(len(node_list)):
167
- temp_list=edge_list[j].split('->')[1]+"|"+edge_list[j].split('->')[0]
168
- if lv_list[i]==2 and lv_list[j]==1 and (target_list.split("|")[1] == temp_list.split("|")[0]) :
169
- dot.edge(temp_list,target_list)
170
- # add edge 第三层
171
- if lv_list[i]==3 and lv_list[j]==2 and gap_rate_list[j]>0.1 and (target_list.split("|")[1] == temp_list.split("|")[0]):
172
- dot.edge(temp_list,target_list)
173
- # add edge 第四层
174
- if lv_list[i]==4 and lv_list[j]==3 and gap_rate_list[j]>0.1 and (target_list.split("|")[1] == temp_list.split("|")[0]):
175
- dot.edge(temp_list,target_list)
176
-
177
-
178
- # filename:图片的名称,若无filename,则使用Digraph对象的name,默认会有gv后缀
179
- # directory:图片保存的路径,默认是在当前路径下保存
180
- # dot.view(filename="水果零食业绩归因", directory="D:\MyTest")
181
- dot.view()
182
-
183
-
184
- #==============================================================================
185
- from graphviz import Digraph
186
-
187
- dot = Digraph(comment='The Test Table')
188
- # 添加圆点A,A的标签是Dot A
189
- dot.node('A', 'Dot A')
190
- # 添加圆点 B, B的标签是Dot B
191
- dot.node('B', 'Dot B')
192
- # dot.view()
193
- # 添加圆点 C, C的标签是Dot C
194
- dot.node(name='C', label= 'Dot C',color='red')
195
- # dot.view()
196
-
197
- # 创建一堆边,即连接AB的两条边,连接AC的一条边。
198
- dot.edges(['AB', 'AC', 'AB'])
199
- # dot.view()
200
- # 在创建两圆点之间创建一条边
201
- dot.edge('B', 'C', 'test')
202
- # dot.view()
203
-
204
- # 获取DOT source源码的字符串形式
205
- print(dot.source)
206
- dot.view()
207
- dot.render('test-table.gv', view=True)
208
-
209
-
210
-
211
-
212
-
213
-
214
-
215
- #==============================================================================
216
-
217
- import graphviz
218
-
219
- # 创建Digraph对象
220
- dot = graphviz.Digraph(comment='Simple Process')
221
-
222
- # 添加节点
223
- dot.node('A', 'Start')
224
- dot.node('B', 'Process 1')
225
- dot.node('C', 'Process 2')
226
- dot.node('D', 'End')
227
-
228
- # 添加边
229
- dot.edges(['AB', 'BC', 'CD'])
230
-
231
- # 保存为PNG图片
232
- dot.format = 'png'
233
- # 渲染和保存流程图
234
- dot.render(filename='simple-process', directory='D:/QTEMP', cleanup=True)
235
- #==============================================================================
236
-
237
- import matplotlib.pyplot as plt
238
- import numpy as np
239
- import matplotlib.patches as mpatches
240
- plt.subplots_adjust(left=0.00, bottom=0.0, right=1.00, top=0.95, wspace=0.0, hspace=0.00)
241
-
242
-
243
- def hexagon_with_text(ax,x,y,text,size,**kwargs):
244
- xy=np.array([x,y])
245
- hexagon = mpatches.RegularPolygon(xy, 6, radius=size,facecolor='#5472bb',edgecolor='#3f597c', orientation=np.pi / 2)
246
- ax.add_patch(hexagon)
247
- ax.text(xy[0],xy[1],text,fontsize=size*14,color='white',va='center',ha='center')
248
-
249
- def circle_with_text(ax,x,y,text,size,**kwargs):
250
- xy=np.array([x,y])
251
- circle = mpatches.Circle(xy, radius=size,facecolor='#83aa51',edgecolor='#546538')
252
- ax.add_patch(circle)
253
- ax.text(xy[0],xy[1],text,fontsize=size*14,color='white',va='center',ha='center')
254
-
255
- def arrow(ax,x,y,size,**kwargs):
256
- ax.plot(x,y,**kwargs)
257
- theta=np.arctan2(x[1]-x[0],y[1]-y[0])
258
- xy=np.array([x[1]-size*np.sin(theta),y[1]-size*np.cos(theta)])
259
- triangle = mpatches.RegularPolygon(xy, 3, radius=size,color=kwargs['color'], orientation=-theta)
260
- ax.add_patch(triangle)
261
-
262
- def arrow_with_rad(ax,x,y,radius,size,**kwargs):
263
- d=np.sqrt((x[1]-x[0])**2+(y[1]-y[0])**2)
264
-
265
- theta=np.arctan2(x[1]-x[0],y[0]-y[1])
266
-
267
- x0=(x[0]+x[1])/2+np.cos(theta)*np.sqrt(radius**2-(d/2)**2)
268
- y0=(y[0]+y[1])/2+np.sin(theta)*np.sqrt(radius**2-(d/2)**2)
269
-
270
- theta1=np.arctan2(y[0]-y0,x[0]-x0)
271
- theta2=np.arctan2(y[1]-y0,x[1]-x0)
272
-
273
- arc_x = []
274
- arc_y = []
275
-
276
- for theta in np.arange(theta1,theta2+(np.pi*2),np.pi/180):
277
- temp_x=x0 + radius * np.cos(theta)
278
- temp_y=y0 + radius * np.sin(theta)
279
- if((temp_x-x[0])**2+(temp_y-y[0])**2>1 and (temp_x-x[1])**2+(temp_y-y[1])**2>1):
280
- arc_x.append(temp_x)
281
- arc_y.append(temp_y)
282
- ax.plot(arc_x,arc_y,**kwargs)
283
-
284
- theta=np.arctan2(arc_y[-2]-arc_y[-1],arc_x[-2]-arc_x[-1])
285
- xy=np.array([arc_x[-1]+size*np.cos(theta),arc_y[-1]+size*np.sin(theta)])
286
- triangle = mpatches.RegularPolygon(xy, 3, radius=size,color=kwargs['color'], orientation=np.pi/2+theta)
287
- ax.add_patch(triangle)
288
-
289
- ax=plt.subplot(1,1,1,aspect='equal')
290
- ax.axis('off')
291
-
292
- circle_with_text(ax,2,23,'$\mathrm{U_{1}}$',1)
293
- circle_with_text(ax,2,20,'$\mathrm{U_{2}}$',1)
294
- circle_with_text(ax,2,17,'$\mathrm{U_{3}}$',1)
295
- circle_with_text(ax,2,14,'$\mathrm{U_{4}}$',1)
296
-
297
- hexagon_with_text(ax,8,22.5,'$\mathrm{I_{1}}$',1)
298
- hexagon_with_text(ax,8,18.5,'$\mathrm{I_{2}}$',1)
299
- hexagon_with_text(ax,8,14.5,'$\mathrm{I_{3}}$',1)
300
-
301
- arrow(ax,[3,8+np.cos(np.pi*3/3)],[23,22.5+np.sin(np.pi*3/3)],0.3,color='#b65576',linestyle='--')
302
- arrow(ax,[3,8+np.cos(np.pi*2/3)],[23,14.5+np.sin(np.pi*2/3)],0.3,color='#b65576',linestyle='--')
303
- arrow(ax,[3,8+np.cos(np.pi*4/3)],[17,22.5+np.sin(np.pi*4/3)],0.3,color='#b65576',linestyle='--')
304
- arrow(ax,[3,8+np.cos(np.pi*4/3)],[14,18.5+np.sin(np.pi*4/3)],0.3,color='#b65576',linestyle='--')
305
-
306
- arrow(ax,[3,8+np.cos(np.pi*3/3)],[20,18.5+np.sin(np.pi*3/3)],0.3,color='#b9b8bd',linestyle='--')
307
- arrow(ax,[3,8+np.cos(np.pi*3/3)],[17,14.5+np.sin(np.pi*3/3)],0.3,color='#b9b8bd',linestyle='--')
308
- arrow(ax,[3,8+np.cos(np.pi*3/3)],[14,14.5+np.sin(np.pi*3/3)],0.3,color='#b9b8bd',linestyle='--')
309
-
310
- ax.text(10.5,15,'${G_{r}}$',fontsize=20)
311
-
312
- circle_with_text(ax,4.2,10.5,'$\mathrm{U_{1}}$',1)
313
- circle_with_text(ax,9.0,10.0,'$\mathrm{U_{2}}$',1)
314
- circle_with_text(ax,8.5,5.8,'$\mathrm{U_{3}}$',1)
315
- circle_with_text(ax,3.8,6.8,'$\mathrm{U_{4}}$',1)
316
-
317
- theta=-np.pi/2-np.arctan2(9.0-4.2,10.0-10.5)
318
- arrow(ax,[9.0+np.cos(theta),4.2-np.cos(theta)],[10.0+np.sin(theta),10.5-np.sin(theta)],0.3,color='#8199bb')
319
-
320
- theta=-np.pi/2-np.arctan2(8.5-9.0,5.8-10.0)
321
- arrow(ax,[8.5+np.cos(theta),9.0-np.cos(theta)],[5.8+np.sin(theta),10.0-np.sin(theta)],0.3,color='#8199bb')
322
-
323
- theta=-np.pi/2-np.arctan2(3.8-4.2,6.8-10.5)
324
- arrow(ax,[3.8+np.cos(theta),4.2-np.cos(theta)],[6.8+np.sin(theta),10.5-np.sin(theta)],0.3,color='#8199bb')
325
-
326
- theta=-np.pi/2-np.arctan2(3.8-8.5,6.8-5.8)
327
- arrow(ax,[3.8+np.cos(theta),8.5-np.cos(theta)],[6.8+np.sin(theta),5.8-np.sin(theta)],0.3,color='#8199bb')
328
-
329
- theta=-np.pi/2-np.arctan2(4.2-8.5,10.5-5.8)
330
- arrow(ax,[4.2+np.cos(theta),8.5-np.cos(theta)],[10.5+np.sin(theta),5.8-np.sin(theta)],0.3,color='#8199bb')
331
-
332
- arrow_with_rad(ax,[4.2,3.8],[10.5,6.8],1.9,0.3,color='#8199bb')
333
-
334
- ax.text(10.5,8,r'${G_s}$',fontsize=20)
335
-
336
- circle_with_text(ax,25.0,19.0,'$\mathrm{U_{1}}$',1)
337
- circle_with_text(ax,35.0,17.0,'$\mathrm{U_{2}}$',1)
338
- circle_with_text(ax,32.0,8.0,'$\mathrm{U_{3}}$',1)
339
- circle_with_text(ax,24.0,10.0,'$\mathrm{U_{4}}$',1)
340
-
341
- hexagon_with_text(ax,32.5,14.0,'$\mathrm{I_{1}}$',1)
342
- hexagon_with_text(ax,23.0,16.0,'$\mathrm{I_{2}}$',1)
343
- hexagon_with_text(ax,27.0,13.0,'$\mathrm{I_{3}}$',1)
344
-
345
- theta=-np.pi/2-np.arctan2(35.0-25.0,17.0-19.0)
346
- arrow(ax,[35.0+np.cos(theta),25.0-np.cos(theta)],[17.0+np.sin(theta),19.0-np.sin(theta)],0.3,color='#8199bb')
347
-
348
- theta=-np.pi/2-np.arctan2(24.0-25.0,10.0-19.0)
349
- arrow(ax,[24.0+np.cos(theta),25.0-np.cos(theta)],[10.0+np.sin(theta),19.0-np.sin(theta)],0.3,color='#8199bb')
350
-
351
- theta=-np.pi/2-np.arctan2(24.0-32.0,10.0-8.0)
352
- arrow(ax,[24.0+np.cos(theta),32.0-np.cos(theta)],[10.0+np.sin(theta),8.0-np.sin(theta)],0.3,color='#8199bb')
353
-
354
- theta=-np.pi/2-np.arctan2(32.0-35.0,8.0-17.0)
355
- arrow(ax,[32.0+np.cos(theta),35.0-np.cos(theta)],[8.0+np.sin(theta),17.0-np.sin(theta)],0.3,color='#8199bb')
356
-
357
- theta=-np.pi/2-np.arctan2(25.0-32.0,19.0-8.0)
358
- arrow(ax,[25.0+np.cos(theta),32.0-np.cos(theta)],[19.0+np.sin(theta),8.0-np.sin(theta)],0.3,color='#8199bb')
359
-
360
- theta=-np.pi/2-np.arctan2(24.0-23-np.cos(np.pi*5/3),10.0-16.0-np.sin(np.pi*5/3))
361
- arrow(ax,[24.0+np.cos(theta),23.0+np.cos(np.pi*5/3)],[10.0+np.sin(theta),16.0+np.sin(np.pi*5/3)],0.3,color='#b65576',linestyle='--')
362
-
363
- theta=-np.pi/2-np.arctan2(32.0-32.5-np.cos(np.pi*4/3),8.0-14.0-np.sin(np.pi*4/3))
364
- arrow(ax,[32.0+np.cos(theta),32.5+np.cos(np.pi*4/3)],[8.0+np.sin(theta),14.0+np.sin(np.pi*4/3)],0.3,color='#b65576',linestyle='--')
365
-
366
- theta=-np.pi/2-np.arctan2(25.0-32.0-np.cos(np.pi*2/3),19.0-8.0-np.sin(np.pi*2/3))
367
- arrow(ax,[25.0+np.cos(theta),27.0+np.cos(np.pi*2/3)],[19.0+np.sin(theta),13.0+np.sin(np.pi*2/3)],0.3,color='#b65576',linestyle='--')
368
- arrow(ax,[25.0+np.cos(theta),32.5+np.cos(np.pi*3/3)],[19.0+np.sin(theta),14.0+np.sin(np.pi*3/3)],0.3,color='#b65576',linestyle='--')
369
-
370
- theta=-np.pi/2-np.arctan2(24.0-23-np.cos(np.pi*5/3),10.0-16.0-np.sin(np.pi*5/3))
371
- arrow(ax,[24.0+np.cos(theta),23.0+np.cos(np.pi*5/3)],[10.0+np.sin(theta),16.0+np.sin(np.pi*5/3)],0.3,color='#b65576',linestyle='--')
372
-
373
- theta=-np.pi/2-np.arctan2(35.0-23-np.cos(np.pi*0/3),17.0-16.0-np.sin(np.pi*0/3))
374
- arrow(ax,[35.0+np.cos(theta),23.0+np.cos(np.pi*0/3)],[17.0+np.sin(theta),16.0+np.sin(np.pi*0/3)],0.3,color='#b9b8bd',linestyle='--')
375
-
376
- theta=-np.pi/2-np.arctan2(24.0-27-np.cos(np.pi*4/3),10.0-13.0-np.sin(np.pi*4/3))
377
- arrow(ax,[24.0+np.cos(theta),27.0+np.cos(np.pi*4/3)],[10.0+np.sin(theta),13.0+np.sin(np.pi*4/3)],0.3,color='#b9b8bd',linestyle='--')
378
-
379
- theta=-np.pi/2-np.arctan2(32.0-27-np.cos(np.pi*5/3),8.0-13.0-np.sin(np.pi*5/3))
380
- arrow(ax,[32.0+np.cos(theta),27.0+np.cos(np.pi*5/3)],[8.0+np.sin(theta),13.0+np.sin(np.pi*5/3)],0.3,color='#b9b8bd',linestyle='--')
381
-
382
- arrow_with_rad(ax,[25,24],[19,10],4.8,0.3,color='#8199bb')
383
-
384
- bbox_props = dict(boxstyle="rarrow,pad=0.3", fc="#629cce", ec="#657084", lw=2)
385
-
386
- ax.text(16, 18, " "*15, ha="center", va="center", rotation=345,
387
- size=15,
388
- bbox=bbox_props)
389
-
390
- ax.text(16, 9, " "*15, ha="center", va="center", rotation=30,
391
- size=15,
392
- bbox=bbox_props)
393
-
394
- arrow(ax,[10,13],[24.5,24.5],0.3,color='#b65576',linestyle='--')
395
- arrow(ax,[20,23],[24.5,24.5],0.3,color='#b9b8bd',linestyle='--')
396
- arrow(ax,[27,30],[24.5,24.5],0.3,color='#8199bb')
397
-
398
- ax.text(9.5,24.5,'Purchase-P',fontsize=15,va='center',ha='right')
399
- ax.text(19.5,24.5,'Purchase-N',fontsize=15,va='center',ha='right')
400
- ax.text(26.5,24.5,'Trust',fontsize=15,va='center',ha='right')
401
-
402
- fig=plt.gcf()
403
- fig.set_size_inches(14, 8)
404
-
405
- ax.set_xlim(0,40)
406
- ax.set_ylim(0,25)
407
-
408
- plt.show()
409
-
410
-
411
- #==============================================================================
@@ -1,198 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
-
3
-
4
- """
5
- 马科维茨有效投资投资边界的基本思想
6
- 通过对资产组合当中不同资产的配置情况进行调整,达到在既定风险水平下的收益最大化,
7
- 或者既定收益水平下的风险最小化。
8
- """
9
-
10
- from datetime import date
11
- import pandas_datareader.data as web
12
- import matplotlib.pyplot as plt
13
- import numpy as np
14
- import seaborn as sns
15
- import warnings
16
- warnings.filterwarnings("ignore")
17
- %matplotlib inline
18
-
19
- #获取股票数据
20
- tickers = {
21
- 'AAPL':'苹果',
22
- 'AMZN':'亚马逊',
23
- 'GOOGL':'谷歌',
24
- 'BABA':'阿里巴巴'
25
- }
26
-
27
- data_source = 'stooq'#定义数据源的参数
28
-
29
- start = date(2016,1,1)#起始时间
30
-
31
- end = date(2017,12,31)#结束时间
32
-
33
- stock_data = web.DataReader(list(tickers), data_source,start,end)["Close"]
34
-
35
- stock_data.rename(columns=tickers,inplace=True)
36
-
37
- stock_data=stock_data.iloc[::-1]
38
- stock_data.head()
39
-
40
- #画出收盘价走势图
41
- sns.set_style("whitegrid")#横坐标有标线,纵坐标没有标线,背景白色
42
- sns.set_style("darkgrid") #默认,横纵坐标都有标线,组成一个一个格子,背景稍微深色
43
- sns.set_style("dark")#背景稍微深色,没有标线线
44
- sns.set_style("white")#背景白色,没有标线线
45
- sns.set_style("ticks")#xy轴都有非常短的小刻度
46
- sns.despine(offset=30,left=True)#去掉上边和右边的轴线,offset=30表示距离轴线(x轴)的距离,left=True表示左边的轴保留
47
-
48
-
49
- sns.set(font='SimHei',rc={'figure.figsize':(10,6)})# 图片大小和中文字体设置
50
- # 图形展示
51
-
52
- # name=input("股票名字")
53
- # stock_data.iloc[0]含有字样Symbols
54
- (stock_data/stock_data.iloc[0]).plot()
55
-
56
-
57
- #------------------------------------------------------------------------------
58
- # 计算收益率和风险
59
- # 收益率
60
- R=stock_data/stock_data.shift(1)-1
61
- R.head()
62
-
63
- # 对数收益率
64
- log_r=np.log(stock_data/stock_data.shift(1))
65
- log_r.head()
66
-
67
- # 年化收益率
68
- r_annual=np.exp(log_r.mean()*250)-1
69
- r_annual
70
-
71
- #------------------------------------------------------------------------------
72
- # 风险
73
- std = np.sqrt(log_r.var() * 250)#假设协方差为0
74
- std
75
-
76
- #------------------------------------------------------------------------------
77
- # 投资组合的收益和风险
78
- def gen_weights(n):
79
- w=np.random.rand(n)
80
- return w /sum(w)
81
-
82
- n=len(list(tickers))
83
- w=gen_weights(n)
84
- list(zip(r_annual.index,w))
85
-
86
- #投资组合收益
87
- def port_ret(w):
88
- return np.sum(w*r_annual)
89
- port_ret(w)
90
-
91
- #投资组合的风险
92
- def port_std(w):
93
- return np.sqrt((w.dot(log_r.cov()*250).dot(w.T)))
94
- port_std(w)
95
-
96
- #若干投资组合的收益和风险
97
- def gen_ports(times):
98
- for _ in range(times):#生成不同的组合
99
- w=gen_weights(n)#每次生成不同的权重
100
- yield (port_std(w),port_ret(w),w)#计算风险和期望收益 以及组合的权重情况
101
-
102
- import pandas as pd
103
- # 投资组合模拟次数
104
- df=pd.DataFrame(gen_ports(25000),columns=["std","ret","w"])
105
- df.head()
106
-
107
-
108
-
109
- #------------------------------------------------------------------------------
110
-
111
- # 引入夏普比率
112
- # 假设无风险利率为0.03,画出投资有效边界
113
- df['sharpe'] = (df['ret'] - 0.015) / df['std']#定义夏普比率
114
- fig, ax = plt.subplots()
115
- df.plot.scatter('std', 'ret', c='sharpe',s=30, alpha=0.3, cmap='cool',marker='o', ax=ax)
116
- plt.style.use('ggplot')
117
- plt.rcParams['axes.unicode_minus'] = False# 显示负号
118
-
119
- list(zip(r_annual.index, df.loc[df.sharpe.idxmax()].w))
120
-
121
-
122
- import scipy.optimize as opt
123
- frontier=pd.DataFrame(columns=['std','ret'])
124
-
125
- # std的范围:0.16,0.25
126
- for std in np.linspace(0.16,0.25):
127
- #for std in np.linspace(0.16,0.26):
128
- res=opt.minimize(lambda x:-port_ret(x),
129
- x0=((1/n),)*n,
130
- method='SLSQP',
131
- bounds=((0,1),)*n,
132
- constraints=[
133
- {"fun":lambda x:port_std(x)-std,"type":"eq"},
134
- {"fun":lambda x:(np.sum(x)-1),"type":"eq"}
135
- ])
136
- if res.success:
137
- frontier=frontier.append({"std":std,"ret":-res.fun},ignore_index=True)
138
- frontier.plot('std','ret',lw=3,c='blue',ax=ax)
139
-
140
- fig
141
-
142
-
143
-
144
- #------------------------------------------------------------------------------
145
- # 计算最优资产配置情况
146
-
147
- res=opt.minimize(lambda x:-((port_ret(x)-0.03)/port_std(x)),
148
- x0=((1/n),)*n,
149
- method='SLSQP',
150
- bounds=((0,1),)*n,
151
- constraints={"fun":lambda x:(np.sum(x)-1), "type":"eq"})
152
-
153
- res.x.round(3)
154
-
155
- ax.scatter(port_std(res.x),port_ret(res.x),marker="*",c="black",s=300)
156
- fig
157
-
158
- #------------------------------------------------------------------------------
159
- # 绘制资本市场线CML=Capital Market Line
160
- ax.plot((0,.27),(.03,-res.fun*.27+.03))
161
- fig
162
-
163
- """
164
- 在上图的所示资本市场线上,星号左边表示将资本用于投资一部分无风险资产和一部分风险资产组合,
165
- 而在星号处代表将所有的资本都用于投资风险资产组合,
166
- 星号右边意味着借入无风险资产并投资于风险资产组合,可以在相同的风险水平下获得更高的收益。
167
-
168
- """
169
- #------------------------------------------------------------------------------
170
- #------------------------------------------------------------------------------
171
- #------------------------------------------------------------------------------
172
- #------------------------------------------------------------------------------
173
- #------------------------------------------------------------------------------
174
- #------------------------------------------------------------------------------
175
- #------------------------------------------------------------------------------
176
- #------------------------------------------------------------------------------
177
- #------------------------------------------------------------------------------
178
- #------------------------------------------------------------------------------
179
- #------------------------------------------------------------------------------
180
-
181
-
182
-
183
-
184
-
185
-
186
-
187
-
188
-
189
-
190
-
191
-
192
-
193
-
194
-
195
-
196
-
197
-
198
-