Use FTPlots class in plot-scripts

This commit is contained in:
Matthias 2019-06-30 09:42:10 +02:00
parent 42ea0a19d2
commit 88545d882c
2 changed files with 14 additions and 68 deletions

View File

@ -14,19 +14,16 @@ Example of usage:
""" """
import logging import logging
import sys import sys
from pathlib import Path
from typing import Any, Dict, List from typing import Any, Dict, List
import pandas as pd import pandas as pd
from freqtrade.arguments import ARGS_PLOT_DATAFRAME, Arguments from freqtrade.arguments import ARGS_PLOT_DATAFRAME, Arguments
from freqtrade.data import history from freqtrade.data.btanalysis import extract_trades_of_period
from freqtrade.data.btanalysis import extract_trades_of_period, load_trades
from freqtrade.optimize import setup_configuration from freqtrade.optimize import setup_configuration
from freqtrade.plot.plotting import (generate_candlestick_graph, from freqtrade.plot.plotting import (FTPlots, generate_candlestick_graph,
store_plot_file, store_plot_file,
generate_plot_filename) generate_plot_filename)
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
from freqtrade.state import RunMode from freqtrade.state import RunMode
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -57,38 +54,17 @@ def analyse_and_plot_pairs(config: Dict[str, Any]):
-Generate plot files -Generate plot files
:return: None :return: None
""" """
exchange = ExchangeResolver(config.get('exchange', {}).get('name'), config).exchange plot = FTPlots(config)
strategy = StrategyResolver(config).strategy
if "pairs" in config:
pairs = config["pairs"].split(',')
else:
pairs = config["exchange"]["pair_whitelist"]
# Set timerange to use
timerange = Arguments.parse_timerange(config["timerange"])
tickers = history.load_data(
datadir=Path(str(config.get("datadir"))),
pairs=pairs,
ticker_interval=config['ticker_interval'],
refresh_pairs=config.get('refresh_pairs', False),
timerange=timerange,
exchange=exchange,
live=config.get("live", False),
)
trades = load_trades(config)
pair_counter = 0 pair_counter = 0
for pair, data in tickers.items(): for pair, data in plot.tickers.items():
pair_counter += 1 pair_counter += 1
logger.info("analyse pair %s", pair) logger.info("analyse pair %s", pair)
tickers = {} tickers = {}
tickers[pair] = data tickers[pair] = data
dataframe = generate_dataframe(strategy, tickers, pair) dataframe = generate_dataframe(plot.strategy, tickers, pair)
trades_pair = trades.loc[trades['pair'] == pair] trades_pair = plot.trades.loc[plot.trades['pair'] == pair]
trades_pair = extract_trades_of_period(dataframe, trades_pair) trades_pair = extract_trades_of_period(dataframe, trades_pair)
fig = generate_candlestick_graph( fig = generate_candlestick_graph(

View File

@ -6,7 +6,6 @@ Use `python plot_profit.py --help` to display the command line arguments
""" """
import logging import logging
import sys import sys
from pathlib import Path
from typing import Any, Dict, List from typing import Any, Dict, List
import pandas as pd import pandas as pd
@ -14,11 +13,9 @@ import plotly.graph_objs as go
from plotly import tools from plotly import tools
from freqtrade.arguments import ARGS_PLOT_PROFIT, Arguments from freqtrade.arguments import ARGS_PLOT_PROFIT, Arguments
from freqtrade.data import history from freqtrade.data.btanalysis import create_cum_profit
from freqtrade.data.btanalysis import create_cum_profit, load_trades
from freqtrade.optimize import setup_configuration from freqtrade.optimize import setup_configuration
from freqtrade.plot.plotting import store_plot_file from freqtrade.plot.plotting import FTPlots, store_plot_file
from freqtrade.resolvers import ExchangeResolver
from freqtrade.state import RunMode from freqtrade.state import RunMode
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -31,41 +28,16 @@ def plot_profit(config: Dict[str, Any]) -> None:
But should be somewhat proportional, and therefor useful But should be somewhat proportional, and therefor useful
in helping out to find a good algorithm. in helping out to find a good algorithm.
""" """
plot = FTPlots(config)
exchange = ExchangeResolver(config.get('exchange', {}).get('name'), config).exchange trades = plot.trades[plot.trades['pair'].isin(plot.pairs)]
# Take pairs from the cli otherwise switch to the pair in the config file
if "pairs" in config:
pairs = config["pairs"].split(',')
else:
pairs = config["exchange"]["pair_whitelist"]
# We need to use the same pairs and the same ticker_interval
# as used in backtesting / trading
# to match the tickerdata against the results
timerange = Arguments.parse_timerange(config["timerange"])
tickers = history.load_data(
datadir=Path(str(config.get("datadir"))),
pairs=pairs,
ticker_interval=config['ticker_interval'],
refresh_pairs=config.get('refresh_pairs', False),
timerange=timerange,
exchange=exchange,
live=config.get("live", False),
)
# Load the profits results
trades = load_trades(config)
trades = trades[trades['pair'].isin(pairs)]
# Create an average close price of all the pairs that were involved. # Create an average close price of all the pairs that were involved.
# this could be useful to gauge the overall market trend # this could be useful to gauge the overall market trend
# Combine close-values for all pairs, rename columns to "pair" # Combine close-values for all pairs, rename columns to "pair"
df_comb = pd.concat([tickers[pair].set_index('date').rename( df_comb = pd.concat([plot.tickers[pair].set_index('date').rename(
{'close': pair}, axis=1)[pair] for pair in tickers], axis=1) {'close': pair}, axis=1)[pair] for pair in plot.tickers], axis=1)
df_comb['mean'] = df_comb.mean(axis=1) df_comb['mean'] = df_comb.mean(axis=1)
# Add combined cumulative profit # Add combined cumulative profit
@ -89,7 +61,7 @@ def plot_profit(config: Dict[str, Any]) -> None:
fig.append_trace(avgclose, 1, 1) fig.append_trace(avgclose, 1, 1)
fig.append_trace(profit, 2, 1) fig.append_trace(profit, 2, 1)
for pair in pairs: for pair in plot.pairs:
profit_col = f'cum_profit_{pair}' profit_col = f'cum_profit_{pair}'
df_comb = create_cum_profit(df_comb, trades[trades['pair'] == pair], profit_col) df_comb = create_cum_profit(df_comb, trades[trades['pair'] == pair], profit_col)
@ -100,9 +72,7 @@ def plot_profit(config: Dict[str, Any]) -> None:
) )
fig.append_trace(pair_profit, 3, 1) fig.append_trace(pair_profit, 3, 1)
store_plot_file(fig, store_plot_file(fig, filename='freqtrade-profit-plot.html', auto_open=True)
filename='freqtrade-profit-plot.html',
auto_open=True)
def plot_parse_args(args: List[str]) -> Dict[str, Any]: def plot_parse_args(args: List[str]) -> Dict[str, Any]: