예제 #1
0
파일: service.py 프로젝트: ACueva/googlecl
 def __init__(self, config):
   """Constructor."""
   FinanceService.__init__(self)
   BaseServiceCL.__init__(self, SECTION_HEADER, config)
   self.max_results = None
예제 #2
0
 def __init__(self, email, password):
     self.client = FinanceService(source='gdata-finance-test')
     self.client.ClientLogin(email, password)
예제 #3
0
    def refresh_creds(self, credentials, sleep):
        global gd_client
        time.sleep(sleep)
        credentials.refresh(httplib2.Http())

        now = datetime.utcnow()
        expires = credentials.token_expiry
        expires_seconds = (expires - now).seconds
        # print ("Expires %s from %s = %s" % (expires,now,expires_seconds) )
        if self.service == 'docs':
            gd_client = DocsService(email='default',
                                    additional_headers={
                                        'Authorization':
                                        'Bearer %s' % credentials.access_token
                                    })
        elif self.service == 'picasa':
            gd_client = PhotosService(email='default',
                                      additional_headers={
                                          'Authorization':
                                          'Bearer %s' %
                                          credentials.access_token
                                      })
        elif self.service == 'finance':
            gd_client = FinanceService(email='default',
                                       additional_headers={
                                           'Authorization':
                                           'Bearer %s' %
                                           credentials.access_token
                                       })
        elif self.service == 'calendar':
            gd_client = CalendarService(email='default',
                                        additional_headers={
                                            'Authorization':
                                            'Bearer %s' %
                                            credentials.access_token
                                        })
        elif self.service == 'contacts':
            gd_client = ContactsService(email='default',
                                        additional_headers={
                                            'Authorization':
                                            'Bearer %s' %
                                            credentials.access_token
                                        })
        elif self.service == 'youtube':
            gd_client = YouTubeService(email='default',
                                       additional_headers={
                                           'Authorization':
                                           'Bearer %s' %
                                           credentials.access_token
                                       })
        elif self.service == 'blogger':
            gd_client = BloggerService(email='default',
                                       additional_headers={
                                           'Authorization':
                                           'Bearer %s' %
                                           credentials.access_token
                                       })

        d = threading.Thread(name='refresh_creds',
                             target=self.refresh_creds,
                             args=(credentials, expires_seconds - 10))
        d.setDaemon(True)
        d.start()
        return gd_client
예제 #4
0
class FinanceTester(object):
    def __init__(self, email, password):
        self.client = FinanceService(source='gdata-finance-test')
        self.client.ClientLogin(email, password)

    def GetPortfolios(self, with_returns=False, inline_positions=False):
        query = PortfolioQuery()
        query.returns = with_returns
        query.positions = inline_positions
        return self.client.GetPortfolioFeed(query=query).entry

    def GetPositions(self,
                     portfolio,
                     with_returns=False,
                     inline_transactions=False):
        query = PositionQuery()
        query.returns = with_returns
        query.transactions = inline_transactions
        return self.client.GetPositionFeed(portfolio, query=query).entry

    def GetTransactions(self, position=None, portfolio=None, ticker=None):
        if position:
            feed = self.client.GetTransactionFeed(position)
        elif portfolio and ticker:
            feed = self.client.GetTransactionFeed(
                portfolio_id=portfolio.portfolio_id, ticker_id=ticker)
        return feed.entry

    @ShowCallDetails
    def TestShowDetails(self,
                        with_returns=False,
                        inline_positions=False,
                        inline_transactions=False):
        portfolios = self.GetPortfolios(with_returns, inline_positions)
        for pfl in portfolios:
            PrintPortfolio(pfl, with_returns)
            positions = self.GetPositions(pfl, with_returns,
                                          inline_transactions)
            for pos in positions:
                PrintPosition(pos, with_returns)
                PrintTransactions(self.GetTransactions(pos))

    def DeletePortfoliosByName(self, portfolio_titles):
        for pfl in self.GetPortfolios():
            if pfl.portfolio_title in portfolio_titles:
                self.client.DeletePortfolio(pfl)

    def AddPortfolio(self, portfolio_title, currency_code):
        pfl = PortfolioEntry(portfolio_data=PortfolioData(
            currency_code=currency_code))
        pfl.portfolio_title = portfolio_title
        return self.client.AddPortfolio(pfl)

    def UpdatePortfolio(self,
                        portfolio,
                        portfolio_title=None,
                        currency_code=None):
        if portfolio_title:
            portfolio.portfolio_title = portfolio_title
        if currency_code:
            portfolio.portfolio_data.currency_code = currency_code
        return self.client.UpdatePortfolio(portfolio)

    def DeletePortfolio(self, portfolio):
        self.client.DeletePortfolio(portfolio)

    @ShowCallDetails
    def TestManagePortfolios(self):
        pfl_one = 'Portfolio Test: Emerging Markets 12345'
        pfl_two = 'Portfolio Test: Renewable Energy 31415'

        print '---- Deleting portfolios ----'
        self.DeletePortfoliosByName([pfl_one, pfl_two])
        PrintPortfolios(self.GetPortfolios())
        print '---- Adding new portfolio ----'
        pfl = self.AddPortfolio(pfl_one, 'SGD')
        PrintPortfolios(self.GetPortfolios())
        print '---- Changing portfolio title and currency code ----'
        pfl = self.UpdatePortfolio(pfl, pfl_two, 'USD')
        PrintPortfolios(self.GetPortfolios())
        print '---- Deleting portfolio ----'
        self.DeletePortfolio(pfl)
        PrintPortfolios(self.GetPortfolios())

    def Transact(self,
                 type,
                 portfolio,
                 ticker,
                 date=None,
                 shares=None,
                 notes=None,
                 price=None,
                 commission=None,
                 currency_code=None):
        if price is not None:
            price = Price(money=[
                Money(amount=str(price),
                      currency_code=currency_code
                      or portfolio.portfolio_data.currency_code)
            ])
        if commission is not None:
            commission = Commission(money=[
                Money(amount=str(comission),
                      currency_code=currency_code
                      or portfolio.portfolio_data.currency_code)
            ])
        if date is not None and isinstance(date, datetime.datetime):
            date = date.isoformat()
        if shares is not None:
            shares = str(shares)
        txn = TransactionEntry(
            transaction_data=TransactionData(type=type,
                                             date=date,
                                             shares=shares,
                                             notes=notes,
                                             price=price,
                                             commission=commission))
        return self.client.AddTransaction(txn,
                                          portfolio_id=portfolio.portfolio_id,
                                          ticker_id=ticker)

    def Buy(self, portfolio, ticker, **kwargs):
        return self.Transact('Buy', portfolio, ticker, **kwargs)

    def Sell(self, portfolio, ticker, **kwargs):
        return self.Transact('Sell', portfolio, ticker, **kwargs)

    def GetPosition(self,
                    portfolio,
                    ticker,
                    with_returns=False,
                    inline_transactions=False):
        query = PositionQuery()
        query.returns = with_returns
        query.transactions = inline_transactions
        return self.client.GetPosition(portfolio_id=portfolio.portfolio_id,
                                       ticker_id=ticker,
                                       query=query)

    def DeletePosition(self, position):
        self.client.DeletePosition(position_entry=position)

    def UpdateTransaction(self, transaction):
        self.client.UpdateTransaction(transaction)

    def DeleteTransaction(self, transaction):
        self.client.DeleteTransaction(transaction)

    @ShowCallDetails
    def TestManageTransactions(self):
        pfl_title = 'Transaction Test: Technology 27182'
        self.DeletePortfoliosByName([pfl_title])

        print '---- Adding new portfolio ----'
        pfl = self.AddPortfolio(pfl_title, 'USD')
        PrintPortfolios(self.GetPortfolios())

        print '---- Adding buy transactions ----'
        tkr1 = 'NASDAQ:GOOG'
        date = datetime.datetime(2009, 04, 01)
        days = datetime.timedelta(1)
        txn1 = self.Buy(pfl, tkr1, shares=500, price=321.00, date=date)
        txn2 = self.Buy(pfl,
                        tkr1,
                        shares=150,
                        price=312.00,
                        date=date + 15 * days)
        pos = self.GetPosition(portfolio=pfl, ticker=tkr1, with_returns=True)
        PrintPosition(pos, with_returns=True)
        PrintTransactions(self.GetTransactions(pos))

        print '---- Adding sell transactions ----'
        txn3 = self.Sell(pfl,
                         tkr1,
                         shares=400,
                         price=322.00,
                         date=date + 30 * days)
        txn4 = self.Sell(pfl,
                         tkr1,
                         shares=200,
                         price=330.00,
                         date=date + 45 * days)
        pos = self.GetPosition(portfolio=pfl, ticker=tkr1, with_returns=True)
        PrintPosition(pos, with_returns=True)
        PrintTransactions(self.GetTransactions(pos))

        print "---- Modifying first and deleting third ----"
        txn1.transaction_data.shares = '400.0'
        self.UpdateTransaction(txn1)
        self.DeleteTransaction(txn3)
        pos = self.GetPosition(portfolio=pfl, ticker=tkr1, with_returns=True)
        PrintPosition(pos, with_returns=True)
        PrintTransactions(self.GetTransactions(pos))

        print "---- Deleting position ----"
        print "Number of positions (before):", len(self.GetPositions(pfl))
        self.DeletePosition(pos)
        print "Number of positions (after) :", len(self.GetPositions(pfl))

        print '---- Deleting portfolio ----'
        self.DeletePortfolio(pfl)
        PrintPortfolios(self.GetPortfolios())
예제 #5
0
 def __init__(self, config):
     """Constructor."""
     FinanceService.__init__(self)
     BaseServiceCL.__init__(self, SECTION_HEADER, config)
     self.max_results = None