We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
plot_dataframe.py
## Step 1: Have you search for this issue before posting it?

Couldn't find similar issue, so starting a new issue.

## Step 2: Describe your environment

  * Python Version: Python 3.6.8
  * CCXT version: ccxt==1.18.992
  * Branch: Master 
  * Last Commit ID: b8713a515e960f1ffadcf1c7ee62c4bee80b506c
  
## Step 3: Describe the problem:
Unable to plot my backtest results.

*Explain the problem you have encountered*
Executing the following command results in error.
Error
### Steps to reproduce:

`
        Command: python3 scripts/plot_dataframe.py -s EMACrossHTF1h --export 
        EMACrossHTF1h_results.json -p BTC/USDT --datadir user_data/data/binance/
`
  
### Observed Results:

Error is thrown. 

### Relevant code exceptions or logs:
`
          File "scripts/plot_dataframe.py", line 113, in <module>
            main(sys.argv[1:])
          File "scripts/plot_dataframe.py", line 107, in main
            plot_parse_args(sysargv)
          File "scripts/plot_dataframe.py", line 58, in analyse_and_plot_pairs
            plot_elements = init_plotscript(config)
          File "/home/ubuntu/freqtrade/freqtrade/plot/plotting.py", line 57, in init_plotscript
            trades = load_trades(config)
          File "/home/ubuntu/freqtrade/freqtrade/data/btanalysis.py", line 113, in load_trades
            return load_backtest_data(Path(config["exportfilename"]))
          File "/home/ubuntu/freqtrade/freqtrade/data/btanalysis.py", line 33, in load_backtest_data
            raise ValueError("File {filename} does not exist.")
        ValueError: File {filename} does not exist.
`


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `freqtrade/data/btanalysis.py`
Content:
```
1 """
2 Helpers when analyzing backtest data
3 """
4 import logging
5 from pathlib import Path
6 from typing import Dict
7 
8 import numpy as np
9 import pandas as pd
10 import pytz
11 
12 from freqtrade import persistence
13 from freqtrade.misc import json_load
14 from freqtrade.persistence import Trade
15 
16 logger = logging.getLogger(__name__)
17 
18 # must align with columns in backtest.py
19 BT_DATA_COLUMNS = ["pair", "profitperc", "open_time", "close_time", "index", "duration",
20                    "open_rate", "close_rate", "open_at_end", "sell_reason"]
21 
22 
23 def load_backtest_data(filename) -> pd.DataFrame:
24     """
25     Load backtest data file.
26     :param filename: pathlib.Path object, or string pointing to the file.
27     :return: a dataframe with the analysis results
28     """
29     if isinstance(filename, str):
30         filename = Path(filename)
31 
32     if not filename.is_file():
33         raise ValueError("File {filename} does not exist.")
34 
35     with filename.open() as file:
36         data = json_load(file)
37 
38     df = pd.DataFrame(data, columns=BT_DATA_COLUMNS)
39 
40     df['open_time'] = pd.to_datetime(df['open_time'],
41                                      unit='s',
42                                      utc=True,
43                                      infer_datetime_format=True
44                                      )
45     df['close_time'] = pd.to_datetime(df['close_time'],
46                                       unit='s',
47                                       utc=True,
48                                       infer_datetime_format=True
49                                       )
50     df['profitabs'] = df['close_rate'] - df['open_rate']
51     df = df.sort_values("open_time").reset_index(drop=True)
52     return df
53 
54 
55 def evaluate_result_multi(results: pd.DataFrame, freq: str, max_open_trades: int) -> pd.DataFrame:
56     """
57     Find overlapping trades by expanding each trade once per period it was open
58     and then counting overlaps
59     :param results: Results Dataframe - can be loaded
60     :param freq: Frequency used for the backtest
61     :param max_open_trades: parameter max_open_trades used during backtest run
62     :return: dataframe with open-counts per time-period in freq
63     """
64     dates = [pd.Series(pd.date_range(row[1].open_time, row[1].close_time, freq=freq))
65              for row in results[['open_time', 'close_time']].iterrows()]
66     deltas = [len(x) for x in dates]
67     dates = pd.Series(pd.concat(dates).values, name='date')
68     df2 = pd.DataFrame(np.repeat(results.values, deltas, axis=0), columns=results.columns)
69 
70     df2 = pd.concat([dates, df2], axis=1)
71     df2 = df2.set_index('date')
72     df_final = df2.resample(freq)[['pair']].count()
73     return df_final[df_final['pair'] > max_open_trades]
74 
75 
76 def load_trades_from_db(db_url: str) -> pd.DataFrame:
77     """
78     Load trades from a DB (using dburl)
79     :param db_url: Sqlite url (default format sqlite:///tradesv3.dry-run.sqlite)
80     :return: Dataframe containing Trades
81     """
82     trades: pd.DataFrame = pd.DataFrame([], columns=BT_DATA_COLUMNS)
83     persistence.init(db_url, clean_open_orders=False)
84     columns = ["pair", "profit", "open_time", "close_time",
85                "open_rate", "close_rate", "duration", "sell_reason",
86                "max_rate", "min_rate"]
87 
88     trades = pd.DataFrame([(t.pair, t.calc_profit(),
89                             t.open_date.replace(tzinfo=pytz.UTC),
90                             t.close_date.replace(tzinfo=pytz.UTC) if t.close_date else None,
91                             t.open_rate, t.close_rate,
92                             t.close_date.timestamp() - t.open_date.timestamp()
93                             if t.close_date else None,
94                             t.sell_reason,
95                             t.max_rate,
96                             t.min_rate,
97                             )
98                            for t in Trade.query.all()],
99                           columns=columns)
100 
101     return trades
102 
103 
104 def load_trades(config) -> pd.DataFrame:
105     """
106     Based on configuration option "trade_source":
107     * loads data from DB (using `db_url`)
108     * loads data from backtestfile (using `exportfilename`)
109     """
110     if config["trade_source"] == "DB":
111         return load_trades_from_db(config["db_url"])
112     elif config["trade_source"] == "file":
113         return load_backtest_data(Path(config["exportfilename"]))
114 
115 
116 def extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame) -> pd.DataFrame:
117     """
118     Compare trades and backtested pair DataFrames to get trades performed on backtested period
119     :return: the DataFrame of a trades of period
120     """
121     trades = trades.loc[(trades['open_time'] >= dataframe.iloc[0]['date']) &
122                         (trades['close_time'] <= dataframe.iloc[-1]['date'])]
123     return trades
124 
125 
126 def combine_tickers_with_mean(tickers: Dict[str, pd.DataFrame], column: str = "close"):
127     """
128     Combine multiple dataframes "column"
129     :param tickers: Dict of Dataframes, dict key should be pair.
130     :param column: Column in the original dataframes to use
131     :return: DataFrame with the column renamed to the dict key, and a column
132         named mean, containing the mean of all pairs.
133     """
134     df_comb = pd.concat([tickers[pair].set_index('date').rename(
135         {column: pair}, axis=1)[pair] for pair in tickers], axis=1)
136 
137     df_comb['mean'] = df_comb.mean(axis=1)
138 
139     return df_comb
140 
141 
142 def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str) -> pd.DataFrame:
143     """
144     Adds a column `col_name` with the cumulative profit for the given trades array.
145     :param df: DataFrame with date index
146     :param trades: DataFrame containing trades (requires columns close_time and profitperc)
147     :return: Returns df with one additional column, col_name, containing the cumulative profit.
148     """
149     df[col_name] = trades.set_index('close_time')['profitperc'].cumsum()
150     # Set first value to 0
151     df.loc[df.iloc[0].name, col_name] = 0
152     # FFill to get continuous
153     df[col_name] = df[col_name].ffill()
154     return df
155
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/freqtrade/data/btanalysis.py b/freqtrade/data/btanalysis.py
--- a/freqtrade/data/btanalysis.py
+++ b/freqtrade/data/btanalysis.py
@@ -30,7 +30,7 @@
         filename = Path(filename)
 
     if not filename.is_file():
-        raise ValueError("File {filename} does not exist.")
+        raise ValueError(f"File {filename} does not exist.")
 
     with filename.open() as file:
         data = json_load(file)

{"golden_diff": "diff --git a/freqtrade/data/btanalysis.py b/freqtrade/data/btanalysis.py\n--- a/freqtrade/data/btanalysis.py\n+++ b/freqtrade/data/btanalysis.py\n@@ -30,7 +30,7 @@\n         filename = Path(filename)\n \n     if not filename.is_file():\n-        raise ValueError(\"File {filename} does not exist.\")\n+        raise ValueError(f\"File {filename} does not exist.\")\n \n     with filename.open() as file:\n         data = json_load(file)\n", "issue": "plot_dataframe.py\n## Step 1: Have you search for this issue before posting it?\r\n\r\nCouldn't find similar issue, so starting a new issue.\r\n\r\n## Step 2: Describe your environment\r\n\r\n  * Python Version: Python 3.6.8\r\n  * CCXT version: ccxt==1.18.992\r\n  * Branch: Master \r\n  * Last Commit ID: b8713a515e960f1ffadcf1c7ee62c4bee80b506c\r\n  \r\n## Step 3: Describe the problem:\r\nUnable to plot my backtest results.\r\n\r\n*Explain the problem you have encountered*\r\nExecuting the following command results in error.\r\nError\r\n### Steps to reproduce:\r\n\r\n`\r\n        Command: python3 scripts/plot_dataframe.py -s EMACrossHTF1h --export \r\n        EMACrossHTF1h_results.json -p BTC/USDT --datadir user_data/data/binance/\r\n`\r\n  \r\n### Observed Results:\r\n\r\nError is thrown. \r\n\r\n### Relevant code exceptions or logs:\r\n`\r\n          File \"scripts/plot_dataframe.py\", line 113, in <module>\r\n            main(sys.argv[1:])\r\n          File \"scripts/plot_dataframe.py\", line 107, in main\r\n            plot_parse_args(sysargv)\r\n          File \"scripts/plot_dataframe.py\", line 58, in analyse_and_plot_pairs\r\n            plot_elements = init_plotscript(config)\r\n          File \"/home/ubuntu/freqtrade/freqtrade/plot/plotting.py\", line 57, in init_plotscript\r\n            trades = load_trades(config)\r\n          File \"/home/ubuntu/freqtrade/freqtrade/data/btanalysis.py\", line 113, in load_trades\r\n            return load_backtest_data(Path(config[\"exportfilename\"]))\r\n          File \"/home/ubuntu/freqtrade/freqtrade/data/btanalysis.py\", line 33, in load_backtest_data\r\n            raise ValueError(\"File {filename} does not exist.\")\r\n        ValueError: File {filename} does not exist.\r\n`\r\n\n", "before_files": [{"content": "\"\"\"\nHelpers when analyzing backtest data\n\"\"\"\nimport logging\nfrom pathlib import Path\nfrom typing import Dict\n\nimport numpy as np\nimport pandas as pd\nimport pytz\n\nfrom freqtrade import persistence\nfrom freqtrade.misc import json_load\nfrom freqtrade.persistence import Trade\n\nlogger = logging.getLogger(__name__)\n\n# must align with columns in backtest.py\nBT_DATA_COLUMNS = [\"pair\", \"profitperc\", \"open_time\", \"close_time\", \"index\", \"duration\",\n                   \"open_rate\", \"close_rate\", \"open_at_end\", \"sell_reason\"]\n\n\ndef load_backtest_data(filename) -> pd.DataFrame:\n    \"\"\"\n    Load backtest data file.\n    :param filename: pathlib.Path object, or string pointing to the file.\n    :return: a dataframe with the analysis results\n    \"\"\"\n    if isinstance(filename, str):\n        filename = Path(filename)\n\n    if not filename.is_file():\n        raise ValueError(\"File {filename} does not exist.\")\n\n    with filename.open() as file:\n        data = json_load(file)\n\n    df = pd.DataFrame(data, columns=BT_DATA_COLUMNS)\n\n    df['open_time'] = pd.to_datetime(df['open_time'],\n                                     unit='s',\n                                     utc=True,\n                                     infer_datetime_format=True\n                                     )\n    df['close_time'] = pd.to_datetime(df['close_time'],\n                                      unit='s',\n                                      utc=True,\n                                      infer_datetime_format=True\n                                      )\n    df['profitabs'] = df['close_rate'] - df['open_rate']\n    df = df.sort_values(\"open_time\").reset_index(drop=True)\n    return df\n\n\ndef evaluate_result_multi(results: pd.DataFrame, freq: str, max_open_trades: int) -> pd.DataFrame:\n    \"\"\"\n    Find overlapping trades by expanding each trade once per period it was open\n    and then counting overlaps\n    :param results: Results Dataframe - can be loaded\n    :param freq: Frequency used for the backtest\n    :param max_open_trades: parameter max_open_trades used during backtest run\n    :return: dataframe with open-counts per time-period in freq\n    \"\"\"\n    dates = [pd.Series(pd.date_range(row[1].open_time, row[1].close_time, freq=freq))\n             for row in results[['open_time', 'close_time']].iterrows()]\n    deltas = [len(x) for x in dates]\n    dates = pd.Series(pd.concat(dates).values, name='date')\n    df2 = pd.DataFrame(np.repeat(results.values, deltas, axis=0), columns=results.columns)\n\n    df2 = pd.concat([dates, df2], axis=1)\n    df2 = df2.set_index('date')\n    df_final = df2.resample(freq)[['pair']].count()\n    return df_final[df_final['pair'] > max_open_trades]\n\n\ndef load_trades_from_db(db_url: str) -> pd.DataFrame:\n    \"\"\"\n    Load trades from a DB (using dburl)\n    :param db_url: Sqlite url (default format sqlite:///tradesv3.dry-run.sqlite)\n    :return: Dataframe containing Trades\n    \"\"\"\n    trades: pd.DataFrame = pd.DataFrame([], columns=BT_DATA_COLUMNS)\n    persistence.init(db_url, clean_open_orders=False)\n    columns = [\"pair\", \"profit\", \"open_time\", \"close_time\",\n               \"open_rate\", \"close_rate\", \"duration\", \"sell_reason\",\n               \"max_rate\", \"min_rate\"]\n\n    trades = pd.DataFrame([(t.pair, t.calc_profit(),\n                            t.open_date.replace(tzinfo=pytz.UTC),\n                            t.close_date.replace(tzinfo=pytz.UTC) if t.close_date else None,\n                            t.open_rate, t.close_rate,\n                            t.close_date.timestamp() - t.open_date.timestamp()\n                            if t.close_date else None,\n                            t.sell_reason,\n                            t.max_rate,\n                            t.min_rate,\n                            )\n                           for t in Trade.query.all()],\n                          columns=columns)\n\n    return trades\n\n\ndef load_trades(config) -> pd.DataFrame:\n    \"\"\"\n    Based on configuration option \"trade_source\":\n    * loads data from DB (using `db_url`)\n    * loads data from backtestfile (using `exportfilename`)\n    \"\"\"\n    if config[\"trade_source\"] == \"DB\":\n        return load_trades_from_db(config[\"db_url\"])\n    elif config[\"trade_source\"] == \"file\":\n        return load_backtest_data(Path(config[\"exportfilename\"]))\n\n\ndef extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame) -> pd.DataFrame:\n    \"\"\"\n    Compare trades and backtested pair DataFrames to get trades performed on backtested period\n    :return: the DataFrame of a trades of period\n    \"\"\"\n    trades = trades.loc[(trades['open_time'] >= dataframe.iloc[0]['date']) &\n                        (trades['close_time'] <= dataframe.iloc[-1]['date'])]\n    return trades\n\n\ndef combine_tickers_with_mean(tickers: Dict[str, pd.DataFrame], column: str = \"close\"):\n    \"\"\"\n    Combine multiple dataframes \"column\"\n    :param tickers: Dict of Dataframes, dict key should be pair.\n    :param column: Column in the original dataframes to use\n    :return: DataFrame with the column renamed to the dict key, and a column\n        named mean, containing the mean of all pairs.\n    \"\"\"\n    df_comb = pd.concat([tickers[pair].set_index('date').rename(\n        {column: pair}, axis=1)[pair] for pair in tickers], axis=1)\n\n    df_comb['mean'] = df_comb.mean(axis=1)\n\n    return df_comb\n\n\ndef create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str) -> pd.DataFrame:\n    \"\"\"\n    Adds a column `col_name` with the cumulative profit for the given trades array.\n    :param df: DataFrame with date index\n    :param trades: DataFrame containing trades (requires columns close_time and profitperc)\n    :return: Returns df with one additional column, col_name, containing the cumulative profit.\n    \"\"\"\n    df[col_name] = trades.set_index('close_time')['profitperc'].cumsum()\n    # Set first value to 0\n    df.loc[df.iloc[0].name, col_name] = 0\n    # FFill to get continuous\n    df[col_name] = df[col_name].ffill()\n    return df\n", "path": "freqtrade/data/btanalysis.py"}], "after_files": [{"content": "\"\"\"\nHelpers when analyzing backtest data\n\"\"\"\nimport logging\nfrom pathlib import Path\nfrom typing import Dict\n\nimport numpy as np\nimport pandas as pd\nimport pytz\n\nfrom freqtrade import persistence\nfrom freqtrade.misc import json_load\nfrom freqtrade.persistence import Trade\n\nlogger = logging.getLogger(__name__)\n\n# must align with columns in backtest.py\nBT_DATA_COLUMNS = [\"pair\", \"profitperc\", \"open_time\", \"close_time\", \"index\", \"duration\",\n                   \"open_rate\", \"close_rate\", \"open_at_end\", \"sell_reason\"]\n\n\ndef load_backtest_data(filename) -> pd.DataFrame:\n    \"\"\"\n    Load backtest data file.\n    :param filename: pathlib.Path object, or string pointing to the file.\n    :return: a dataframe with the analysis results\n    \"\"\"\n    if isinstance(filename, str):\n        filename = Path(filename)\n\n    if not filename.is_file():\n        raise ValueError(f\"File {filename} does not exist.\")\n\n    with filename.open() as file:\n        data = json_load(file)\n\n    df = pd.DataFrame(data, columns=BT_DATA_COLUMNS)\n\n    df['open_time'] = pd.to_datetime(df['open_time'],\n                                     unit='s',\n                                     utc=True,\n                                     infer_datetime_format=True\n                                     )\n    df['close_time'] = pd.to_datetime(df['close_time'],\n                                      unit='s',\n                                      utc=True,\n                                      infer_datetime_format=True\n                                      )\n    df['profitabs'] = df['close_rate'] - df['open_rate']\n    df = df.sort_values(\"open_time\").reset_index(drop=True)\n    return df\n\n\ndef evaluate_result_multi(results: pd.DataFrame, freq: str, max_open_trades: int) -> pd.DataFrame:\n    \"\"\"\n    Find overlapping trades by expanding each trade once per period it was open\n    and then counting overlaps\n    :param results: Results Dataframe - can be loaded\n    :param freq: Frequency used for the backtest\n    :param max_open_trades: parameter max_open_trades used during backtest run\n    :return: dataframe with open-counts per time-period in freq\n    \"\"\"\n    dates = [pd.Series(pd.date_range(row[1].open_time, row[1].close_time, freq=freq))\n             for row in results[['open_time', 'close_time']].iterrows()]\n    deltas = [len(x) for x in dates]\n    dates = pd.Series(pd.concat(dates).values, name='date')\n    df2 = pd.DataFrame(np.repeat(results.values, deltas, axis=0), columns=results.columns)\n\n    df2 = pd.concat([dates, df2], axis=1)\n    df2 = df2.set_index('date')\n    df_final = df2.resample(freq)[['pair']].count()\n    return df_final[df_final['pair'] > max_open_trades]\n\n\ndef load_trades_from_db(db_url: str) -> pd.DataFrame:\n    \"\"\"\n    Load trades from a DB (using dburl)\n    :param db_url: Sqlite url (default format sqlite:///tradesv3.dry-run.sqlite)\n    :return: Dataframe containing Trades\n    \"\"\"\n    trades: pd.DataFrame = pd.DataFrame([], columns=BT_DATA_COLUMNS)\n    persistence.init(db_url, clean_open_orders=False)\n    columns = [\"pair\", \"profit\", \"open_time\", \"close_time\",\n               \"open_rate\", \"close_rate\", \"duration\", \"sell_reason\",\n               \"max_rate\", \"min_rate\"]\n\n    trades = pd.DataFrame([(t.pair, t.calc_profit(),\n                            t.open_date.replace(tzinfo=pytz.UTC),\n                            t.close_date.replace(tzinfo=pytz.UTC) if t.close_date else None,\n                            t.open_rate, t.close_rate,\n                            t.close_date.timestamp() - t.open_date.timestamp()\n                            if t.close_date else None,\n                            t.sell_reason,\n                            t.max_rate,\n                            t.min_rate,\n                            )\n                           for t in Trade.query.all()],\n                          columns=columns)\n\n    return trades\n\n\ndef load_trades(config) -> pd.DataFrame:\n    \"\"\"\n    Based on configuration option \"trade_source\":\n    * loads data from DB (using `db_url`)\n    * loads data from backtestfile (using `exportfilename`)\n    \"\"\"\n    if config[\"trade_source\"] == \"DB\":\n        return load_trades_from_db(config[\"db_url\"])\n    elif config[\"trade_source\"] == \"file\":\n        return load_backtest_data(Path(config[\"exportfilename\"]))\n\n\ndef extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame) -> pd.DataFrame:\n    \"\"\"\n    Compare trades and backtested pair DataFrames to get trades performed on backtested period\n    :return: the DataFrame of a trades of period\n    \"\"\"\n    trades = trades.loc[(trades['open_time'] >= dataframe.iloc[0]['date']) &\n                        (trades['close_time'] <= dataframe.iloc[-1]['date'])]\n    return trades\n\n\ndef combine_tickers_with_mean(tickers: Dict[str, pd.DataFrame], column: str = \"close\"):\n    \"\"\"\n    Combine multiple dataframes \"column\"\n    :param tickers: Dict of Dataframes, dict key should be pair.\n    :param column: Column in the original dataframes to use\n    :return: DataFrame with the column renamed to the dict key, and a column\n        named mean, containing the mean of all pairs.\n    \"\"\"\n    df_comb = pd.concat([tickers[pair].set_index('date').rename(\n        {column: pair}, axis=1)[pair] for pair in tickers], axis=1)\n\n    df_comb['mean'] = df_comb.mean(axis=1)\n\n    return df_comb\n\n\ndef create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str) -> pd.DataFrame:\n    \"\"\"\n    Adds a column `col_name` with the cumulative profit for the given trades array.\n    :param df: DataFrame with date index\n    :param trades: DataFrame containing trades (requires columns close_time and profitperc)\n    :return: Returns df with one additional column, col_name, containing the cumulative profit.\n    \"\"\"\n    df[col_name] = trades.set_index('close_time')['profitperc'].cumsum()\n    # Set first value to 0\n    df.loc[df.iloc[0].name, col_name] = 0\n    # FFill to get continuous\n    df[col_name] = df[col_name].ffill()\n    return df\n", "path": "freqtrade/data/btanalysis.py"}]}