GnuCash  2.6.99
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
quotes_historic.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 # quotes_historic.py -- Example Script to read historic quote data into gnucash
4 #
5 
6 ## @file
7 # @brief Example Script to read historic stock data into gnucash
8 # @author Peter Holtermann
9 # @date January 2011
10 # @ingroup python_bindings_examples
11 #
12 # Call the perl-script @code
13 # ./get_quotes.pl INTC
14 # @endcode first to achieve data into file INTC which can thereafter be imported to GnuCash using this script.
15 #
16 # For explanation of use have a look at the wiki:
17 # http://wiki.gnucash.org/wiki/Stocks/get_prices
18 #
19 
20 from gnucash import Session, Account, Split
21 import gnucash
22 import datetime
23 from fractions import Fraction
24 from gnc_convenience import find_account
25 
26 FILE = "./test.gnucash"
27 url = "xml://"+FILE
28 
29 # Read data from file
30 f = open('INTC')
31 data = []
32 while 1:
33  tmp = f.readline()
34  if(len(tmp)<2):
35  break
36 
37  data.append(tmp)
38 
39 f.close()
40 
41 stock_date = []
42 stock_price = []
43 for i in range(1,len(data)):
44  year = int(data[i].rsplit(',')[1].rsplit('/')[0])
45  month = int(data[i].rsplit(',')[1].rsplit('/')[1])
46  day = int(data[i].rsplit(',')[1].rsplit('/')[2])
47  stock_date.append(datetime.datetime(year,month,day))
48  stock_price.append(float(data[i].rsplit(',')[5]))
49 
50 # Initialize Gnucash session
51 session = Session(url, True, False, False)
52 root = session.book.get_root_account()
53 book = session.book
54 account = book.get_root_account()
55 pdb = book.get_price_db()
56 comm_table = book.get_table()
57 ac = find_account(account,'Intel')[0]
58 
59 stock = ac.GetCommodity()
60 # Add the prices
61 pdb = book.get_price_db()
62 if len(ac.GetSplitList())<1:
63  print 'Need at least one Split to get currency info ... '
64  raise SystemExit
65 cur = ac.GetSplitList()[0].GetParent().GetCurrency()
66 
67 # Get stock data
68 pl = pdb.get_prices(stock,cur)
69 if len(pl)<1:
70  print 'Need at least one database entry to clone ...'
71  raise SystemExit
72 
73 pl0 = pl[0]
74 for i in range(1,len(pl)):
75  pdb.remove_price(pl[i])
76 
77 for i in range(0,len(stock_date)):
78  p_new = pl0.clone(book)
79  p_new = gnucash.GncPrice(instance=p_new)
80  print 'Adding',i,stock_date[i],stock_price[i]
81  p_new.set_time(stock_date[i])
82  v = p_new.get_value()
83  v.num = int(Fraction.from_float(stock_price[i]).limit_denominator(100000).numerator)
84  v.denom = int(Fraction.from_float(stock_price[i]).limit_denominator(100000).denominator)
85  p_new.set_value(v)
86  p_new.set_source("Finance::Quotes::Historic")
87  pdb.add_price(p_new)
88 
89 # Clean up
90 session.save()
91 session.end()
92 session.destroy()