siat 3.10.125__py3-none-any.whl → 3.10.126__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.126.dist-info}/METADATA +234 -226
  7. siat-3.10.126.dist-info/RECORD +76 -0
  8. {siat-3.10.125.dist-info → siat-3.10.126.dist-info}/WHEEL +1 -1
  9. {siat-3.10.125.dist-info → siat-3.10.126.dist-info/licenses}/LICENSE +0 -0
  10. {siat-3.10.125.dist-info → siat-3.10.126.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
@@ -1,370 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- 本模块功能:马科维茨投资组合快速示意图
4
- 所属工具包:证券投资分析工具SIAT
5
- SIAT:Security Investment Analysis Tool
6
- 创建日期:2023年7月8日
7
- 最新修订日期:2023年7月9日
8
- 作者:王德宏 (WANG Dehong, Peter)
9
- 作者单位:北京外国语大学国际商学院
10
- 作者邮件:wdehong2000@163.com
11
- 版权所有:王德宏
12
- 用途限制:仅限研究与教学使用,不可商用!商用需要额外授权。
13
- 特别声明:作者不对使用本工具进行证券投资导致的任何损益负责!
14
- """
15
-
16
- #==============================================================================
17
- #关闭所有警告
18
- import warnings; warnings.filterwarnings('ignore')
19
- from siat.security_prices import *
20
-
21
- #==============================================================================
22
- import matplotlib.pyplot as plt
23
-
24
- #统一设定绘制的图片大小:数值为英寸,1英寸=100像素
25
- plt.rcParams['figure.figsize']=(12.8,7.2)
26
- plt.rcParams['figure.dpi']=300
27
- plt.rcParams['font.size'] = 13
28
- plt.rcParams['xtick.labelsize']=11 #横轴字体大小
29
- plt.rcParams['ytick.labelsize']=11 #纵轴字体大小
30
-
31
- title_txt_size=16
32
- ylabel_txt_size=14
33
- xlabel_txt_size=14
34
- legend_txt_size=14
35
-
36
- #设置绘图风格:网格虚线
37
- plt.rcParams['axes.grid']=True
38
- plt.rcParams['grid.color']='steelblue'
39
- plt.rcParams['grid.linestyle']='dashed'
40
- plt.rcParams['grid.linewidth']=0.5
41
- plt.rcParams['axes.facecolor']='whitesmoke'
42
-
43
- #处理绘图汉字乱码问题
44
- import sys; czxt=sys.platform
45
- if czxt in ['win32','win64']:
46
- plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置默认字体
47
- mpfrc={'font.family': 'SimHei'}
48
-
49
- if czxt in ['darwin']: #MacOSX
50
- plt.rcParams['font.family']= ['Heiti TC']
51
- mpfrc={'font.family': 'Heiti TC'}
52
-
53
- if czxt in ['linux']: #website Jupyter
54
- plt.rcParams['font.family']= ['Heiti TC']
55
- mpfrc={'font.family':'Heiti TC'}
56
-
57
- # 解决保存图像时'-'显示为方块的问题
58
- plt.rcParams['axes.unicode_minus'] = False
59
- #==============================================================================
60
-
61
- # 全局引用,函数中无需再import
62
- from datetime import date
63
- import pandas as pd
64
- import numpy as np
65
- import scipy.optimize as opt
66
- import seaborn as sns
67
-
68
- #==============================================================================
69
- if __name__=='__main__':
70
- components = {
71
- 'AAPL':'苹果',
72
- 'AMZN':'亚马逊',
73
- 'GOOGL':'谷歌',
74
- 'BABA':'阿里巴巴'
75
- }
76
-
77
- start='2016-1-1'
78
- end='2017-12-31'
79
-
80
- risk_free=0.015
81
- simulation=25000
82
- price_trend=True
83
- feasible_set=True
84
- efficient_frontier=True
85
- MOP=True #Markowitz Optimized Point
86
- MSR=True #Maximized Sharpe Ratio
87
-
88
- ef_adjust=1.008
89
-
90
- markowitz_sharpe(components,start,end)
91
- markowitz_sharpe(components,start,end,ef_adjust=1.008)
92
- markowitz_sharpe(components,start,end,MOP=True)
93
- markowitz_sharpe(components,start,end,MSR=True)
94
- markowitz_sharpe(components,start,end,MOP=True,MSR=True)
95
-
96
- def markowitz_sharpe(components,start,end,risk_free=0.015,simulation=25000, \
97
- price_trend=True,feasible_set=True,efficient_frontier=True, \
98
- MOP=False,MSR=False,ef_adjust=1.008):
99
- """
100
- 功能:使用期间内夏普比率寻找马科维茨最优点,绘制可行集、有效边界和最优点
101
- components:投资组合成分股票代码与名称,节省搜索股票名称的时间
102
- start,end:开始/结束日期
103
- risk_free:人工指定无风险利率,节省搜索时间,减少搜索失败概率
104
- simulation:生成可行集的模拟次数
105
- price_trend:是否绘制各个成分股票的价格走势,采用股价/起点股价的比值,可一图绘制多只股票
106
- feasible_set:是否绘制可行集
107
- efficient_frontier:是否绘制有效边界
108
- MOP:是否标注MOP点,Markowitz Optimized Point,可能与MSR点不同
109
- MSR:是否标注MSR点,Maximized Sharpe Ratio,可能与MOP点不同
110
- ef_adjust:对有效边界曲线微调,使其处于可行集的上边沿
111
- """
112
- #获取股票数据
113
- tickers=list(components)
114
- stock_data=get_prices(tickers,start,end)['Close']
115
- stock_data.rename(columns=components,inplace=True)
116
-
117
- stock_data=stock_data.iloc[::-1]
118
- #stock_data.head()
119
-
120
- #画出收盘价走势图
121
- sns.set_style("whitegrid")#横坐标有标线,纵坐标没有标线,背景白色
122
- sns.set_style("darkgrid") #默认,横纵坐标都有标线,组成一个一个格子,背景稍微深色
123
- sns.set_style("dark")#背景稍微深色,没有标线线
124
- sns.set_style("white")#背景白色,没有标线线
125
- sns.set_style("ticks")#xy轴都有非常短的小刻度
126
- sns.despine(offset=30,left=True)#去掉上边和右边的轴线,offset=30表示距离轴线(x轴)的距离,left=True表示左边的轴保留
127
- sns.set(font='SimHei',rc={'figure.figsize':(10,6)})# 图片大小和中文字体设置
128
-
129
- # 绘制各个成分股票的价格走势,采用股价/起点股价的比值,可一图绘制多只股票
130
- if price_trend:
131
- (stock_data/stock_data.iloc[0]).plot()
132
- titletxt='投资组合的成分股价格走势示意图'
133
- plt.xlabel('')
134
- plt.ylabel("价格/起点值")
135
- plt.title(titletxt)
136
- plt.show()
137
-
138
- #------------------------------------------------------------------------------
139
- # 计算收益率和风险
140
- # 收益率
141
- R=stock_data/stock_data.shift(1)-1
142
- #R.head()
143
-
144
- # 对数收益率
145
- log_r=np.log(stock_data/stock_data.shift(1))
146
- #log_r.head()
147
-
148
- # 年化收益率
149
- r_annual=np.exp(log_r.mean()*250)-1
150
- #r_annual
151
-
152
- # 风险
153
- std = np.sqrt(log_r.var() * 250)#假设协方差为0
154
- #std
155
-
156
- #------------------------------------------------------------------------------
157
- # 投资组合的收益和风险
158
- def gen_weights(n):
159
- w=np.random.rand(n)
160
- return w /sum(w)
161
-
162
- n=len(list(tickers))
163
- w=gen_weights(n)
164
- #list(zip(r_annual.index,w))
165
-
166
- #投资组合收益
167
- def port_ret(w):
168
- return -np.sum(w*r_annual)
169
- #port_ret(w)
170
-
171
- #投资组合的风险
172
- def port_std(w):
173
- return np.sqrt((w.dot(log_r.cov()*250).dot(w.T)))
174
- #port_std(w)
175
-
176
- #若干投资组合的收益和风险
177
- def gen_ports(times):
178
- for _ in range(times):#生成不同的组合
179
- w=gen_weights(n)#每次生成不同的权重
180
- yield (port_std(w),port_ret(w),w)#计算风险和期望收益 以及组合的权重情况
181
-
182
- # 投资组合模拟次数
183
- print("\n Generating portfolio feasible set ...")
184
- df=pd.DataFrame(gen_ports(25000),columns=["std","ret","w"])
185
- #df.head()
186
- std_min=df['std'].min()
187
- std_max=df['std'].max()
188
-
189
- #------------------------------------------------------------------------------
190
- #计算可行集中每个投资组合期间内的夏普比率
191
- df['sharpe'] = (df['ret'] - risk_free) / df['std']
192
- #list(zip(r_annual.index, df.loc[df.sharpe.idxmax()].w))
193
-
194
- # 画出投资可行集
195
- df_ef=df.rename(columns={'std':'收益率标准差','ret':'收益率','sharpe':'夏普比率'})
196
- fig, ax = plt.subplots()
197
- titletxt="马科维茨投资组合示意图"
198
- plt.title(titletxt)
199
-
200
- #df.plot.scatter('std','ret',c='sharpe',s=30,alpha=0.3,cmap='cool',marker='o',ax=ax)
201
- df_ef.plot.scatter('收益率标准差','收益率',c='夏普比率',s=30,alpha=0.3,cmap='cool',marker='o',ax=ax)
202
- plt.style.use('ggplot')
203
- plt.rcParams['axes.unicode_minus'] = False# 显示负号
204
-
205
- #绘制有效边界曲线
206
- if efficient_frontier:
207
- frontier=pd.DataFrame(columns=['std','ret'])
208
- for std in np.linspace(std_min,std_max):
209
- res=opt.minimize(lambda x:-port_ret(x),
210
- x0=((1/n),)*n,
211
- method='SLSQP',
212
- bounds=((0,1),)*n,
213
- constraints=[
214
- {"fun":lambda x:port_std(x)-std,"type":"eq"},
215
- {"fun":lambda x:(np.sum(x)-1),"type":"eq"}
216
- ])
217
- if res.success:
218
- frontier=frontier.append({"std":std,"ret":-res.fun},ignore_index=True)
219
-
220
- # 略微上调有效边界
221
- frontier2=frontier.copy()
222
- """
223
- fstd0=frontier2['std'].values[0]
224
- frontier2['ret']=frontier2['ret'] * ef_adjust*fstd0/frontier2['std']
225
- """
226
- frontier2['ret']=frontier2['ret'] * ef_adjust
227
- frontier3=frontier2.rename(columns={'std':'收益率标准差','ret':'收益率'})
228
- frontier3.plot('收益率标准差','收益率',label='有效边界',lw=3,c='blue',ax=ax)
229
- plt.legend()
230
- fig
231
-
232
- #------------------------------------------------------------------------------
233
- #单个投资组合的收益和风险
234
- def one_ports(w):
235
- return (port_std(w),port_ret(w),w)#计算风险和期望收益 以及组合的权重情况
236
-
237
- # 计算最优资产配置情况
238
- if MOP:
239
- res=opt.minimize(lambda x:-((port_ret(x)-risk_free)/port_std(x)),
240
- x0=((1/n),)*n,
241
- method='SLSQP',
242
- bounds=((0,1),)*n,
243
- constraints={"fun":lambda x:(np.sum(x)-1), "type":"eq"})
244
-
245
- ax.scatter(port_std(res.x),port_ret(res.x),label='MOP点',marker="*",c="brown",s=300)
246
- ax.legend()
247
- fig
248
-
249
- print("\n***马科维茨优化后组合(MOP)配置:")
250
- ticker_names=components.values()
251
- best_proportion=res.x.round(3)
252
- #best_config = dict(zip(tickers, best_proportion))
253
- best_config = dict(zip(ticker_names, best_proportion))
254
- print(best_config)
255
-
256
- #计算期间内投资组合收益率均值
257
- best_std,best_ret,_=one_ports(best_proportion)
258
- print("收益率标准差:",round(best_std,4),"\b,投资组合收益率:",round(best_ret,4))
259
-
260
- """
261
- #绘制MOP组合价格走势
262
- stock_data2=stock_data.copy()
263
- stock_data2['MOP']=stock_data2.dot(best_proportion)
264
- (stock_data2/stock_data2.iloc[0]).plot()
265
-
266
- titletxt='投资组合及其成分股价格走势示意图'
267
- plt.xlabel('')
268
- plt.ylabel("价格/起点值")
269
- plt.title(titletxt)
270
- plt.show()
271
- """
272
-
273
- if MSR:
274
- sharpe_max=df['sharpe'].max()
275
- std_msr=df[df['sharpe']==sharpe_max]['std'].values[0]
276
- ret_msr=df[df['sharpe']==sharpe_max]['ret'].values[0]
277
- w_msr=df[df['sharpe']==sharpe_max]['w'].values[0]
278
-
279
- ax.scatter(std_msr,ret_msr,label='MSR点',marker="*",c="orange",s=300)
280
- ax.legend()
281
- fig
282
-
283
- print("\n***最大夏普比率组合(MSR)配置:")
284
- ticker_names=components.values()
285
- best_proportion=w_msr
286
- best_config = dict(zip(ticker_names, best_proportion.round(3)))
287
- print(best_config)
288
-
289
- #计算期间内投资组合收益率均值
290
- best_std,best_ret,_=one_ports(best_proportion)
291
- print("收益率标准差:",round(best_std,4),"\b,投资组合收益率:",round(best_ret,4))
292
-
293
- #绘制MOP组合价格走势
294
- """
295
- stock_data3=stock_data.copy()
296
- stock_data3['MOP']=stock_data3.dot(best_proportion)
297
- (stock_data3/stock_data3.iloc[0]).plot()
298
-
299
- titletxt='投资组合及其成分股价格走势示意图'
300
- plt.xlabel('')
301
- plt.ylabel("价格/起点值")
302
- plt.title(titletxt)
303
- plt.show()
304
- """
305
-
306
- if MOP or MSR:
307
- std_min=df['std'].min()
308
- ret_gmvs=df[df['std']==std_min]['ret'].values[0]
309
- w_gmvs=df[df['std']==std_min]['w'].values[0]
310
-
311
- ax.scatter(std_min,ret_gmvs,label='LVS点',marker="o",c="green",s=300)
312
- ax.legend()
313
- fig
314
-
315
- print("\n***最小波动风险组合(LVS)配置:")
316
- ticker_names=components.values()
317
- best_proportion=w_gmvs
318
- best_config = dict(zip(ticker_names, best_proportion.round(3)))
319
- print(best_config)
320
-
321
- #计算期间内投资组合收益率均值
322
- best_std,best_ret,_=one_ports(best_proportion)
323
- print("收益率标准差:",round(best_std,4),"\b,投资组合收益率:",round(best_ret,4))
324
-
325
- #绘制GMVS组合价格走势
326
- """
327
- stock_data4=stock_data.copy()
328
- stock_data4['GMVS']=stock_data4.dot(best_proportion)
329
- (stock_data4/stock_data4.iloc[0]).plot()
330
-
331
- titletxt='投资组合及其成分股价格走势示意图'
332
- plt.xlabel('')
333
- plt.ylabel("价格/起点值")
334
- plt.title(titletxt)
335
- plt.show()
336
- """
337
-
338
- return
339
-
340
-
341
- #------------------------------------------------------------------------------
342
- #------------------------------------------------------------------------------
343
- #------------------------------------------------------------------------------
344
- #------------------------------------------------------------------------------
345
- #------------------------------------------------------------------------------
346
- #------------------------------------------------------------------------------
347
- #------------------------------------------------------------------------------
348
- #------------------------------------------------------------------------------
349
- #------------------------------------------------------------------------------
350
- #------------------------------------------------------------------------------
351
- #------------------------------------------------------------------------------
352
-
353
-
354
-
355
-
356
-
357
-
358
-
359
-
360
-
361
-
362
-
363
-
364
-
365
-
366
-
367
-
368
-
369
-
370
-
siat/markowitz_test.py DELETED
@@ -1,164 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
-
3
- #==============================================================================
4
- import os; os.chdir("S:/siat"); from siat import *
5
- #==============================================================================
6
-
7
- #定义投资组合:我的组合001
8
- Market={'Market':('US','^GSPC','自选组合1号')}
9
- Stocks1={'AAPL':.02,'MSFT':.01,'AMZN':.03,'FB':.04,'GOOG':.05}
10
- Stocks2={'XOM':.2,'JNJ':.24,'JPM':.05,'TSLA':.06,'SBUX':.3}
11
- portfolio=dict(Market,**Stocks1,**Stocks2)
12
-
13
- #比较业绩表现:我的组合001,等权重组合,流动性组合
14
- pf_info=portfolio_expret(portfolio,'2019-12-31')
15
- pf_info_noRF=portfolio_expret(portfolio,'2019-12-31',RF=False)
16
-
17
- #观察投资组合成分股收益率之间的相关性
18
- portfolio_corr(pf_info)
19
- portfolio_corr(pf_info_noRF)
20
-
21
- #观察马科维茨可行集:收益率-标准差,接近椭圆形,可用于解释有效边界(左上沿)
22
- es=portfolio_es(pf_info,simulation=50000)
23
- #------------------------------------------------------------------------------
24
-
25
- portfolio_optimize_strategy(pf_info,ratio='sharpe',simulation=1000)
26
- portfolio_optimize_strategy(pf_info,ratio='sharpe',simulation=1000,RF=False)
27
-
28
- portfolio_optimize_strategy(pf_info,ratio='sortino',simulation=1000)
29
- portfolio_optimize_strategy(pf_info,ratio='sortino',simulation=1000,RF=False)
30
-
31
- portfolio_optimize_strategy(pf_info,ratio='alpha',simulation=1000)
32
- portfolio_optimize_strategy(pf_info,ratio='alpha',simulation=1000,RF=False)
33
-
34
- portfolio_optimize_strategy(pf_info,ratio='treynor',simulation=1000)
35
- portfolio_optimize_strategy(pf_info,ratio='treynor',simulation=1000,RF=False)
36
-
37
-
38
- #------------------------------------------------------------------------------
39
- #详细过程
40
-
41
- #观察马科维茨可行集:风险溢价-标准差,用于夏普比率优化
42
- es_sharpe=portfolio_es_sharpe(pf_info,simulation=50000)
43
- [[portfolio,_,_,_],_]=pf_info
44
- pname=portfolio_name(portfolio)
45
-
46
- #寻找夏普比率最优点:最大夏普比率策略MSR和最小风险策略GMV
47
- MSR_weights,GMVS_weights,portfolio_returns_sharpe=portfolio_optimize_sharpe(es_sharpe)
48
-
49
- #现有投资组合的排名
50
- portfolio_ranks(portfolio_returns_sharpe)
51
-
52
- #打印业绩表现:MSR组合和GMV组合
53
- portfolio_expectation2('MSR组合',pf_info,MSR_weights)
54
- portfolio_expectation2('GMVS组合',pf_info,GMV_weights)
55
-
56
- #绘制投资组合策略业绩比较曲线
57
- name_list=[pname,'MSR组合','GMVS组合']
58
- portfolio_expret_plot(portfolio_returns_sharpe,name_list)
59
-
60
- #------------------------------------------------------------------------------
61
- #观察马科维茨可行集:索替诺比率优化
62
- es_sortino=portfolio_es_sortino(pf_info,simulation=50000)
63
-
64
- #寻找比率最优点:
65
- MSO_weights,GML_weights,portfolio_returns_sortino=portfolio_optimize_sortino(es_sortino)
66
-
67
- #现有投资组合的排名
68
- portfolio_ranks(portfolio_returns_sortino)
69
-
70
- #打印业绩表现:MSO组合和GML组合
71
- portfolio_expectation2('MSO组合',pf_info,MSO_weights)
72
- portfolio_expectation2('GML组合',pf_info,GML_weights)
73
-
74
- #绘制投资组合策略业绩比较曲线
75
- portfolio_expret_plot(portfolio_returns_sortino)
76
-
77
- #------------------------------------------------------------------------------
78
- #观察马科维茨可行集:阿尔法优化
79
- es_alpha=portfolio_es_alpha(pf_info,simulation=50000)
80
-
81
- #寻找比率最优点:
82
- MAR_weights,GMBA_weights,portfolio_returns_alpha=portfolio_optimize_alpha(es_alpha)
83
-
84
- #现有投资组合的排名
85
- portfolio_ranks(portfolio_returns_alpha)
86
-
87
- #打印业绩表现:MAR组合和GMB组合
88
- portfolio_expectation2('MAR组合',pf_info,MAR_weights)
89
- portfolio_expectation2('GMBA组合',pf_info,GMB_weights)
90
-
91
- #绘制投资组合策略业绩比较曲线
92
- portfolio_expret_plot(portfolio_returns_alpha)
93
-
94
- #------------------------------------------------------------------------------
95
- #观察马科维茨可行集:特雷诺比率优化
96
- es_treynor=portfolio_es_treynor(pf_info,simulation=50000)
97
-
98
- #寻找比率最优点:
99
- MTR_weights,GMBT_weights,portfolio_returns_treynor=portfolio_optimize_treynor(es_treynor)
100
-
101
- #现有投资组合的排名
102
- portfolio_ranks(portfolio_returns_treynor)
103
-
104
- #打印业绩表现:MTR组合和GMB2组合
105
- portfolio_expectation2('MTR组合',pf_info,MTR_weights)
106
- portfolio_expectation2('GMBT组合',pf_info,GMB2_weights)
107
-
108
- #绘制投资组合策略业绩比较曲线
109
- portfolio_expret_plot(portfolio_returns_treynor)
110
-
111
-
112
-
113
-
114
-
115
- #==============================================================================
116
- import os; os.chdir("S:/siat")
117
- from siat.markowitz import *
118
-
119
- Market={'Market':('US','^GSPC')}
120
- Stocks={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09,'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
121
- portfolio=dict(Market,**Stocks)
122
-
123
- pf_info=portfolio_cumret(portfolio,'2019-12-31')
124
- portfolio_covar(pf_info)
125
- portfolio_corr(pf_info)
126
- portfolio_expectation(pf_info)
127
-
128
- es_info=portfolio_es(pf_info,simulation=50000)
129
-
130
- df=portfolio_MSR_GMV(es_info)
131
-
132
- stocks=['IBM','WMT','AAPL','C','MSFT']
133
- ef=portfolio_ef(stocks,'2019-1-1','2020-8-1')
134
-
135
-
136
-
137
-
138
-
139
- _,_,tickerlist,sharelist=decompose_portfolio(portfolio)
140
-
141
- today='2020-12-31'
142
- pastyears=1
143
-
144
- pf_info=portfolio_cumret(portfolio,'2020-12-31')
145
-
146
- portfolio_covar(pf_info)
147
-
148
- portfolio_corr(pf_info)
149
-
150
-
151
- #定义投资组合
152
- Market={'Market':('US','^GSPC')}
153
- Stocks={'BABA':.4,'JD':.3,'PDD':.2,'VIPS':.1}
154
- portfolio=dict(Market,**Stocks)
155
-
156
- #搜寻该投资组合中所有成分股的价格信息,默认观察期为一年,pastyears=1
157
- pf_info=portfolio_cumret(portfolio,'2020-11-30',pastyears=1)
158
-
159
- #生成了投资组合的可行集
160
- es_info=portfolio_es(pf_info,simulation=50000)
161
- es_info10=portfolio_es(pf_info,simulation=100000)
162
-
163
- #寻找投资组合的MSR优化策略点和GMV优化策略点
164
- psr=portfolio_MSR_GMV(es_info)
siat/markowitz_test2.py DELETED
@@ -1,69 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- import os; os.chdir('S:/siat')
3
- from siat import *
4
-
5
- #==============================================================================
6
- # 近三年期间
7
- start='2023-1-1'; end='2023-4-10'
8
-
9
- # 一级行业
10
- print_industry_sw(itype='I')
11
-
12
- # 二级行业
13
- print_industry_sw(itype='T')
14
-
15
- # 三级行业
16
- print_industry_sw(itype='3')
17
-
18
- # 搜索行业数据并进行初步计算:基于申万行业分类
19
- # 本步骤可能耗费较多时间,具体取决于网速和电脑计算速度
20
- idf1,idfall1=get_industry_info_sw(start,end,itype='I')
21
-
22
- idf2,idfall2=get_industry_info_sw(start,end,itype='T')
23
-
24
- idf3,idfall3=get_industry_info_sw(start,end,itype='3')
25
-
26
- # 收益排名
27
- idf=idf1
28
- df1=rank_industry_sw(idf1,measure='Exp Ret%',
29
- axisamp=0.9)
30
-
31
- df2=rank_industry_sw(idf2,measure='Exp Ret%')
32
-
33
- industries=['游戏Ⅲ','通信网络设备及器件','国际工程','横向通用软件','激光设备','集成电路封测','安防设备']
34
- df3=rank_industry_sw(idf3,measure='Exp Ret%',industries=industries,axisamp=2.5)
35
-
36
-
37
- # 选择感兴趣的行业,观察其持有收益率的发展趋势
38
- industries1=industry_sw_codes(['电力设备','食品饮料','国防军工','银行'])
39
- df1i=compare_industry_sw(idfall,industries1,measure='Exp Ret%')
40
-
41
- # 收益-风险性价比
42
-
43
- # 全行业,夏普比率横向对比
44
- df1sharpe=rank_industry_sw_sharpe(idfall,base_return='Exp Ret%',axisamp=0.8)
45
-
46
- # 感兴趣行业,时间序列对比
47
- df1isharpe=compare_industry_sw_sharpe(idfall,industries1,
48
- base_return='Exp Ret%')
49
-
50
-
51
-
52
-
53
-
54
-
55
-
56
- #==============================================================================
57
-
58
- # 一级行业
59
- print_industry_sw(itype='I')
60
-
61
- # 搜索行业数据并进行初步计算:基于申万行业分类
62
- # 本步骤可能耗费较多时间,具体取决于网速和电脑计算速度
63
- idf1,idfall1=get_industry_info_sw(start,end,itype='I')
64
- idf=idf1
65
-
66
- industries=['801770', '801720', '医药生物']
67
- df1=rank_industry_sw(idf1,measure='Exp Ret%',industries=industries,axisamp=0.9,printout=True)
68
-
69
- #==============================================================================
siat/ml_cases_example1.py DELETED
@@ -1,60 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- 作者:王德宏
4
- 功能:测试ml_cases中的函数功能,仅限测试用
5
- """
6
-
7
- from siat import *
8
- dfprice=get_stock_price('MSFT','3/24/2022', '1/1/2015')
9
- dfprice.head(5)
10
- dfprice.tail(3)
11
-
12
- dfprice[dfprice.Date == '2019-03-20']
13
- dfprice[(dfprice.Date>='2019-03-11') & (dfprice.Date<='2019-03-15')]
14
-
15
- X,y,ndprice=make_price_sample(dfprice,1,240,20)
16
-
17
- from sklearn.model_selection import train_test_split
18
- X_train,X_test,y_train,y_test= train_test_split(X,y,random_state=0)
19
-
20
- from sklearn.neighbors import KNeighborsRegressor
21
- reg=KNeighborsRegressor(n_neighbors=10,weights='distance')
22
-
23
- reg.fit(X_train,y_train)
24
- reg.score(X_train,y_train)
25
- reg.score(X_test,y_test)
26
-
27
- X_new=ndprice[0,0:20]
28
- y_new=reg.predict(X_new)
29
-
30
- print(y_new)
31
-
32
- get_stock_price('MSFT', '3/25/2022', '3/24/2022')
33
-
34
- bestmodel,bestk,bestscore_train,bestscore_test=bestKN(X,y)
35
- print(bestk,bestscore_train,bestscore_test)
36
-
37
- y_new=bestmodel.predict(X_new)
38
- print(y_new)
39
-
40
- bestmodel,bestk,bestscore_train,bestscore_test,bestrate=bestKN2(X,y)
41
- print(bestk,bestscore_train,bestscore_test,bestrate)
42
-
43
- y_new=bestmodel.predict(X_new)
44
- print(y_new)
45
-
46
-
47
- bestmodel,bestf,bestk,bestscore_train,bestscore_test=bestFN(dfprice,1,240)
48
- print(bestf,bestk,bestscore_train,bestscore_test)
49
- X_new=ndprice[0,0:bestf]
50
- y_new=bestmodel.predict(X_new)
51
- print(y_new)
52
-
53
- bestmodel,bestf,bestk,bestscore_train,bestscore_test,bestrate=bestFN2(dfprice,1,240)
54
- print(bestf,bestk,bestscore_train,bestscore_test)
55
- X_new=ndprice[0,0:bestf]
56
- y_new=bestmodel.predict(X_new)
57
- print(y_new)
58
-
59
- fprice,fprice2=forecast_stock_price2(dfprice,1,240)
60
- forecast_stock_price('MSFT','2022-3-24',1)