PageRenderTime 40ms CodeModel.GetById 13ms app.highlight 22ms RepoModel.GetById 1ms app.codeStats 1ms

/gdata/finance/service.py

http://radioappz.googlecode.com/
Python | 243 lines | 219 code | 8 blank | 16 comment | 0 complexity | 7e29d74c6eec402be194ab0b0fc5a99a MD5 | raw file
  1#!/usr/bin/python
  2#
  3# Copyright (C) 2009 Tan Swee Heng
  4#
  5# Licensed under the Apache License, Version 2.0 (the "License");
  6# you may not use this file except in compliance with the License.
  7# You may obtain a copy of the License at
  8#
  9#      http://www.apache.org/licenses/LICENSE-2.0
 10#
 11# Unless required by applicable law or agreed to in writing, software
 12# distributed under the License is distributed on an "AS IS" BASIS,
 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 14# See the License for the specific language governing permissions and
 15# limitations under the License.
 16
 17
 18"""Classes to interact with the Google Finance server."""
 19
 20
 21__author__ = 'thesweeheng@gmail.com'
 22
 23
 24import gdata.service
 25import gdata.finance
 26import atom
 27
 28
 29class PortfolioQuery(gdata.service.Query):
 30  """A query object for the list of a user's portfolios."""
 31
 32  def returns(self):
 33    return self.get('returns', False)
 34
 35  def set_returns(self, value):
 36    if value is 'true' or value is True:
 37      self['returns'] = 'true'
 38
 39  returns = property(returns, set_returns, doc="The returns query parameter")
 40
 41  def positions(self):
 42    return self.get('positions', False)
 43
 44  def set_positions(self, value):
 45    if value is 'true' or value is True:
 46      self['positions'] = 'true'
 47
 48  positions = property(positions, set_positions,
 49      doc="The positions query parameter")
 50
 51
 52class PositionQuery(gdata.service.Query):
 53  """A query object for the list of a user's positions in a portfolio."""
 54
 55  def returns(self):
 56    return self.get('returns', False)
 57
 58  def set_returns(self, value):
 59    if value is 'true' or value is True:
 60      self['returns'] = 'true'
 61
 62  returns = property(returns, set_returns,
 63      doc="The returns query parameter")
 64
 65  def transactions(self):
 66    return self.get('transactions', False)
 67
 68  def set_transactions(self, value):
 69    if value is 'true' or value is True:
 70      self['transactions'] = 'true'
 71
 72  transactions = property(transactions, set_transactions,
 73      doc="The transactions query parameter")
 74
 75
 76class FinanceService(gdata.service.GDataService):
 77
 78  def __init__(self, email=None, password=None, source=None,
 79               server='finance.google.com', **kwargs):
 80    """Creates a client for the Finance service.
 81
 82    Args:
 83      email: string (optional) The user's email address, used for
 84          authentication.
 85      password: string (optional) The user's password.
 86      source: string (optional) The name of the user's application.
 87      server: string (optional) The name of the server to which a connection
 88          will be opened. Default value: 'finance.google.com'.
 89      **kwargs: The other parameters to pass to gdata.service.GDataService
 90          constructor.
 91    """
 92    gdata.service.GDataService.__init__(self,
 93        email=email, password=password, service='finance', server=server,
 94        **kwargs)
 95
 96  def GetPortfolioFeed(self, query=None):
 97    uri = '/finance/feeds/default/portfolios'
 98    if query:
 99      uri = PortfolioQuery(feed=uri, params=query).ToUri()
100    return self.Get(uri, converter=gdata.finance.PortfolioFeedFromString)
101
102  def GetPositionFeed(self, portfolio_entry=None, portfolio_id=None,
103      query=None):
104    """
105    Args:
106      portfolio_entry: PortfolioEntry (optional; see Notes)
107      portfolio_id: string (optional; see Notes) This may be obtained
108          from a PortfolioEntry's portfolio_id attribute.
109      query: PortfolioQuery (optional)
110
111    Notes:
112      Either a PortfolioEntry OR a portfolio ID must be provided.
113    """
114    if portfolio_entry:
115      uri = portfolio_entry.GetSelfLink().href + '/positions'
116    elif portfolio_id:
117      uri = '/finance/feeds/default/portfolios/%s/positions' % portfolio_id
118    if query:
119      uri = PositionQuery(feed=uri, params=query).ToUri()
120    return self.Get(uri, converter=gdata.finance.PositionFeedFromString)
121
122  def GetTransactionFeed(self, position_entry=None,
123      portfolio_id=None, ticker_id=None):
124    """
125    Args:
126      position_entry: PositionEntry (optional; see Notes)
127      portfolio_id: string (optional; see Notes) This may be obtained
128          from a PortfolioEntry's portfolio_id attribute.
129      ticker_id: string (optional; see Notes) This may be obtained from
130          a PositionEntry's ticker_id attribute. Alternatively it can
131          be constructed using the security's exchange and symbol,
132          e.g. 'NASDAQ:GOOG'
133
134    Notes:
135      Either a PositionEntry OR (a portfolio ID AND ticker ID) must
136      be provided.
137    """
138    if position_entry:
139      uri = position_entry.GetSelfLink().href + '/transactions'
140    elif portfolio_id and ticker_id:
141      uri = '/finance/feeds/default/portfolios/%s/positions/%s/transactions' \
142          % (portfolio_id, ticker_id)
143    return self.Get(uri, converter=gdata.finance.TransactionFeedFromString)
144
145  def GetPortfolio(self, portfolio_id=None, query=None):
146    uri = '/finance/feeds/default/portfolios/%s' % portfolio_id
147    if query:
148      uri = PortfolioQuery(feed=uri, params=query).ToUri()
149    return self.Get(uri, converter=gdata.finance.PortfolioEntryFromString)
150
151  def AddPortfolio(self, portfolio_entry=None):
152    uri = '/finance/feeds/default/portfolios'
153    return self.Post(portfolio_entry, uri,
154        converter=gdata.finance.PortfolioEntryFromString)
155
156  def UpdatePortfolio(self, portfolio_entry=None):
157    uri = portfolio_entry.GetEditLink().href
158    return self.Put(portfolio_entry, uri,
159        converter=gdata.finance.PortfolioEntryFromString)
160
161  def DeletePortfolio(self, portfolio_entry=None):
162    uri = portfolio_entry.GetEditLink().href
163    return self.Delete(uri)
164
165  def GetPosition(self, portfolio_id=None, ticker_id=None, query=None):
166    uri = '/finance/feeds/default/portfolios/%s/positions/%s' \
167        % (portfolio_id, ticker_id)
168    if query:
169      uri = PositionQuery(feed=uri, params=query).ToUri()
170    return self.Get(uri, converter=gdata.finance.PositionEntryFromString)
171
172  def DeletePosition(self, position_entry=None,
173      portfolio_id=None, ticker_id=None, transaction_feed=None):
174    """A position is deleted by deleting all its transactions.
175
176    Args:
177      position_entry: PositionEntry (optional; see Notes)
178      portfolio_id: string (optional; see Notes) This may be obtained
179          from a PortfolioEntry's portfolio_id attribute.
180      ticker_id: string (optional; see Notes) This may be obtained from
181          a PositionEntry's ticker_id attribute. Alternatively it can
182          be constructed using the security's exchange and symbol,
183          e.g. 'NASDAQ:GOOG'
184      transaction_feed: TransactionFeed (optional; see Notes)
185
186    Notes:
187      Either a PositionEntry OR (a portfolio ID AND ticker ID) OR
188      a TransactionFeed must be provided.
189    """
190    if transaction_feed:
191      feed = transaction_feed
192    else:
193      if position_entry:
194        feed = self.GetTransactionFeed(position_entry=position_entry)
195      elif portfolio_id and ticker_id:
196        feed = self.GetTransactionFeed(
197            portfolio_id=portfolio_id, ticker_id=ticker_id)
198    for txn in feed.entry:
199      self.DeleteTransaction(txn)
200    return True
201
202  def GetTransaction(self, portfolio_id=None, ticker_id=None,
203      transaction_id=None):
204    uri = '/finance/feeds/default/portfolios/%s/positions/%s/transactions/%s' \
205        % (portfolio_id, ticker_id, transaction_id)
206    return self.Get(uri, converter=gdata.finance.TransactionEntryFromString)
207
208  def AddTransaction(self, transaction_entry=None, transaction_feed = None,
209      position_entry=None, portfolio_id=None, ticker_id=None):
210    """
211    Args:
212      transaction_entry: TransactionEntry (required)
213      transaction_feed: TransactionFeed (optional; see Notes)
214      position_entry: PositionEntry (optional; see Notes)
215      portfolio_id: string (optional; see Notes) This may be obtained
216          from a PortfolioEntry's portfolio_id attribute.
217      ticker_id: string (optional; see Notes) This may be obtained from
218          a PositionEntry's ticker_id attribute. Alternatively it can
219          be constructed using the security's exchange and symbol,
220          e.g. 'NASDAQ:GOOG'
221
222    Notes:
223      Either a TransactionFeed OR a PositionEntry OR (a portfolio ID AND
224      ticker ID) must be provided.
225    """
226    if transaction_feed:
227      uri = transaction_feed.GetPostLink().href
228    elif position_entry:
229      uri = position_entry.GetSelfLink().href + '/transactions'
230    elif portfolio_id and ticker_id:
231      uri = '/finance/feeds/default/portfolios/%s/positions/%s/transactions' \
232          % (portfolio_id, ticker_id)
233    return self.Post(transaction_entry, uri,
234        converter=gdata.finance.TransactionEntryFromString)
235
236  def UpdateTransaction(self, transaction_entry=None):
237    uri = transaction_entry.GetEditLink().href
238    return self.Put(transaction_entry, uri,
239        converter=gdata.finance.TransactionEntryFromString)
240
241  def DeleteTransaction(self, transaction_entry=None):
242    uri = transaction_entry.GetEditLink().href
243    return self.Delete(uri)