Don't use class for plotting

This will allow easy usage of the methods from jupter notebooks
This commit is contained in:
Matthias 2019-06-30 11:06:51 +02:00
parent 587d71efb5
commit db59d39e2c
3 changed files with 45 additions and 37 deletions

View File

@ -1,6 +1,6 @@
import logging import logging
from pathlib import Path from pathlib import Path
from typing import Any, Dict, List, Optional from typing import Dict, List, Optional
import pandas as pd import pandas as pd
@ -23,37 +23,43 @@ except ImportError:
exit(1) exit(1)
class FTPlots(): def init_plotscript(config):
"""
Initialize objects needed for plotting
:return: Dict with tickers, trades, pairs and strategy
"""
exchange: Optional[Exchange] = None
def __init__(self, config: Dict[str, Any]): # Exchange is only needed when downloading data!
self._config = config if config.get("live", False) or config.get("refresh_pairs", False):
self.exchange: Optional[Exchange] = None exchange = ExchangeResolver(config.get('exchange', {}).get('name'),
config).exchange
# Exchange is only needed when downloading data! strategy = StrategyResolver(config).strategy
if self._config.get("live", False) or self._config.get("refresh_pairs", False): if "pairs" in config:
self.exchange = ExchangeResolver(self._config.get('exchange', {}).get('name'), pairs = config["pairs"].split(',')
self._config).exchange else:
pairs = config["exchange"]["pair_whitelist"]
self.strategy = StrategyResolver(self._config).strategy # Set timerange to use
if "pairs" in self._config: timerange = Arguments.parse_timerange(config["timerange"])
self.pairs = self._config["pairs"].split(',')
else:
self.pairs = self._config["exchange"]["pair_whitelist"]
# Set timerange to use tickers = history.load_data(
self.timerange = Arguments.parse_timerange(self._config["timerange"]) 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),
)
self.tickers = history.load_data( trades = load_trades(config)
datadir=Path(str(self._config.get("datadir"))), return {"tickers": tickers,
pairs=self.pairs, "trades": trades,
ticker_interval=self._config['ticker_interval'], "pairs": pairs,
refresh_pairs=self._config.get('refresh_pairs', False), "strategy": strategy,
timerange=self.timerange, }
exchange=self.exchange,
live=self._config.get("live", False),
)
self.trades = load_trades(self._config)
def add_indicators(fig, row, indicators: List[str], data: pd.DataFrame) -> tools.make_subplots: def add_indicators(fig, row, indicators: List[str], data: pd.DataFrame) -> tools.make_subplots:

View File

@ -21,7 +21,7 @@ import pandas as pd
from freqtrade.arguments import ARGS_PLOT_DATAFRAME, Arguments from freqtrade.arguments import ARGS_PLOT_DATAFRAME, Arguments
from freqtrade.data.btanalysis import extract_trades_of_period from freqtrade.data.btanalysis import extract_trades_of_period
from freqtrade.optimize import setup_configuration from freqtrade.optimize import setup_configuration
from freqtrade.plot.plotting import (FTPlots, generate_candlestick_graph, from freqtrade.plot.plotting import (init_plotscript, generate_candlestick_graph,
store_plot_file, store_plot_file,
generate_plot_filename) generate_plot_filename)
from freqtrade.state import RunMode from freqtrade.state import RunMode
@ -54,17 +54,18 @@ def analyse_and_plot_pairs(config: Dict[str, Any]):
-Generate plot files -Generate plot files
:return: None :return: None
""" """
plot = FTPlots(config) plot_elements = init_plotscript(config)
trades = plot_elements['trades']
pair_counter = 0 pair_counter = 0
for pair, data in plot.tickers.items(): for pair, data in plot_elements["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(plot.strategy, tickers, pair) dataframe = generate_dataframe(plot_elements["strategy"], tickers, pair)
trades_pair = plot.trades.loc[plot.trades['pair'] == pair] trades_pair = trades.loc[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

@ -10,7 +10,7 @@ from typing import Any, Dict, List
from freqtrade.arguments import ARGS_PLOT_PROFIT, Arguments from freqtrade.arguments import ARGS_PLOT_PROFIT, Arguments
from freqtrade.optimize import setup_configuration from freqtrade.optimize import setup_configuration
from freqtrade.plot.plotting import FTPlots, generate_profit_graph, store_plot_file from freqtrade.plot.plotting import init_plotscript, generate_profit_graph, store_plot_file
from freqtrade.state import RunMode from freqtrade.state import RunMode
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -23,13 +23,14 @@ 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) plot_elements = init_plotscript(config)
trades = plot_elements['trades']
trades = plot.trades[plot.trades['pair'].isin(plot.pairs)] # Filter trades to relevant pairs
trades = trades[trades['pair'].isin(plot_elements["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
fig = generate_profit_graph(plot.pairs, plot.tickers, trades) fig = generate_profit_graph(plot_elements["pairs"], plot_elements["tickers"], trades)
store_plot_file(fig, filename='freqtrade-profit-plot.html', auto_open=True) store_plot_file(fig, filename='freqtrade-profit-plot.html', auto_open=True)