Code Monkey home page Code Monkey logo

jal's Introduction

JAL (Just Another Ledger)

Track and manage your personal finances seamlessly.

image

English, Русский

📌 Overview

JAL is tailored for those who want a clear insight into their personal incomes, expenditures, investments, and up-to-date information on account balances and portfolio values.

⭐️ Features

Multiple Accounts Management

  • Support for various currencies with user-selected base currency totals.

Transaction Types

  • Generic income/spending with multi-category split.
  • Asset and money transfers, including currency conversion.
  • Trading operations: Buy/Sell securities (stocks, ETFs, options, and more).
  • Dividends for stocks and bond interest payments (including bond amortization).
  • Corporate actions for stocks.
  • Term deposits.

Reports

  • Daily history of account balance.
  • Portfolio asset allocation for a given date.
  • Monthly income/expenditure by category.
  • Investment profit/loss and history of payments for an assets.
  • Closed deals summary.

Price Updates

  • Stock/ETF/Crypto prices updated for major global exchanges.
  • Currency exchange rates from European and Russian central banks.

Broker Statement Imports

  • Supports various Russian and international brokers.

Tax Reports

  • Assistance for tax declaration in Russia and Portugal.
  • Tax burden estimation for a given asset in the portfolio.

Experimental Features

  • Electronic slips download for russian and some european shops.
  • Category recognition for goods in electronic slips using TensorFlow.

📥 Installation

JAL offers cross-platform compatibility and portability. Here's how to get started:

  1. From GitHub Repository:
    • Clone repository locally with git https://github.com/titov-vv/jal.git
    • Ensure you have Python 3.8.1 or later and meet all dependencies in requirements.txt.
    • Tips Windows users: Ensure Python installation from the official site and turn on options pip installation and add Python to environment variables during the installation. Reboot to apply changes.
    • Use run.py to launch the application.
  2. Using pip:
    • Install using pip install jal.
    • Launch with the jal command or alternatively python -m jal.jal.
  3. Hybrid Installation:
    • Download source files and use setup.py for tailored installation.

Database will be initialized automatically with minimal required set of data, and you will be able to start use the program.

You may choose program language in menu Languages.

❗️ Upgrades

If you installed jal via pip then you may upgrade it to newer version with help of command pip install jal -U

🖭 Backups

You can use menu Data->Backup and Data->Restore to save and restore a copy of your data. But you may get the same result by simply saving jal.sqlite file that contains everything. You may see a location of the file that jal uses in menu About.

📈 Tax report for investment account

Tax report can be prepared based on data from any broker if operations are present in JAL. Tax reports are supported for Russia and Portugal.
You can import operations from broker statement with help of menu Import->Statement.
Step-by-step example (in russian language) of Russian tax report preparation for Interactive Brokers can be found on this page. Use contacts from beginning of this page if you need support regarding statements or reports.

Screenshots

Qt have a better look on Linux out of the box. Here is main program window:
Main Window on Linux

The same window on Windows - the same functions with a bit different look:
Main Window on Windows

Accounts are be arranged in groups (Cash, Cards, Investments, etc), each account holds one currency. Below is a view of main window where one account is chosen ('Mastercard') and account select/edit window is opened on top:
One Account

Example of investment account view with Buy, Sell and Dividend operations recorded (there is an asset select/edit window on top):
Investment Account

'Holdings' tab contains portfolio overview (You display account and portfolio balances for any date). Holdings are grouped by currencies and then by accounts.
Holdings

Examples of reports are below: Monthly incomes/spendings (categories hierarchy is supported with sub-totals calculation)
Income/Spending report Profit/Loss for investment account (Assets value to be fixed, Returns include dividends and other payments)
Profit/Loss report List of all closed deals for investment account
Deals report

📞 Support, Feedback

If you want to ask a question, report a bug, provide help or support an author - you may use email [email protected] or Telegram (Issues on GitHub are always welcome also).

❤️ Acknowledgements

I would like to a mention people who helped me in 2022 and 2023 as I got more donations, help and feedback from users this year. And while I can't name every one of them I would like to confirm my appreciation for this help. They did the project better!


Hits

jal's People

Contributors

a18 avatar flmnvd avatar grunichev avatar iliakan avatar korxif avatar pedro-camargo11 avatar titov-vv avatar trellixvulnteam avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

jal's Issues

Tax report: Процент на остаток по счёту попал в комиссии

Процент на остаток кеша на счёте IB зачислил на счёт в соответствующей валюте.
В отчёте по налогам эти начисления попали в комиссии и уменьшили их. Не уверен, что это корректно - эти поступления вроде бы нужно подавать с отдельным кодом дохода и платить с них налог.
Даже если можно их сальдировать с комиссиями за неактивность, логично было бы видеть эти поступления на отдельном листе.

Так выглядит в отчёте брокера
image

Вот так зачлось в налоговом отчёте
image

Операции с валютами

Насколько я правильно понял, налоговую интересуют также операции по покупке\продаже валюты в валютной секции IB.

Например, заводил я на счёт рубли, потом менял на доллары. На доллары покупал акции. Затем менял доллары на рубли обратно.

Не нашёл в сделках такой информации, хотя брокер мне делает отчёт по движению валютной секции.
Также не нашёл в выгрузке в эксель и для налоговой секцию операций с валютами? Или это как-то по другому решается?

Дивиденды

Справа-снизу "Налог, уплаченный в иностранном государстве" - откуда берётся?

Вот скрин из Декларации 20, один дивиденд:
image

Но дело в том, что по Dividend report там не было Withholding tax, вот кусочек:

image

Так как Qualified dividends, то налог не брался.

======
Dividend report скачал только что за 2020, как и отчёт.

Возможно, различие из-за корректировок? Я не очень разобрался с этим.
Как быть с этими корректировками? ;)

Декларация за 2 счета в IB

Как действовать, если в IB открыто 2 accounts у одного человека?

Верно ли так?

  1. Создать дополнительные счета Data → Accounts и импортировать все отчёты (они подхватятся как надо?).
  2. Вызвать Reports → Tax Report два раза, указав при втором вызове .dc0-декларацию, заполненную в результате первого вызова (добавит записи?).

Tax Report[RU] exception for declaration file

При попытке генерации файла "Декларация 2020" возникает exception
image
Поскольку ссылка на Country code, есть подозрение, что дело в тикере VALE, у которого не определяется страна (скриншот со вкладки "Дивиденды":
image
Если нужен полный отчет IBKR, могу выслать приватно.

Ошибка по корпоративным действиям (split initial amount failure)

Traceback (most recent call last):
File "c:\users\aleontye\appdata\local\programs\python\python38\lib\site-packages\jal\widgets\main_window.py", line 241, in onStatementImport
self.ledger.rebuild()
File "c:\users\aleontye\appdata\local\programs\python\python38\lib\site-packages\jal\db\ledger.py", line 446, in rebuild
operationProcessself.current['type']
File "c:\users\aleontye\appdata\local\programs\python\python38\lib\site-packages\jal\db\ledger.py", line 340, in processCorporateAction
raise ValueError(self.tr("Unhandled case: Corporate action covers not full open position"))
ValueError: Unhandled case: Corporate action covers not full open position

Где-то давится corporate actions. в отчете:
image

А в экспорте только
image

Подойдет ли Jal при отсутствии старых отчётов?

Нужно составить 3-НДФЛ за 2020.

При этом были некоторые продажи ETF, приобретённых в 2015 году.

За старые года (более 5 лет) никакой возможности получить от Interactive Brokers репорт нет. Я их уже 3 недели трясу по-разному, похоже прям совсем никак. Хотя в HTML-формате данные у меня есть (Activity Report).

Полагаю, подобный вопрос возникнет не только у меня, а у любого человека, который захочет использовать Jal, и покупка была более 5 лет назад.

Позволяет ли Jal как-то решить эту ситуацию? Ввести дату и стоимость покупки вручную, например.

Ошибка в курсе валют в отчете

Попробовал запустить процесс с декларацией за 2020 год.

  • Сделал Load Quotes с 2010 года по 2021 примерно так:

image

  • После Tax Report [RU] в excel появились такие строки:
    image

Тут курс доллара 35, определенно он таким не был 2020м году.

Неверный курс на всех страницах Excel-отчета.

Ошибка при работе отчётов

Некоторые отчёты не работают. Они должны работать или они в разработке?

  1. Раздел Holdings, вообще пусто, ничего не отображает при выборе любой даты
  2. Раздел Reports, опция Any accounts не выбирается
  3. Раздел Reports, если выбрать Income\Spending
    2021-04-09 14:31:50,841 - CRITICAL - EXCEPTION: ['Traceback (most recent call last):\n', ' File "C:\Users\request\AppData\Roaming\Python\Python39\site-packages\jal\widgets\main_window.py", line 255, in onRunReport\n self.reports.runReport(report_type, begin, end, self.ReportAccountBtn.account_id, group_dates)\n', ' File "C:\Users\request\AppData\Roaming\Python\Python39\site-packages\jal\reports\reports.py", line 55, in runReport\n self.model.prepare(begin, end, account_id, group_dates)\n', ' File "C:\Users\request\AppData\Roaming\Python\Python39\site-packages\jal\reports\income_spending_report.py", line 272, in prepare\n self._root = ReportTreeItem(begin, end, -1, "ROOT") # invisible root\n', ' File "C:\Users\request\AppData\Roaming\Python\Python39\site-packages\jal\reports\income_spending_report.py", line 17, in init\n self._m_s = int(datetime.utcfromtimestamp(begin).strftime('%-m'))\n', 'ValueError: Invalid format string\n']
  4. При выборе By category
    2021-04-09 14:33:32,754 - CRITICAL - EXCEPTION: ['Traceback (most recent call last):\n', ' File "C:\Users\request\AppData\Roaming\Python\Python39\site-packages\jal\widgets\main_window.py", line 253, in onRunReport\n self.reports.runReport(report_type, begin, end, self.ReportCategoryEdit.selected_id, group_dates)\n', ' File "C:\Users\request\AppData\Roaming\Python\Python39\site-packages\jal\reports\reports.py", line 55, in runReport\n self.model.prepare(begin, end, account_id, group_dates)\n', ' File "C:\Users\request\AppData\Roaming\Python\Python39\site-packages\jal\reports\category_report.py", line 51, in prepare\n self.report_failure.emit(g_tr('Reports', "You should select category to create By Category report"))\n', "AttributeError: 'CategoryReportModel' object has no attribute 'report_failure'\n"]

No selection when importing IBKR flex report

When I import an IBKR report, a new account is being created automatically. But when i choose as the selected one and click OK, it shows an error saying "No selection: Please select different account". Am i selecting wrong (i do triple click on the wanted account)?
image

Declaration file uses transaction date not settlement date

В генерируемой декларации для операций с ЦБ указывается дата продажи и курс на эту дату. При этом в Excel таблице рублевые расчеты ведутся по дате расчетов. Есть разные мнения, указывать ли в декларации T или T+2 (я считаю T+2 вернее), но по крайней мере Excel и декларация должны придерживаться одного подхода. Я бы предложил сделать в декларации T+, либо соответствующую настройку.
image
image

Migration from PySide2 to PySide6

Qt 6 was already released and upgrade is required. But PySide6 lacks modules QtMultimedia. QtWebEngine, etc.
These modules are expected to be available in Qt 6.2 LTS expected on Sep-Oct 2021.
Migrations is planned to be done in 2021 Q4.

Tax report: missed one of trades (GLTR ticker)

В налоговом отчёте потерялась одна из сделок. При этом в отчёте и в базе она есть
image

Налоговый отчёт генерирую за 20 год, другие три сделки есть, а по данному тикеру пустота
image

Отчёт обезличенный прилагаю
titov-vv_jal_anon.xml.zip

ERROR - Неверный формат файла резервной копии

Сделал резервную копию (Данные-> Бэкап..)
Пытаюсь восстановиться из резервной копии (Данные->Восстановление..)
Получаю ошибку "ERROR - Неверный формат файла резервной копии"
Что делаю неверно?

Использую данный механизм чтобы вернуть БД в исходное состояние, т.к. проводок много и удалять за весь период вручную совсем не вариант.

Новый импорт из HTML, вводить ли assets?

Запустил на чистой базе импорт из activity report за 2015.

Задаёт вопросы такого вида:

image

Это нормально?

VHT - это ETF. Выбирать Funds?

Что-то еще вводить? На что это влияет?

Ошибка при экспорте в файл декларации

Добрый день.

Возникла проблема, описываю порядок действий.

  1. Создал файл декларации .dc0.
  2. Выгрузил операции со счёта IB USD в файл декларации .dc0, операции в долларах успешно добавились. Тут всё ок.
  3. Далее мне нужно добавить в эту же декларацию данные по другой валюте. Запускаю выгрузку в этот же файл со второго счёта IB CAD (аккаунт IB тот же, но валюта другая, канадский доллар), получаю ошибку и файл не сохраняется

2021-04-08 22:18:34,904 - ERROR - Currency isn't known for tax form: CAD
2021-04-08 22:18:34,909 - CRITICAL - EXCEPTION: ['Traceback (most recent call last):\n', ' File "C:\Users\request\AppData\Roaming\Python\Python39\site-packages\jal\reports\dlsg.py", line 232, in get_country_currency\n currency_code = self.currencies[currency_name]\n', "KeyError: 'CAD'\n", '\nDuring handling of the above exception, another exception occurred:\n\n', 'Traceback (most recent call last):\n', ' File "C:\Users\request\AppData\Roaming\Python\Python39\site-packages\jal\reports\taxes.py", line 262, in showTaxesDialog\n self.save2file(dialog.xls_filename, dialog.year, dialog.account, dlsg_update=dialog.update_dlsg,\n', ' File "C:\Users\request\AppData\Roaming\Python\Python39\site-packages\jal\reports\taxes.py", line 296, in save2file\n next_row = report_descriptionself.RPT_METHOD\n', ' File "C:\Users\request\AppData\Roaming\Python\Python39\site-packages\jal\reports\taxes.py", line 522, in prepare_stocks_and_etf\n self.statement.add_stock_profit(deal['country_code'], self.broker_name, deal['cs_date'],\n', ' File "C:\Users\request\AppData\Roaming\Python\Python39\site-packages\jal\reports\dlsg.py", line 216, in add_stock_profit\n country_code, currency_code = self.get_country_currency(country, currency_name)\n', ' File "C:\Users\request\AppData\Roaming\Python\Python39\site-packages\jal\reports\dlsg.py", line 235, in get_country_currency\n raise ValueError\n', 'ValueError\n']

2021-04-08_22-18-30

'Fatal Python error: Segmentation fault' happens at application exit

Problem appeared after project structure change and incupsulation of all code inside main() function.
Everything works but exception 'Fatal Python error: Segmentation fault' happens at the end of execution. It apparently happens due to some clean-up of already destroyed Qt object (Objects that cause the problem are linked in LedgerOperationsView.setOperationsDetails method)

Запуск под Windows

Решил попробовать под Windows, которая в виртуалке на моей основной ОС.

Поставил туда python 3.8 x64 и запустил pip install jal.

А как его потом запускать?

Вот попробовал перейти в пакет и запустить python3 jal.py, но как-то оно не работает:

image

Warning: dividend not found

При импорте на чистую базу в логе сообщения такого вида:

2021-03-25 23:06:16,306 - WARNING - Dividend not found for withholding tax: VHT(US92204A5048) CHOICE DIVIDEND 0.44300000 USD DISTRIBUTION VALUE - US TAX
2021-03-25 23:06:16,324 - WARNING - Dividend not found for withholding tax: VUG(US9229087369) CHOICE DIVIDEND 0.37900000 USD DISTRIBUTION VALUE - US TAX
2021-03-25 23:06:16,343 - WARNING - Dividend not found for withholding tax: VOO(US9229083632) CHOICE DIVIDEND 1.01000000 USD DISTRIBUTION VALUE - US TAX
2021-03-25 23:06:16,360 - WARNING - Dividend not found for withholding tax: VUG(US9229087369) CHOICE DIVIDEND 0.34100000 USD DISTRIBUTION VALUE - US TAX
2021-03-25 23:06:16,378 - WARNING - Dividend not found for withholding tax: VHT(US92204A5048) CHOICE DIVIDEND 0.49800000 USD DISTRIBUTION VALUE - US TAX
2021-03-25 23:06:16,397 - WARNING - Dividend not found for withholding tax: VNQI(US9220426764) CHOICE DIVIDEND 0.27800000 USD DISTRIBUTION VALUE - US TAX

Это ок?

BND/BNDX quotes not loaded

Котировки по данным двум тикерам не тянутся с яхи.

curl -I "https://query1.finance.yahoo.com/v7/finance/download/BNDX?period1=1611273600&period2=1609372800&interval=1d&events=history" HTTP/2 400

Spin-off: Russian Tax code requires to make cost basis adjustments

При расчете налога для выделяемой компании (после корпоративного действия Spin-Off) берётся цена покупки равная нулю.
Однако п.5 ст.277 НК РФ требует пропорционального изменения цены покупки для материнской компании и для выделяемой компании.
Т.е. в операции Spin-off нужно учитывать процент распределения активов при выделении (для американских компаний - см. Form 8937)

Группировка позиций при экспорте в отчёт для налоговой

Можно ли где-то включить опцию чтобы группировать операции при экспорте в эксель файл, и затем в файл для налоговой?

Операции совершены в один день, курс ЦБ один и тот же, курс продажи тоже.
В первой строке отличается дата, а вторая и третья совершены в один день

image

NULL rate for some transfer fee transactions in db

It seems some transfer import operations (from IBKR statements for example) created records with NULL 'rate' field in 'transfers' table for transfer fees. Need to check import and fix transfer if required.

Dividends in lieu not parsed

С новым регэкспом записи в логах такого вида:

2021-03-27 09:42:17,461 - WARNING - Dividend not found for withholding tax: VCIT (US92206C8709) CASH DIVIDEND USD 0.25420000 - US TAX
2021-03-27 09:42:17,464 - WARNING - Dividend not found for withholding tax: VCIT (US92206C8709) CASH DIVIDEND USD 0.25420000 - US TAX
2021-03-27 09:42:17,503 - WARNING - *** MANUAL ENTRY REQUIRED ***
2021-03-27 09:42:17,505 - WARNING - Unhandled tax pattern found: VHT(US92204A5048) PAYMENT IN LIEU OF DIVIDEND - US TAX

Возможно, тут две разные ошибки, а может они и связаны.

Вот пример записи, которая не парсится регом (в desc отсутствует сумма):

<CashTransaction accountId="U1234567" acctAlias="" model="" currency="USD" fxRateToBase="1" assetCategory="STK" symbol="VHT" description="VHT(US92204A5048) PAYMENT IN LIEU OF DIVIDEND - US TAX" conid="27638082" securityID="92204A504" securityIDType="CUSIP" cusip="92204A504" isin="" listingExchange="ARCA" underlyingConid="" underlyingSymbol="" underlyingSecurityID="" underlyingListingExchange="" issuer="" multiplier="1" strike="" expiry="" putCall="" principalAdjustFactor="" dateTime="20181218;202000" settleDate="20181218" amount="-1.38" type="Withholding Tax" tradeID="" code="" transactionID="9988459058" reportDate="20181218" clientReference="" levelOfDetail="DETAIL" />

Таких строк несколько, для разных бумаг.

Я бы поправил, но что они означают - не знаю, не понимаю что с ними делать. Все они в конце декабря, может как-то связаны со следующим годом.

Load old quotes not working

Если сперва загрузить котировки за последнюю неделю, а потом пробовать догрузить котировки за последний год, то они не подгрузятся без каких либо ошибок в логе

MacOS Mojave - нет иконок

Инсталял при помощи pip install jal.

Запустил, и в обоих языках что-то с иконками (См справа где плюс и минус должен быть):
image

Вообще, под MacOS Mojave оно должно работать, кто-то проверял, или на мне будут все шишки? :)

❯ pip -V
pip 21.0.1 from /opt/local/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip (python 3.8)

❯ python -V
Python 3.8.8

Поддержка активов типа варранты

Здравствуйте, не получается загрузить варранты, можно как то добавить поддержку данного типа активов?
Или сделать возможность загрузки без них для начала? Пока не загружается весь отчёт из-за ошибки.

2021-04-07 23:35:53,275 - ERROR - Asset type isn't supported: WAR
2021-04-07 23:35:53,314 - ERROR - Failed to load attribute: assetCategory / {'currency': 'USD', 'assetCategory': 'WAR', 'symbol': 'CLRBZ', 'description': 'CLRB 08APR21 3.04 C', 'conid': '230464637', 'securityID': 'US15117F1387', 'securityIDType': 'ISIN', 'cusip': '15117F138', 'isin': 'US15117F1387', 'listingExchange': 'NASDAQ', 'underlyingConid': '326006322', 'underlyingSymbol': 'CLRB', 'underlyingSecurityID': 'US15117F5008', 'underlyingListingExchange': 'NASDAQ', 'issuer': '', 'multiplier': '1', 'strike': '3.04', 'expiry': '20210408', 'putCall': '', 'principalAdjustFactor': '', 'serialNumber': '', 'deliveryType': '', 'commodityType': '', 'fineness': '0.0', 'weight': '0.0 ()', 'maturity': '', 'issueDate': '', 'underlyingCategory': 'STK', 'subCategory': '', 'settlementPolicyMethod': 'Delivery', 'code': ''}

Withdrawal - автоматизация

Делаю импорт XML за 2017 год.

Получаю пачку вопросов такого вида:
image

Это ок? Я перед этим создал Bank accounts:

image

Стесняюсь спросить - можно ли, чтобы автоматом нужный банковский счет выбирало, с той же валютой? Для налогов ведь это вообще не важно.

Tax report[RU]: empty summary fields

Делал всё по инструкции, курсы подгрузил, суммы всех операций посчитались корректно, но в колонках "Итого" всё по нулям на всех листах (комиссии/сделки/дивы)
image

Declaration file - bonds and commissions not included

В файле декларации не указываются купонные доходы по облигациям, присутствующие в эксель-расчете.
Также в расходы не включены прочие комиссии.

PS есть какая-то еще площадка для интерактивного общения с автором?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.