【问题标题】:Progress bar (using tqdm) prints in a new line everytime the update is called on the tqdm object (VSCode terminal)每次在 tqdm 对象(VSCode 终端)上调用更新时,进度条(使用 tqdm)都会在新行中打印
【发布时间】:2021-01-02 15:04:45
【问题描述】:

我正在尝试使用 Python 中可用的 tqdm 模块打印优化算法的进度状态,但是,每次我尝试更新它时,它都会在新行中打印进度,有没有办法可以只更新开始实例化的原始 tqdm 条?我的代码如下,基于 backtrader 回测库:

def optimizer_callbacks(cb):
    pbar.update()

def strategy_optim(**kwargs):

    total = np.prod([len(value) for key,value in kwargs.items()])

    csv_file = FDaxCSVData(---data---)
    cerebro = bt.Cerebro()
    cerebro.adddata(csv_file)    
    cerebro.broker.setcash(500000.0)
    cerebro.broker.setcommission(commission=2.0)

    strats = cerebro.optstrategy(strategy_name, printlog = False, **kwargs)

    global pbar
    pbar = tqdm.tqdm(smoothing=0.05, desc='Optimization Runs', total=total)
    cerebro.optcallback(optimizer_callbacks)

    runnings = cerebro.run(optreturn=False, maxcpus=2)  

if __name__=="__main__":
    strategy_optim(periods = [100, 200, 300],  abs_margin= [25, 50, 75], trail_stop=[10, 20, 30, 40])

输出:

Optimization Runs:   0%|                                                    | 0/12 [00:00<?, ?it/s]
Optimization Runs:   8%|██████▉                                             | 1/12 [00:18<03:21, 18.29s/it]
Optimization Runs:  17%|█████████████▊                                      | 2/12 [00:19<01:35,  9.59s/it]
Optimization Runs:  25%|████████████████████▊                               | 3/12 [00:40<02:19, 15.55s/it]

我确实查看了 stackoverflow 上有关类似问题的其他帖子(其中大部分都集中在 jupyter notebook 界面上),但它们并没有解决我的错误。此外,这是一个多线程过程,cerebro.optcallback 在参数的唯一值集的每次迭代后调用 optimizer_callbacks 函数

【问题讨论】:

  • 使用 tqdm.notebook.tqdm 或 tqdm.auto.tqdm 代替 tqdm.tqdm
  • 使用 tqdm.notebook.tqdm 打印如下内容: HBox(children=(FloatProgress(value=0.0, description='Optimization Runs', max=16.0, style=ProgressStyle(description_width='initial' )), HTML(value='')) 如果我使用 tqdm.auto.tqdm,结果一样,它只是多次打印状态栏

标签: python tqdm back-testing backtrader


【解决方案1】:

我经常遇到这个问题,有时position = 0leave = True 不起作用。所以,我找到了另一种方法。

您可以使用 tqdm.auto.tqdm
而不是 tqdm.tqdm
而不是

from tqdm import tqdm

尝试使用

from tqdm.auto import tqdm

【讨论】:

    【解决方案2】:

    使用tqdm.tqdm(epochs, position=0, leave=True) 确保进度条保持在同一位置,并且不会每次都打印在新行上。

    干杯

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-15
      • 2020-09-24
      • 2017-07-01
      • 2018-01-09
      相关资源
      最近更新 更多