GnuCash fec5643+
Loading...
Searching...
No Matches
quotes_historic.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2
3# quotes_historic.py -- Example Script to read historic quote data into gnucash
4#
5
6
19
20from gnucash import Session, GncNumeric, GncPrice, PriceSource, GNC_HOW_DENOM_FIXED, GNC_HOW_RND_ROUND_HALF_UP
21from gnucash.gnucash_core_c import COMMODITY_DENOM_MULT
22import datetime
23from gnc_convenience import find_account
24
25FILE = "./test.gnucash"
26url = "xml://"+FILE
27
28# Read data from file
29f = open('INTC')
30data = []
31while 1:
32 tmp = f.readline()
33 if(len(tmp)<2):
34 break
35
36 data.append(tmp)
37
38f.close()
39
40stock_date = []
41stock_price = []
42for i in range(1,len(data)):
43 year = int(data[i].rsplit(',')[1].rsplit('/')[0])
44 month = int(data[i].rsplit(',')[1].rsplit('/')[1])
45 day = int(data[i].rsplit(',')[1].rsplit('/')[2])
46 stock_date.append(datetime.datetime(year,month,day))
47 stock_price.append(float(data[i].rsplit(',')[5]))
48
49# Initialize Gnucash session
50session = Session(url)
51root = session.book.get_root_account()
52book = session.book
53account = book.get_root_account()
54pdb = book.get_price_db()
55comm_table = book.get_table()
56
57# This example assumes the Intel holding is priced in USD.
58ac = find_account(account, 'Intel')[0]
59stock = ac.GetCommodity()
60cur = comm_table.lookup("CURRENCY", "USD")
61
62# Construct the price at the precision GnuCash uses for a commodity quoted in a
63# currency: the currency's smallest unit (its SCU -- get_fraction() is 100 for
64# USD, i.e. cents) times COMMODITY_DENOM_MULT (10000), the extra precision a
65# price carries beyond an ordinary amount. See "Price policy" in gnc-pricedb.h.
66price_denom = cur.get_fraction() * COMMODITY_DENOM_MULT
67for i in range(0, len(stock_date)):
68 print('Adding', i, stock_date[i], stock_price[i])
69 # --- Create a fresh price object with all properties set ------------------
70 p_new = GncPrice(book)
71 p_new.set_commodity(stock)
72 p_new.set_currency(cur)
73 p_new.set_time64(stock_date[i])
74 p_new.set_value(GncNumeric(stock_price[i], price_denom,
75 GNC_HOW_DENOM_FIXED | GNC_HOW_RND_ROUND_HALF_UP))
76 p_new.set_source(PriceSource.FINANCE_QUOTE)
77 p_new.set_typestr("last") # bid / ask / last / nav / unknown
78 # --------------------------------------------------------------------------
79 pdb.add_price(p_new)
80
81# Clean up
82session.save()
83session.end()
84session.destroy()
The primary numeric class for representing amounts and values.