diff --git a/docs/backtesting.md b/docs/backtesting.md index 79bfa2350..3d08d5332 100644 --- a/docs/backtesting.md +++ b/docs/backtesting.md @@ -11,8 +11,8 @@ Now you have good Buy and Sell strategies and some historic data, you want to te real data. This is what we call [backtesting](https://en.wikipedia.org/wiki/Backtesting). -Backtesting will use the crypto-currencies (pairs) from your config file and load ticker data from `user_data/data/` by default. -If no data is available for the exchange / pair / ticker interval combination, backtesting will ask you to download them first using `freqtrade download-data`. +Backtesting will use the crypto-currencies (pairs) from your config file and load historical candle (OHCLV) data from `user_data/data/` by default. +If no data is available for the exchange / pair / timeframe (ticker interval) combination, backtesting will ask you to download them first using `freqtrade download-data`. For details on downloading, please refer to the [Data Downloading](data-download.md) section in the documentation. The result of backtesting will confirm if your bot has better odds of making a profit than a loss. @@ -22,19 +22,19 @@ The result of backtesting will confirm if your bot has better odds of making a p ### Run a backtesting against the currencies listed in your config file -#### With 5 min tickers (Per default) +#### With 5 min candle (OHLCV) data (per default) ```bash freqtrade backtesting ``` -#### With 1 min tickers +#### With 1 min candle (OHLCV) data ```bash freqtrade backtesting --ticker-interval 1m ``` -#### Using a different on-disk ticker-data source +#### Using a different on-disk historical candle (OHLCV) data source Assume you downloaded the history data from the Bittrex exchange and kept it in the `user_data/data/bittrex-20180101` directory. You can then use this data for backtesting as follows: @@ -223,7 +223,7 @@ You can then load the trades to perform further analysis as shown in our [data a To compare multiple strategies, a list of Strategies can be provided to backtesting. -This is limited to 1 ticker-interval per run, however, data is only loaded once from disk so if you have multiple +This is limited to 1 timeframe (ticker interval) value per run. However, data is only loaded once from disk so if you have multiple strategies you'd like to compare, this will give a nice runtime boost. All listed Strategies need to be in the same directory. diff --git a/docs/configuration.md b/docs/configuration.md index 5580b9c68..42018a499 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -47,7 +47,7 @@ Mandatory parameters are marked as **Required**, which means that they are requi | `amend_last_stake_amount` | Use reduced last stake amount if necessary. [More information below](#configuring-amount-per-trade).
*Defaults to `false`.*
**Datatype:** Boolean | `last_stake_amount_min_ratio` | Defines minimum stake amount that has to be left and executed. Applies only to the last stake amount when it's amended to a reduced value (i.e. if `amend_last_stake_amount` is set to `true`). [More information below](#configuring-amount-per-trade).
*Defaults to `0.5`.*
**Datatype:** Float (as ratio) | `amount_reserve_percent` | Reserve some amount in min pair stake amount. The bot will reserve `amount_reserve_percent` + stoploss value when calculating min pair stake amount in order to avoid possible trade refusals.
*Defaults to `0.05` (5%).*
**Datatype:** Positive Float as ratio. -| `ticker_interval` | The ticker interval to use (e.g `1m`, `5m`, `15m`, `30m`, `1h` ...). [Strategy Override](#parameters-in-the-strategy).
**Datatype:** String +| `ticker_interval` | The timeframe (ticker interval) to use (e.g `1m`, `5m`, `15m`, `30m`, `1h` ...). [Strategy Override](#parameters-in-the-strategy).
**Datatype:** String | `fiat_display_currency` | Fiat currency used to show your profits. [More information below](#what-values-can-be-used-for-fiat_display_currency).
**Datatype:** String | `dry_run` | **Required.** Define if the bot must be in Dry Run or production mode.
*Defaults to `true`.*
**Datatype:** Boolean | `dry_run_wallet` | Define the starting amount in stake currency for the simulated wallet used by the bot running in the Dry Run mode.
*Defaults to `1000`.*
**Datatype:** Float @@ -113,8 +113,8 @@ Mandatory parameters are marked as **Required**, which means that they are requi | `internals.sd_notify` | Enables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See [here](installation.md#7-optional-configure-freqtrade-as-a-systemd-service) for more details.
**Datatype:** Boolean | `logfile` | Specifies logfile name. Uses a rolling strategy for log file rotation for 10 files with the 1MB limit per file.
**Datatype:** String | `user_data_dir` | Directory containing user data.
*Defaults to `./user_data/`*.
**Datatype:** String -| `dataformat_ohlcv` | Data format to use to store OHLCV historic data.
*Defaults to `json`*.
**Datatype:** String -| `dataformat_trades` | Data format to use to store trades historic data.
*Defaults to `jsongz`*.
**Datatype:** String +| `dataformat_ohlcv` | Data format to use to store historical candle (OHLCV) data.
*Defaults to `json`*.
**Datatype:** String +| `dataformat_trades` | Data format to use to store historical trades data.
*Defaults to `jsongz`*.
**Datatype:** String ### Parameters in the strategy @@ -413,7 +413,7 @@ Advanced options can be configured using the `_ft_has_params` setting, which wil Available options are listed in the exchange-class as `_ft_has_default`. -For example, to test the order type `FOK` with Kraken, and modify candle_limit to 200 (so you only get 200 candles per call): +For example, to test the order type `FOK` with Kraken, and modify candle limit to 200 (so you only get 200 candles per API call): ```json "exchange": { diff --git a/docs/data-download.md b/docs/data-download.md index 76e22f4ea..903d62854 100644 --- a/docs/data-download.md +++ b/docs/data-download.md @@ -33,7 +33,7 @@ optional arguments: Specify which tickers to download. Space-separated list. Default: `1m 5m`. --erase Clean all existing data for the selected exchange/pairs/timeframes. --data-format-ohlcv {json,jsongz} - Storage format for downloaded ohlcv data. (default: `json`). + Storage format for downloaded candle (OHLCV) data. (default: `json`). --data-format-trades {json,jsongz} Storage format for downloaded trades data. (default: `jsongz`). @@ -105,7 +105,7 @@ Common arguments: ##### Example converting data -The following command will convert all ohlcv (candle) data available in `~/.freqtrade/data/binance` from json to jsongz, saving diskspace in the process. +The following command will convert all candle (OHLCV) data available in `~/.freqtrade/data/binance` from json to jsongz, saving diskspace in the process. It'll also remove original json data files (`--erase` parameter). ``` bash @@ -192,15 +192,15 @@ Then run: freqtrade download-data --exchange binance ``` -This will download ticker data for all the currency pairs you defined in `pairs.json`. +This will download historical candle (OHLCV) data for all the currency pairs you defined in `pairs.json`. ### Other Notes - To use a different directory than the exchange specific default, use `--datadir user_data/data/some_directory`. -- To change the exchange used to download the tickers, please use a different configuration file (you'll probably need to adjust ratelimits etc.) +- To change the exchange used to download the historical data from, please use a different configuration file (you'll probably need to adjust ratelimits etc.) - To use `pairs.json` from some other directory, use `--pairs-file some_other_dir/pairs.json`. -- To download ticker data for only 10 days, use `--days 10` (defaults to 30 days). -- Use `--timeframes` to specify which tickers to download. Default is `--timeframes 1m 5m` which will download 1-minute and 5-minute tickers. +- To download historical candle (OHLCV) data for only 10 days, use `--days 10` (defaults to 30 days). +- Use `--timeframes` to specify what timeframe download the historical candle (OHLCV) data for. Default is `--timeframes 1m 5m` which will download 1-minute and 5-minute data. - To use exchange, timeframe and list of pairs as defined in your configuration file, use the `-c/--config` option. With this, the script uses the whitelist defined in the config as the list of currency pairs to download data for and does not require the pairs.json file. You can combine `-c/--config` with most other options. ### Trades (tick) data diff --git a/docs/developer.md b/docs/developer.md index ef9232a59..34b2f1ba5 100644 --- a/docs/developer.md +++ b/docs/developer.md @@ -165,7 +165,7 @@ Since CCXT does not provide unification for Stoploss On Exchange yet, we'll need ### Incomplete candles -While fetching OHLCV data, we're may end up getting incomplete candles (Depending on the exchange). +While fetching candle (OHLCV) data, we may end up getting incomplete candles (depending on the exchange). To demonstrate this, we'll use daily candles (`"1d"`) to keep things simple. We query the api (`ct.fetch_ohlcv()`) for the timeframe and look at the date of the last entry. If this entry changes or shows the date of a "incomplete" candle, then we should drop this since having incomplete candles is problematic because indicators assume that only complete candles are passed to them, and will generate a lot of false buy signals. By default, we're therefore removing the last candle assuming it's incomplete. @@ -174,14 +174,14 @@ To check how the new exchange behaves, you can use the following snippet: ``` python import ccxt from datetime import datetime -from freqtrade.data.converter import parse_ticker_dataframe +from freqtrade.data.converter import ohlcv_to_dataframe ct = ccxt.binance() timeframe = "1d" pair = "XLM/BTC" # Make sure to use a pair that exists on that exchange! raw = ct.fetch_ohlcv(pair, timeframe=timeframe) # convert to dataframe -df1 = parse_ticker_dataframe(raw, timeframe, pair=pair, drop_incomplete=False) +df1 = ohlcv_to_dataframe(raw, timeframe, pair=pair, drop_incomplete=False) print(df1.tail(1)) print(datetime.utcnow()) diff --git a/docs/edge.md b/docs/edge.md index 6a301b044..721f570c7 100644 --- a/docs/edge.md +++ b/docs/edge.md @@ -156,7 +156,7 @@ Edge module has following configuration options: | `minimum_winrate` | It filters out pairs which don't have at least minimum_winrate.
This comes handy if you want to be conservative and don't comprise win rate in favour of risk reward ratio.
*Defaults to `0.60`.*
**Datatype:** Float | `minimum_expectancy` | It filters out pairs which have the expectancy lower than this number.
Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return.
*Defaults to `0.20`.*
**Datatype:** Float | `min_trade_number` | When calculating *W*, *R* and *E* (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable.
Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something.
*Defaults to `10` (it is highly recommended not to decrease this number).*
**Datatype:** Integer -| `max_trade_duration_minute` | Edge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign.
**NOTICE:** While configuring this value, you should take into consideration your ticker interval. As an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. Default value is set assuming your strategy interval is relatively small (1m or 5m, etc.).
*Defaults to `1440` (one day).*
**Datatype:** Integer +| `max_trade_duration_minute` | Edge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign.
**NOTICE:** While configuring this value, you should take into consideration your timeframe (ticker interval). As an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. Default value is set assuming your strategy interval is relatively small (1m or 5m, etc.).
*Defaults to `1440` (one day).*
**Datatype:** Integer | `remove_pumps` | Edge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off.
*Defaults to `false`.*
**Datatype:** Boolean ## Running Edge independently diff --git a/docs/exchanges.md b/docs/exchanges.md index 70dae0aa5..66a0e96da 100644 --- a/docs/exchanges.md +++ b/docs/exchanges.md @@ -76,8 +76,8 @@ $ pip3 install web3 ### Send incomplete candles to the strategy -Most exchanges return incomplete candles via their ohlcv / klines interface. -By default, Freqtrade assumes that incomplete candles are returned and removes the last candle assuming it's an incomplete candle. +Most exchanges return current incomplete candle via their OHLCV/klines API interface. +By default, Freqtrade assumes that incomplete candle is fetched from the exchange and removes the last candle assuming it's the incomplete candle. Whether your exchange returns incomplete candles or not can be checked using [the helper script](developer.md#Incomplete-candles) from the Contributor documentation. diff --git a/docs/hyperopt.md b/docs/hyperopt.md index 9bc5888ce..abd7aa7ce 100644 --- a/docs/hyperopt.md +++ b/docs/hyperopt.md @@ -103,9 +103,10 @@ Place the corresponding settings into the following methods The configuration and rules are the same than for buy signals. To avoid naming collisions in the search-space, please prefix all sell-spaces with `sell-`. -#### Using ticker-interval as part of the Strategy +#### Using timeframe as a part of the Strategy -The Strategy exposes the ticker-interval as `self.ticker_interval`. The same value is available as class-attribute `HyperoptName.ticker_interval`. +The Strategy class exposes the timeframe (ticker interval) value as the `self.ticker_interval` attribute. +The same value is available as class-attribute `HyperoptName.ticker_interval`. In the case of the linked sample-value this would be `SampleHyperOpt.ticker_interval`. ## Solving a Mystery @@ -222,11 +223,11 @@ The `--spaces all` option determines that all possible parameters should be opti !!! Warning When switching parameters or changing configuration options, make sure to not use the argument `--continue` so temporary results can be removed. -### Execute Hyperopt with Different Ticker-Data Source +### Execute Hyperopt with different historical data source -If you would like to hyperopt parameters using an alternate ticker data that -you have on-disk, use the `--datadir PATH` option. Default hyperopt will -use data from directory `user_data/data`. +If you would like to hyperopt parameters using an alternate historical data set that +you have on-disk, use the `--datadir PATH` option. By default, hyperopt +uses data from directory `user_data/data`. ### Running Hyperopt with Smaller Testset @@ -380,7 +381,7 @@ As stated in the comment, you can also use it as the value of the `minimal_roi` #### Default ROI Search Space -If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace for you -- it's the hyperspace of components for the ROI tables. By default, each ROI table generated by the Freqtrade consists of 4 rows (steps). Hyperopt implements adaptive ranges for ROI tables with ranges for values in the ROI steps that depend on the ticker_interval used. By default the values vary in the following ranges (for some of the most used ticker intervals, values are rounded to 5 digits after the decimal point): +If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace for you -- it's the hyperspace of components for the ROI tables. By default, each ROI table generated by the Freqtrade consists of 4 rows (steps). Hyperopt implements adaptive ranges for ROI tables with ranges for values in the ROI steps that depend on the ticker_interval used. By default the values vary in the following ranges (for some of the most used timeframes, values are rounded to 5 digits after the decimal point): | # step | 1m | | 5m | | 1h | | 1d | | | ------ | ------ | ----------------- | -------- | ----------- | ---------- | ----------------- | ------------ | ----------------- | @@ -389,7 +390,7 @@ If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace f | 3 | 4...20 | 0.00387...0.01547 | 20...100 | 0.01...0.04 | 240...1200 | 0.02294...0.09177 | 5760...28800 | 0.04059...0.16237 | | 4 | 6...44 | 0.0 | 30...220 | 0.0 | 360...2640 | 0.0 | 8640...63360 | 0.0 | -These ranges should be sufficient in most cases. The minutes in the steps (ROI dict keys) are scaled linearly depending on the ticker interval used. The ROI values in the steps (ROI dict values) are scaled logarithmically depending on the ticker interval used. +These ranges should be sufficient in most cases. The minutes in the steps (ROI dict keys) are scaled linearly depending on the timeframe (ticker interval) used. The ROI values in the steps (ROI dict values) are scaled logarithmically depending on the timeframe used. If you have the `generate_roi_table()` and `roi_space()` methods in your custom hyperopt file, remove them in order to utilize these adaptive ROI tables and the ROI hyperoptimization space generated by Freqtrade by default. diff --git a/docs/strategy-customization.md b/docs/strategy-customization.md index 4aacd3af6..7793ea148 100644 --- a/docs/strategy-customization.md +++ b/docs/strategy-customization.md @@ -84,7 +84,7 @@ def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame Performance Note: For the best performance be frugal on the number of indicators you are using. Let uncomment only the indicator you are using in your strategies or your hyperopt configuration, otherwise you will waste your memory and CPU usage. - :param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe() + :param dataframe: Dataframe with data from the exchange :param metadata: Additional information, like the currently traded pair :return: a Dataframe with all mandatory indicators for the strategies """ @@ -284,13 +284,14 @@ If your exchange supports it, it's recommended to also set `"stoploss_on_exchang For more information on order_types please look [here](configuration.md#understand-order_types). -### Ticker interval +### Timeframe (ticker interval) This is the set of candles the bot should download and use for the analysis. Common values are `"1m"`, `"5m"`, `"15m"`, `"1h"`, however all values supported by your exchange should work. -Please note that the same buy/sell signals may work with one interval, but not the other. -This setting is accessible within the strategy by using `self.ticker_interval`. +Please note that the same buy/sell signals may work well with one timeframe, but not with the others. + +This setting is accessible within the strategy methods as the `self.ticker_interval` attribute. ### Metadata dict @@ -335,14 +336,14 @@ Please always check the mode of operation to select the correct method to get da #### Possible options for DataProvider - `available_pairs` - Property with tuples listing cached pairs with their intervals (pair, interval). -- `ohlcv(pair, timeframe)` - Currently cached ticker data for the pair, returns DataFrame or empty DataFrame. +- `ohlcv(pair, timeframe)` - Currently cached candle (OHLCV) data for the pair, returns DataFrame or empty DataFrame. - `historic_ohlcv(pair, timeframe)` - Returns historical data stored on disk. - `get_pair_dataframe(pair, timeframe)` - This is a universal method, which returns either historical data (for backtesting) or cached live data (for the Dry-Run and Live-Run modes). - `orderbook(pair, maximum)` - Returns latest orderbook data for the pair, a dict with bids/asks with a total of `maximum` entries. - `market(pair)` - Returns market data for the pair: fees, limits, precisions, activity flag, etc. See [ccxt documentation](https://github.com/ccxt/ccxt/wiki/Manual#markets) for more details on Market data structure. - `runmode` - Property containing the current runmode. -#### Example: fetch live ohlcv / historic data for the first informative pair +#### Example: fetch live / historical candle (OHLCV) data for the first informative pair ``` python if self.dp: @@ -377,8 +378,8 @@ if self.dp: ``` python if self.dp: - for pair, ticker in self.dp.available_pairs: - print(f"available {pair}, {ticker}") + for pair, timeframe in self.dp.available_pairs: + print(f"available {pair}, {timeframe}") ``` #### Get data for non-tradeable pairs diff --git a/docs/utils.md b/docs/utils.md index cdf0c31af..ec9ceeac9 100644 --- a/docs/utils.md +++ b/docs/utils.md @@ -61,8 +61,8 @@ $ freqtrade new-config --config config_binance.json ? Do you want to enable Dry-run (simulated trades)? Yes ? Please insert your stake currency: BTC ? Please insert your stake amount: 0.05 -? Please insert max_open_trades (Integer or 'unlimited'): 5 -? Please insert your ticker interval: 15m +? Please insert max_open_trades (Integer or 'unlimited'): 3 +? Please insert your timeframe (ticker interval): 5m ? Please insert your display Currency (for reporting): USD ? Select exchange binance ? Do you want to enable Telegram? No @@ -258,7 +258,7 @@ All exchanges supported by the ccxt library: _1btcxe, acx, adara, allcoin, anxpr ## List Timeframes -Use the `list-timeframes` subcommand to see the list of ticker intervals (timeframes) available for the exchange. +Use the `list-timeframes` subcommand to see the list of timeframes (ticker intervals) available for the exchange. ``` usage: freqtrade list-timeframes [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--exchange EXCHANGE] [-1] diff --git a/freqtrade/commands/arguments.py b/freqtrade/commands/arguments.py index 73e77d69d..06acea69e 100644 --- a/freqtrade/commands/arguments.py +++ b/freqtrade/commands/arguments.py @@ -296,7 +296,7 @@ class Arguments: # Add convert-data subcommand convert_data_cmd = subparsers.add_parser( 'convert-data', - help='Convert OHLCV data from one format to another.', + help='Convert candle (OHLCV) data from one format to another.', parents=[_common_parser], ) convert_data_cmd.set_defaults(func=partial(start_convert_data, ohlcv=True)) @@ -305,7 +305,7 @@ class Arguments: # Add convert-trade-data subcommand convert_trade_data_cmd = subparsers.add_parser( 'convert-trade-data', - help='Convert trade-data from one format to another.', + help='Convert trade data from one format to another.', parents=[_common_parser], ) convert_trade_data_cmd.set_defaults(func=partial(start_convert_data, ohlcv=False)) diff --git a/freqtrade/commands/build_config_commands.py b/freqtrade/commands/build_config_commands.py index 1598fa2ae..58ac6ec27 100644 --- a/freqtrade/commands/build_config_commands.py +++ b/freqtrade/commands/build_config_commands.py @@ -76,7 +76,7 @@ def ask_user_config() -> Dict[str, Any]: { "type": "text", "name": "ticker_interval", - "message": "Please insert your ticker interval:", + "message": "Please insert your timeframe (ticker interval):", "default": "5m", }, { diff --git a/freqtrade/commands/cli_options.py b/freqtrade/commands/cli_options.py index ef674c5c2..e92acef30 100644 --- a/freqtrade/commands/cli_options.py +++ b/freqtrade/commands/cli_options.py @@ -348,7 +348,7 @@ AVAILABLE_CLI_OPTIONS = { ), "dataformat_ohlcv": Arg( '--data-format-ohlcv', - help='Storage format for downloaded ohlcv data. (default: `%(default)s`).', + help='Storage format for downloaded candle (OHLCV) data. (default: `%(default)s`).', choices=constants.AVAILABLE_DATAHANDLERS, default='json' ), diff --git a/freqtrade/configuration/timerange.py b/freqtrade/configuration/timerange.py index 3db5f6217..151003999 100644 --- a/freqtrade/configuration/timerange.py +++ b/freqtrade/configuration/timerange.py @@ -45,7 +45,7 @@ class TimeRange: """ Adjust startts by candles. Applies only if no startup-candles have been available. - :param timeframe_secs: Ticker timeframe in seconds e.g. `timeframe_to_seconds('5m')` + :param timeframe_secs: Timeframe in seconds e.g. `timeframe_to_seconds('5m')` :param startup_candles: Number of candles to move start-date forward :param min_date: Minimum data date loaded. Key kriterium to decide if start-time has to be moved diff --git a/freqtrade/data/btanalysis.py b/freqtrade/data/btanalysis.py index 7972c6333..681bf6734 100644 --- a/freqtrade/data/btanalysis.py +++ b/freqtrade/data/btanalysis.py @@ -151,17 +151,17 @@ def extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame) -> p return trades -def combine_tickers_with_mean(tickers: Dict[str, pd.DataFrame], - column: str = "close") -> pd.DataFrame: +def combine_dataframes_with_mean(data: Dict[str, pd.DataFrame], + column: str = "close") -> pd.DataFrame: """ Combine multiple dataframes "column" - :param tickers: Dict of Dataframes, dict key should be pair. + :param data: Dict of Dataframes, dict key should be pair. :param column: Column in the original dataframes to use :return: DataFrame with the column renamed to the dict key, and a column named mean, containing the mean of all pairs. """ - df_comb = pd.concat([tickers[pair].set_index('date').rename( - {column: pair}, axis=1)[pair] for pair in tickers], axis=1) + df_comb = pd.concat([data[pair].set_index('date').rename( + {column: pair}, axis=1)[pair] for pair in data], axis=1) df_comb['mean'] = df_comb.mean(axis=1) diff --git a/freqtrade/data/converter.py b/freqtrade/data/converter.py index 49a2a25bc..77371bf27 100644 --- a/freqtrade/data/converter.py +++ b/freqtrade/data/converter.py @@ -13,12 +13,12 @@ from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS logger = logging.getLogger(__name__) -def parse_ticker_dataframe(ticker: list, timeframe: str, pair: str, *, - fill_missing: bool = True, - drop_incomplete: bool = True) -> DataFrame: +def ohlcv_to_dataframe(ohlcv: list, timeframe: str, pair: str, *, + fill_missing: bool = True, drop_incomplete: bool = True) -> DataFrame: """ - Converts a ticker-list (format ccxt.fetch_ohlcv) to a Dataframe - :param ticker: ticker list, as returned by exchange.async_get_candle_history + Converts a list with candle (OHLCV) data (in format returned by ccxt.fetch_ohlcv) + to a Dataframe + :param ohlcv: list with candle (OHLCV) data, as returned by exchange.async_get_candle_history :param timeframe: timeframe (e.g. 5m). Used to fill up eventual missing data :param pair: Pair this data is for (used to warn if fillup was necessary) :param fill_missing: fill up missing candles with 0 candles @@ -26,21 +26,18 @@ def parse_ticker_dataframe(ticker: list, timeframe: str, pair: str, *, :param drop_incomplete: Drop the last candle of the dataframe, assuming it's incomplete :return: DataFrame """ - logger.debug("Parsing tickerlist to dataframe") + logger.debug(f"Converting candle (OHLCV) data to dataframe for pair {pair}.") cols = DEFAULT_DATAFRAME_COLUMNS - frame = DataFrame(ticker, columns=cols) + df = DataFrame(ohlcv, columns=cols) - frame['date'] = to_datetime(frame['date'], - unit='ms', - utc=True, - infer_datetime_format=True) + df['date'] = to_datetime(df['date'], unit='ms', utc=True, infer_datetime_format=True) - # Some exchanges return int values for volume and even for ohlc. + # Some exchanges return int values for Volume and even for OHLC. # Convert them since TA-LIB indicators used in the strategy assume floats # and fail with exception... - frame = frame.astype(dtype={'open': 'float', 'high': 'float', 'low': 'float', 'close': 'float', - 'volume': 'float'}) - return clean_ohlcv_dataframe(frame, timeframe, pair, + df = df.astype(dtype={'open': 'float', 'high': 'float', 'low': 'float', 'close': 'float', + 'volume': 'float'}) + return clean_ohlcv_dataframe(df, timeframe, pair, fill_missing=fill_missing, drop_incomplete=drop_incomplete) @@ -49,11 +46,11 @@ def clean_ohlcv_dataframe(data: DataFrame, timeframe: str, pair: str, *, fill_missing: bool = True, drop_incomplete: bool = True) -> DataFrame: """ - Clense a ohlcv dataframe by + Clense a OHLCV dataframe by * Grouping it by date (removes duplicate tics) * dropping last candles if requested * Filling up missing data (if requested) - :param data: DataFrame containing ohlcv data. + :param data: DataFrame containing candle (OHLCV) data. :param timeframe: timeframe (e.g. 5m). Used to fill up eventual missing data :param pair: Pair this data is for (used to warn if fillup was necessary) :param fill_missing: fill up missing candles with 0 candles @@ -88,16 +85,16 @@ def ohlcv_fill_up_missing_data(dataframe: DataFrame, timeframe: str, pair: str) """ from freqtrade.exchange import timeframe_to_minutes - ohlc_dict = { + ohlcv_dict = { 'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum' } - ticker_minutes = timeframe_to_minutes(timeframe) + timeframe_minutes = timeframe_to_minutes(timeframe) # Resample to create "NAN" values - df = dataframe.resample(f'{ticker_minutes}min', on='date').agg(ohlc_dict) + df = dataframe.resample(f'{timeframe_minutes}min', on='date').agg(ohlcv_dict) # Forwardfill close for missing columns df['close'] = df['close'].fillna(method='ffill') @@ -159,20 +156,20 @@ def order_book_to_dataframe(bids: list, asks: list) -> DataFrame: def trades_to_ohlcv(trades: list, timeframe: str) -> DataFrame: """ - Converts trades list to ohlcv list + Converts trades list to OHLCV list TODO: This should get a dedicated test :param trades: List of trades, as returned by ccxt.fetch_trades. - :param timeframe: Ticker timeframe to resample data to - :return: ohlcv Dataframe. + :param timeframe: Timeframe to resample data to + :return: OHLCV Dataframe. """ from freqtrade.exchange import timeframe_to_minutes - ticker_minutes = timeframe_to_minutes(timeframe) + timeframe_minutes = timeframe_to_minutes(timeframe) df = pd.DataFrame(trades) df['datetime'] = pd.to_datetime(df['datetime']) df = df.set_index('datetime') - df_new = df['price'].resample(f'{ticker_minutes}min').ohlc() - df_new['volume'] = df['amount'].resample(f'{ticker_minutes}min').sum() + df_new = df['price'].resample(f'{timeframe_minutes}min').ohlc() + df_new['volume'] = df['amount'].resample(f'{timeframe_minutes}min').sum() df_new['date'] = df_new.index # Drop 0 volume rows df_new = df_new.dropna() @@ -206,7 +203,7 @@ def convert_trades_format(config: Dict[str, Any], convert_from: str, convert_to: def convert_ohlcv_format(config: Dict[str, Any], convert_from: str, convert_to: str, erase: bool): """ - Convert ohlcv from one format to another format. + Convert OHLCV from one format to another :param config: Config dictionary :param convert_from: Source format :param convert_to: Target format @@ -216,7 +213,7 @@ def convert_ohlcv_format(config: Dict[str, Any], convert_from: str, convert_to: src = get_datahandler(config['datadir'], convert_from) trg = get_datahandler(config['datadir'], convert_to) timeframes = config.get('timeframes', [config.get('ticker_interval')]) - logger.info(f"Converting OHLCV for timeframe {timeframes}") + logger.info(f"Converting candle (OHLCV) for timeframe {timeframes}") if 'pairs' not in config: config['pairs'] = [] @@ -224,7 +221,7 @@ def convert_ohlcv_format(config: Dict[str, Any], convert_from: str, convert_to: for timeframe in timeframes: config['pairs'].extend(src.ohlcv_get_pairs(config['datadir'], timeframe)) - logger.info(f"Converting OHLCV for {config['pairs']}") + logger.info(f"Converting candle (OHLCV) data for {config['pairs']}") for timeframe in timeframes: for pair in config['pairs']: diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 2964d1cb7..1df710152 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -1,7 +1,7 @@ """ Dataprovider Responsible to provide data to the bot -including Klines, tickers, historic data +including ticker and orderbook data, live and historical candle (OHLCV) data Common Interface for bot and strategy to access data. """ import logging @@ -43,10 +43,10 @@ class DataProvider: def ohlcv(self, pair: str, timeframe: str = None, copy: bool = True) -> DataFrame: """ - Get ohlcv data for the given pair as DataFrame + Get candle (OHLCV) data for the given pair as DataFrame Please use the `available_pairs` method to verify which pairs are currently cached. :param pair: pair to get the data for - :param timeframe: Ticker timeframe to get data for + :param timeframe: Timeframe to get data for :param copy: copy dataframe before returning if True. Use False only for read-only operations (where the dataframe is not modified) """ @@ -58,7 +58,7 @@ class DataProvider: def historic_ohlcv(self, pair: str, timeframe: str = None) -> DataFrame: """ - Get stored historic ohlcv data + Get stored historical candle (OHLCV) data :param pair: pair to get the data for :param timeframe: timeframe to get data for """ @@ -69,17 +69,17 @@ class DataProvider: def get_pair_dataframe(self, pair: str, timeframe: str = None) -> DataFrame: """ - Return pair ohlcv data, either live or cached historical -- depending + Return pair candle (OHLCV) data, either live or cached historical -- depending on the runmode. :param pair: pair to get the data for :param timeframe: timeframe to get data for :return: Dataframe for this pair """ if self.runmode in (RunMode.DRY_RUN, RunMode.LIVE): - # Get live ohlcv data. + # Get live OHLCV data. data = self.ohlcv(pair=pair, timeframe=timeframe) else: - # Get historic ohlcv data (cached on disk). + # Get historical OHLCV data (cached on disk). data = self.historic_ohlcv(pair=pair, timeframe=timeframe) if len(data) == 0: logger.warning(f"No data found for ({pair}, {timeframe}).") diff --git a/freqtrade/data/history/history_utils.py b/freqtrade/data/history/history_utils.py index 5f9a7da20..89d29d33b 100644 --- a/freqtrade/data/history/history_utils.py +++ b/freqtrade/data/history/history_utils.py @@ -9,7 +9,7 @@ from pandas import DataFrame from freqtrade.configuration import TimeRange from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS -from freqtrade.data.converter import parse_ticker_dataframe, trades_to_ohlcv +from freqtrade.data.converter import ohlcv_to_dataframe, trades_to_ohlcv from freqtrade.data.history.idatahandler import IDataHandler, get_datahandler from freqtrade.exceptions import OperationalException from freqtrade.exchange import Exchange @@ -28,10 +28,10 @@ def load_pair_history(pair: str, data_handler: IDataHandler = None, ) -> DataFrame: """ - Load cached ticker history for the given pair. + Load cached ohlcv history for the given pair. :param pair: Pair to load data for - :param timeframe: Ticker timeframe (e.g. "5m") + :param timeframe: Timeframe (e.g. "5m") :param datadir: Path to the data storage location. :param data_format: Format of the data. Ignored if data_handler is set. :param timerange: Limit data to be loaded to this timerange @@ -63,10 +63,10 @@ def load_data(datadir: Path, data_format: str = 'json', ) -> Dict[str, DataFrame]: """ - Load ticker history data for a list of pairs. + Load ohlcv history data for a list of pairs. :param datadir: Path to the data storage location. - :param timeframe: Ticker Timeframe (e.g. "5m") + :param timeframe: Timeframe (e.g. "5m") :param pairs: List of pairs to load :param timerange: Limit data to be loaded to this timerange :param fill_up_missing: Fill missing values with "No action"-candles @@ -104,10 +104,10 @@ def refresh_data(datadir: Path, timerange: Optional[TimeRange] = None, ) -> None: """ - Refresh ticker history data for a list of pairs. + Refresh ohlcv history data for a list of pairs. :param datadir: Path to the data storage location. - :param timeframe: Ticker Timeframe (e.g. "5m") + :param timeframe: Timeframe (e.g. "5m") :param pairs: List of pairs to load :param exchange: Exchange object :param timerange: Limit data to be loaded to this timerange @@ -165,7 +165,7 @@ def _download_pair_history(datadir: Path, Based on @Rybolov work: https://github.com/rybolov/freqtrade-data :param pair: pair to download - :param timeframe: Ticker Timeframe (e.g 5m) + :param timeframe: Timeframe (e.g "5m") :param timerange: range of time to download :return: bool with success state """ @@ -194,8 +194,8 @@ def _download_pair_history(datadir: Path, days=-30).float_timestamp) * 1000 ) # TODO: Maybe move parsing to exchange class (?) - new_dataframe = parse_ticker_dataframe(new_data, timeframe, pair, - fill_missing=False, drop_incomplete=True) + new_dataframe = ohlcv_to_dataframe(new_data, timeframe, pair, + fill_missing=False, drop_incomplete=True) if data.empty: data = new_dataframe else: @@ -362,7 +362,7 @@ def validate_backtest_data(data: DataFrame, pair: str, min_date: datetime, :param pair: pair used for log output. :param min_date: start-date of the data :param max_date: end-date of the data - :param timeframe_min: ticker Timeframe in minutes + :param timeframe_min: Timeframe in minutes """ # total difference in minutes / timeframe-minutes expected_frames = int((max_date - min_date).total_seconds() // 60 // timeframe_min) diff --git a/freqtrade/data/history/idatahandler.py b/freqtrade/data/history/idatahandler.py index df03e7713..b08292604 100644 --- a/freqtrade/data/history/idatahandler.py +++ b/freqtrade/data/history/idatahandler.py @@ -55,7 +55,7 @@ class IDataHandler(ABC): Implements the loading and conversion to a Pandas dataframe. Timerange trimming and dataframe validation happens outside of this method. :param pair: Pair to load data - :param timeframe: Ticker timeframe (e.g. "5m") + :param timeframe: Timeframe (e.g. "5m") :param timerange: Limit data to be loaded to this timerange. Optionally implemented by subclasses to avoid loading all data where possible. @@ -67,7 +67,7 @@ class IDataHandler(ABC): """ Remove data for this pair :param pair: Delete data for this pair. - :param timeframe: Ticker timeframe (e.g. "5m") + :param timeframe: Timeframe (e.g. "5m") :return: True when deleted, false if file did not exist. """ @@ -129,10 +129,10 @@ class IDataHandler(ABC): warn_no_data: bool = True ) -> DataFrame: """ - Load cached ticker history for the given pair. + Load cached candle (OHLCV) data for the given pair. :param pair: Pair to load data for - :param timeframe: Ticker timeframe (e.g. "5m") + :param timeframe: Timeframe (e.g. "5m") :param timerange: Limit data to be loaded to this timerange :param fill_missing: Fill missing values with "No action"-candles :param drop_incomplete: Drop last candle assuming it may be incomplete. @@ -145,28 +145,27 @@ class IDataHandler(ABC): if startup_candles > 0 and timerange_startup: timerange_startup.subtract_start(timeframe_to_seconds(timeframe) * startup_candles) - pairdf = self._ohlcv_load(pair, timeframe, - timerange=timerange_startup) - if pairdf.empty: + df = self._ohlcv_load(pair, timeframe, timerange=timerange_startup) + if df.empty: if warn_no_data: logger.warning( f'No history data for pair: "{pair}", timeframe: {timeframe}. ' 'Use `freqtrade download-data` to download the data' ) - return pairdf + return df else: - enddate = pairdf.iloc[-1]['date'] + enddate = df.iloc[-1]['date'] if timerange_startup: - self._validate_pairdata(pair, pairdf, timerange_startup) - pairdf = trim_dataframe(pairdf, timerange_startup) + self._validate_pairdata(pair, df, timerange_startup) + df = trim_dataframe(df, timerange_startup) # incomplete candles should only be dropped if we didn't trim the end beforehand. - return clean_ohlcv_dataframe(pairdf, timeframe, + return clean_ohlcv_dataframe(df, timeframe, pair=pair, fill_missing=fill_missing, drop_incomplete=(drop_incomplete and - enddate == pairdf.iloc[-1]['date'])) + enddate == df.iloc[-1]['date'])) def _validate_pairdata(self, pair, pairdata: DataFrame, timerange: TimeRange): """ diff --git a/freqtrade/data/history/jsondatahandler.py b/freqtrade/data/history/jsondatahandler.py index 2b738a94a..363b03958 100644 --- a/freqtrade/data/history/jsondatahandler.py +++ b/freqtrade/data/history/jsondatahandler.py @@ -60,7 +60,7 @@ class JsonDataHandler(IDataHandler): Implements the loading and conversion to a Pandas dataframe. Timerange trimming and dataframe validation happens outside of this method. :param pair: Pair to load data - :param timeframe: Ticker timeframe (e.g. "5m") + :param timeframe: Timeframe (e.g. "5m") :param timerange: Limit data to be loaded to this timerange. Optionally implemented by subclasses to avoid loading all data where possible. @@ -83,7 +83,7 @@ class JsonDataHandler(IDataHandler): """ Remove data for this pair :param pair: Delete data for this pair. - :param timeframe: Ticker timeframe (e.g. "5m") + :param timeframe: Timeframe (e.g. "5m") :return: True when deleted, false if file did not exist. """ filename = self._pair_data_filename(self._datadir, pair, timeframe) diff --git a/freqtrade/edge/edge_positioning.py b/freqtrade/edge/edge_positioning.py index 57a8f4a7c..a24e29efb 100644 --- a/freqtrade/edge/edge_positioning.py +++ b/freqtrade/edge/edge_positioning.py @@ -119,7 +119,7 @@ class Edge: logger.critical("No data found. Edge is stopped ...") return False - preprocessed = self.strategy.tickerdata_to_dataframe(data) + preprocessed = self.strategy.ohlcvdata_to_dataframe(data) # Print timeframe min_date, max_date = history.get_timerange(preprocessed) @@ -137,10 +137,10 @@ class Edge: pair_data = pair_data.sort_values(by=['date']) pair_data = pair_data.reset_index(drop=True) - ticker_data = self.strategy.advise_sell( + dataframe = self.strategy.advise_sell( self.strategy.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy() - trades += self._find_trades_for_stoploss_range(ticker_data, pair, self._stoploss_range) + trades += self._find_trades_for_stoploss_range(dataframe, pair, self._stoploss_range) # If no trade found then exit if len(trades) == 0: @@ -359,11 +359,11 @@ class Edge: # Returning a list of pairs in order of "expectancy" return final - def _find_trades_for_stoploss_range(self, ticker_data, pair, stoploss_range): - buy_column = ticker_data['buy'].values - sell_column = ticker_data['sell'].values - date_column = ticker_data['date'].values - ohlc_columns = ticker_data[['open', 'high', 'low', 'close']].values + def _find_trades_for_stoploss_range(self, dataframe, pair, stoploss_range): + buy_column = dataframe['buy'].values + sell_column = dataframe['sell'].values + date_column = dataframe['date'].values + ohlc_columns = dataframe[['open', 'high', 'low', 'close']].values result: list = [] for stoploss in stoploss_range: diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index 522b4e40e..f4c94a1ca 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -18,7 +18,7 @@ from ccxt.base.decimal_to_precision import (ROUND_DOWN, ROUND_UP, TICK_SIZE, TRUNCATE, decimal_to_precision) from pandas import DataFrame -from freqtrade.data.converter import parse_ticker_dataframe +from freqtrade.data.converter import ohlcv_to_dataframe from freqtrade.exceptions import (DependencyException, InvalidOrderException, OperationalException, TemporaryError) from freqtrade.exchange.common import BAD_EXCHANGES, retrier, retrier_async @@ -351,7 +351,7 @@ class Exchange: def validate_timeframes(self, timeframe: Optional[str]) -> None: """ - Checks if ticker interval from config is a supported timeframe on the exchange + Check if timeframe from config is a supported timeframe on the exchange """ if not hasattr(self._api, "timeframes") or self._api.timeframes is None: # If timeframes attribute is missing (or is None), the exchange probably @@ -364,7 +364,7 @@ class Exchange: if timeframe and (timeframe not in self.timeframes): raise OperationalException( - f"Invalid ticker interval '{timeframe}'. This exchange supports: {self.timeframes}") + f"Invalid timeframe '{timeframe}'. This exchange supports: {self.timeframes}") if timeframe and timeframe_to_minutes(timeframe) < 1: raise OperationalException( @@ -599,7 +599,7 @@ class Exchange: return self._api.fetch_tickers() except ccxt.NotSupported as e: raise OperationalException( - f'Exchange {self._api.name} does not support fetching tickers in batch.' + f'Exchange {self._api.name} does not support fetching tickers in batch. ' f'Message: {e}') from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: raise TemporaryError( @@ -623,13 +623,13 @@ class Exchange: def get_historic_ohlcv(self, pair: str, timeframe: str, since_ms: int) -> List: """ - Gets candle history using asyncio and returns the list of candles. - Handles all async doing. - Async over one pair, assuming we get `_ohlcv_candle_limit` candles per call. + Get candle history using asyncio and returns the list of candles. + Handles all async work for this. + Async over one pair, assuming we get `self._ohlcv_candle_limit` candles per call. :param pair: Pair to download - :param timeframe: Ticker Timeframe to get + :param timeframe: Timeframe to get data for :param since_ms: Timestamp in milliseconds to get history from - :returns List of tickers + :returns List with candle (OHLCV) data """ return asyncio.get_event_loop().run_until_complete( self._async_get_historic_ohlcv(pair=pair, timeframe=timeframe, @@ -649,26 +649,27 @@ class Exchange: pair, timeframe, since) for since in range(since_ms, arrow.utcnow().timestamp * 1000, one_call)] - tickers = await asyncio.gather(*input_coroutines, return_exceptions=True) + results = await asyncio.gather(*input_coroutines, return_exceptions=True) - # Combine tickers + # Combine gathered results data: List = [] - for p, timeframe, ticker in tickers: + for p, timeframe, res in results: if p == pair: - data.extend(ticker) + data.extend(res) # Sort data again after extending the result - above calls return in "async order" data = sorted(data, key=lambda x: x[0]) - logger.info("downloaded %s with length %s.", pair, len(data)) + logger.info("Downloaded data for %s with length %s.", pair, len(data)) return data def refresh_latest_ohlcv(self, pair_list: List[Tuple[str, str]]) -> List[Tuple[str, List]]: """ - Refresh in-memory ohlcv asynchronously and set `_klines` with the result + Refresh in-memory OHLCV asynchronously and set `_klines` with the result Loops asynchronously over pair_list and downloads all pairs async (semi-parallel). + Only used in the dataprovider.refresh() method. :param pair_list: List of 2 element tuples containing pair, interval to refresh - :return: Returns a List of ticker-dataframes. + :return: TODO: return value is only used in the tests, get rid of it """ - logger.debug("Refreshing ohlcv data for %d pairs", len(pair_list)) + logger.debug("Refreshing candle (OHLCV) data for %d pairs", len(pair_list)) input_coroutines = [] @@ -679,15 +680,15 @@ class Exchange: input_coroutines.append(self._async_get_candle_history(pair, timeframe)) else: logger.debug( - "Using cached ohlcv data for pair %s, timeframe %s ...", + "Using cached candle (OHLCV) data for pair %s, timeframe %s ...", pair, timeframe ) - tickers = asyncio.get_event_loop().run_until_complete( + results = asyncio.get_event_loop().run_until_complete( asyncio.gather(*input_coroutines, return_exceptions=True)) # handle caching - for res in tickers: + for res in results: if isinstance(res, Exception): logger.warning("Async code raised an exception: %s", res.__class__.__name__) continue @@ -698,13 +699,14 @@ class Exchange: if ticks: self._pairs_last_refresh_time[(pair, timeframe)] = ticks[-1][0] // 1000 # keeping parsed dataframe in cache - self._klines[(pair, timeframe)] = parse_ticker_dataframe( + self._klines[(pair, timeframe)] = ohlcv_to_dataframe( ticks, timeframe, pair=pair, fill_missing=True, drop_incomplete=self._ohlcv_partial_candle) - return tickers + + return results def _now_is_time_to_refresh(self, pair: str, timeframe: str) -> bool: - # Calculating ticker interval in seconds + # Timeframe in seconds interval_in_sec = timeframe_to_seconds(timeframe) return not ((self._pairs_last_refresh_time.get((pair, timeframe), 0) @@ -714,11 +716,11 @@ class Exchange: async def _async_get_candle_history(self, pair: str, timeframe: str, since_ms: Optional[int] = None) -> Tuple[str, str, List]: """ - Asynchronously gets candle histories using fetch_ohlcv + Asynchronously get candle history data using fetch_ohlcv returns tuple: (pair, timeframe, ohlcv_list) """ try: - # fetch ohlcv asynchronously + # Fetch OHLCV asynchronously s = '(' + arrow.get(since_ms // 1000).isoformat() + ') ' if since_ms is not None else '' logger.debug( "Fetching pair %s, interval %s, since %s %s...", @@ -728,9 +730,9 @@ class Exchange: data = await self._api_async.fetch_ohlcv(pair, timeframe=timeframe, since=since_ms) - # Because some exchange sort Tickers ASC and other DESC. - # Ex: Bittrex returns a list of tickers ASC (oldest first, newest last) - # when GDAX returns a list of tickers DESC (newest first, oldest last) + # Some exchanges sort OHLCV in ASC order and others in DESC. + # Ex: Bittrex returns the list of OHLCV in ASC order (oldest first, newest last) + # while GDAX returns the list of OHLCV in DESC order (newest first, oldest last) # Only sort if necessary to save computing time try: if data and data[0][0] > data[-1][0]: @@ -743,14 +745,15 @@ class Exchange: except ccxt.NotSupported as e: raise OperationalException( - f'Exchange {self._api.name} does not support fetching historical candlestick data.' - f'Message: {e}') from e + f'Exchange {self._api.name} does not support fetching historical ' + f'candle (OHLCV) data. Message: {e}') from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: - raise TemporaryError(f'Could not load ticker history for pair {pair} due to ' - f'{e.__class__.__name__}. Message: {e}') from e + raise TemporaryError(f'Could not fetch historical candle (OHLCV) data ' + f'for pair {pair} due to {e.__class__.__name__}. ' + f'Message: {e}') from e except ccxt.BaseError as e: - raise OperationalException(f'Could not fetch ticker data for pair {pair}. ' - f'Msg: {e}') from e + raise OperationalException(f'Could not fetch historical candle (OHLCV) data ' + f'for pair {pair}. Message: {e}') from e @retrier_async async def _async_fetch_trades(self, pair: str, @@ -883,14 +886,14 @@ class Exchange: until: Optional[int] = None, from_id: Optional[str] = None) -> Tuple[str, List]: """ - Gets candle history using asyncio and returns the list of candles. - Handles all async doing. - Async over one pair, assuming we get `_ohlcv_candle_limit` candles per call. + Get trade history data using asyncio. + Handles all async work and returns the list of candles. + Async over one pair, assuming we get `self._ohlcv_candle_limit` candles per call. :param pair: Pair to download :param since: Timestamp in milliseconds to get history from :param until: Timestamp in milliseconds. Defaults to current timestamp if not defined. :param from_id: Download data starting with ID (if id is known) - :returns List of tickers + :returns List of trade data """ if not self.exchange_has("fetchTrades"): raise OperationalException("This exchange does not suport downloading Trades.") diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 914b8d9cd..9897b39b4 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -172,8 +172,8 @@ class FreqtradeBot: _whitelist = self.edge.adjust(_whitelist) if trades: - # Extend active-pair whitelist with pairs from open trades - # It ensures that tickers are downloaded for open trades + # Extend active-pair whitelist with pairs of open trades + # It ensures that candle (OHLCV) data are downloaded for open trades as well _whitelist.extend([trade.pair for trade in trades if trade.pair not in _whitelist]) return _whitelist @@ -628,7 +628,7 @@ class FreqtradeBot: def get_sell_rate(self, pair: str, refresh: bool) -> float: """ - Get sell rate - either using get-ticker bid or first bid based on orderbook + Get sell rate - either using ticker bid or first bid based on orderbook The orderbook portion is only used for rpc messaging, which would otherwise fail for BitMex (has no bid/ask in fetch_ticker) or remain static in any other case since it's not updating. @@ -1043,7 +1043,7 @@ class FreqtradeBot: """ profit_rate = trade.close_rate if trade.close_rate else trade.close_rate_requested profit_trade = trade.calc_profit(rate=profit_rate) - # Use cached ticker here - it was updated seconds ago. + # Use cached rates here - it was updated seconds ago. current_rate = self.get_sell_rate(trade.pair, False) profit_ratio = trade.calc_profit_ratio(profit_rate) gain = "profit" if profit_ratio > 0 else "loss" diff --git a/freqtrade/misc.py b/freqtrade/misc.py index 96bac28d8..1f52b75ec 100644 --- a/freqtrade/misc.py +++ b/freqtrade/misc.py @@ -81,13 +81,13 @@ def file_load_json(file): gzipfile = file # Try gzip file first, otherwise regular json file. if gzipfile.is_file(): - logger.debug('Loading ticker data from file %s', gzipfile) - with gzip.open(gzipfile) as tickerdata: - pairdata = json_load(tickerdata) + logger.debug(f"Loading historical data from file {gzipfile}") + with gzip.open(gzipfile) as datafile: + pairdata = json_load(datafile) elif file.is_file(): - logger.debug('Loading ticker data from file %s', file) - with open(file) as tickerdata: - pairdata = json_load(tickerdata) + logger.debug(f"Loading historical data from file {file}") + with open(file) as datafile: + pairdata = json_load(datafile) else: return None return pairdata diff --git a/freqtrade/optimize/backtesting.py b/freqtrade/optimize/backtesting.py index 94441ce24..949c072c5 100644 --- a/freqtrade/optimize/backtesting.py +++ b/freqtrade/optimize/backtesting.py @@ -88,8 +88,8 @@ class Backtesting: validate_config_consistency(self.config) if "ticker_interval" not in self.config: - raise OperationalException("Ticker-interval needs to be set in either configuration " - "or as cli argument `--ticker-interval 5m`") + raise OperationalException("Timeframe (ticker interval) needs to be set in either " + "configuration or as cli argument `--ticker-interval 5m`") self.timeframe = str(self.config.get('ticker_interval')) self.timeframe_min = timeframe_to_minutes(self.timeframe) @@ -151,32 +151,33 @@ class Backtesting: logger.info(f'Dumping backtest results to {recordfilename}') file_dump_json(recordfilename, records) - def _get_ticker_list(self, processed: Dict) -> Dict[str, DataFrame]: + def _get_ohlcv_as_lists(self, processed: Dict) -> Dict[str, DataFrame]: """ - Helper function to convert a processed tickerlist into a list for performance reasons. + Helper function to convert a processed dataframes into lists for performance reasons. Used by backtest() - so keep this optimized for performance. """ headers = ['date', 'buy', 'open', 'close', 'sell', 'low', 'high'] - ticker: Dict = {} - # Create ticker dict + data: Dict = {} + # Create dict with data for pair, pair_data in processed.items(): pair_data.loc[:, 'buy'] = 0 # cleanup from previous run pair_data.loc[:, 'sell'] = 0 # cleanup from previous run - ticker_data = self.strategy.advise_sell( + dataframe = self.strategy.advise_sell( self.strategy.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy() - # to avoid using data from future, we buy/sell with signal from previous candle - ticker_data.loc[:, 'buy'] = ticker_data['buy'].shift(1) - ticker_data.loc[:, 'sell'] = ticker_data['sell'].shift(1) + # To avoid using data from future, we use buy/sell signals shifted + # from the previous candle + dataframe.loc[:, 'buy'] = dataframe['buy'].shift(1) + dataframe.loc[:, 'sell'] = dataframe['sell'].shift(1) - ticker_data.drop(ticker_data.head(1).index, inplace=True) + dataframe.drop(dataframe.head(1).index, inplace=True) # Convert from Pandas to list for performance reasons # (Looping Pandas is slow.) - ticker[pair] = [x for x in ticker_data.itertuples()] - return ticker + data[pair] = [x for x in dataframe.itertuples()] + return data def _get_close_rate(self, sell_row, trade: Trade, sell: SellCheckTuple, trade_dur: int) -> float: @@ -220,7 +221,7 @@ class Backtesting: def _get_sell_trade_entry( self, pair: str, buy_row: DataFrame, - partial_ticker: List, trade_count_lock: Dict, + partial_ohlcv: List, trade_count_lock: Dict, stake_amount: float, max_open_trades: int) -> Optional[BacktestResult]: trade = Trade( @@ -235,7 +236,7 @@ class Backtesting: ) logger.debug(f"{pair} - Backtesting emulates creation of new trade: {trade}.") # calculate win/lose forwards from buy point - for sell_row in partial_ticker: + for sell_row in partial_ohlcv: if max_open_trades > 0: # Increase trade_count_lock for every iteration trade_count_lock[sell_row.date] = trade_count_lock.get(sell_row.date, 0) + 1 @@ -259,9 +260,9 @@ class Backtesting: close_rate=closerate, sell_reason=sell.sell_type ) - if partial_ticker: + if partial_ohlcv: # no sell condition found - trade stil open at end of backtest period - sell_row = partial_ticker[-1] + sell_row = partial_ohlcv[-1] bt_res = BacktestResult(pair=pair, profit_percent=trade.calc_profit_ratio(rate=sell_row.open), profit_abs=trade.calc_profit(rate=sell_row.open), @@ -308,8 +309,9 @@ class Backtesting: trades = [] trade_count_lock: Dict = {} - # Dict of ticker-lists for performance (looping lists is a lot faster than dataframes) - ticker: Dict = self._get_ticker_list(processed) + # Use dict of lists with data for performance + # (looping lists is a lot faster than pandas DataFrames) + data: Dict = self._get_ohlcv_as_lists(processed) lock_pair_until: Dict = {} # Indexes per pair, so some pairs are allowed to have a missing start. @@ -319,12 +321,12 @@ class Backtesting: # Loop timerange and get candle for each pair at that point in time while tmp < end_date: - for i, pair in enumerate(ticker): + for i, pair in enumerate(data): if pair not in indexes: indexes[pair] = 0 try: - row = ticker[pair][indexes[pair]] + row = data[pair][indexes[pair]] except IndexError: # missing Data for one pair at the end. # Warnings for this are shown during data loading @@ -352,7 +354,7 @@ class Backtesting: # since indexes has been incremented before, we need to go one step back to # also check the buying candle for sell conditions. - trade_entry = self._get_sell_trade_entry(pair, row, ticker[pair][indexes[pair]-1:], + trade_entry = self._get_sell_trade_entry(pair, row, data[pair][indexes[pair]-1:], trade_count_lock, stake_amount, max_open_trades) @@ -395,7 +397,7 @@ class Backtesting: self._set_strategy(strat) # need to reprocess data every time to populate signals - preprocessed = self.strategy.tickerdata_to_dataframe(data) + preprocessed = self.strategy.ohlcvdata_to_dataframe(data) # Trim startup period from analyzed dataframe for pair, df in preprocessed.items(): diff --git a/freqtrade/optimize/hyperopt.py b/freqtrade/optimize/hyperopt.py index e9ab469f4..ed58db977 100644 --- a/freqtrade/optimize/hyperopt.py +++ b/freqtrade/optimize/hyperopt.py @@ -75,8 +75,8 @@ class Hyperopt: self.trials_file = (self.config['user_data_dir'] / 'hyperopt_results' / 'hyperopt_results.pickle') - self.tickerdata_pickle = (self.config['user_data_dir'] / - 'hyperopt_results' / 'hyperopt_tickerdata.pkl') + self.data_pickle_file = (self.config['user_data_dir'] / + 'hyperopt_results' / 'hyperopt_data.pkl') self.total_epochs = config.get('epochs', 0) self.current_best_loss = 100 @@ -130,7 +130,7 @@ class Hyperopt: """ Remove hyperopt pickle files to restart hyperopt. """ - for f in [self.tickerdata_pickle, self.trials_file]: + for f in [self.data_pickle_file, self.trials_file]: p = Path(f) if p.is_file(): logger.info(f"Removing `{p}`.") @@ -454,7 +454,7 @@ class Hyperopt: self.backtesting.strategy.trailing_only_offset_is_reached = \ d['trailing_only_offset_is_reached'] - processed = load(self.tickerdata_pickle) + processed = load(self.data_pickle_file) min_date, max_date = get_timerange(processed) @@ -570,7 +570,7 @@ class Hyperopt: self.hyperopt_table_header = -1 data, timerange = self.backtesting.load_bt_data() - preprocessed = self.backtesting.strategy.tickerdata_to_dataframe(data) + preprocessed = self.backtesting.strategy.ohlcvdata_to_dataframe(data) # Trim startup period from analyzed dataframe for pair, df in preprocessed.items(): @@ -581,7 +581,7 @@ class Hyperopt: 'Hyperopting with data from %s up to %s (%s days)..', min_date.isoformat(), max_date.isoformat(), (max_date - min_date).days ) - dump(preprocessed, self.tickerdata_pickle) + dump(preprocessed, self.data_pickle_file) # We don't need exchange instance anymore while running hyperopt self.backtesting.exchange = None # type: ignore diff --git a/freqtrade/plot/plotting.py b/freqtrade/plot/plotting.py index d979a40e0..cfbda6714 100644 --- a/freqtrade/plot/plotting.py +++ b/freqtrade/plot/plotting.py @@ -6,7 +6,7 @@ import pandas as pd from freqtrade.configuration import TimeRange from freqtrade.data.btanalysis import (calculate_max_drawdown, - combine_tickers_with_mean, + combine_dataframes_with_mean, create_cum_profit, extract_trades_of_period, load_trades) from freqtrade.data.converter import trim_dataframe @@ -29,7 +29,7 @@ except ImportError: def init_plotscript(config): """ Initialize objects needed for plotting - :return: Dict with tickers, trades and pairs + :return: Dict with candle (OHLCV) data, trades and pairs """ if "pairs" in config: @@ -40,7 +40,7 @@ def init_plotscript(config): # Set timerange to use timerange = TimeRange.parse_timerange(config.get("timerange")) - tickers = load_data( + data = load_data( datadir=config.get("datadir"), pairs=pairs, timeframe=config.get('ticker_interval', '5m'), @@ -53,7 +53,7 @@ def init_plotscript(config): exportfilename=config.get('exportfilename'), ) trades = trim_dataframe(trades, timerange, 'open_time') - return {"tickers": tickers, + return {"ohlcv": data, "trades": trades, "pairs": pairs, } @@ -368,10 +368,10 @@ def generate_candlestick_graph(pair: str, data: pd.DataFrame, trades: pd.DataFra return fig -def generate_profit_graph(pairs: str, tickers: Dict[str, pd.DataFrame], +def generate_profit_graph(pairs: str, data: Dict[str, pd.DataFrame], trades: pd.DataFrame, timeframe: str) -> go.Figure: # Combine close-values for all pairs, rename columns to "pair" - df_comb = combine_tickers_with_mean(tickers, "close") + df_comb = combine_dataframes_with_mean(data, "close") # Add combined cumulative profit df_comb = create_cum_profit(df_comb, trades, 'cum_profit', timeframe) @@ -439,7 +439,7 @@ def load_and_plot_trades(config: Dict[str, Any]): """ From configuration provided - Initializes plot-script - - Get tickers data + - Get candle (OHLCV) data - Generate Dafaframes populated with indicators and signals based on configured strategy - Load trades excecuted during the selected period - Generate Plotly plot objects @@ -451,13 +451,13 @@ def load_and_plot_trades(config: Dict[str, Any]): plot_elements = init_plotscript(config) trades = plot_elements['trades'] pair_counter = 0 - for pair, data in plot_elements["tickers"].items(): + for pair, data in plot_elements["ohlcv"].items(): pair_counter += 1 logger.info("analyse pair %s", pair) - tickers = {} - tickers[pair] = data + ohlcv = {} + ohlcv[pair] = data - dataframe = strategy.analyze_ticker(tickers[pair], {'pair': pair}) + dataframe = strategy.analyze_ticker(ohlcv[pair], {'pair': pair}) trades_pair = trades.loc[trades['pair'] == pair] trades_pair = extract_trades_of_period(dataframe, trades_pair) @@ -494,7 +494,7 @@ def plot_profit(config: Dict[str, Any]) -> None: # Create an average close price of all the pairs that were involved. # this could be useful to gauge the overall market trend - fig = generate_profit_graph(plot_elements["pairs"], plot_elements["tickers"], + fig = generate_profit_graph(plot_elements["pairs"], plot_elements["ohlcv"], trades, config.get('ticker_interval', '5m')) store_plot_file(fig, filename='freqtrade-profit-plot.html', directory=config['user_data_dir'] / "plot", auto_open=True) diff --git a/freqtrade/strategy/interface.py b/freqtrade/strategy/interface.py index d23af3f6e..696d2b2d2 100644 --- a/freqtrade/strategy/interface.py +++ b/freqtrade/strategy/interface.py @@ -59,7 +59,7 @@ class IStrategy(ABC): Attributes you can use: minimal_roi -> Dict: Minimal ROI designed for the strategy stoploss -> float: optimal stoploss designed for the strategy - ticker_interval -> str: value of the ticker interval to use for the strategy + ticker_interval -> str: value of the timeframe (ticker interval) to use with the strategy """ # Strategy interface version # Default to version 2 @@ -125,7 +125,7 @@ class IStrategy(ABC): def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ Populate indicators that will be used in the Buy and Sell strategy - :param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe() + :param dataframe: DataFrame with data from the exchange :param metadata: Additional information, like the currently traded pair :return: a Dataframe with all mandatory indicators for the strategies """ @@ -200,11 +200,11 @@ class IStrategy(ABC): def analyze_ticker(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ - Parses the given ticker history and returns a populated DataFrame + Parses the given candle (OHLCV) data and returns a populated DataFrame add several TA indicators and buy signal to it - :param dataframe: Dataframe containing ticker data + :param dataframe: Dataframe containing data from exchange :param metadata: Metadata dictionary with additional data (e.g. 'pair') - :return: DataFrame with ticker data and indicator data + :return: DataFrame of candle (OHLCV) data with indicator data and signals added """ logger.debug("TA Analysis Launched") dataframe = self.advise_indicators(dataframe, metadata) @@ -214,12 +214,12 @@ class IStrategy(ABC): def _analyze_ticker_internal(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ - Parses the given ticker history and returns a populated DataFrame + Parses the given candle (OHLCV) data and returns a populated DataFrame add several TA indicators and buy signal to it WARNING: Used internally only, may skip analysis if `process_only_new_candles` is set. - :param dataframe: Dataframe containing ticker data + :param dataframe: Dataframe containing data from exchange :param metadata: Metadata dictionary with additional data (e.g. 'pair') - :return: DataFrame with ticker data and indicator data + :return: DataFrame of candle (OHLCV) data with indicator data and signals added """ pair = str(metadata.get('pair')) @@ -251,21 +251,21 @@ class IStrategy(ABC): :return: (Buy, Sell) A bool-tuple indicating buy/sell signal """ if not isinstance(dataframe, DataFrame) or dataframe.empty: - logger.warning('Empty ticker history for pair %s', pair) + logger.warning('Empty candle (OHLCV) data for pair %s', pair) return False, False try: dataframe = self._analyze_ticker_internal(dataframe, {'pair': pair}) except ValueError as error: logger.warning( - 'Unable to analyze ticker for pair %s: %s', + 'Unable to analyze candle (OHLCV) data for pair %s: %s', pair, str(error) ) return False, False except Exception as error: logger.exception( - 'Unexpected error when analyzing ticker for pair %s: %s', + 'Unexpected error when analyzing candle (OHLCV) data for pair %s: %s', pair, str(error) ) @@ -440,19 +440,19 @@ class IStrategy(ABC): else: return current_profit > roi - def tickerdata_to_dataframe(self, tickerdata: Dict[str, DataFrame]) -> Dict[str, DataFrame]: + def ohlcvdata_to_dataframe(self, data: Dict[str, DataFrame]) -> Dict[str, DataFrame]: """ - Creates a dataframe and populates indicators for given ticker data + Creates a dataframe and populates indicators for given candle (OHLCV) data Used by optimize operations only, not during dry / live runs. """ return {pair: self.advise_indicators(pair_data, {'pair': pair}) - for pair, pair_data in tickerdata.items()} + for pair, pair_data in data.items()} def advise_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ Populate indicators that will be used in the Buy and Sell strategy This method should not be overridden. - :param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe() + :param dataframe: Dataframe with data from the exchange :param metadata: Additional information, like the currently traded pair :return: a Dataframe with all mandatory indicators for the strategies """ diff --git a/freqtrade/templates/base_strategy.py.j2 b/freqtrade/templates/base_strategy.py.j2 index fbf083387..97a189ff4 100644 --- a/freqtrade/templates/base_strategy.py.j2 +++ b/freqtrade/templates/base_strategy.py.j2 @@ -99,7 +99,7 @@ class {{ strategy }}(IStrategy): Performance Note: For the best performance be frugal on the number of indicators you are using. Let uncomment only the indicator you are using in your strategies or your hyperopt configuration, otherwise you will waste your memory and CPU usage. - :param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe() + :param dataframe: Dataframe with data from the exchange :param metadata: Additional information, like the currently traded pair :return: a Dataframe with all mandatory indicators for the strategies """ diff --git a/freqtrade/templates/sample_strategy.py b/freqtrade/templates/sample_strategy.py index 17372e1e0..f78489173 100644 --- a/freqtrade/templates/sample_strategy.py +++ b/freqtrade/templates/sample_strategy.py @@ -116,7 +116,7 @@ class SampleStrategy(IStrategy): Performance Note: For the best performance be frugal on the number of indicators you are using. Let uncomment only the indicator you are using in your strategies or your hyperopt configuration, otherwise you will waste your memory and CPU usage. - :param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe() + :param dataframe: Dataframe with data from the exchange :param metadata: Additional information, like the currently traded pair :return: a Dataframe with all mandatory indicators for the strategies """ diff --git a/tests/conftest.py b/tests/conftest.py index e8e3fe9e3..64d0cd5ee 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -15,7 +15,7 @@ from telegram import Chat, Message, Update from freqtrade import constants, persistence from freqtrade.commands import Arguments -from freqtrade.data.converter import parse_ticker_dataframe +from freqtrade.data.converter import ohlcv_to_dataframe from freqtrade.edge import Edge, PairInfo from freqtrade.exchange import Exchange from freqtrade.freqtradebot import FreqtradeBot @@ -849,15 +849,15 @@ def order_book_l2(): @pytest.fixture -def ticker_history_list(): +def ohlcv_history_list(): return [ [ 1511686200000, # unix timestamp ms - 8.794e-05, # open - 8.948e-05, # high - 8.794e-05, # low - 8.88e-05, # close - 0.0877869, # volume (in quote currency) + 8.794e-05, # open + 8.948e-05, # high + 8.794e-05, # low + 8.88e-05, # close + 0.0877869, # volume (in quote currency) ], [ 1511686500000, @@ -879,8 +879,9 @@ def ticker_history_list(): @pytest.fixture -def ticker_history(ticker_history_list): - return parse_ticker_dataframe(ticker_history_list, "5m", pair="UNITTEST/BTC", fill_missing=True) +def ohlcv_history(ohlcv_history_list): + return ohlcv_to_dataframe(ohlcv_history_list, "5m", pair="UNITTEST/BTC", + fill_missing=True) @pytest.fixture @@ -1195,8 +1196,8 @@ def tickers(): @pytest.fixture def result(testdatadir): with (testdatadir / 'UNITTEST_BTC-1m.json').open('r') as data_file: - return parse_ticker_dataframe(json.load(data_file), '1m', pair="UNITTEST/BTC", - fill_missing=True) + return ohlcv_to_dataframe(json.load(data_file), '1m', pair="UNITTEST/BTC", + fill_missing=True) @pytest.fixture(scope="function") diff --git a/tests/data/test_btanalysis.py b/tests/data/test_btanalysis.py index 7e3c1f077..da5d225b9 100644 --- a/tests/data/test_btanalysis.py +++ b/tests/data/test_btanalysis.py @@ -8,7 +8,7 @@ from freqtrade.configuration import TimeRange from freqtrade.data.btanalysis import (BT_DATA_COLUMNS, analyze_trade_parallelism, calculate_max_drawdown, - combine_tickers_with_mean, + combine_dataframes_with_mean, create_cum_profit, extract_trades_of_period, load_backtest_data, load_trades, @@ -120,13 +120,10 @@ def test_load_trades(default_conf, mocker): assert bt_mock.call_count == 1 -def test_combine_tickers_with_mean(testdatadir): +def test_combine_dataframes_with_mean(testdatadir): pairs = ["ETH/BTC", "ADA/BTC"] - tickers = load_data(datadir=testdatadir, - pairs=pairs, - timeframe='5m' - ) - df = combine_tickers_with_mean(tickers) + data = load_data(datadir=testdatadir, pairs=pairs, timeframe='5m') + df = combine_dataframes_with_mean(data) assert isinstance(df, DataFrame) assert "ETH/BTC" in df.columns assert "ADA/BTC" in df.columns diff --git a/tests/data/test_converter.py b/tests/data/test_converter.py index a0ec2f46f..7dff520e0 100644 --- a/tests/data/test_converter.py +++ b/tests/data/test_converter.py @@ -5,9 +5,12 @@ from freqtrade.configuration.timerange import TimeRange from freqtrade.data.converter import (convert_ohlcv_format, convert_trades_format, ohlcv_fill_up_missing_data, - parse_ticker_dataframe, trim_dataframe) -from freqtrade.data.history import (get_timerange, load_data, - load_pair_history, validate_backtest_data) + ohlcv_to_dataframe, + trim_dataframe) +from freqtrade.data.history import (get_timerange, + load_data, + load_pair_history, + validate_backtest_data) from tests.conftest import log_has from tests.data.test_history import _backup_file, _clean_test_file @@ -16,15 +19,15 @@ def test_dataframe_correct_columns(result): assert result.columns.tolist() == ['date', 'open', 'high', 'low', 'close', 'volume'] -def test_parse_ticker_dataframe(ticker_history_list, caplog): +def test_ohlcv_to_dataframe(ohlcv_history_list, caplog): columns = ['date', 'open', 'high', 'low', 'close', 'volume'] caplog.set_level(logging.DEBUG) # Test file with BV data - dataframe = parse_ticker_dataframe(ticker_history_list, '5m', - pair="UNITTEST/BTC", fill_missing=True) + dataframe = ohlcv_to_dataframe(ohlcv_history_list, '5m', pair="UNITTEST/BTC", + fill_missing=True) assert dataframe.columns.tolist() == columns - assert log_has('Parsing tickerlist to dataframe', caplog) + assert log_has('Converting candle (OHLCV) data to dataframe for pair UNITTEST/BTC.', caplog) def test_ohlcv_fill_up_missing_data(testdatadir, caplog): @@ -84,7 +87,8 @@ def test_ohlcv_fill_up_missing_data2(caplog): ] # Generate test-data without filling missing - data = parse_ticker_dataframe(ticks, timeframe, pair="UNITTEST/BTC", fill_missing=False) + data = ohlcv_to_dataframe(ticks, timeframe, pair="UNITTEST/BTC", + fill_missing=False) assert len(data) == 3 caplog.set_level(logging.DEBUG) data2 = ohlcv_fill_up_missing_data(data, timeframe, "UNITTEST/BTC") @@ -140,14 +144,14 @@ def test_ohlcv_drop_incomplete(caplog): ] ] caplog.set_level(logging.DEBUG) - data = parse_ticker_dataframe(ticks, timeframe, pair="UNITTEST/BTC", - fill_missing=False, drop_incomplete=False) + data = ohlcv_to_dataframe(ticks, timeframe, pair="UNITTEST/BTC", + fill_missing=False, drop_incomplete=False) assert len(data) == 4 assert not log_has("Dropping last candle", caplog) # Drop last candle - data = parse_ticker_dataframe(ticks, timeframe, pair="UNITTEST/BTC", - fill_missing=False, drop_incomplete=True) + data = ohlcv_to_dataframe(ticks, timeframe, pair="UNITTEST/BTC", + fill_missing=False, drop_incomplete=True) assert len(data) == 3 assert log_has("Dropping last candle", caplog) diff --git a/tests/data/test_dataprovider.py b/tests/data/test_dataprovider.py index 1dbe20936..2b3dda188 100644 --- a/tests/data/test_dataprovider.py +++ b/tests/data/test_dataprovider.py @@ -7,19 +7,19 @@ from freqtrade.state import RunMode from tests.conftest import get_patched_exchange -def test_ohlcv(mocker, default_conf, ticker_history): +def test_ohlcv(mocker, default_conf, ohlcv_history): default_conf["runmode"] = RunMode.DRY_RUN timeframe = default_conf["ticker_interval"] exchange = get_patched_exchange(mocker, default_conf) - exchange._klines[("XRP/BTC", timeframe)] = ticker_history - exchange._klines[("UNITTEST/BTC", timeframe)] = ticker_history + exchange._klines[("XRP/BTC", timeframe)] = ohlcv_history + exchange._klines[("UNITTEST/BTC", timeframe)] = ohlcv_history dp = DataProvider(default_conf, exchange) assert dp.runmode == RunMode.DRY_RUN - assert ticker_history.equals(dp.ohlcv("UNITTEST/BTC", timeframe)) + assert ohlcv_history.equals(dp.ohlcv("UNITTEST/BTC", timeframe)) assert isinstance(dp.ohlcv("UNITTEST/BTC", timeframe), DataFrame) - assert dp.ohlcv("UNITTEST/BTC", timeframe) is not ticker_history - assert dp.ohlcv("UNITTEST/BTC", timeframe, copy=False) is ticker_history + assert dp.ohlcv("UNITTEST/BTC", timeframe) is not ohlcv_history + assert dp.ohlcv("UNITTEST/BTC", timeframe, copy=False) is ohlcv_history assert not dp.ohlcv("UNITTEST/BTC", timeframe).empty assert dp.ohlcv("NONESENSE/AAA", timeframe).empty @@ -37,8 +37,8 @@ def test_ohlcv(mocker, default_conf, ticker_history): assert dp.ohlcv("UNITTEST/BTC", timeframe).empty -def test_historic_ohlcv(mocker, default_conf, ticker_history): - historymock = MagicMock(return_value=ticker_history) +def test_historic_ohlcv(mocker, default_conf, ohlcv_history): + historymock = MagicMock(return_value=ohlcv_history) mocker.patch("freqtrade.data.dataprovider.load_pair_history", historymock) dp = DataProvider(default_conf, None) @@ -48,18 +48,18 @@ def test_historic_ohlcv(mocker, default_conf, ticker_history): assert historymock.call_args_list[0][1]["timeframe"] == "5m" -def test_get_pair_dataframe(mocker, default_conf, ticker_history): +def test_get_pair_dataframe(mocker, default_conf, ohlcv_history): default_conf["runmode"] = RunMode.DRY_RUN ticker_interval = default_conf["ticker_interval"] exchange = get_patched_exchange(mocker, default_conf) - exchange._klines[("XRP/BTC", ticker_interval)] = ticker_history - exchange._klines[("UNITTEST/BTC", ticker_interval)] = ticker_history + exchange._klines[("XRP/BTC", ticker_interval)] = ohlcv_history + exchange._klines[("UNITTEST/BTC", ticker_interval)] = ohlcv_history dp = DataProvider(default_conf, exchange) assert dp.runmode == RunMode.DRY_RUN - assert ticker_history.equals(dp.get_pair_dataframe("UNITTEST/BTC", ticker_interval)) + assert ohlcv_history.equals(dp.get_pair_dataframe("UNITTEST/BTC", ticker_interval)) assert isinstance(dp.get_pair_dataframe("UNITTEST/BTC", ticker_interval), DataFrame) - assert dp.get_pair_dataframe("UNITTEST/BTC", ticker_interval) is not ticker_history + assert dp.get_pair_dataframe("UNITTEST/BTC", ticker_interval) is not ohlcv_history assert not dp.get_pair_dataframe("UNITTEST/BTC", ticker_interval).empty assert dp.get_pair_dataframe("NONESENSE/AAA", ticker_interval).empty @@ -73,7 +73,7 @@ def test_get_pair_dataframe(mocker, default_conf, ticker_history): assert isinstance(dp.get_pair_dataframe("UNITTEST/BTC", ticker_interval), DataFrame) assert dp.get_pair_dataframe("NONESENSE/AAA", ticker_interval).empty - historymock = MagicMock(return_value=ticker_history) + historymock = MagicMock(return_value=ohlcv_history) mocker.patch("freqtrade.data.dataprovider.load_pair_history", historymock) default_conf["runmode"] = RunMode.BACKTEST dp = DataProvider(default_conf, exchange) @@ -82,11 +82,11 @@ def test_get_pair_dataframe(mocker, default_conf, ticker_history): # assert dp.get_pair_dataframe("NONESENSE/AAA", ticker_interval).empty -def test_available_pairs(mocker, default_conf, ticker_history): +def test_available_pairs(mocker, default_conf, ohlcv_history): exchange = get_patched_exchange(mocker, default_conf) ticker_interval = default_conf["ticker_interval"] - exchange._klines[("XRP/BTC", ticker_interval)] = ticker_history - exchange._klines[("UNITTEST/BTC", ticker_interval)] = ticker_history + exchange._klines[("XRP/BTC", ticker_interval)] = ohlcv_history + exchange._klines[("UNITTEST/BTC", ticker_interval)] = ohlcv_history dp = DataProvider(default_conf, exchange) assert len(dp.available_pairs) == 2 @@ -96,7 +96,7 @@ def test_available_pairs(mocker, default_conf, ticker_history): ] -def test_refresh(mocker, default_conf, ticker_history): +def test_refresh(mocker, default_conf, ohlcv_history): refresh_mock = MagicMock() mocker.patch("freqtrade.exchange.Exchange.refresh_latest_ohlcv", refresh_mock) diff --git a/tests/data/test_history.py b/tests/data/test_history.py index 9c9af9acd..12390538a 100644 --- a/tests/data/test_history.py +++ b/tests/data/test_history.py @@ -12,7 +12,7 @@ from pandas import DataFrame from pandas.testing import assert_frame_equal from freqtrade.configuration import TimeRange -from freqtrade.data.converter import parse_ticker_dataframe +from freqtrade.data.converter import ohlcv_to_dataframe from freqtrade.data.history.history_utils import ( _download_pair_history, _download_trades_history, _load_cached_data_for_updating, convert_trades_to_ohlcv, get_timerange, @@ -63,7 +63,7 @@ def _clean_test_file(file: Path) -> None: file_swp.rename(file) -def test_load_data_30min_ticker(mocker, caplog, default_conf, testdatadir) -> None: +def test_load_data_30min_timeframe(mocker, caplog, default_conf, testdatadir) -> None: ld = load_pair_history(pair='UNITTEST/BTC', timeframe='30m', datadir=testdatadir) assert isinstance(ld, DataFrame) assert not log_has( @@ -72,7 +72,7 @@ def test_load_data_30min_ticker(mocker, caplog, default_conf, testdatadir) -> No ) -def test_load_data_7min_ticker(mocker, caplog, default_conf, testdatadir) -> None: +def test_load_data_7min_timeframe(mocker, caplog, default_conf, testdatadir) -> None: ld = load_pair_history(pair='UNITTEST/BTC', timeframe='7m', datadir=testdatadir) assert isinstance(ld, DataFrame) assert ld.empty @@ -82,8 +82,8 @@ def test_load_data_7min_ticker(mocker, caplog, default_conf, testdatadir) -> Non ) -def test_load_data_1min_ticker(ticker_history, mocker, caplog, testdatadir) -> None: - mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv', return_value=ticker_history) +def test_load_data_1min_timeframe(ohlcv_history, mocker, caplog, testdatadir) -> None: + mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv', return_value=ohlcv_history) file = testdatadir / 'UNITTEST_BTC-1m.json' _backup_file(file, copy_file=True) load_data(datadir=testdatadir, timeframe='1m', pairs=['UNITTEST/BTC']) @@ -110,12 +110,12 @@ def test_load_data_startup_candles(mocker, caplog, default_conf, testdatadir) -> assert ltfmock.call_args_list[0][1]['timerange'].startts == timerange.startts - 20 * 60 -def test_load_data_with_new_pair_1min(ticker_history_list, mocker, caplog, +def test_load_data_with_new_pair_1min(ohlcv_history_list, mocker, caplog, default_conf, testdatadir) -> None: """ - Test load_pair_history() with 1 min ticker + Test load_pair_history() with 1 min timeframe """ - mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv', return_value=ticker_history_list) + mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv', return_value=ohlcv_history_list) exchange = get_patched_exchange(mocker, default_conf) file = testdatadir / 'MEME_BTC-1m.json' @@ -188,8 +188,8 @@ def test_load_cached_data_for_updating(mocker, testdatadir) -> None: with open(test_filename, "rt") as file: test_data = json.load(file) - test_data_df = parse_ticker_dataframe(test_data, '1m', 'UNITTEST/BTC', - fill_missing=False, drop_incomplete=False) + test_data_df = ohlcv_to_dataframe(test_data, '1m', 'UNITTEST/BTC', + fill_missing=False, drop_incomplete=False) # now = last cached item + 1 hour now_ts = test_data[-1][0] / 1000 + 60 * 60 mocker.patch('arrow.utcnow', return_value=arrow.get(now_ts)) @@ -230,8 +230,8 @@ def test_load_cached_data_for_updating(mocker, testdatadir) -> None: assert start_ts is None -def test_download_pair_history(ticker_history_list, mocker, default_conf, testdatadir) -> None: - mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv', return_value=ticker_history_list) +def test_download_pair_history(ohlcv_history_list, mocker, default_conf, testdatadir) -> None: + mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv', return_value=ohlcv_history_list) exchange = get_patched_exchange(mocker, default_conf) file1_1 = testdatadir / 'MEME_BTC-1m.json' file1_5 = testdatadir / 'MEME_BTC-5m.json' @@ -293,7 +293,7 @@ def test_download_pair_history2(mocker, default_conf, testdatadir) -> None: assert json_dump_mock.call_count == 2 -def test_download_backtesting_data_exception(ticker_history, mocker, caplog, +def test_download_backtesting_data_exception(ohlcv_history, mocker, caplog, default_conf, testdatadir) -> None: mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv', side_effect=Exception('File Error')) @@ -321,15 +321,15 @@ def test_load_partial_missing(testdatadir, caplog) -> None: # Make sure we start fresh - test missing data at start start = arrow.get('2018-01-01T00:00:00') end = arrow.get('2018-01-11T00:00:00') - tickerdata = load_data(testdatadir, '5m', ['UNITTEST/BTC'], startup_candles=20, - timerange=TimeRange('date', 'date', start.timestamp, end.timestamp)) + data = load_data(testdatadir, '5m', ['UNITTEST/BTC'], startup_candles=20, + timerange=TimeRange('date', 'date', start.timestamp, end.timestamp)) assert log_has( 'Using indicator startup period: 20 ...', caplog ) # timedifference in 5 minutes td = ((end - start).total_seconds() // 60 // 5) + 1 - assert td != len(tickerdata['UNITTEST/BTC']) - start_real = tickerdata['UNITTEST/BTC'].iloc[0, 0] + assert td != len(data['UNITTEST/BTC']) + start_real = data['UNITTEST/BTC'].iloc[0, 0] assert log_has(f'Missing data at start for pair ' f'UNITTEST/BTC, data starts at {start_real.strftime("%Y-%m-%d %H:%M:%S")}', caplog) @@ -337,14 +337,14 @@ def test_load_partial_missing(testdatadir, caplog) -> None: caplog.clear() start = arrow.get('2018-01-10T00:00:00') end = arrow.get('2018-02-20T00:00:00') - tickerdata = load_data(datadir=testdatadir, timeframe='5m', pairs=['UNITTEST/BTC'], - timerange=TimeRange('date', 'date', start.timestamp, end.timestamp)) + data = load_data(datadir=testdatadir, timeframe='5m', pairs=['UNITTEST/BTC'], + timerange=TimeRange('date', 'date', start.timestamp, end.timestamp)) # timedifference in 5 minutes td = ((end - start).total_seconds() // 60 // 5) + 1 - assert td != len(tickerdata['UNITTEST/BTC']) + assert td != len(data['UNITTEST/BTC']) # Shift endtime with +5 - as last candle is dropped (partial candle) - end_real = arrow.get(tickerdata['UNITTEST/BTC'].iloc[-1, 0]).shift(minutes=5) + end_real = arrow.get(data['UNITTEST/BTC'].iloc[-1, 0]).shift(minutes=5) assert log_has(f'Missing data at end for pair ' f'UNITTEST/BTC, data ends at {end_real.strftime("%Y-%m-%d %H:%M:%S")}', caplog) @@ -403,7 +403,7 @@ def test_get_timerange(default_conf, mocker, testdatadir) -> None: default_conf.update({'strategy': 'DefaultStrategy'}) strategy = StrategyResolver.load_strategy(default_conf) - data = strategy.tickerdata_to_dataframe( + data = strategy.ohlcvdata_to_dataframe( load_data( datadir=testdatadir, timeframe='1m', @@ -421,7 +421,7 @@ def test_validate_backtest_data_warn(default_conf, mocker, caplog, testdatadir) default_conf.update({'strategy': 'DefaultStrategy'}) strategy = StrategyResolver.load_strategy(default_conf) - data = strategy.tickerdata_to_dataframe( + data = strategy.ohlcvdata_to_dataframe( load_data( datadir=testdatadir, timeframe='1m', @@ -446,7 +446,7 @@ def test_validate_backtest_data(default_conf, mocker, caplog, testdatadir) -> No strategy = StrategyResolver.load_strategy(default_conf) timerange = TimeRange('index', 'index', 200, 250) - data = strategy.tickerdata_to_dataframe( + data = strategy.ohlcvdata_to_dataframe( load_data( datadir=testdatadir, timeframe='5m', diff --git a/tests/edge/test_edge.py b/tests/edge/test_edge.py index 2a0d19128..c68ac477c 100644 --- a/tests/edge/test_edge.py +++ b/tests/edge/test_edge.py @@ -11,7 +11,7 @@ import pytest from pandas import DataFrame, to_datetime from freqtrade.exceptions import OperationalException -from freqtrade.data.converter import parse_ticker_dataframe +from freqtrade.data.converter import ohlcv_to_dataframe from freqtrade.edge import Edge, PairInfo from freqtrade.strategy.interface import SellType from tests.conftest import get_patched_freqtradebot, log_has @@ -26,7 +26,7 @@ from tests.optimize import (BTContainer, BTrade, _build_backtest_dataframe, # 5) Stoploss and sell are hit. should sell on stoploss #################################################################### -ticker_start_time = arrow.get(2018, 10, 3) +tests_start_time = arrow.get(2018, 10, 3) ticker_interval_in_minute = 60 _ohlc = {'date': 0, 'buy': 1, 'open': 2, 'high': 3, 'low': 4, 'close': 5, 'sell': 6, 'volume': 7} @@ -43,10 +43,10 @@ def _validate_ohlc(buy_ohlc_sell_matrice): def _build_dataframe(buy_ohlc_sell_matrice): _validate_ohlc(buy_ohlc_sell_matrice) - tickers = [] + data = [] for ohlc in buy_ohlc_sell_matrice: - ticker = { - 'date': ticker_start_time.shift( + d = { + 'date': tests_start_time.shift( minutes=( ohlc[0] * ticker_interval_in_minute)).timestamp * @@ -57,9 +57,9 @@ def _build_dataframe(buy_ohlc_sell_matrice): 'low': ohlc[4], 'close': ohlc[5], 'sell': ohlc[6]} - tickers.append(ticker) + data.append(d) - frame = DataFrame(tickers) + frame = DataFrame(data) frame['date'] = to_datetime(frame['date'], unit='ms', utc=True, @@ -69,7 +69,7 @@ def _build_dataframe(buy_ohlc_sell_matrice): def _time_on_candle(number): - return np.datetime64(ticker_start_time.shift( + return np.datetime64(tests_start_time.shift( minutes=(number * ticker_interval_in_minute)).timestamp * 1000, 'ms') @@ -262,7 +262,7 @@ def mocked_load_data(datadir, pairs=[], timeframe='0m', NEOBTC = [ [ - ticker_start_time.shift(minutes=(x * ticker_interval_in_minute)).timestamp * 1000, + tests_start_time.shift(minutes=(x * ticker_interval_in_minute)).timestamp * 1000, math.sin(x * hz) / 1000 + base, math.sin(x * hz) / 1000 + base + 0.0001, math.sin(x * hz) / 1000 + base - 0.0001, @@ -274,7 +274,7 @@ def mocked_load_data(datadir, pairs=[], timeframe='0m', base = 0.002 LTCBTC = [ [ - ticker_start_time.shift(minutes=(x * ticker_interval_in_minute)).timestamp * 1000, + tests_start_time.shift(minutes=(x * ticker_interval_in_minute)).timestamp * 1000, math.sin(x * hz) / 1000 + base, math.sin(x * hz) / 1000 + base + 0.0001, math.sin(x * hz) / 1000 + base - 0.0001, @@ -282,8 +282,10 @@ def mocked_load_data(datadir, pairs=[], timeframe='0m', 123.45 ] for x in range(0, 500)] - pairdata = {'NEO/BTC': parse_ticker_dataframe(NEOBTC, '1h', pair="NEO/BTC", fill_missing=True), - 'LTC/BTC': parse_ticker_dataframe(LTCBTC, '1h', pair="LTC/BTC", fill_missing=True)} + pairdata = {'NEO/BTC': ohlcv_to_dataframe(NEOBTC, '1h', pair="NEO/BTC", + fill_missing=True), + 'LTC/BTC': ohlcv_to_dataframe(LTCBTC, '1h', pair="LTC/BTC", + fill_missing=True)} return pairdata diff --git a/tests/exchange/test_exchange.py b/tests/exchange/test_exchange.py index 6bec53d49..8d8930f66 100644 --- a/tests/exchange/test_exchange.py +++ b/tests/exchange/test_exchange.py @@ -581,7 +581,7 @@ def test_validate_timeframes_failed(default_conf, mocker): mocker.patch('freqtrade.exchange.Exchange._load_markets', MagicMock(return_value={})) mocker.patch('freqtrade.exchange.Exchange.validate_pairs', MagicMock()) with pytest.raises(OperationalException, - match=r"Invalid ticker interval '3m'. This exchange supports.*"): + match=r"Invalid timeframe '3m'. This exchange supports.*"): Exchange(default_conf) default_conf["ticker_interval"] = "15s" @@ -1211,7 +1211,7 @@ def test_fetch_ticker(default_conf, mocker, exchange_name): @pytest.mark.parametrize("exchange_name", EXCHANGES) def test_get_historic_ohlcv(default_conf, mocker, caplog, exchange_name): exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) - tick = [ + ohlcv = [ [ arrow.utcnow().timestamp * 1000, # unix timestamp ms 1, # open @@ -1224,7 +1224,7 @@ def test_get_historic_ohlcv(default_conf, mocker, caplog, exchange_name): pair = 'ETH/BTC' async def mock_candle_hist(pair, timeframe, since_ms): - return pair, timeframe, tick + return pair, timeframe, ohlcv exchange._async_get_candle_history = Mock(wraps=mock_candle_hist) # one_call calculation * 1.8 should do 2 calls @@ -1232,12 +1232,12 @@ def test_get_historic_ohlcv(default_conf, mocker, caplog, exchange_name): ret = exchange.get_historic_ohlcv(pair, "5m", int((arrow.utcnow().timestamp - since) * 1000)) assert exchange._async_get_candle_history.call_count == 2 - # Returns twice the above tick + # Returns twice the above OHLCV data assert len(ret) == 2 def test_refresh_latest_ohlcv(mocker, default_conf, caplog) -> None: - tick = [ + ohlcv = [ [ (arrow.utcnow().timestamp - 1) * 1000, # unix timestamp ms 1, # open @@ -1258,14 +1258,14 @@ def test_refresh_latest_ohlcv(mocker, default_conf, caplog) -> None: caplog.set_level(logging.DEBUG) exchange = get_patched_exchange(mocker, default_conf) - exchange._api_async.fetch_ohlcv = get_mock_coro(tick) + exchange._api_async.fetch_ohlcv = get_mock_coro(ohlcv) pairs = [('IOTA/ETH', '5m'), ('XRP/ETH', '5m')] # empty dicts assert not exchange._klines exchange.refresh_latest_ohlcv(pairs) - assert log_has(f'Refreshing ohlcv data for {len(pairs)} pairs', caplog) + assert log_has(f'Refreshing candle (OHLCV) data for {len(pairs)} pairs', caplog) assert exchange._klines assert exchange._api_async.fetch_ohlcv.call_count == 2 for pair in pairs: @@ -1283,14 +1283,15 @@ def test_refresh_latest_ohlcv(mocker, default_conf, caplog) -> None: exchange.refresh_latest_ohlcv([('IOTA/ETH', '5m'), ('XRP/ETH', '5m')]) assert exchange._api_async.fetch_ohlcv.call_count == 2 - assert log_has(f"Using cached ohlcv data for pair {pairs[0][0]}, timeframe {pairs[0][1]} ...", + assert log_has(f"Using cached candle (OHLCV) data for pair {pairs[0][0]}, " + f"timeframe {pairs[0][1]} ...", caplog) @pytest.mark.asyncio @pytest.mark.parametrize("exchange_name", EXCHANGES) async def test__async_get_candle_history(default_conf, mocker, caplog, exchange_name): - tick = [ + ohlcv = [ [ arrow.utcnow().timestamp * 1000, # unix timestamp ms 1, # open @@ -1304,7 +1305,7 @@ async def test__async_get_candle_history(default_conf, mocker, caplog, exchange_ caplog.set_level(logging.DEBUG) exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) # Monkey-patch async function - exchange._api_async.fetch_ohlcv = get_mock_coro(tick) + exchange._api_async.fetch_ohlcv = get_mock_coro(ohlcv) pair = 'ETH/BTC' res = await exchange._async_get_candle_history(pair, "5m") @@ -1312,9 +1313,9 @@ async def test__async_get_candle_history(default_conf, mocker, caplog, exchange_ assert len(res) == 3 assert res[0] == pair assert res[1] == "5m" - assert res[2] == tick + assert res[2] == ohlcv assert exchange._api_async.fetch_ohlcv.call_count == 1 - assert not log_has(f"Using cached ohlcv data for {pair} ...", caplog) + assert not log_has(f"Using cached candle (OHLCV) data for {pair} ...", caplog) # exchange = Exchange(default_conf) await async_ccxt_exception(mocker, default_conf, MagicMock(), @@ -1322,14 +1323,15 @@ async def test__async_get_candle_history(default_conf, mocker, caplog, exchange_ pair='ABCD/BTC', timeframe=default_conf['ticker_interval']) api_mock = MagicMock() - with pytest.raises(OperationalException, match=r'Could not fetch ticker data*'): + with pytest.raises(OperationalException, + match=r'Could not fetch historical candle \(OHLCV\) data.*'): api_mock.fetch_ohlcv = MagicMock(side_effect=ccxt.BaseError("Unknown error")) exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) await exchange._async_get_candle_history(pair, "5m", (arrow.utcnow().timestamp - 2000) * 1000) with pytest.raises(OperationalException, match=r'Exchange.* does not support fetching ' - r'historical candlestick data\..*'): + r'historical candle \(OHLCV\) data\..*'): api_mock.fetch_ohlcv = MagicMock(side_effect=ccxt.NotSupported("Not supported")) exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) await exchange._async_get_candle_history(pair, "5m", @@ -1339,7 +1341,7 @@ async def test__async_get_candle_history(default_conf, mocker, caplog, exchange_ @pytest.mark.asyncio async def test__async_get_candle_history_empty(default_conf, mocker, caplog): """ Test empty exchange result """ - tick = [] + ohlcv = [] caplog.set_level(logging.DEBUG) exchange = get_patched_exchange(mocker, default_conf) @@ -1353,7 +1355,7 @@ async def test__async_get_candle_history_empty(default_conf, mocker, caplog): assert len(res) == 3 assert res[0] == pair assert res[1] == "5m" - assert res[2] == tick + assert res[2] == ohlcv assert exchange._api_async.fetch_ohlcv.call_count == 1 @@ -1431,8 +1433,8 @@ async def test___async_get_candle_history_sort(default_conf, mocker, exchange_na return sorted(data, key=key) # GDAX use-case (real data from GDAX) - # This ticker history is ordered DESC (newest first, oldest last) - tick = [ + # This OHLCV data is ordered DESC (newest first, oldest last) + ohlcv = [ [1527833100000, 0.07666, 0.07671, 0.07666, 0.07668, 16.65244264], [1527832800000, 0.07662, 0.07666, 0.07662, 0.07666, 1.30051526], [1527832500000, 0.07656, 0.07661, 0.07656, 0.07661, 12.034778840000001], @@ -1445,31 +1447,31 @@ async def test___async_get_candle_history_sort(default_conf, mocker, exchange_na [1527830400000, 0.07649, 0.07651, 0.07649, 0.07651, 2.5734867] ] exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) - exchange._api_async.fetch_ohlcv = get_mock_coro(tick) + exchange._api_async.fetch_ohlcv = get_mock_coro(ohlcv) sort_mock = mocker.patch('freqtrade.exchange.exchange.sorted', MagicMock(side_effect=sort_data)) - # Test the ticker history sort + # Test the OHLCV data sort res = await exchange._async_get_candle_history('ETH/BTC', default_conf['ticker_interval']) assert res[0] == 'ETH/BTC' - ticks = res[2] + res_ohlcv = res[2] assert sort_mock.call_count == 1 - assert ticks[0][0] == 1527830400000 - assert ticks[0][1] == 0.07649 - assert ticks[0][2] == 0.07651 - assert ticks[0][3] == 0.07649 - assert ticks[0][4] == 0.07651 - assert ticks[0][5] == 2.5734867 + assert res_ohlcv[0][0] == 1527830400000 + assert res_ohlcv[0][1] == 0.07649 + assert res_ohlcv[0][2] == 0.07651 + assert res_ohlcv[0][3] == 0.07649 + assert res_ohlcv[0][4] == 0.07651 + assert res_ohlcv[0][5] == 2.5734867 - assert ticks[9][0] == 1527833100000 - assert ticks[9][1] == 0.07666 - assert ticks[9][2] == 0.07671 - assert ticks[9][3] == 0.07666 - assert ticks[9][4] == 0.07668 - assert ticks[9][5] == 16.65244264 + assert res_ohlcv[9][0] == 1527833100000 + assert res_ohlcv[9][1] == 0.07666 + assert res_ohlcv[9][2] == 0.07671 + assert res_ohlcv[9][3] == 0.07666 + assert res_ohlcv[9][4] == 0.07668 + assert res_ohlcv[9][5] == 16.65244264 # Bittrex use-case (real data from Bittrex) - # This ticker history is ordered ASC (oldest first, newest last) - tick = [ + # This OHLCV data is ordered ASC (oldest first, newest last) + ohlcv = [ [1527827700000, 0.07659999, 0.0766, 0.07627, 0.07657998, 1.85216924], [1527828000000, 0.07657995, 0.07657995, 0.0763, 0.0763, 26.04051037], [1527828300000, 0.0763, 0.07659998, 0.0763, 0.0764, 10.36434124], @@ -1481,29 +1483,29 @@ async def test___async_get_candle_history_sort(default_conf, mocker, exchange_na [1527830100000, 0.076695, 0.07671, 0.07624171, 0.07671, 1.80689244], [1527830400000, 0.07671, 0.07674399, 0.07629216, 0.07655213, 2.31452783] ] - exchange._api_async.fetch_ohlcv = get_mock_coro(tick) + exchange._api_async.fetch_ohlcv = get_mock_coro(ohlcv) # Reset sort mock sort_mock = mocker.patch('freqtrade.exchange.sorted', MagicMock(side_effect=sort_data)) - # Test the ticker history sort + # Test the OHLCV data sort res = await exchange._async_get_candle_history('ETH/BTC', default_conf['ticker_interval']) assert res[0] == 'ETH/BTC' assert res[1] == default_conf['ticker_interval'] - ticks = res[2] + res_ohlcv = res[2] # Sorted not called again - data is already in order assert sort_mock.call_count == 0 - assert ticks[0][0] == 1527827700000 - assert ticks[0][1] == 0.07659999 - assert ticks[0][2] == 0.0766 - assert ticks[0][3] == 0.07627 - assert ticks[0][4] == 0.07657998 - assert ticks[0][5] == 1.85216924 + assert res_ohlcv[0][0] == 1527827700000 + assert res_ohlcv[0][1] == 0.07659999 + assert res_ohlcv[0][2] == 0.0766 + assert res_ohlcv[0][3] == 0.07627 + assert res_ohlcv[0][4] == 0.07657998 + assert res_ohlcv[0][5] == 1.85216924 - assert ticks[9][0] == 1527830400000 - assert ticks[9][1] == 0.07671 - assert ticks[9][2] == 0.07674399 - assert ticks[9][3] == 0.07629216 - assert ticks[9][4] == 0.07655213 - assert ticks[9][5] == 2.31452783 + assert res_ohlcv[9][0] == 1527830400000 + assert res_ohlcv[9][1] == 0.07671 + assert res_ohlcv[9][2] == 0.07674399 + assert res_ohlcv[9][3] == 0.07629216 + assert res_ohlcv[9][4] == 0.07655213 + assert res_ohlcv[9][5] == 2.31452783 @pytest.mark.asyncio diff --git a/tests/optimize/__init__.py b/tests/optimize/__init__.py index 13605a38c..8bc66f02c 100644 --- a/tests/optimize/__init__.py +++ b/tests/optimize/__init__.py @@ -6,7 +6,7 @@ from pandas import DataFrame from freqtrade.exchange import timeframe_to_minutes from freqtrade.strategy.interface import SellType -ticker_start_time = arrow.get(2018, 10, 3) +tests_start_time = arrow.get(2018, 10, 3) tests_timeframe = '1h' @@ -36,14 +36,14 @@ class BTContainer(NamedTuple): def _get_frame_time_from_offset(offset): - return ticker_start_time.shift(minutes=(offset * timeframe_to_minutes(tests_timeframe)) - ).datetime + minutes = offset * timeframe_to_minutes(tests_timeframe) + return tests_start_time.shift(minutes=minutes).datetime -def _build_backtest_dataframe(ticker_with_signals): +def _build_backtest_dataframe(data): columns = ['date', 'open', 'high', 'low', 'close', 'volume', 'buy', 'sell'] - frame = DataFrame.from_records(ticker_with_signals, columns=columns) + frame = DataFrame.from_records(data, columns=columns) frame['date'] = frame['date'].apply(_get_frame_time_from_offset) # Ensure floats are in place for column in ['open', 'high', 'low', 'close', 'volume']: diff --git a/tests/optimize/test_backtesting.py b/tests/optimize/test_backtesting.py index 96855dc9d..1b6e23ffa 100644 --- a/tests/optimize/test_backtesting.py +++ b/tests/optimize/test_backtesting.py @@ -84,7 +84,7 @@ def simple_backtest(config, contour, num_results, mocker, testdatadir) -> None: backtesting = Backtesting(config) data = load_data_test(contour, testdatadir) - processed = backtesting.strategy.tickerdata_to_dataframe(data) + processed = backtesting.strategy.ohlcvdata_to_dataframe(data) min_date, max_date = get_timerange(processed) assert isinstance(processed, dict) results = backtesting.backtest( @@ -105,7 +105,7 @@ def _make_backtest_conf(mocker, datadir, conf=None, pair='UNITTEST/BTC'): data = trim_dictlist(data, -201) patch_exchange(mocker) backtesting = Backtesting(conf) - processed = backtesting.strategy.tickerdata_to_dataframe(data) + processed = backtesting.strategy.ohlcvdata_to_dataframe(data) min_date, max_date = get_timerange(processed) return { 'processed': processed, @@ -275,7 +275,7 @@ def test_backtesting_init(mocker, default_conf, order_types) -> None: backtesting = Backtesting(default_conf) assert backtesting.config == default_conf assert backtesting.timeframe == '5m' - assert callable(backtesting.strategy.tickerdata_to_dataframe) + assert callable(backtesting.strategy.ohlcvdata_to_dataframe) assert callable(backtesting.strategy.advise_buy) assert callable(backtesting.strategy.advise_sell) assert isinstance(backtesting.strategy.dp, DataProvider) @@ -297,7 +297,7 @@ def test_backtesting_init_no_ticker_interval(mocker, default_conf, caplog) -> No "or as cli argument `--ticker-interval 5m`", caplog) -def test_tickerdata_with_fee(default_conf, mocker, testdatadir) -> None: +def test_data_with_fee(default_conf, mocker, testdatadir) -> None: patch_exchange(mocker) default_conf['fee'] = 0.1234 @@ -307,21 +307,21 @@ def test_tickerdata_with_fee(default_conf, mocker, testdatadir) -> None: assert fee_mock.call_count == 0 -def test_tickerdata_to_dataframe_bt(default_conf, mocker, testdatadir) -> None: +def test_data_to_dataframe_bt(default_conf, mocker, testdatadir) -> None: patch_exchange(mocker) timerange = TimeRange.parse_timerange('1510694220-1510700340') - tickerlist = history.load_data(testdatadir, '1m', ['UNITTEST/BTC'], timerange=timerange, - fill_up_missing=True) + data = history.load_data(testdatadir, '1m', ['UNITTEST/BTC'], timerange=timerange, + fill_up_missing=True) backtesting = Backtesting(default_conf) - data = backtesting.strategy.tickerdata_to_dataframe(tickerlist) - assert len(data['UNITTEST/BTC']) == 102 + processed = backtesting.strategy.ohlcvdata_to_dataframe(data) + assert len(processed['UNITTEST/BTC']) == 102 # Load strategy to compare the result between Backtesting function and strategy are the same default_conf.update({'strategy': 'DefaultStrategy'}) strategy = StrategyResolver.load_strategy(default_conf) - data2 = strategy.tickerdata_to_dataframe(tickerlist) - assert data['UNITTEST/BTC'].equals(data2['UNITTEST/BTC']) + processed2 = strategy.ohlcvdata_to_dataframe(data) + assert processed['UNITTEST/BTC'].equals(processed2['UNITTEST/BTC']) def test_backtesting_start(default_conf, mocker, testdatadir, caplog) -> None: @@ -329,7 +329,6 @@ def test_backtesting_start(default_conf, mocker, testdatadir, caplog) -> None: return Arrow(2017, 11, 14, 21, 17), Arrow(2017, 11, 14, 22, 59) mocker.patch('freqtrade.data.history.get_timerange', get_timerange) - mocker.patch('freqtrade.exchange.Exchange.refresh_latest_ohlcv', MagicMock()) patch_exchange(mocker) mocker.patch('freqtrade.optimize.backtesting.Backtesting.backtest', MagicMock()) mocker.patch('freqtrade.optimize.backtesting.generate_text_table', MagicMock(return_value=1)) @@ -360,7 +359,6 @@ def test_backtesting_start_no_data(default_conf, mocker, caplog, testdatadir) -> mocker.patch('freqtrade.data.history.history_utils.load_pair_history', MagicMock(return_value=pd.DataFrame())) mocker.patch('freqtrade.data.history.get_timerange', get_timerange) - mocker.patch('freqtrade.exchange.Exchange.refresh_latest_ohlcv', MagicMock()) patch_exchange(mocker) mocker.patch('freqtrade.optimize.backtesting.Backtesting.backtest', MagicMock()) mocker.patch('freqtrade.optimize.backtesting.generate_text_table', MagicMock(return_value=1)) @@ -385,10 +383,10 @@ def test_backtest(default_conf, fee, mocker, testdatadir) -> None: timerange = TimeRange('date', None, 1517227800, 0) data = history.load_data(datadir=testdatadir, timeframe='5m', pairs=['UNITTEST/BTC'], timerange=timerange) - data_processed = backtesting.strategy.tickerdata_to_dataframe(data) - min_date, max_date = get_timerange(data_processed) + processed = backtesting.strategy.ohlcvdata_to_dataframe(data) + min_date, max_date = get_timerange(processed) results = backtesting.backtest( - processed=data_processed, + processed=processed, stake_amount=default_conf['stake_amount'], start_date=min_date, end_date=max_date, @@ -416,7 +414,7 @@ def test_backtest(default_conf, fee, mocker, testdatadir) -> None: 'sell_reason': [SellType.ROI, SellType.ROI] }) pd.testing.assert_frame_equal(results, expected) - data_pair = data_processed[pair] + data_pair = processed[pair] for _, t in results.iterrows(): ln = data_pair.loc[data_pair["date"] == t["open_time"]] # Check open trade rate alignes to open rate @@ -439,7 +437,7 @@ def test_backtest_1min_ticker_interval(default_conf, fee, mocker, testdatadir) - timerange = TimeRange.parse_timerange('1510688220-1510700340') data = history.load_data(datadir=testdatadir, timeframe='1m', pairs=['UNITTEST/BTC'], timerange=timerange) - processed = backtesting.strategy.tickerdata_to_dataframe(data) + processed = backtesting.strategy.ohlcvdata_to_dataframe(data) min_date, max_date = get_timerange(processed) results = backtesting.backtest( processed=processed, @@ -458,7 +456,7 @@ def test_processed(default_conf, mocker, testdatadir) -> None: backtesting = Backtesting(default_conf) dict_of_tickerrows = load_data_test('raise', testdatadir) - dataframes = backtesting.strategy.tickerdata_to_dataframe(dict_of_tickerrows) + dataframes = backtesting.strategy.ohlcvdata_to_dataframe(dict_of_tickerrows) dataframe = dataframes['UNITTEST/BTC'] cols = dataframe.columns # assert the dataframe got some of the indicator columns @@ -557,10 +555,10 @@ def test_backtest_multi_pair(default_conf, fee, mocker, tres, pair, testdatadir) backtesting.strategy.advise_buy = _trend_alternate_hold # Override backtesting.strategy.advise_sell = _trend_alternate_hold # Override - data_processed = backtesting.strategy.tickerdata_to_dataframe(data) - min_date, max_date = get_timerange(data_processed) + processed = backtesting.strategy.ohlcvdata_to_dataframe(data) + min_date, max_date = get_timerange(processed) backtest_conf = { - 'processed': data_processed, + 'processed': processed, 'stake_amount': default_conf['stake_amount'], 'start_date': min_date, 'end_date': max_date, @@ -576,7 +574,7 @@ def test_backtest_multi_pair(default_conf, fee, mocker, tres, pair, testdatadir) assert len(evaluate_result_multi(results, '5m', 3)) == 0 backtest_conf = { - 'processed': data_processed, + 'processed': processed, 'stake_amount': default_conf['stake_amount'], 'start_date': min_date, 'end_date': max_date, diff --git a/tests/optimize/test_hyperopt.py b/tests/optimize/test_hyperopt.py index 0406157f6..eefc6b28a 100644 --- a/tests/optimize/test_hyperopt.py +++ b/tests/optimize/test_hyperopt.py @@ -524,7 +524,7 @@ def test_start_calls_optimizer(mocker, default_conf, caplog, capsys) -> None: }]) ) patch_exchange(mocker) - # Co-test loading ticker-interval from strategy + # Co-test loading timeframe from strategy del default_conf['ticker_interval'] default_conf.update({'config': 'config.json.example', 'hyperopt': 'DefaultHyperOpt', @@ -534,7 +534,7 @@ def test_start_calls_optimizer(mocker, default_conf, caplog, capsys) -> None: 'hyperopt_jobs': 1, }) hyperopt = Hyperopt(default_conf) - hyperopt.backtesting.strategy.tickerdata_to_dataframe = MagicMock() + hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock() hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={}) hyperopt.start() @@ -544,7 +544,7 @@ def test_start_calls_optimizer(mocker, default_conf, caplog, capsys) -> None: out, err = capsys.readouterr() assert 'Best result:\n\n* 1/1: foo result Objective: 1.00000\n' in out assert dumper.called - # Should be called twice, once for tickerdata, once to save evaluations + # Should be called twice, once for historical candle data, once to save evaluations assert dumper.call_count == 2 assert hasattr(hyperopt.backtesting.strategy, "advise_sell") assert hasattr(hyperopt.backtesting.strategy, "advise_buy") @@ -630,8 +630,8 @@ def test_has_space(hyperopt, spaces, expected_results): def test_populate_indicators(hyperopt, testdatadir) -> None: - tickerlist = load_data(testdatadir, '1m', ['UNITTEST/BTC'], fill_up_missing=True) - dataframes = hyperopt.backtesting.strategy.tickerdata_to_dataframe(tickerlist) + data = load_data(testdatadir, '1m', ['UNITTEST/BTC'], fill_up_missing=True) + dataframes = hyperopt.backtesting.strategy.ohlcvdata_to_dataframe(data) dataframe = hyperopt.custom_hyperopt.populate_indicators(dataframes['UNITTEST/BTC'], {'pair': 'UNITTEST/BTC'}) @@ -642,8 +642,8 @@ def test_populate_indicators(hyperopt, testdatadir) -> None: def test_buy_strategy_generator(hyperopt, testdatadir) -> None: - tickerlist = load_data(testdatadir, '1m', ['UNITTEST/BTC'], fill_up_missing=True) - dataframes = hyperopt.backtesting.strategy.tickerdata_to_dataframe(tickerlist) + data = load_data(testdatadir, '1m', ['UNITTEST/BTC'], fill_up_missing=True) + dataframes = hyperopt.backtesting.strategy.ohlcvdata_to_dataframe(data) dataframe = hyperopt.custom_hyperopt.populate_indicators(dataframes['UNITTEST/BTC'], {'pair': 'UNITTEST/BTC'}) @@ -783,7 +783,7 @@ def test_clean_hyperopt(mocker, default_conf, caplog): h = Hyperopt(default_conf) assert unlinkmock.call_count == 2 - assert log_has(f"Removing `{h.tickerdata_pickle}`.", caplog) + assert log_has(f"Removing `{h.data_pickle_file}`.", caplog) def test_continue_hyperopt(mocker, default_conf, caplog): @@ -845,7 +845,7 @@ def test_print_json_spaces_all(mocker, default_conf, caplog, capsys) -> None: }) hyperopt = Hyperopt(default_conf) - hyperopt.backtesting.strategy.tickerdata_to_dataframe = MagicMock() + hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock() hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={}) hyperopt.start() @@ -859,7 +859,7 @@ def test_print_json_spaces_all(mocker, default_conf, caplog, capsys) -> None: ) assert result_str in out # noqa: E501 assert dumper.called - # Should be called twice, once for tickerdata, once to save evaluations + # Should be called twice, once for historical candle data, once to save evaluations assert dumper.call_count == 2 @@ -903,7 +903,7 @@ def test_print_json_spaces_default(mocker, default_conf, caplog, capsys) -> None }) hyperopt = Hyperopt(default_conf) - hyperopt.backtesting.strategy.tickerdata_to_dataframe = MagicMock() + hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock() hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={}) hyperopt.start() @@ -913,7 +913,7 @@ def test_print_json_spaces_default(mocker, default_conf, caplog, capsys) -> None out, err = capsys.readouterr() assert '{"params":{"mfi-value":null,"sell-mfi-value":null},"minimal_roi":{},"stoploss":null}' in out # noqa: E501 assert dumper.called - # Should be called twice, once for tickerdata, once to save evaluations + # Should be called twice, once for historical candle data, once to save evaluations assert dumper.call_count == 2 @@ -953,7 +953,7 @@ def test_print_json_spaces_roi_stoploss(mocker, default_conf, caplog, capsys) -> }) hyperopt = Hyperopt(default_conf) - hyperopt.backtesting.strategy.tickerdata_to_dataframe = MagicMock() + hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock() hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={}) hyperopt.start() @@ -963,7 +963,7 @@ def test_print_json_spaces_roi_stoploss(mocker, default_conf, caplog, capsys) -> out, err = capsys.readouterr() assert '{"minimal_roi":{},"stoploss":null}' in out assert dumper.called - # Should be called twice, once for tickerdata, once to save evaluations + # Should be called twice, once for historical candle data, once to save evaluations assert dumper.call_count == 2 @@ -1000,7 +1000,7 @@ def test_simplified_interface_roi_stoploss(mocker, default_conf, caplog, capsys) 'hyperopt_jobs': 1, }) hyperopt = Hyperopt(default_conf) - hyperopt.backtesting.strategy.tickerdata_to_dataframe = MagicMock() + hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock() hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={}) del hyperopt.custom_hyperopt.__class__.buy_strategy_generator @@ -1015,7 +1015,7 @@ def test_simplified_interface_roi_stoploss(mocker, default_conf, caplog, capsys) out, err = capsys.readouterr() assert 'Best result:\n\n* 1/1: foo result Objective: 1.00000\n' in out assert dumper.called - # Should be called twice, once for tickerdata, once to save evaluations + # Should be called twice, once for historical candle data, once to save evaluations assert dumper.call_count == 2 assert hasattr(hyperopt.backtesting.strategy, "advise_sell") assert hasattr(hyperopt.backtesting.strategy, "advise_buy") @@ -1043,7 +1043,7 @@ def test_simplified_interface_all_failed(mocker, default_conf, caplog, capsys) - 'hyperopt_jobs': 1, }) hyperopt = Hyperopt(default_conf) - hyperopt.backtesting.strategy.tickerdata_to_dataframe = MagicMock() + hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock() hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={}) del hyperopt.custom_hyperopt.__class__.buy_strategy_generator @@ -1088,7 +1088,7 @@ def test_simplified_interface_buy(mocker, default_conf, caplog, capsys) -> None: 'hyperopt_jobs': 1, }) hyperopt = Hyperopt(default_conf) - hyperopt.backtesting.strategy.tickerdata_to_dataframe = MagicMock() + hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock() hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={}) # TODO: sell_strategy_generator() is actually not called because @@ -1103,7 +1103,7 @@ def test_simplified_interface_buy(mocker, default_conf, caplog, capsys) -> None: out, err = capsys.readouterr() assert 'Best result:\n\n* 1/1: foo result Objective: 1.00000\n' in out assert dumper.called - # Should be called twice, once for tickerdata, once to save evaluations + # Should be called twice, once for historical candle data, once to save evaluations assert dumper.call_count == 2 assert hasattr(hyperopt.backtesting.strategy, "advise_sell") assert hasattr(hyperopt.backtesting.strategy, "advise_buy") @@ -1145,7 +1145,7 @@ def test_simplified_interface_sell(mocker, default_conf, caplog, capsys) -> None 'hyperopt_jobs': 1, }) hyperopt = Hyperopt(default_conf) - hyperopt.backtesting.strategy.tickerdata_to_dataframe = MagicMock() + hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock() hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={}) # TODO: buy_strategy_generator() is actually not called because @@ -1160,7 +1160,7 @@ def test_simplified_interface_sell(mocker, default_conf, caplog, capsys) -> None out, err = capsys.readouterr() assert 'Best result:\n\n* 1/1: foo result Objective: 1.00000\n' in out assert dumper.called - # Should be called twice, once for tickerdata, once to save evaluations + # Should be called twice, once for historical candle data, once to save evaluations assert dumper.call_count == 2 assert hasattr(hyperopt.backtesting.strategy, "advise_sell") assert hasattr(hyperopt.backtesting.strategy, "advise_buy") @@ -1194,7 +1194,7 @@ def test_simplified_interface_failed(mocker, default_conf, caplog, capsys, metho 'hyperopt_jobs': 1, }) hyperopt = Hyperopt(default_conf) - hyperopt.backtesting.strategy.tickerdata_to_dataframe = MagicMock() + hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock() hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={}) delattr(hyperopt.custom_hyperopt.__class__, method) diff --git a/tests/strategy/strats/default_strategy.py b/tests/strategy/strats/default_strategy.py index 6c343b477..7ea55d3f9 100644 --- a/tests/strategy/strats/default_strategy.py +++ b/tests/strategy/strats/default_strategy.py @@ -68,7 +68,7 @@ class DefaultStrategy(IStrategy): Performance Note: For the best performance be frugal on the number of indicators you are using. Let uncomment only the indicator you are using in your strategies or your hyperopt configuration, otherwise you will waste your memory and CPU usage. - :param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe() + :param dataframe: Dataframe with data from the exchange :param metadata: Additional information, like the currently traded pair :return: a Dataframe with all mandatory indicators for the strategies """ diff --git a/tests/strategy/test_interface.py b/tests/strategy/test_interface.py index 86d0738c6..949dda4a0 100644 --- a/tests/strategy/test_interface.py +++ b/tests/strategy/test_interface.py @@ -17,69 +17,69 @@ from tests.conftest import get_patched_exchange, log_has _STRATEGY = DefaultStrategy(config={}) -def test_returns_latest_buy_signal(mocker, default_conf, ticker_history): +def test_returns_latest_buy_signal(mocker, default_conf, ohlcv_history): mocker.patch.object( _STRATEGY, '_analyze_ticker_internal', return_value=DataFrame([{'buy': 1, 'sell': 0, 'date': arrow.utcnow()}]) ) - assert _STRATEGY.get_signal('ETH/BTC', '5m', ticker_history) == (True, False) + assert _STRATEGY.get_signal('ETH/BTC', '5m', ohlcv_history) == (True, False) mocker.patch.object( _STRATEGY, '_analyze_ticker_internal', return_value=DataFrame([{'buy': 0, 'sell': 1, 'date': arrow.utcnow()}]) ) - assert _STRATEGY.get_signal('ETH/BTC', '5m', ticker_history) == (False, True) + assert _STRATEGY.get_signal('ETH/BTC', '5m', ohlcv_history) == (False, True) -def test_returns_latest_sell_signal(mocker, default_conf, ticker_history): +def test_returns_latest_sell_signal(mocker, default_conf, ohlcv_history): mocker.patch.object( _STRATEGY, '_analyze_ticker_internal', return_value=DataFrame([{'sell': 1, 'buy': 0, 'date': arrow.utcnow()}]) ) - assert _STRATEGY.get_signal('ETH/BTC', '5m', ticker_history) == (False, True) + assert _STRATEGY.get_signal('ETH/BTC', '5m', ohlcv_history) == (False, True) mocker.patch.object( _STRATEGY, '_analyze_ticker_internal', return_value=DataFrame([{'sell': 0, 'buy': 1, 'date': arrow.utcnow()}]) ) - assert _STRATEGY.get_signal('ETH/BTC', '5m', ticker_history) == (True, False) + assert _STRATEGY.get_signal('ETH/BTC', '5m', ohlcv_history) == (True, False) def test_get_signal_empty(default_conf, mocker, caplog): assert (False, False) == _STRATEGY.get_signal('foo', default_conf['ticker_interval'], DataFrame()) - assert log_has('Empty ticker history for pair foo', caplog) + assert log_has('Empty candle (OHLCV) data for pair foo', caplog) caplog.clear() assert (False, False) == _STRATEGY.get_signal('bar', default_conf['ticker_interval'], []) - assert log_has('Empty ticker history for pair bar', caplog) + assert log_has('Empty candle (OHLCV) data for pair bar', caplog) -def test_get_signal_exception_valueerror(default_conf, mocker, caplog, ticker_history): +def test_get_signal_exception_valueerror(default_conf, mocker, caplog, ohlcv_history): caplog.set_level(logging.INFO) mocker.patch.object( _STRATEGY, '_analyze_ticker_internal', side_effect=ValueError('xyz') ) assert (False, False) == _STRATEGY.get_signal('foo', default_conf['ticker_interval'], - ticker_history) - assert log_has('Unable to analyze ticker for pair foo: xyz', caplog) + ohlcv_history) + assert log_has('Unable to analyze candle (OHLCV) data for pair foo: xyz', caplog) -def test_get_signal_empty_dataframe(default_conf, mocker, caplog, ticker_history): +def test_get_signal_empty_dataframe(default_conf, mocker, caplog, ohlcv_history): caplog.set_level(logging.INFO) mocker.patch.object( _STRATEGY, '_analyze_ticker_internal', return_value=DataFrame([]) ) assert (False, False) == _STRATEGY.get_signal('xyz', default_conf['ticker_interval'], - ticker_history) + ohlcv_history) assert log_has('Empty dataframe for pair xyz', caplog) -def test_get_signal_old_dataframe(default_conf, mocker, caplog, ticker_history): +def test_get_signal_old_dataframe(default_conf, mocker, caplog, ohlcv_history): caplog.set_level(logging.INFO) # default_conf defines a 5m interval. we check interval * 2 + 5m # this is necessary as the last candle is removed (partial candles) by default @@ -90,7 +90,7 @@ def test_get_signal_old_dataframe(default_conf, mocker, caplog, ticker_history): return_value=DataFrame(ticks) ) assert (False, False) == _STRATEGY.get_signal('xyz', default_conf['ticker_interval'], - ticker_history) + ohlcv_history) assert log_has('Outdated history for pair xyz. Last tick is 16 minutes old', caplog) @@ -103,15 +103,15 @@ def test_get_signal_handles_exceptions(mocker, default_conf): assert _STRATEGY.get_signal(exchange, 'ETH/BTC', '5m') == (False, False) -def test_tickerdata_to_dataframe(default_conf, testdatadir) -> None: +def test_ohlcvdata_to_dataframe(default_conf, testdatadir) -> None: default_conf.update({'strategy': 'DefaultStrategy'}) strategy = StrategyResolver.load_strategy(default_conf) timerange = TimeRange.parse_timerange('1510694220-1510700340') - tickerlist = load_data(testdatadir, '1m', ['UNITTEST/BTC'], timerange=timerange, - fill_up_missing=True) - data = strategy.tickerdata_to_dataframe(tickerlist) - assert len(data['UNITTEST/BTC']) == 102 # partial candle was removed + data = load_data(testdatadir, '1m', ['UNITTEST/BTC'], timerange=timerange, + fill_up_missing=True) + processed = strategy.ohlcvdata_to_dataframe(data) + assert len(processed['UNITTEST/BTC']) == 102 # partial candle was removed def test_min_roi_reached(default_conf, fee) -> None: @@ -222,7 +222,7 @@ def test_min_roi_reached3(default_conf, fee) -> None: assert strategy.min_roi_reached(trade, 0.31, arrow.utcnow().shift(minutes=-2).datetime) -def test_analyze_ticker_default(ticker_history, mocker, caplog) -> None: +def test_analyze_ticker_default(ohlcv_history, mocker, caplog) -> None: caplog.set_level(logging.DEBUG) ind_mock = MagicMock(side_effect=lambda x, meta: x) buy_mock = MagicMock(side_effect=lambda x, meta: x) @@ -235,7 +235,7 @@ def test_analyze_ticker_default(ticker_history, mocker, caplog) -> None: ) strategy = DefaultStrategy({}) - strategy.analyze_ticker(ticker_history, {'pair': 'ETH/BTC'}) + strategy.analyze_ticker(ohlcv_history, {'pair': 'ETH/BTC'}) assert ind_mock.call_count == 1 assert buy_mock.call_count == 1 assert buy_mock.call_count == 1 @@ -244,7 +244,7 @@ def test_analyze_ticker_default(ticker_history, mocker, caplog) -> None: assert not log_has('Skipping TA Analysis for already analyzed candle', caplog) caplog.clear() - strategy.analyze_ticker(ticker_history, {'pair': 'ETH/BTC'}) + strategy.analyze_ticker(ohlcv_history, {'pair': 'ETH/BTC'}) # No analysis happens as process_only_new_candles is true assert ind_mock.call_count == 2 assert buy_mock.call_count == 2 @@ -253,7 +253,7 @@ def test_analyze_ticker_default(ticker_history, mocker, caplog) -> None: assert not log_has('Skipping TA Analysis for already analyzed candle', caplog) -def test__analyze_ticker_internal_skip_analyze(ticker_history, mocker, caplog) -> None: +def test__analyze_ticker_internal_skip_analyze(ohlcv_history, mocker, caplog) -> None: caplog.set_level(logging.DEBUG) ind_mock = MagicMock(side_effect=lambda x, meta: x) buy_mock = MagicMock(side_effect=lambda x, meta: x) @@ -268,7 +268,7 @@ def test__analyze_ticker_internal_skip_analyze(ticker_history, mocker, caplog) - strategy = DefaultStrategy({}) strategy.process_only_new_candles = True - ret = strategy._analyze_ticker_internal(ticker_history, {'pair': 'ETH/BTC'}) + ret = strategy._analyze_ticker_internal(ohlcv_history, {'pair': 'ETH/BTC'}) assert 'high' in ret.columns assert 'low' in ret.columns assert 'close' in ret.columns @@ -280,7 +280,7 @@ def test__analyze_ticker_internal_skip_analyze(ticker_history, mocker, caplog) - assert not log_has('Skipping TA Analysis for already analyzed candle', caplog) caplog.clear() - ret = strategy._analyze_ticker_internal(ticker_history, {'pair': 'ETH/BTC'}) + ret = strategy._analyze_ticker_internal(ohlcv_history, {'pair': 'ETH/BTC'}) # No analysis happens as process_only_new_candles is true assert ind_mock.call_count == 1 assert buy_mock.call_count == 1 diff --git a/tests/test_misc.py b/tests/test_misc.py index 83e008466..c1e23926b 100644 --- a/tests/test_misc.py +++ b/tests/test_misc.py @@ -6,7 +6,7 @@ from unittest.mock import MagicMock import pytest -from freqtrade.data.converter import parse_ticker_dataframe +from freqtrade.data.converter import ohlcv_to_dataframe from freqtrade.misc import (datesarray_to_datetimearray, file_dump_json, file_load_json, format_ms_time, pair_to_filename, plural, shorten_date) @@ -18,9 +18,9 @@ def test_shorten_date() -> None: assert shorten_date(str_data) == str_shorten_data -def test_datesarray_to_datetimearray(ticker_history_list): - dataframes = parse_ticker_dataframe(ticker_history_list, "5m", pair="UNITTEST/BTC", - fill_missing=True) +def test_datesarray_to_datetimearray(ohlcv_history_list): + dataframes = ohlcv_to_dataframe(ohlcv_history_list, "5m", pair="UNITTEST/BTC", + fill_missing=True) dates = datesarray_to_datetimearray(dataframes['date']) assert isinstance(dates[0], datetime.datetime) diff --git a/tests/test_plotting.py b/tests/test_plotting.py index dd04035b7..42010ad0d 100644 --- a/tests/test_plotting.py +++ b/tests/test_plotting.py @@ -51,15 +51,15 @@ def test_init_plotscript(default_conf, mocker, testdatadir): default_conf["datadir"] = testdatadir default_conf['exportfilename'] = str(testdatadir / "backtest-result_test.json") ret = init_plotscript(default_conf) - assert "tickers" in ret + assert "ohlcv" in ret assert "trades" in ret assert "pairs" in ret default_conf['pairs'] = ["TRX/BTC", "ADA/BTC"] ret = init_plotscript(default_conf) - assert "tickers" in ret - assert "TRX/BTC" in ret["tickers"] - assert "ADA/BTC" in ret["tickers"] + assert "ohlcv" in ret + assert "TRX/BTC" in ret["ohlcv"] + assert "ADA/BTC" in ret["ohlcv"] def test_add_indicators(default_conf, testdatadir, caplog): @@ -269,14 +269,14 @@ def test_generate_profit_graph(testdatadir): pairs = ["TRX/BTC", "ADA/BTC"] trades = trades[trades['close_time'] < pd.Timestamp('2018-01-12', tz='UTC')] - tickers = history.load_data(datadir=testdatadir, - pairs=pairs, - timeframe='5m', - timerange=timerange - ) + data = history.load_data(datadir=testdatadir, + pairs=pairs, + timeframe='5m', + timerange=timerange) + trades = trades[trades['pair'].isin(pairs)] - fig = generate_profit_graph(pairs, tickers, trades, timeframe="5m") + fig = generate_profit_graph(pairs, data, trades, timeframe="5m") assert isinstance(fig, go.Figure) assert fig.layout.title.text == "Freqtrade Profit plot"