-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweekly_review.py
More file actions
186 lines (159 loc) · 7.42 KB
/
Copy pathweekly_review.py
File metadata and controls
186 lines (159 loc) · 7.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
"""Weekly Portfolio Review - 2026-05-23"""
import baostock as bs
import pandas as pd
import numpy as np
lg = bs.login()
# ============================================================
# Portfolio definitions (建仓日 2026-05-15)
# ============================================================
ai_portfolio = {
"sh.600000": {"name": "浦发银行", "weight": 4.75},
"sh.601800": {"name": "中国交建", "weight": 4.75},
"sz.000877": {"name": "天山股份", "weight": 4.75},
"sh.601186": {"name": "中国铁建", "weight": 4.75},
"sh.600373": {"name": "中文传媒", "weight": 4.75},
"sh.600997": {"name": "开滦股份", "weight": 4.75},
"sh.601686": {"name": "友发集团", "weight": 4.75},
"sh.601166": {"name": "兴业银行", "weight": 4.75},
}
user_portfolio = {
"sz.002050": {"name": "三花智控", "weight": 4.125},
"sz.002938": {"name": "鹏鼎控股", "weight": 4.125},
"sh.600584": {"name": "长电科技", "weight": 4.125},
"sh.688820": {"name": "盛合晶微", "weight": 4.125},
"sh.688212": {"name": "澳华内镜", "weight": 5.0},
"sz.003031": {"name": "中瓷电子", "weight": 4.125},
"sh.600941": {"name": "中国移动", "weight": 4.125},
"sh.600373": {"name": "中文传媒", "weight": 4.125},
"sh.600406": {"name": "国电南瑞", "weight": 4.125},
}
base_date = "2026-05-15"
current_date = "2026-05-23"
def get_prices(code, start, end):
rs = bs.query_history_k_data_plus(code,
"date,close,pctChg,amount",
start_date=start, end_date=end,
frequency="d", adjustflag="3")
data = []
while (rs.error_code == "0") & rs.next():
data.append(rs.get_row_data())
if not data:
return None
df = pd.DataFrame(data, columns=rs.fields)
df["date"] = pd.to_datetime(df["date"])
df = df.sort_values("date")
df["close"] = pd.to_numeric(df["close"], errors="coerce")
df["pctChg"] = pd.to_numeric(df["pctChg"], errors="coerce")
df["amount"] = pd.to_numeric(df["amount"], errors="coerce")
return df
# ============================================================
# Part 1: Portfolio Returns
# ============================================================
print("=" * 90)
print(f"WEEKLY PORTFOLIO REVIEW ({base_date} → {current_date})")
print("=" * 90)
for label, portfolio in [("🤖 AI (S1纯价值)", ai_portfolio), ("👤 用户 (成长+价值)", user_portfolio)]:
total_weight = sum(v["weight"] for v in portfolio.values())
print(f"\n{label} | 总资金: {total_weight:.2f}万")
print(f" {'Stock':<10} {'5/15价':>8} {'5/23价':>8} {'涨幅':>8} {'权重':>6} {'贡献':>8}")
print(f" {'-'*10} {'-'*8} {'-'*8} {'-'*8} {'-'*6} {'-'*8}")
weighted_return = 0
for code, info in portfolio.items():
df = get_prices(code, base_date, current_date)
if df is not None and len(df) > 0:
base_price = df.iloc[0]["close"]
last_price = df.iloc[-1]["close"]
ret = (last_price / base_price - 1) * 100
weight_pct = info["weight"] / total_weight
contribution = ret * weight_pct
weighted_return += contribution
print(f" {info['name']:<10} {base_price:>8.2f} {last_price:>8.2f} {ret:>+7.2f}% {weight_pct:>5.1%} {contribution:>+7.2f}%")
else:
print(f" {info['name']:<10} {'N/A':>8} {'N/A':>8} {'N/A':>8}")
print(f" {'─'*50}")
print(f" 组合加权收益率: {weighted_return:>+7.2f}%")
print(f" 组合市值: {total_weight * (1 + weighted_return/100):.2f}万 (初始{total_weight:.2f}万)")
# ============================================================
# Part 2: Daily Performance
# ============================================================
print(f"\n{'='*90}")
print("DAILY PERFORMANCE (5/15 - 5/23)")
print("=" * 90)
for label, portfolio in [("AI", ai_portfolio), ("USER", user_portfolio)]:
total_weight = sum(v["weight"] for v in portfolio.values())
daily_returns = {}
for code, info in portfolio.items():
df = get_prices(code, base_date, current_date)
if df is not None and len(df) > 1:
weight_pct = info["weight"] / total_weight
for _, row in df.iterrows():
date_str = row["date"].strftime("%m/%d")
if date_str not in daily_returns:
daily_returns[date_str] = 0
daily_returns[date_str] += row["pctChg"] * weight_pct
print(f"\n {label} Daily Returns:")
print(f" {'Date':<8} {'Return':>8} {'Cumulative':>12}")
cum = 0
for date_str, ret in sorted(daily_returns.items()):
cum += ret
print(f" {date_str:<8} {ret:>+7.2f}% {cum:>+10.2f}%")
# ============================================================
# Part 3: Market Index Comparison
# ============================================================
print(f"\n{'='*90}")
print("MARKET INDEX COMPARISON")
print("=" * 90)
for code, name in [("sh.000001", "上证指数"), ("sz.399006", "创业板指"), ("sh.000300", "沪深300")]:
df = get_prices(code, base_date, current_date)
if df is not None and len(df) > 0:
ret = (df.iloc[-1]["close"] / df.iloc[0]["close"] - 1) * 100
print(f" {name}: {ret:>+7.2f}%")
# ============================================================
# Part 4: Individual Stock Technical Status
# ============================================================
print(f"\n{'='*90}")
print("INDIVIDUAL STOCK STATUS (5/23)")
print("=" * 90)
all_stocks = {}
for code, info in {**ai_portfolio, **user_portfolio}.items():
if code not in all_stocks:
all_stocks[code] = info
for code, info in sorted(all_stocks.items(), key=lambda x: x[1]["name"]):
df = get_prices(code, "2026-04-20", current_date)
if df is None or len(df) < 20:
continue
# RSI14
delta = df["close"].diff()
gain = delta.where(delta > 0, 0).rolling(14).mean()
loss_val = (-delta.where(delta < 0, 0)).rolling(14).mean()
rs_val = gain / loss_val.replace(0, 0.001)
df["RSI14"] = 100 - (100 / (1 + rs_val))
# MA
df["MA5"] = df["close"].rolling(5).mean()
df["MA20"] = df["close"].rolling(20).mean()
# MACD
df["EMA12"] = df["close"].ewm(span=12).mean()
df["EMA26"] = df["close"].ewm(span=26).mean()
df["DIF"] = df["EMA12"] - df["EMA26"]
df["DEA"] = df["DIF"].ewm(span=9).mean()
last = df.iloc[-1]
rsi = last["RSI14"]
macd_signal = "BULL" if last["DIF"] > last["DEA"] else "BEAR"
ma_signal = "ABOVE" if last["close"] > last["MA20"] else "BELOW"
# Capital flow (5d)
df["inflow"] = df.apply(lambda r: r["amount"] if r["pctChg"] > 0 else 0, axis=1)
df["outflow"] = df.apply(lambda r: r["amount"] if r["pctChg"] < 0 else 0, axis=1)
net_5d = (df["inflow"].tail(5).sum() - df["outflow"].tail(5).sum()) / 1e8
total_5d = (df["inflow"].tail(5).sum() + df["outflow"].tail(5).sum()) / 1e8
net_ratio = (net_5d / total_5d * 100) if total_5d > 0 else 0
# Return since 5/15
base_df = get_prices(code, base_date, current_date)
if base_df is not None and len(base_df) > 0:
ret = (base_df.iloc[-1]["close"] / base_df.iloc[0]["close"] - 1) * 100
else:
ret = 0
portfolio = "AI" if code in ai_portfolio else ""
portfolio2 = "USER" if code in user_portfolio else ""
port_label = "/".join(filter(None, [portfolio, portfolio2]))
print(f" {info['name']:<10} [{port_label:>8}] Price:{last['close']:>8.2f} Ret:{ret:>+6.2f}% RSI:{rsi:>5.1f} MACD:{macd_signal:>4} MA20:{ma_signal:>5} Flow5d:{net_ratio:>+6.1f}%")
bs.logout()