Repository: freqtrade/freqtrade

Issue:
Freqtrade plot-profit crash
## Step 1: Have you search for this issue before posting it?

Yes

## Step 2: Describe your environment

  * Operating system: Docker
  * Digest: sha256:6c321963e1ab57d829e2465c08d48d9066e1bd90d5b213fc182b5a26dc671f58

  
## Step 3: Describe the problem:

I can't get plot-profit to work

### Steps to reproduce:


```
docker-compose run --rm freqtrade backtesting --ticker-interval 5m -s SampleStrategy --config user_data/config.json --export trades
```

```
docker-compose run --rm freqtrade plot-profit --ticker-interval 5m --config user_data/config.json  --export=trades --export-filename=backtest_results/backtest-result.json
```

I get:
```
Traceback (most recent call last):
  File "/freqtrade/freqtrade/main.py", line 36, in main
    return_code = args['func'](args)
  File "/freqtrade/freqtrade/commands/plot_commands.py", line 36, in start_plot_profit
    plot_profit(config)
  File "/freqtrade/freqtrade/plot/plotting.py", line 510, in plot_profit
    fig = generate_profit_graph(plot_elements["pairs"], plot_elements["ohlcv"],
  File "/freqtrade/freqtrade/plot/plotting.py", line 392, in generate_profit_graph
    df_comb = create_cum_profit(df_comb, trades, 'cum_profit', timeframe)
  File "/freqtrade/freqtrade/data/btanalysis.py", line 201, in create_cum_profit
    _trades_sum = trades.resample(f'{timeframe_minutes}min', on='close_time')[['profitperc']].sum()
  File "/usr/local/lib/python3.8/site-packages/pandas/core/generic.py", line 8104, in resample
    return resample(
  File "/usr/local/lib/python3.8/site-packages/pandas/core/resample.py", line 1270, in resample
    return tg._get_resampler(obj, kind=kind)
  File "/usr/local/lib/python3.8/site-packages/pandas/core/resample.py", line 1403, in _get_resampler
    raise TypeError(
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'
```
### Observed Results:

  * What happened?
  * What did you expect to happen?

### Relevant code exceptions or logs:

  ```
  // paste your log here
  ```



Discussion:
well the docker digest won't help us to determine the version since the official images don't include plotly - so you've for sure rebuilt it (there is no other way to use plotly within docker).

what's the output of `docker-compose run --rm freqtrade -V`?
I am just adding to rebuilding from the docker image

```
FROM freqtradeorg/freqtrade:master

RUN pip install technical plotly

ENTRYPOINT [ "freqtrade" ]

```
That's clear - but depending on WHEN you first pulled the initial image, your version may be an uptodate one, or an outdated one.

Please post the output of `docker-compose run --rm freqtrade -V` - so we know which version you're using and don't waste time chasing already fixed bugs.
```
freqtrade 2020.4
```
Right above the exception - are you receiving `2020-05-21 07:01:44,903 - freqtrade.plot.plotting - WARNING - Backtest file is missing skipping trades.`?


I think the filename you're passing in explicitly is wrong.
can you try with the following - basically omitting the explicit filename (backtesting and plot-profit default to the same filename if not specified explicitly.

```
docker-compose run --rm freqtrade plot-profit --ticker-interval 5m --config user_data/config.json
```


The only way i can recreate this issue is by not having trades available ... 
there's 2 possibilities for this i think - backtesting didn't generate a trade - or plot-profit did not find the exported file.

Resolving patch:
diff --git a/freqtrade/data/btanalysis.py b/freqtrade/data/btanalysis.py
--- a/freqtrade/data/btanalysis.py
+++ b/freqtrade/data/btanalysis.py
@@ -194,7 +194,10 @@ def create_cum_profit(df: pd.DataFrame, trades: pd.DataFrame, col_name: str,
     :param col_name: Column name that will be assigned the results
     :param timeframe: Timeframe used during the operations
     :return: Returns df with one additional column, col_name, containing the cumulative profit.
+    :raise: ValueError if trade-dataframe was found empty.
     """
+    if len(trades) == 0:
+        raise ValueError("Trade dataframe empty.")
     from freqtrade.exchange import timeframe_to_minutes
     timeframe_minutes = timeframe_to_minutes(timeframe)
     # Resample to timeframe to make sure trades match candles
diff --git a/freqtrade/plot/plotting.py b/freqtrade/plot/plotting.py
--- a/freqtrade/plot/plotting.py
+++ b/freqtrade/plot/plotting.py
@@ -10,8 +10,9 @@
                                        create_cum_profit,
                                        extract_trades_of_period, load_trades)
 from freqtrade.data.converter import trim_dataframe
-from freqtrade.exchange import timeframe_to_prev_date
 from freqtrade.data.history import load_data
+from freqtrade.exceptions import OperationalException
+from freqtrade.exchange import timeframe_to_prev_date
 from freqtrade.misc import pair_to_filename
 from freqtrade.resolvers import StrategyResolver
 
@@ -504,6 +505,9 @@ def plot_profit(config: Dict[str, Any]) -> None:
     trades = trades[(trades['pair'].isin(plot_elements["pairs"]))
                     & (~trades['close_time'].isnull())
                     ]
+    if len(trades) == 0:
+        raise OperationalException("No trades found, cannot generate Profit-plot without "
+                                   "trades from either Backtest result or database.")
 
     # Create an average close price of all the pairs that were involved.
     # this could be useful to gauge the overall market trend


Test patch:
diff --git a/tests/data/test_btanalysis.py b/tests/data/test_btanalysis.py
--- a/tests/data/test_btanalysis.py
+++ b/tests/data/test_btanalysis.py
@@ -178,6 +178,10 @@ def test_create_cum_profit1(testdatadir):
     assert cum_profits.iloc[0]['cum_profits'] == 0
     assert cum_profits.iloc[-1]['cum_profits'] == 0.0798005
 
+    with pytest.raises(ValueError, match='Trade dataframe empty.'):
+        create_cum_profit(df.set_index('date'), bt_data[bt_data["pair"] == 'NOTAPAIR'],
+                          "cum_profits", timeframe="5m")
+
 
 def test_calculate_max_drawdown(testdatadir):
     filename = testdatadir / "backtest-result_test.json"
diff --git a/tests/test_plotting.py b/tests/test_plotting.py
--- a/tests/test_plotting.py
+++ b/tests/test_plotting.py
@@ -374,7 +374,7 @@ def test_start_plot_profit_error(mocker):
 def test_plot_profit(default_conf, mocker, testdatadir, caplog):
     default_conf['trade_source'] = 'file'
     default_conf["datadir"] = testdatadir
-    default_conf['exportfilename'] = testdatadir / "backtest-result_test.json"
+    default_conf['exportfilename'] = testdatadir / "backtest-result_test_nofile.json"
     default_conf['pairs'] = ["ETH/BTC", "LTC/BTC"]
 
     profit_mock = MagicMock()
@@ -384,6 +384,12 @@ def test_plot_profit(default_conf, mocker, testdatadir, caplog):
         generate_profit_graph=profit_mock,
         store_plot_file=store_mock
     )
+    with pytest.raises(OperationalException,
+                       match=r"No trades found, cannot generate Profit-plot.*"):
+        plot_profit(default_conf)
+
+    default_conf['exportfilename'] = testdatadir / "backtest-result_test.json"
+
     plot_profit(default_conf)
 
     # Plot-profit generates one combined plot