GnuCash  5.6-150-g038405b370+
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 
20 from gnucash import Session, GncNumeric, GncPrice, PriceSource, GNC_HOW_DENOM_FIXED, GNC_HOW_RND_ROUND_HALF_UP
21 from gnucash.gnucash_core_c import COMMODITY_DENOM_MULT
22 import datetime
23 from gnc_convenience import find_account
24 
25 FILE = "./test.gnucash"
26 url = "xml://"+FILE
27 
28 # Read data from file
29 f = open('INTC')
30 data = []
31 while 1:
32  tmp = f.readline()
33  if(len(tmp)<2):
34  break
35 
36  data.append(tmp)
37 
38 f.close()
39 
40 stock_date = []
41 stock_price = []
42 for 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
50 session = Session(url)
51 root = session.book.get_root_account()
52 book = session.book
53 account = book.get_root_account()
54 pdb = book.get_price_db()
55 comm_table = book.get_table()
56 
57 # This example assumes the Intel holding is priced in USD.
58 ac = find_account(account, 'Intel')[0]
59 stock = ac.GetCommodity()
60 cur = 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.
66 price_denom = cur.get_fraction() * COMMODITY_DENOM_MULT
67 for 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
82 session.save()
83 session.end()
84 session.destroy()
The primary numeric class for representing amounts and values.
Definition: gnc-numeric.hpp:60