将多个tinyDB数据库添加到一起

2024-05-16 07:35:42 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将多个tinyDB(基于文档的数据库)数据库添加到一起而不出现AssertionError错误? 在本例中,我试图将12个tinyDB数据库添加到一起

文件结构:
enter image description here

每个编号的文件如下所示:

{
    "_default": {
        "1": {
            "Strategy": "MAShift",
            "Symbol": "AAVE/USD",
            "Timeframes": [
                "30T"
            ],
            "Parameters": {
                "atr": 14,
                "sma": 5,
                "longLine": 3,
                "shortLine": 5,
                "slMultipier": 12,
                "leverage": 1
            },
            "Start": "2020-10-13 12:00:00",
            "End": "2021-04-26 11:30:00",
            "Duration (days)": 194,
            "Equity Start [$]": 10000,
            "Equity Final [$]": 90470.5732,
            "Return [%]": 804.71,
            "Max. Drawdown [%]": -28.1,
            "Win rate [%]": 69.12,
            "Total trades": 570,
            "Avg. trade [%]": 0.43,
            "Avg. winning trade [%]": 1.88,
            "Avg. losing trade [%]": -2.81
        }, ...
    }
}

我的代码:

from tinydb import TinyDB

resultsTotalDb = TinyDB(f'db/backtestingResultsTotal.json')

for i in range(12):
    resultsDb = TinyDB(f'db/backtestingResults{i}.json')
    for result in resultsDb.all():
        resultsTotalDb.insert(result)

错误:

AssertionError: doc_id 1 already exists


Tags: 文件in数据库jsonfordb错误start
1条回答
网友
1楼 · 发布于 2024-05-16 07:35:42

您可以根据数据库计数器重新计算新的文档ID:

from tinydb import TinyDB
from tinydb.table import Document

# ...

for i in range(12):
    resultsDb = TinyDB(f"db/backtestingResults{i}.json")

    for result in resultsDb.all():
        new_id = i * 100000000 + result.doc_id
        resultsTotalDb.insert(Document(result, doc_id=new_id))

相关问题 更多 >