[Python] piecash 介紹

程式語言:Python
Package:
piecash
官方文件
官方 GitHub 網址

功能:操作 gnucash 的 SQL 存檔
介紹內容並非完整,只有筆者認為比較常用的部分

import piecash

with piecash.open_book("example.gnucash", readonly=True, open_if_lock=True) as book:
    # get default currency of book
    print( book.default_currency )  # ==> Commodity<CURRENCY:EUR>

    # iterating over all splits in all books and print the transaction description:
    for acc in book.accounts:
        for sp in acc.splits:
            print(sp.transaction.description)
import piecash

with piecash.open_book("example.gnucash", readonly=True, open_if_lock=True) as book:
    # 可用多個屬性得到對應的物件,若有多個物件則只會回傳找到的第一個
    print(book.accounts(name="Cash in Wallet 手頭現金", type=piecash.AccountType.cash.value))
    print(book.root_account.children(type=piecash.AccountType.asset.value))
    print(book.splits(transaction=book.transactions[0]))
    print(book.transactions(description="小籠包"))
    print(book.prices(commodity=book.commodities(mnemonic="USD")))

piecash.core.account

官方文件
class piecash.core.account.AccountType
An enumeration.
class AccountType(Enum):
    root = "ROOT"
    receivable = "RECEIVABLE"
    mutual = "MUTUAL"
    cash = "CASH"
    asset = "ASSET"
    bank = "BANK"
    stock = "STOCK"
    credit = "CREDIT"
    liability = "LIABILITY"
    payable = "PAYABLE"
    income = "INCOME"
    expense = "EXPENSE"
    trading = "TRADING"
    equity = "EQUITY"
        
class piecash.core.account.Account(name, type, commodity, parent=None, description="", commodity_scu=None, hidden=0, placeholder=0, code="", book=None, children=None)
GnuCash 帳戶的 property & method
type
str – 帳戶類型
sign
int
  • 1 表示正資產,例:BANK
  • -1 表示負資產,例:負債
code
str – 帳戶代碼
commodity
piecash.core.commodity.Commodity – 帳戶商品,BANK 的商品是貨幣,STOCK 的商品是股票
commodity_scu
int – 帳戶的最小商品單位
non_std_scu
int – 如果帳戶商品最小單位與預設的不同,則設為 1
description
str – 帳戶說明
name
str – 帳戶名稱
fullname
str – 帳戶的全名(包括以:分隔的 parent 帳戶名稱)
placeholder
int – 如果帳戶是佔位符,則為 1(不應參與交易)
hidden
int – 如果帳戶被隱藏,則為 1
is_template
bool – 如果帳戶是 template 帳戶,則為 True (ie commodity=template/template),使用在 piecash.core.transaction.ScheduledTransaction
parent
Account – 帳戶的 parent 帳戶,root 帳戶為 None
children
list of Account – 帳戶的 children 帳戶
splits
list of piecash.core.transaction.Split – 帳戶的拆分交易
lots
list of piecash.business.Lot – 帳戶的批次清單
book
piecash.core.book.Book – 帳戶的 book
budget_amounts
list of piecash.budget.BudgetAmount – 帳戶的預算清單
scheduled_transaction
piecash.core.transaction.ScheduledTransaction – template 帳戶的排程交易
get_balance(recurse=True, commodity=None, natural_sign=True)
import piecash

with piecash.open_book("example.gnucash", readonly=True, open_if_lock=True) as book:
    print( book.accounts(name="手頭現金").get_balance() )
recurse
bool – True 包含 children 帳戶
commodity
piecash.core.commodity.Commodity – 指定餘額所代表的商品,None 表示原帳戶商品
natural_sign
bool – True 將負現金流調整為正號,像是 {‘LIABILITY’, ‘PAYABLE’, ‘CREDIT’, ‘INCOME’, ‘EQUITY’}
Returns: 帳戶餘額

piecash.core.book

官方文件
class piecash.core.book.Book(root_account=None, root_template=None)
Book 表示 GnuCash document, property & method 如下
不用時記得 call book.close() 以釋放 file/DB
root_account
piecash.core.account.Account – the root account of the book
root_template
piecash.core.account.Account – the root template of the book (usage not yet clear…)
default_currency
piecash.core.commodity.Commodity – 預設貨幣,若是舊版資料庫,值會是 None
uri
str – 連結檔案位置
session
sqlalchemy.orm.session.Session – the sqlalchemy session
add(obj)
加入 object
delete(obj)
刪除 object
save()
存檔 (=commit)
flush()
Flush the book
cancel()
取消改變 (=rollback)
is_saved
是否已存檔
close()
關閉 session,未存檔的改變,皆會 rolled back,然後釋放 file/DB
get(cls, **kwargs)
無 kwargs 時,回傳所有物件的 list (其實是 sqlalchemy.orm.query.Query)
提供 kwargs 時,回傳對應物件,必須只有一個
import piecash

with piecash.open_book("example.gnucash", readonly=True, open_if_lock=True) as book:
    # 回傳 sqlalchemy.orm.query.Query
    print(book.get(piecash.Account))
    # 依屬性尋找物件,必須只有一個,多個或沒有會報錯
    print(book.get(piecash.Account, name="Cash in Wallet 手頭現金", type=piecash.AccountType.cash.value))
cls
cls – 物件的 class,例:Account, Price, Budget,…
kwargs
dict – filter 物件屬性的值
Returns: 對應物件
transactions
所有交易,可使用 transactions(xxx=..., yyy=...) 得到其中一個物件,實際為
piecash.model_common.CallableList of piecash.core.transaction.Transaction
splits
所有拆分交易,可使用 splits(xxx=..., yyy=...) 得到其中一個物件,實際為
piecash.model_common.CallableList of piecash.core.transaction.Split
accounts
所有帳戶,可使用 accounts(xxx=..., yyy=...) 得到其中一個物件,實際為
piecash.model_common.CallableList of piecash.core.account.Account
commodities
所有商品,可使用 commodities(xxx=..., yyy=...) 得到其中一個物件,實際為
piecash.model_common.CallableList of piecash.core.commodity.Commodity
invoices
所有發票,可使用 invoices(xxx=..., yyy=...) 得到其中一個物件,實際為
<piecash.model_common.CallableList of piecash.core.commodity.Commodity
currencies
所有貨幣,可使用 currencies(xxx=..., yyy=...) 得到其中一個物件,實際為piecash.model_common.CallableList of piecash.core.commodity.Commodity
prices
所有價格,可使用 prices(xxx=..., yyy=...) 得到其中一個物件,實際為piecash.model_common.CallableList of piecash.core.commodity.Price
customers
所有客戶,可使用 customers(xxx=..., yyy=...) 得到其中一個物件,實際為piecash.model_common.CallableList of piecash.business.people.Customer
vendors
所有供應商,可使用 vendors(xxx=..., yyy=...) 得到其中一個物件,實際為piecash.model_common.CallableList of piecash.business.people.Vendor
employees
所有職員,可使用 employees(xxx=..., yyy=...) 得到其中一個物件,實際為piecash.model_common.CallableList of piecash.business.people.Employee
taxtables
所有稅表,可使用 taxtables(xxx=..., yyy=...) 得到其中一個物件,實際為piecash.model_common.CallableList of piecash.business.tax.Taxtable
query
sqlalchemy session 的 query
splits_df(additional_fields=None)
回傳所有拆分交易,但 type 為 pandas DataFrame
additional_fields
list, optional – 想新增的欄位
Returns: pandas.DataFrame
prices_df()
回傳所有價格,但 type 為 pandas DataFrame
Returns: pandas.DataFrame

piecash.core.commodity.Price

官方文件
class piecash.core.commodity.Price(commodity, currency, date, value, type='unknown', source='user:price')
GnuCash 商品價格的 property & method 如下
commodity
Commodity – 對應的商品
currency
Commodity – 對應的貨幣
date
datetime.date – 日期
source
str – 價格來源
type
str – last, ask, bid, unknown, nav
value
decimal.Decimal – 價格的值

piecash.core.commodity.Commodity

官方文件
class piecash.core.commodity.Commodity(namespace, mnemonic, fullname, fraction=100, cusip="", quote_flag=0, quote_source=None, quote_tz="", book=None)
GnuCash 商品的 property & method 如下
cusip
str – cusip code
fraction
int – 商品最小單位,例:100 表示 1/100
namespace
str – 商品分類,例:CURRENCY 表示為貨幣
mnemonic
str – 貨幣的 ISO 符號 或 股票符號
quote_flag
int – 1 表示會進行線上報價
quote_source
str – 報價來源
quote_tz
str – 報價時區
base_currency
Commodity – 商品基礎貨幣
  • 商品若為貨幣,則回傳 book 的預設貨幣
  • 商品若為其他,目前會報錯,作者待實現回傳 quoted_currency
accounts
list of piecash.core.account.Account – 對應使用的所有帳戶
transactions
list of piecash.core.transaction.Transaction – 對應的所有交易
prices
iterator of Price – 對應的所有價格
currency_conversion(currency)
指定貨幣,回傳最後一次商品的單價
import piecash

with piecash.open_book("example.gnucash", readonly=True, open_if_lock=True) as book:
    # 台幣買美金匯率
    print(book.commodities(mnemonic="USD").currency_conversion(book.commodities(mnemonic="TWD")))
currency
piecash.core.commodity.Commodity – 指定的貨幣
Returns: 商品指定貨幣的單價
Raises: GncConversionError – 表示無法轉換

piecash.core.session

官方文件
piecash.core.session.open_book(sqlite_file=None, uri_conn=None, readonly=True, open_if_lock=False, do_backup=True, db_type=None, db_user=None, db_password=None, db_name=None, db_host=None, db_port=None, check_same_thread=True, **kwargs)
打開一個已存在的 SQL 存檔
sqlite_file
str – sqlite3 檔案路徑
uri_conn
str – sqlalchemy connection string
readonly
bool – 唯讀模式
open_if_lock
bool – 上鎖仍打開
do_backup
bool – readonly=False,是否備份
db_type
str – 數據庫類型可為 ["postgres", "mysql"]
db_user
str – 數據庫的用戶名
db_password
str – 數據庫的密碼
db_name
str – 數據庫名稱
db_host
str – 數據庫主機
db_port
str – 數據庫端口
check_same_thread
bool – sqlite 標誌,用於限制對已創建線程的連接使用(在ipython / flask /中使用False,但請先閱讀 https://docs.python.org/3/library/sqlite3.html)
Returns: piecash.core.book.Book
Raises:
  • GnucashException – 當檔案不存在
  • GnucashException – 當已上鎖且 open_if_lock=False

piecash.core.transaction.Split

官方文件
class piecash.core.transaction.Split(account, value, quantity=None, transaction=None, memo="", action="", reconcile_date=None, reconcile_state='n', lot=None)
GnuCash 拆分交易的 property & method 如下
transaction
piecash.core.transaction.Transaction – 對應交易
account
piecash.core.account.Account – 對應帳號
lot
piecash.business.Lot – 對應批次清單
memo
str – 對應備忘錄
value
decimal.Decimal – 貨幣值
quantity
decimal.Decimal – 商品數量
reconcile_state
str – ‘n’, ‘c’ or ‘y’
reconcile_date
datetime.datetime – 對帳時間
action
str – 用戶提供的提醒描述

piecash.core.transaction.Transaction

官方文件
class piecash.core.transaction.Transaction(currency, description="", notes=None, splits=None, enter_date=None, post_date=None, num="")
GnuCash 交易的 property & method 如下
currency
piecash.core.commodity.Commodity – 對應貨幣
description
str – 交易說明
enter_date
datetime.datetime – 輸入日期
post_date
datetime.date – 發佈日期
num
str – 用戶提供的交易號碼
splits
list of Split – 對應的所有拆分交易
scheduled_transaction
ScheduledTransaction – 對應的排程交易
notes
str – 交易筆記

piecash.core.transaction.ScheduledTransaction

官方文件
class piecash.core.transaction.ScheduledTransaction(*args, **kwargs)
GnuCash 排程交易的 property & method 如下
adv_creation
int – 多久前建立
adv_notify
int – 幾天前提醒
auto_create
bool – 是否自動建立
auto_notify
bool – 建立時是否通知
enabled
bool – 是否啟用
start_date
datetime.datetime – 開始日期
last_occur
datetime.datetime – 上次發生日期
end_date
datetime.datetime – 結束日期
instance_count
int – 已發生次數
name
str – 排程交易名字
num_occur
int – 預計發生次數
rem_occur
int – 剩下次數
template_account
piecash.core.account.Account – template 帳戶

留言