Python遍历tickers存交易策略结果到字典TypeError问题求助
问题修复方案
错误原因说明
- 第一个报错
TypeError: must be str, not list:代码中的tickers是存储多只股票代码的列表,不能直接和路径字符串拼接,必须循环遍历列表中的每一个股票代码单独处理。 - 原
meanReversionStrategy函数缺少返回值,且总利润计算逻辑存在错误(仅保留最后一笔交易利润,未累加所有交易利润),同时未处理无交易触发时first_buy为空的除零风险。
完整可运行代码
import json def meanReversionStrategy(prices): total_profit = 0 first_buy = None buy = 0 for i in range(len(prices)): if i >= 5: current_price = prices[i] moving_average = (prices[i-1] + prices[i-2] + prices[i-3] + prices[i-4] + prices[i-5]) / 5 if current_price < moving_average * 0.95 and buy == 0: buy = current_price print("buy at: ", round(current_price,2)) if first_buy is None: first_buy = buy elif current_price > moving_average * 1.05 and buy != 0: print("sell at: ", round(current_price,2)) trade_profit = current_price - buy print("trade profit: ", round(trade_profit,2)) total_profit += trade_profit buy = 0 # 处理无交易触发的边界情况 if first_buy is None: final_profit_percentage = 0 total_profit = 0 else: final_profit_percentage = (total_profit / first_buy) * 100 print("First buy: " , round(first_buy,2) if first_buy else 0) print("Total profit: " , round(total_profit, 2)) print("Percentage return: ", round(final_profit_percentage, 2),"%") # 新增返回值 return total_profit, final_profit_percentage def simpleMovingAverageStrategy(prices): i = 0 buy = 0 total_profit = 0 first_buy = 0 for p in prices: if i >= 5: moving_average = (prices[i-1] + prices[i-2] + prices[i-3] + prices[i-4] + prices[i-5]) / 5 if p > moving_average and buy == 0: # 买入逻辑 print("buying at: ", p) buy = p if first_buy == 0: first_buy = p elif p < moving_average and buy != 0: # 卖出逻辑 print("selling at: ", p) trade_profit = p - buy print("trade profit: ", trade_profit) total_profit += trade_profit buy = 0 i += 1 # 处理无交易触发的边界情况 if first_buy == 0: final_percentage = 0 total_profit = 0 else: final_percentage = (total_profit / first_buy) * 100 print("first buy: ", first_buy) print("total profit: ", total_profit) print("final percentage: ", final_percentage, "%") return total_profit, final_percentage # 新增保存结果函数 def saveResults(data): with open("/home/ubuntu/environment/hw5/results.json", "w", encoding="utf-8") as f: json.dump(data, f, indent=4, ensure_ascii=False) tickers = ["AAPL1" , "ADBE" , "BA", "CMCSA", "CSCO", "CVS", "GOOG", "TLSYY","TM"] results = {} # 遍历所有股票代码处理 for ticker in tickers: print(f"\n===== 处理股票:{ticker} =====") # 读取对应股票的价格文件 file_path = f"/home/ubuntu/environment/hw5/{ticker}.txt" with open(file_path, "r", encoding="utf-8") as f: lines = f.readlines() prices = [float(line.strip()) for line in lines] # 存储价格数据 results[f"{ticker}_prices"] = prices # 运行均值回归策略并存结果 mr_profit, mr_returns = meanReversionStrategy(prices) results[f"{ticker}_mr_profit"] = mr_profit results[f"{ticker}_mr_returns"] = mr_returns # 运行简单移动平均策略并存结果 sma_profit, sma_returns = simpleMovingAverageStrategy(prices) results[f"{ticker}_sma_profit"] = sma_profit results[f"{ticker}_sma_returns"] = sma_returns # 保存最终结果 saveResults(results)
关键修改说明
- 修复了均值回归策略的利润累加逻辑,新增返回值,补充了无交易场景的边界处理,符合开发要求
- 新增
saveResults函数,负责将结果字典格式化写入json文件 - 新增tickers列表遍历逻辑,按要求将每只股票的价格、两个策略的计算结果存入结果字典
- 替换了直接拼接列表和字符串的错误写法,逐个读取对应股票的价格文件
内容的提问来源于stack exchange,提问作者s34052
相关产品推荐
相关产品推荐

