Skip to content

Commit

Permalink
add Portfolio class
Browse files Browse the repository at this point in the history
  • Loading branch information
sirfoga committed Jan 2, 2018
1 parent bc77c95 commit 3165ccc
Show file tree
Hide file tree
Showing 5 changed files with 99 additions and 128 deletions.
7 changes: 3 additions & 4 deletions pyhodl/charts/balances.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import matplotlib.pyplot as plt

from pyhodl.app import VALUE_KEY, DATE_TIME_KEY
from pyhodl.stats.wallets import get_total_equivalent_balances
from pyhodl.models.exchanges import Portfolio
from pyhodl.utils import generate_dates, normalize


Expand Down Expand Up @@ -148,6 +148,7 @@ def __init__(self, wallets, base_currency="USD"):
wallet.get_balance_equivalent(self.base_currency)
for wallet in self.wallets
}
self.portfolio = Portfolio(self.wallets)

def _plot_balance(self, wallet):
"""
Expand Down Expand Up @@ -219,9 +220,7 @@ def plot_buy_sells(self, wallet):
)

def plot_total_balances(self):
balances = get_total_equivalent_balances(
self.wallets, self.base_currency
)
balances = self.portfolio.get_balance_values(self.base_currency)
plt.plot(
[balance[DATE_TIME_KEY] for balance in balances],
[balance[VALUE_KEY] for balance in balances],
Expand Down
51 changes: 35 additions & 16 deletions pyhodl/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,20 @@
import os
import time
import traceback
from datetime import timedelta
from datetime import timedelta, datetime
from enum import Enum

from hal.files.save_as import write_dicts_to_json
from hal.streams.pretty_table import pretty_format_table
from hal.streams.user import UserInput

from pyhodl.apis.prices import get_market_cap, get_prices
from pyhodl.app import DATA_FOLDER
from pyhodl.charts.balances import OtherCurrencyPlotter
from pyhodl.data.parsers import build_parser
from pyhodl.data.parsers import build_parser, build_exchanges
from pyhodl.models.exchanges import Portfolio
from pyhodl.stats.transactions import get_transactions_dates, \
get_all_exchanges, get_all_coins
from pyhodl.stats.wallets import show_balance_of_exchange, \
show_balance_of_folder
from pyhodl.updater.core import Updater


Expand Down Expand Up @@ -67,9 +67,9 @@ def create_args():
parser.add_argument("-plot", dest="plot",
help="Creates charts of your data",
required=False)
parser.add_argument("-stats", dest="stats",
help="Computes statistics and trends using local data",
required=False)
parser.add_argument("-stats", "--stats", action="store_true",
help="Computes"
"statistics and trends using local data")
parser.add_argument("-verbose", "--verbose", action="store_true",
help="Increase verbosity")
parser.add_argument("-tor", dest="tor",
Expand All @@ -94,7 +94,7 @@ def parse_args(parser):
elif args.plot:
return RunMode.PLOTTER, os.path.join(args.plot), args.verbose
elif args.stats:
return RunMode.STATS, os.path.join(args.stats), args.verbose
return RunMode.STATS, DATA_FOLDER, args.verbose
elif args.hist:
return RunMode.DOWNLOAD_HISTORICAL, \
os.path.join(args.hist), args.verbose, args.tor
Expand All @@ -114,17 +114,36 @@ def plot(input_file, verbose):
parser = build_parser(input_file)
exchange = parser.build_exchange()
wallets = exchange.build_wallets()
plotter = OtherCurrencyPlotter(list(wallets.values()))
plotter = OtherCurrencyPlotter(wallets.values())
plotter.plot_total_balances()
plotter.show("Balances from " + input_file)


def compute_stats(exchange, verbose):
show_balance_of_exchange(exchange, verbose)
def show_exchange_balance(exchange, verbose):
if verbose:
print("\n\nPrinting balances of", exchange.exchange_name)

wallets = exchange.build_wallets()
portfolio = Portfolio(wallets.values())
table, tot_balance = portfolio.get_current_balance()
pretty_table = pretty_format_table(
["symbol", "balance", "$ value", "$ price per coin"],
table
)

print("As of", datetime.now(), "you got")
print(pretty_table)
print("Total value: ~", tot_balance, "$")
return tot_balance


def compute_stats_of_folder(input_folder):
show_balance_of_folder(input_folder)
def show_folder_balance(input_folder):
exchanges = build_exchanges(input_folder)
total_value = 0.0
for exchange in exchanges:
exchange_value = show_exchange_balance(exchange, True)
total_value += exchange_value
print("Total value of all exchanges ~", total_value, "$")


def download_market_cap(since, until, where_to, verbose):
Expand Down Expand Up @@ -165,11 +184,11 @@ def main():
plot(args[0], args[1])
elif run_mode == RunMode.STATS:
if os.path.isfile(args[0]):
compute_stats(args[0], args[1])
show_exchange_balance(args[0], args[1])
elif os.path.isdir(args[0]):
compute_stats_of_folder(args[0])
show_folder_balance(args[0])
else:
compute_stats_of_folder(DATA_FOLDER)
show_folder_balance(DATA_FOLDER)
elif run_mode == RunMode.DOWNLOAD_HISTORICAL:
exchanges = get_all_exchanges()
dates = get_transactions_dates(exchanges)
Expand Down
60 changes: 60 additions & 0 deletions pyhodl/models/exchanges.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

""" Analyze transactions in exchanges """

from pyhodl.app import DATE_TIME_KEY, VALUE_KEY

from pyhodl.models.transactions import Wallet


Expand Down Expand Up @@ -114,3 +116,61 @@ def build_wallets(self):
wallets[coin].add_transaction(transaction)

return wallets


class Portfolio:
""" Contains wallets, of also different coins """

def __init__(self, wallets, portfolio_name=None):
self.wallets = wallets
self.portfolio_name = str(portfolio_name) if portfolio_name else None

def get_balance_values(self, currency):
all_deltas = []
for wallet in self.wallets:
deltas = list(wallet.get_delta_balance_by_transaction())
equivalents = [
{
DATE_TIME_KEY: delta["transaction"].date,
VALUE_KEY: wallet.get_equivalent(
delta["transaction"].date,
currency,
delta[VALUE_KEY]
)
} for delta in deltas
]
all_deltas += equivalents

all_deltas = sorted(all_deltas, key=lambda x: x[DATE_TIME_KEY])
all_balances = [all_deltas[0]]
for delta in all_deltas[1:]:
all_balances.append({
DATE_TIME_KEY: delta[DATE_TIME_KEY],
VALUE_KEY: all_balances[-1][VALUE_KEY] + delta[VALUE_KEY]
})
return all_balances

def get_current_balance(self):
balances = [
{
"symbol": wallet.base_currency,
"balance": wallet.balance(),
"value": wallet.get_balance_equivalent_now()
}
for wallet in self.wallets
]
balances = sorted([
balance for balance in balances if float(balance["balance"]) > 0.0
], key=lambda x: x["value"], reverse=True)
table = [
[
str(balance["symbol"]),
str(balance["balance"]),
str(balance["value"]) + " $",
str(float(balance["value"] / float(balance["balance"]))) + " $"
]
for balance in balances
]

tot_balance = sum([balance["value"] for balance in balances])
return table, tot_balance
107 changes: 0 additions & 107 deletions pyhodl/stats/wallets.py

This file was deleted.

2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@

setup(
name="pyhodl",
version="0.2.2",
version="0.2.4",
author="sirfoga",
author_email="sirfoga@protonmail.com",
description=LITTLE_DESCRIPTION,
Expand Down

0 comments on commit 3165ccc

Please sign in to comment.