Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backtest/backtest_result_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ def _add_trade_record(self, trades_list, pos, stock, exit_date, exit_price, tax,
"stockno": stock,
"entry_date": pos["entry_date"],
"entry_price": pos["entry_price"],
"buy_signal": pos.get("buy_signal"),
"exit_date": exit_date,
"exit_price": exit_price,
"hold_days": hold_days,
Expand Down Expand Up @@ -243,6 +244,7 @@ def analyze_transactions(self, df_records: pd.DataFrame, tax: float = 0.002, out
active_positions[stock] = {
"entry_date": date,
"entry_price": price,
"buy_signal": row.get("buy_signal"),
"max_price": price,
"max_date": date,
"min_price": price,
Expand Down
33 changes: 30 additions & 3 deletions backtest/backtest_strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,15 @@ def generate_date_list(self) -> List[str]:
d += timedelta(days=1)
return result

def upgrade_records(self, action: str, stockno: str, ope_date: str, price: float, update_time: str):
def upgrade_records(
self,
action: str,
stockno: str,
ope_date: str,
price: float,
update_time: str,
buy_signal: Optional[str] = None,
):
"""
更新交易或持仓记录表。

Expand Down Expand Up @@ -233,6 +241,7 @@ def upgrade_records(self, action: str, stockno: str, ope_date: str, price: float
"current_weight": current_weight,
"price": price,
"stockno": stockno,
"buy_signal": buy_signal,
"operation_succ": 1,
"update_time": update_time,
"version": f"{self.strategy.__class__.__name__}",
Expand Down Expand Up @@ -280,7 +289,18 @@ def run(self):
trade_date, trade_price = self.data_loader.get_next_trade_day_price(stockno, order["request_date"])
if trade_date and pd.to_datetime(trade_date) <= pd.to_datetime(date):
# 成交
self.upgrade_records(action, stockno, trade_date, trade_price, order["request_date"])
if action == "SELL":
buy_signal = self.holdings.get(stockno, {}).get("buy_signal")
else:
buy_signal = info.get("buy_signal")
self.upgrade_records(
action,
stockno,
trade_date,
trade_price,
order["request_date"],
buy_signal=buy_signal,
)
for table in self.detail_tables: # 存入详细信息
extra = order["info"].get(table, {})
self.update_detail_record(table,{
Expand Down Expand Up @@ -311,7 +331,14 @@ def run(self):
if stockno not in self.holdings:
continue
recent_price = self.data_loader.get_recent_price(stockno, date)
self.upgrade_records("HOLD", stockno, date, recent_price, date)
self.upgrade_records(
"HOLD",
stockno,
date,
recent_price,
date,
buy_signal=self.holdings[stockno].get("buy_signal"),
)

# 3. 卖出
for stockno in self.holdings.keys():
Expand Down