UVXY股票历史月度最佳买卖日期计算与非交易日问题求解
问题核心
- 固定日期(10号、20号)大概率不属于交易日,导致买卖价格数组长度不匹配、统计逻辑失效
- 原代码存在变量名拼写错误(
openPriceOftrades和定义的openPriceOfTrades大小写不一致)、硬切字符串位置易出错、difference在循环内重复初始化的问题,本身也无法正常输出结果
方案1:基于现有行情文本数据处理
处理逻辑:
- 先把原始文本解析为结构化的行情数据,日期转为可操作的时间格式
- 按年月分组,直接统计每月的最高/最低点对应日期,无需硬绑定固定日期
- 如果仍需要固定日期附近的交易日,可按月份筛选最接近指定日期的交易记录
from bs4 import BeautifulSoup import pandas as pd from datetime import datetime content = """ <pre style="word-wrap: break-word; white-space: pre-wrap;"> Fri 09-24-2021 22.22 22.27 20.38 20.49 47101392 Thu 09-23-2021 22.52 22.63 21.32 21.48 48145436 Wed 09-22-2021 24.88 25.37 22.88 23.68 59917888 Tue 09-21-2021 26.03 28.18 25.20 25.86 73069928 Mon 09-20-2021 26.26 30.81 25.36 27.31 104578920 Fri 09-17-2021 21.56 23.58 21.33 23.48 61526336 Thu 09-16-2021 21.91 22.66 21.04 21.38 42485960 Wed 12-07-2016 9150.00 9390.00 8780.00 9270.00 37485 Tue 12-06-2016 9530.00 9660.00 9130.00 9210.00 27220 </pre>""" # 解析原始数据 soup = BeautifulSoup(content, "html.parser") raw_text = soup.find('pre').text.strip() lines = [l for l in raw_text.split("\n") if l.strip()] # 结构化处理 data = [] for line in lines: parts = list(filter(None, line.split())) date_str = parts[1] dt = datetime.strptime(date_str, "%m-%d-%Y") open_p = float(parts[2]) high_p = float(parts[3]) low_p = float(parts[4]) close_p = float(parts[5]) volume = int(parts[6]) data.append([dt, open_p, high_p, low_p, close_p, volume]) # 转DataFrame设置时间索引 df = pd.DataFrame(data, columns=['date', 'open', 'high', 'low', 'close', 'volume']) df = df.set_index('date').sort_index() # 按月度分组找高低点 monthly_stats = [] for ym, group in df.groupby([df.index.year, df.index.month]): year, month = ym # 月度最低点对应日期 min_row = group[group['low'] == group['low'].min()].iloc[0] min_day = min_row.name.day # 月度最高点对应日期 max_row = group[group['high'] == group['high'].max()].iloc[0] max_day = max_row.name.day monthly_stats.append({ 'year': year, 'month': month, 'low_day': min_day, 'high_day': max_day, 'low_price': min_row['low'], 'high_price': max_row['high'] }) stats_df = pd.DataFrame(monthly_stats) # 计算平均高低点日期 avg_low_day = round(stats_df['low_day'].mean(), 1) avg_high_day = round(stats_df['high_day'].mean(), 1) print(f"历史月度低点平均出现日期:每月{avg_low_day}号") print(f"历史月度高点平均出现日期:每月{avg_high_day}号") # 如果需要统计指定日期附近的交易收益,比如每月10号附近买,20号附近卖 def get_nearest_trade_day(group, target_day): # 计算日期差的绝对值,找最小的 group['day_diff'] = abs(group.index.day - target_day) return group[group['day_diff'] == group['day_diff'].min()].iloc[0] trade_profit = [] for ym, group in df.groupby([df.index.year, df.index.month]): buy_row = get_nearest_trade_day(group, 10) sell_row = get_nearest_trade_day(group, 20) # 仅当卖的日期在买之后有效 if sell_row.name > buy_row.name: profit = (sell_row['close'] - buy_row['open']) / buy_row['open'] trade_profit.append(profit) avg_profit = round(sum(trade_profit)/len(trade_profit)*100, 2) print(f"10号附近买20号附近卖的历史平均收益率:{avg_profit}%")
方案2:使用yfinance获取UVXY历史数据
处理逻辑:
- 直接调用yfinance拉取UVXY全部历史行情,无需自行维护文本数据
- 后续统计逻辑和方案1完全一致
import yfinance as yf import pandas as pd # 拉取UVXY全部历史日线数据 uvxy = yf.Ticker("UVXY") df = uvxy.history(period="max") # 清理不需要的列 df = df[['Open', 'High', 'Low', 'Close', 'Volume']] df.columns = df.columns.str.lower() # 后续高低点统计、固定日期交易统计逻辑和方案1完全一致,直接复用即可
内容的提问来源于stack exchange,提问作者Roy Lee
相关产品推荐
相关产品推荐

