Python加密货币交易函数while循环累计利润与交易列表存储异常问题
问题原因
- 核心错误是累计利润变量
total和交易利润列表trade定义在函数内部:每次调用tradingstrat函数时,这两个变量都会被重新初始化为0和空列表,自然无法留存之前的交易记录和累计收益。 - 现有逻辑中两个
while循环都加了break,函数每次执行只会完成1次买+1次卖就直接结束,单次运行只会产生1条交易记录,自然会出现单笔利润和累计利润数值一致的情况。 - 额外注意:代码中使用的
money变量没有作为参数传入函数,默认读取全局变量,后续多标的交易时容易出现变量污染问题。
修正方案
简易修改版(适合快速调试)
将累计相关变量移到函数外部,用global声明后即可跨调用留存数据:
# 全局定义累计变量,避免每次调用函数被重置 total_profit = 0 trade_records = [] money = 1000 # 替换为你的实际初始交易资金 def tradingstrat(symbol, open_position = False): global total_profit, trade_records, money while True: df = getminutedata(symbol) if not open_position: buyprice = df.Close[-1] qty = money/buyprice print('Bought', qty,"amount of", symbol,"@",buyprice) open_position = True break if open_position: while True: df = getminutedata(symbol) # 此处需补充你的卖出触发条件(比如涨跌幅度达标),否则买入后会立刻卖出 sellprice = df.Close[-1] profit = (sellprice-buyprice)*qty print('Sell', qty,"amount of", symbol,"@",sellprice) open_position = False # 更新可用资金,用于下一次交易计算 money = sellprice * qty break total_profit += profit trade_records.append(profit) print("单笔交易利润:", profit) print("所有交易利润明细:", trade_records) print("累计利润:", total_profit)
如果需要持续执行多笔交易,可在函数外部加循环调用逻辑即可。
规范实现版(避免全局变量污染)
推荐用类封装所有交易状态,更适合后续扩展策略:
class TradingStrategy: def __init__(self, init_money): self.money = init_money self.total_profit = 0 self.trade_records = [] self.open_position = False def run_single_trade(self, symbol): # 买入逻辑 while True: df = getminutedata(symbol) if not self.open_position: buyprice = df.Close[-1] qty = self.money / buyprice print('Bought', qty,"amount of", symbol,"@",buyprice) self.open_position = True break # 卖出逻辑 if self.open_position: while True: df = getminutedata(symbol) # 此处补充你的卖出触发条件 sellprice = df.Close[-1] profit = (sellprice - buyprice) * qty print('Sell', qty,"amount of", symbol,"@",sellprice) self.open_position = False self.money = sellprice * qty break # 更新收益记录 self.total_profit += profit self.trade_records.append(profit) print("单笔利润:", profit) print("利润明细:", self.trade_records) print("累计利润:", self.total_profit) # 使用示例 if __name__ == "__main__": strat = TradingStrategy(init_money=1000) # 循环执行多笔交易 while True: strat.run_single_trade("BTC/USDT") # 替换为你的交易标的
内容的提问来源于stack exchange,提问作者Yohannes Cahyadi
相关产品推荐
相关产品推荐

