AMQuantME 0.0.4__tar.gz

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.
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2018 The Python Packaging Authority
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: AMQuantME
3
+ Version: 0.0.4
4
+ Summary: A Stringer Divinator Series Product
5
+ Project-URL: Homepage, https://github.com/pypa/sampleproject
6
+ Project-URL: Issues, https://github.com/pypa/sampleproject/issues
7
+ Author-email: Future Jiang <futurestringer@sina.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE.txt
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+
15
+ $E = m * C ** 2$
@@ -0,0 +1 @@
1
+ $E = m * C ** 2$
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["hatchling >= 1.26"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "AMQuantME"
7
+ version = "0.0.4"
8
+ authors = [
9
+ { name="Future Jiang", email="futurestringer@sina.com", maintainers="Future Jiang" },
10
+ ]
11
+ description = "A Stringer Divinator Series Product"
12
+ readme = "README.md"
13
+ requires-python = ">=3.9"
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: OS Independent",
17
+ ]
18
+ license = "MIT"
19
+ license-files = ["LICEN[CS]E*"]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/pypa/sampleproject"
23
+ Issues = "https://github.com/pypa/sampleproject/issues"
@@ -0,0 +1,5 @@
1
+ __version__ = "beta0.0.0.1"
2
+ # __author__ = "Justan"
3
+ # __organization__ = "Future Stringer"
4
+ # __welcom__ = "Welcom from China Quant."
5
+ print("Welcome from FutureStringer!")
@@ -0,0 +1,73 @@
1
+ import pandas as pd
2
+ import pandas_ta as ta
3
+
4
+ from AMQuantME import fetchpv as ftpv
5
+ from AMQuantME import normdf as nd
6
+
7
+ import datetime as dt
8
+ todaydate = dt.date.today()
9
+ todaystr = f"{todaydate.year}-{todaydate.month}-{todaydate.day}"
10
+ print(f"Today is {todaystr}.")
11
+
12
+ # Fetch raw price-volume data of the target index
13
+ exsymb_SSEC = "sh.000001"
14
+ print(f"Fetching {exsymb_SSEC}")
15
+ pv_SSEC = ftpv.bsindexpv(exsymb = exsymb_SSEC, enddate = todaystr)
16
+
17
+ exsymb_CNIA = "sz.399317"
18
+ print(f"Fetching {exsymb_CNIA}")
19
+ pv_CNIA = ftpv.bsindexpv(exsymb = exsymb_CNIA, enddate = todaystr)
20
+
21
+ print(f"Data have been updated to {pv_SSEC['date'][len(pv_SSEC) - 1]}")
22
+
23
+ # Format the DataFrames
24
+ pv_SSEC_norm = nd.normdftype(pv_SSEC)
25
+ pv_CNIA_norm = nd.normdftype(pv_CNIA)
26
+
27
+ # Record the historical max of the indices
28
+ SSEC_hs_max = pv_SSEC_norm.CLOSE.max()
29
+ CNIA_hs_max = pv_CNIA_norm.CLOSE.max()
30
+
31
+ # Truncate interested timeframe and reset the index
32
+ pv_SSEC_timeframe = pv_SSEC_norm[pv_SSEC_norm["DATE"] >= "2024-09-23"]
33
+ pv_SSEC_timeframe.reset_index(drop = True, inplace = True)
34
+
35
+ pv_CNIA_timeframe = pv_CNIA_norm[pv_CNIA_norm["DATE"] >= "2024-09-23"]
36
+ pv_CNIA_timeframe.reset_index(drop = True, inplace = True)
37
+
38
+ # Enhance the original DataFrame with calculated daily Return and other interested items
39
+ SSEC_Daily_df = pv_SSEC_timeframe.copy(deep = True)
40
+
41
+ SSEC_Daily_df["Return"] = SSEC_Daily_df["CLOSE"].pct_change()
42
+ # Compress VOLUME into millions and AMOUNT into billions
43
+ SSEC_Daily_df["Volume_mln"] = SSEC_Daily_df["VOLUME"]/(10**6)
44
+ SSEC_Daily_df = SSEC_Daily_df.drop("VOLUME", axis=1)
45
+
46
+ SSEC_Daily_df["Amount_bln"] = SSEC_Daily_df["AMOUNT"]/(10**9)
47
+ SSEC_Daily_df = SSEC_Daily_df.drop("AMOUNT", axis=1)
48
+
49
+ # Calculate daily volume percent change of SSEC to illustrate price-volume relationship
50
+ SSEC_Daily_df["Vol_chg"] = SSEC_Daily_df["Volume_mln"].pct_change()
51
+ SSEC_Daily_df["Amt_chg"] = SSEC_Daily_df["Amount_bln"].pct_change()
52
+
53
+ # Calculate normalized VARation
54
+ SSEC_Daily_df["PurchasePower"] = SSEC_Daily_df["Volume_mln"] / SSEC_Daily_df["Amount_bln"]
55
+ SSEC_Daily_df["VARatio_norm"] = SSEC_Daily_df["PurchasePower"] / SSEC_Daily_df["PurchasePower"][0]
56
+
57
+ # Do the same to the auxiliary index
58
+ CNIA_Daily_df = pv_CNIA_timeframe.copy(deep = True)
59
+ CNIA_Daily_df["Return"] = CNIA_Daily_df["CLOSE"].pct_change()
60
+ CNIA_Daily_df["Volume_mln"] = CNIA_Daily_df["VOLUME"]/(10**6)
61
+ CNIA_Daily_df = CNIA_Daily_df.drop("VOLUME", axis=1)
62
+ CNIA_Daily_df["Amount_bln"] = CNIA_Daily_df["AMOUNT"]/(10**9)
63
+ CNIA_Daily_df = CNIA_Daily_df.drop("AMOUNT", axis=1)
64
+ CNIA_Daily_df["Vol_chg"] = CNIA_Daily_df["Volume_mln"].pct_change()
65
+ CNIA_Daily_df["PurchasePower"] = CNIA_Daily_df["Volume_mln"] / CNIA_Daily_df["Amount_bln"]
66
+ CNIA_Daily_df["VARatio_norm"] = CNIA_Daily_df["PurchasePower"] / CNIA_Daily_df["PurchasePower"][0]
67
+
68
+ # Calculate employed technical indicators
69
+ rstd = ta.stdev(SSEC_Daily_df["Return"], 5)
70
+ pmacd = ta.macd(SSEC_Daily_df.CLOSE, fast = 5, slow = 10, signal = 7)
71
+ amt_chg_sma = ta.sma(SSEC_Daily_df["Amt_chg"], 10)
72
+ obv = ta.obv(SSEC_Daily_df.CLOSE, SSEC_Daily_df.Volume_mln)
73
+ pvmfi = ta.mfi(SSEC_Daily_df.HIGH, SSEC_Daily_df.LOW, SSEC_Daily_df.CLOSE, SSEC_Daily_df.Volume_mln, length = 10)
@@ -0,0 +1,186 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+ import matplotlib.pyplot as plt
5
+ from matplotlib.ticker import MultipleLocator, FormatStrFormatter
6
+ import matplotlib.dates as mdates
7
+ from matplotlib import font_manager
8
+ my_font = font_manager.FontProperties(fname="C:/WINDOWS/Fonts/STSONG.TTF")
9
+
10
+ from AMQuantME import augcal as ac
11
+
12
+ '''
13
+ Visualize CLOSE, Volumes, Amount, and their changes of the target index during the whole timeframe
14
+ and employ some technical indicators to illustrate the movement of the index.
15
+ '''
16
+
17
+ # Record the first, second, and last time points with in the interested timeframe for calculation and illustration
18
+ date_index = ac.SSEC_Daily_df["DATE"]
19
+ fst_date = f"{date_index[0].year}-{date_index[0].month}-{date_index[0].day}"
20
+ sec_date = f"{date_index[1].year}-{date_index[1].month}-{date_index[1].day}"
21
+ lst_date = f"{date_index[len(date_index)-1].year}-{date_index[len(date_index)-1].month}-{date_index[len(date_index)-1].day}"
22
+
23
+ def express_pict(df = ac.SSEC_Daily_df, aux_df = ac.CNIA_Daily_df):
24
+ fig, axs = plt.subplots(4, 1, figsize = (18, 24), constrained_layout=True)
25
+ date_index = pd.to_datetime(df["DATE"]).dt.to_period("D")
26
+
27
+
28
+ # Subplot 1
29
+ '''Price behavior'''
30
+ # Plot daily CLOSE of the main index (x1) on the left axis
31
+ x1 = df["CLOSE"]
32
+ last_x_ind, last_x_val = len(x1) - 1, x1.iloc[-1]
33
+ axs[0].plot(range(len(x1)), np.where(np.isnan(x1), None, x1),
34
+ linewidth = 1, color = "b", label = f"SSEC, Close: {fst_date} - {lst_date}")
35
+
36
+ # Plot the latest daily close of x1
37
+ axs[0].plot(last_x_ind, last_x_val, "ro", alpha=0.4)
38
+ axs[0].annotate(f"{lst_date:>16}:\n{last_x_val:>16.2f}",
39
+ xy=(last_x_ind, last_x_val), xytext=(-40, 10), textcoords = "offset points", fontsize=10, color="royalblue")
40
+
41
+ # Plot expending mean and up quartile of x1
42
+ exp_mean1 = x1.expanding().mean()
43
+ exp_qu1 = x1.expanding().quantile(0.75)
44
+ axs[0].plot(range(len(x1)), exp_mean1, linewidth = 1, color = "skyblue",
45
+ label = f"SSEC, Close, Expanding Mean, latest{exp_mean1[len(exp_mean1) - 1]:.0f}")
46
+ axs[0].plot(range(len(x1)), exp_qu1, linewidth = 1, color = (174/255, 11/255, 42/255), label = "SSEC, Close, Expanding Upper Quartile")
47
+
48
+
49
+ # axs0_high = x1.mean() + (max(x1) - x1.mean()) * 1.2
50
+ # axs0_low = x1.mean() + (min(x1) - x1.mean()) * 1.2
51
+ axs0_high = 6000
52
+ axs0_low = 2500
53
+ axs[0].set_ylim(axs0_low,axs0_high)
54
+
55
+ # Set sparse display of the date index
56
+ data_locator = MultipleLocator(40)
57
+ axs[0].set_xticks(range(len(x1)), date_index)
58
+ axs[0].xaxis.set_major_locator(data_locator)
59
+ axs[0].legend(loc = 4)
60
+
61
+ # Plot dialy CLOSE of the auxiliary index (x1_1) on the right axis
62
+ axs0_r = axs[0].twinx()
63
+ x1_1 = aux_df["CLOSE"]
64
+ last_x1_1_ind, last_x1_1_val = len(x1_1) - 1, x1_1.iloc[-1]
65
+ axs0_r.plot(range(len(x1_1)), np.where(np.isnan(x1_1), None, x1_1),
66
+ linewidth = 1, color = "orange", label = f"CNIS, Close: {fst_date} - {lst_date}")
67
+ axs0_r.plot(last_x1_1_ind, last_x1_1_val, "ro", alpha=0.5)
68
+ axs0_r.annotate(f"{lst_date:>16}:\n{last_x1_1_val:>16.2f}",
69
+ xy=(last_x1_1_ind, last_x1_1_val), xytext=(-40, 10), textcoords = "offset points", fontsize=10, color="royalblue")
70
+
71
+ # Plot the highest daily close of x1_1 within the timeframe
72
+ max_aux = np.argmax(x1_1)
73
+ max_x1_1_ind, max_x1_1_val = range(len(x1_1))[max_aux], x1_1[max_aux]
74
+ auxmax_date = f"{date_index[max_aux].year}-{date_index[max_aux].month}-{date_index[max_aux].day}"
75
+ axs0_r.plot(max_x1_1_ind, max_x1_1_val, "bo", alpha=0.3)
76
+ axs0_r.annotate(f"{auxmax_date:>16}:\n{max_x1_1_val:>16.2f}",
77
+ xy=(max_x1_1_ind, max_x1_1_val), xytext=(-60, 5), textcoords = "offset points", fontsize=10, color="royalblue")
78
+
79
+ # Plot the historical highest daily close of x1_1
80
+ aux_hs_max = ac.CNIA_hs_max
81
+ axs0_r.axhline(y = aux_hs_max,
82
+ color="magenta", linestyle="--", linewidth=1,
83
+ label=f"CNIA Historical Max: {aux_hs_max:.0f} = {aux_hs_max / max_x1_1_val:.2f} * {max_x1_1_val:.0f}")
84
+
85
+ # axs0_r_high = x1_1.mean() + (max(x1_1) - x1_1.mean()) * 1.2
86
+ # axs0_r_low = x1_1.mean() + (min(x1_1) - x1_1.mean()) * 1.2
87
+ axs0_r_high = 8000
88
+ axs0_r_low = 3500
89
+ axs0_r.set_ylim(axs0_r_low,axs0_r_high)
90
+ axs0_r.legend(loc = 2)
91
+
92
+
93
+ # Subplot 2
94
+ '''Volume behavior'''
95
+ x2 = df["Volume_mln"]/(10**3)
96
+ x2_mean = x2.mean()
97
+ last_x2 = x2.iloc[-1]
98
+ x2_1 = aux_df["Volume_mln"]/(10**3)
99
+
100
+ axs[1].bar(range(len(x2_1)), np.nan_to_num(x2_1),
101
+ width = 1, color = "Orange", alpha = 0.6, label = f"CNIA, Volume in bln shares: {fst_date} - {lst_date}")
102
+ axs[1].bar(range(len(x2)), np.nan_to_num(x2),
103
+ width = 1, color = "Royalblue", alpha = 0.8, label = f"SSEC, Volume in bln shares: {fst_date} - {lst_date}")
104
+
105
+ axs[1].annotate(f"{lst_date:>16}:\n{last_x2:>16.2f}",
106
+ xy=(last_x_ind, last_x2), xytext=(-40, 20), textcoords = "offset points", fontsize=10, color="royalblue")
107
+
108
+ # Plot mean of daily Volume of SSEC during the whole time span
109
+ axs[1].axhline(y = x2_mean,
110
+ color="navy", linestyle="--", linewidth=1, label=f"Volume_mean: {x2_mean:.2f}")
111
+
112
+ varatio_norm_aux = aux_df["VARatio_norm"] * 100
113
+ axs[1].plot(range(len(x2_1)), varatio_norm_aux, linewidth = 2, color = "yellow", alpha = 0.8, label = "CNIA, VARatio_norm*100")
114
+
115
+ varatio_norm = df["VARatio_norm"] * 100
116
+ axs[1].plot(range(len(x2)), varatio_norm, linewidth = 2, color = "magenta", alpha = 0.8, label = f"SSEC, VARatio_norm*100: {round(varatio_norm[len(x2) - 1],2)}")
117
+
118
+ axs1_high = max(x2.mean() + (max(x2) - x2.mean()) * 1.2, x2_1.mean() + (max(x2_1) - x2_1.mean()) * 1.2, 0)
119
+ axs1_low = min(x2.mean() + (min(x2) - x2.mean()) * 1.2, x2_1.mean() + (max(x2_1) - x2_1.mean()) * 1.2, 0)
120
+ axs[1].set_ylim(axs1_low,axs1_high)
121
+ axs[1].set_xticks(range(len(x1)), date_index)
122
+ axs[1].xaxis.set_major_locator(data_locator)
123
+ axs[1].legend(loc = 9)
124
+
125
+
126
+ # Subplot 3
127
+ '''Return behavior'''
128
+ x3 = df["Return"]
129
+ x3_mean = x3.mean()
130
+ axs[2].bar(range(len(x3)), np.nan_to_num(x3), width = 0.5, color = "b", label = f"SSEC, Daily return: {sec_date} - {lst_date}")
131
+ axs[2].axhline(y=x3_mean,
132
+ color="navy", linestyle="--", linewidth=0.5, label=f"return_mean: {x3_mean:.4f}")
133
+
134
+ exp_std3 = x3.expanding().std()
135
+ axs[2].plot(range(len(x3)), exp_std3, linewidth = 1.5, color = "violet", label = "SSEC, Daily return, Expanding Standard Deviation")
136
+
137
+ x3_2 = ac.pmacd.MACDh_5_10_7 / 200
138
+ axs[2].bar(range(len(x3_2)), np.nan_to_num(x3_2), width = 0.5, color = "c", alpha = 0.6, label = "SSEC, CLOSE, MACD_5_10_7")
139
+
140
+ x3_3 = ac.rstd
141
+ axs[2].plot(range(len(x3_3)), x3_3, linewidth = 1.5, color = "orange", label = "SSEC, Daily return, Rolling Std_5")
142
+
143
+ axs[2].set_xticks(range(len(x3)), date_index)
144
+ axs[2].xaxis.set_major_locator(data_locator)
145
+ axs[2].legend(loc = 4)
146
+
147
+ # Subplot 4
148
+ '''Amount behavior'''
149
+ x4 = df["Amt_chg"]
150
+ x4_mean = x4.mean()
151
+ axs[3].plot(range(len(x4)), np.where(np.isnan(x4), None, x4),
152
+ linewidth = 1, color = "b", label = f"SSEC, Amount Percentage Change: {sec_date} - {lst_date}")
153
+ axs[3].axhline(y = x4_mean,
154
+ color="navy", linestyle="--", linewidth=0.5, label=f"Amount Percentage Change_mean: {x4_mean:.4f}")
155
+
156
+ sma4 = ac.amt_chg_sma
157
+ axs[3].plot(range(len(x4)), sma4, linewidth = 2, color = (174/255, 11/255, 42/255), label = "SSEC, Amount Pct. Change, SMA_10")
158
+
159
+ x4_2 = ac.obv / (10 ** 7)
160
+ axs[3].bar(range(len(x4_2)), np.nan_to_num(x4_2),
161
+ width = 0.5, color = "skyblue", alpha = 0.6, label = "SSEC, OBV")
162
+
163
+ max_x4_2 = np.argmax(x4_2)
164
+ max_x4_2_ind, max_x4_2_val = range(len(x4_2))[max_x4_2], x4_2[max_x4_2]
165
+ max_x4_2date = f"{date_index[max_x4_2].year}-{date_index[max_x4_2].month}-{date_index[max_x4_2].day}"
166
+
167
+ axs[3].plot(max_x4_2_ind, max_x4_2_val, "ro", alpha=0.5)
168
+ axs[3].annotate(f"{max_x4_2date:>16}",
169
+ xy=(max_x4_2_ind, max_x4_2_val), xytext=(-50, 10), textcoords = "offset points", fontsize=10, color="royalblue")
170
+
171
+ axs[3].plot(range(len(x4)), ac.pvmfi / 100, linewidth = 1.5, alpha = 0.8, linestyle = "--", color = "red", label = "SSEC, MFI_10")
172
+
173
+ axs[3].set_xticks(range(len(x4)), date_index)
174
+ axs[3].xaxis.set_major_locator(data_locator)
175
+ axs[3].legend(loc = 9)
176
+
177
+ fig.suptitle(
178
+ ("Chinese SSEC Index Daily Close, Volume, Amount and Their Daily Percentage Changes: "
179
+ ) + (f"{fst_date} - {lst_date}")
180
+ )
181
+
182
+ plt.savefig("Chinese SSEC Daily Closes Volumes Amounts and Changes_beta002.png")
183
+ plt.show()
184
+ print("For technical indicator explanation, please refer to https://mp.weixin.qq.com/s/PU70IyS-ByyIen5iTnuwfQ")
185
+
186
+ return
@@ -0,0 +1,23 @@
1
+ import pandas as pd
2
+ import baostock as bs
3
+
4
+ def bsindexpv(exsymb, enddate):
5
+ '''
6
+ As instance code, taking CSI A Shares("sz.399317")
7
+ end_date form: '2026-01-27'
8
+ adjustflag: "1" for hfq, "2" for qfq, "3" for bfq
9
+ tradestatus: 1 for in trading, 0 for out of trading
10
+ Indices has no adjustflag
11
+ '''
12
+ lg = bs.login()
13
+ pv_bs = bs.query_history_k_data_plus(exsymb,
14
+ "date,code,open,high,low,close,volume,amount",
15
+ start_date = '1900-01-01', end_date = enddate,
16
+ frequency = "d")
17
+ _result_list = []
18
+ while (pv_bs.error_code == '0') & pv_bs.next():
19
+ _result_list.append(pv_bs.get_row_data())
20
+ _result = pd.DataFrame(_result_list, columns = pv_bs.fields)
21
+ bs.logout()
22
+
23
+ return _result
@@ -0,0 +1,20 @@
1
+ import pandas as pd
2
+
3
+ def normdftype(pvdf):
4
+ # Change data type of fields
5
+ df = pvdf.copy()
6
+ df["date"] = pd.to_datetime(df["date"])
7
+
8
+ for field in ["open", "high", "low", "close", "volume", "amount"]:
9
+ df[field] = df[field].astype(float)
10
+
11
+ # Keep appropriate decimal
12
+ df.round({"open":4, "high":4, "low":4, "close":4, "volume":4, "amount":4})
13
+
14
+ # Rename the original fields
15
+ original_rename_dict = {"date":"DATE", "code":"CODE",
16
+ "open":"OPEN", "high":"HIGH", "low":"LOW", "close":"CLOSE",
17
+ "volume":"VOLUME", "amount":"AMOUNT"}
18
+ df.rename(columns = original_rename_dict, inplace = True)
19
+
20
+ return df