Beautify code a bit

This commit is contained in:
Matthias 2020-12-07 14:54:39 +01:00
parent 245c19f5e9
commit e873cafdc4
2 changed files with 17 additions and 20 deletions

View File

@ -275,38 +275,38 @@ class RPC:
"trades_count": len(output) "trades_count": len(output)
} }
def _rpc_stats(self): def _rpc_stats(self) -> Dict[str, Any]:
""" """
Generate generic stats for trades in database Generate generic stats for trades in database
""" """
def trade_win_loss(trade): def trade_win_loss(trade):
if trade.close_profit > 0: if trade.close_profit > 0:
return 'Wins' return 'wins'
elif trade.close_profit < 0: elif trade.close_profit < 0:
return 'Losses' return 'losses'
else: else:
return 'Draws' return 'draws'
trades = trades = Trade.get_trades([Trade.is_open.is_(False)]) trades = trades = Trade.get_trades([Trade.is_open.is_(False)])
# Sell reason # Sell reason
sell_reasons = {} sell_reasons = {}
for trade in trades: for trade in trades:
if trade.sell_reason not in sell_reasons: if trade.sell_reason not in sell_reasons:
sell_reasons[trade.sell_reason] = {'Wins': 0, 'Losses': 0, 'Draws': 0} sell_reasons[trade.sell_reason] = {'wins': 0, 'losses': 0, 'draws': 0}
sell_reasons[trade.sell_reason][trade_win_loss(trade)] += 1 sell_reasons[trade.sell_reason][trade_win_loss(trade)] += 1
# Duration # Duration
dur: Dict[str, List[int]] = {'Wins': [], 'Draws': [], 'Losses': []} dur: Dict[str, List[int]] = {'wins': [], 'draws': [], 'losses': []}
for trade in trades: for trade in trades:
if trade.close_date is not None and trade.open_date is not None: if trade.close_date is not None and trade.open_date is not None:
trade_dur = (trade.close_date - trade.open_date).total_seconds() trade_dur = (trade.close_date - trade.open_date).total_seconds()
dur[trade_win_loss(trade)].append(trade_dur) dur[trade_win_loss(trade)].append(trade_dur)
wins_dur = sum(dur['Wins']) / len(dur['Wins']) if len(dur['Wins']) > 0 else 'N/A' wins_dur = sum(dur['wins']) / len(dur['wins']) if len(dur['wins']) > 0 else 'N/A'
draws_dur = sum(dur['Draws']) / len(dur['Draws']) if len(dur['Draws']) > 0 else 'N/A' draws_dur = sum(dur['draws']) / len(dur['draws']) if len(dur['draws']) > 0 else 'N/A'
losses_dur = sum(dur['Losses']) / len(dur['Losses']) if len(dur['Losses']) > 0 else 'N/A' losses_dur = sum(dur['losses']) / len(dur['losses']) if len(dur['losses']) > 0 else 'N/A'
durations = {'wins': wins_dur, 'draws': draws_dur, 'losses': losses_dur} durations = {'wins': wins_dur, 'draws': draws_dur, 'losses': losses_dur}
return sell_reasons, durations return {'sell_reasons': sell_reasons, 'durations': durations}
def _rpc_trade_statistics( def _rpc_trade_statistics(
self, stake_currency: str, fiat_display_currency: str) -> Dict[str, Any]: self, stake_currency: str, fiat_display_currency: str) -> Dict[str, Any]:

View File

@ -3,9 +3,9 @@
""" """
This module manage Telegram communication This module manage Telegram communication
""" """
from datetime import timedelta
import json import json
import logging import logging
from datetime import timedelta
from typing import Any, Callable, Dict, List, Union from typing import Any, Callable, Dict, List, Union
import arrow import arrow
@ -395,9 +395,8 @@ class Telegram(RPC):
""" """
Handler for /stats Handler for /stats
Show stats of recent trades Show stats of recent trades
:return: None
""" """
sell_reasons, durations = self._rpc_stats() stats = self._rpc_stats()
sell_reasons_tabulate = [] sell_reasons_tabulate = []
reason_map = { reason_map = {
@ -409,26 +408,24 @@ class Telegram(RPC):
'force_sell': 'Forcesell', 'force_sell': 'Forcesell',
'emergency_sell': 'Emergency Sell', 'emergency_sell': 'Emergency Sell',
} }
for reason, count in sell_reasons.items(): for reason, count in stats['sell_reasons'].items():
sell_reasons_tabulate.append([ sell_reasons_tabulate.append([
reason_map.get(reason, reason), reason_map.get(reason, reason),
sum(count.values()), sum(count.values()),
count['Wins'], count['wins'],
# count['Draws'], count['losses']
count['Losses']
]) ])
sell_reasons_msg = tabulate( sell_reasons_msg = tabulate(
sell_reasons_tabulate, sell_reasons_tabulate,
headers=['Sell Reason', 'Sells', 'Wins', 'Losses'] headers=['Sell Reason', 'Sells', 'Wins', 'Losses']
) )
durations = stats['durations']
duration_msg = tabulate([ duration_msg = tabulate([
['Wins', str(timedelta(seconds=durations['wins'])) ['Wins', str(timedelta(seconds=durations['wins']))
if durations['wins'] != 'N/A' else 'N/A'], if durations['wins'] != 'N/A' else 'N/A'],
# ['Draws', str(timedelta(seconds=durations['draws']))],
['Losses', str(timedelta(seconds=durations['losses'])) ['Losses', str(timedelta(seconds=durations['losses']))
if durations['losses'] != 'N/A' else 'N/A'] if durations['losses'] != 'N/A' else 'N/A']
], ],
headers=['', 'Avg. Duration'] headers=['', 'Avg. Duration']
) )
msg = (f"""```\n{sell_reasons_msg}```\n```\n{duration_msg}```""") msg = (f"""```\n{sell_reasons_msg}```\n```\n{duration_msg}```""")