如何为定时执行的投资机器人函数仅首次传入初始余额?
解决投资机器人余额持续追踪问题
下面提供几种实用方案,解决每次运行main函数时余额重置的问题:
方案1:使用全局变量
将余额变量定义在main函数外部作为全局变量,函数内部通过global关键字声明修改该变量,这样每次运行都会基于最新值更新。
示例代码:
import schedule import datetime import time # 初始余额定义在全局作用域 balance = 1000 def main(): global balance # 这里写你的预测逻辑和余额更新代码,比如模拟盈利10% profit_rate = 0.1 balance = balance * (1 + profit_rate) print(f"当前余额: {balance:.2f}") schedule.every().hour.at(":01").do(main) while True: now = datetime.now() current_time = now.strftime("%H:%M:%S") schedule.run_pending() print(f"监控中: {current_time}") time.sleep(60)
方案2:用类封装状态
把机器人的余额和业务逻辑封装成类,余额作为实例属性,每次调用实例方法时自然保留最新状态,这种方式更符合面向对象的设计思路,适合后续功能扩展。
示例代码:
import schedule import datetime import time class InvestmentBot: def __init__(self): self.balance = 1000 # 初始化余额 def run_strategy(self): # 执行预测逻辑并更新余额 # 模拟盈利计算 self.balance *= 1.08 print(f"当前余额: {self.balance:.2f}") # 实例化机器人 bot = InvestmentBot() # 调度调用实例的方法 schedule.every().hour.at(":01").do(bot.run_strategy) while True: now = datetime.now() current_time = now.strftime("%H:%M:%S") schedule.run_pending() print(f"监控中: {current_time}") time.sleep(60)
方案3:通过可变对象传递状态
如果不想用全局变量或类,可以用列表、字典这类可变对象来存储余额,因为可变对象在函数内部修改会直接影响外部的原始对象,无需额外声明。
示例代码:
import schedule import datetime import time # 用列表存储余额(可变对象) balance_container = [1000] def main(container): # 更新容器内的余额 container[0] *= 1.05 print(f"当前余额: {container[0]:.2f}") # 调度时传入容器对象 schedule.every().hour.at(":01").do(main, container=balance_container) while True: now = datetime.now() current_time = now.strftime("%H:%M:%S") schedule.run_pending() print(f"监控中: {current_time}") time.sleep(60)
内容的提问来源于stack exchange,提问作者robocop96
相关产品推荐
相关产品推荐

