def __init__(self, symbol, name, sector, industry):
     self.symbol = symbol
     self.name = name
     self.sector = sector
     self.industry = industry
     self.price_srvr = PriceServer(
         Alphavantage(Application.getConfigFileName()))
class MarketDataTest(unittest.TestCase):
    def setUp(self):
        self.yahoo = YahooServer('../trades.conf')
        self.alpha = Alphavantage('../alpha.conf')
        mock = ServerMock.MockAlphaServer()
        self.price_server=PriceServer(mock)
        
        self.json_regex=re.compile(r"^\{.*\}$", RegexFlag.DOTALL)
        self.url_regex=re.compile(r"https://.*/.*?", RegexFlag.DOTALL)
        
        self.client = Client(1, "Adil", "*****@*****.**")
    def test_connect_to_Yahoo_server(self):
        url=self.yahoo.getURL()
        self.assertRegex(url, self.url_regex, 'URL of server should match a REGEX')
    
    @unittest.skip("skipping yahoo json test")
    def test_get_Yahoo_data_as_json(self):
        self.assertTrue('chart' in self.yahoo.getDataAsJSON(), 'Data from server looks like a json object')
    
    @unittest.skip("skipping yahoo text test")
    def test_get_Yahoo_data_as_text(self):
        self.assertRegex(self.yahoo.getDataAsText(), self.json_regex, 'Text from server looks like a json object')
        
    def test_connect_to_Alphavantage_server(self):
        url = self.alpha.getURL()
        self.assertRegex(url, 'https://.*/.*?', 'URL of server should match a REGEX')
        
    @unittest.skip("skipping alpha json test")
    def test_get_Alphavantage_data_as_json(self):
        self.assertTrue('Meta Data' in self.alpha.getDataAsJSON(), 'Data from server looks like a json object')
    
    @unittest.skip("skipping alpha text test")
    def test_get_Alphavantage_data_as_text(self):
        self.assertRegex(self.alpha.getDataAsText(), self.json_regex, 'Text from server looks like a json object')
        
    #@unittest.skip("skipping today's price  test")
    @unittest.expectedFailure(PriceUnavailableEx)
    def test_tody_price_by_symbol(self):
        self.assertEqual(self.price_server.getTodaySecurityPriceBySymbol("MSFT"), '83.8700', 'todays price')   
    
    #@unittest.skip("skipping last recorded price  test")
    #@unittest.expectedFailure
    def test_last_recorded_price_by_symbol(self):
        self.assertEqual(self.price_server.getLastRecordedPriceBySymbol("MSFT"), '83.8700', 'todays price')     
    
    #@unittest.skip("skipping creating a client test")
    #@unittest.expectedFailure
    def test_create_client(self):
        client = Client(1, "Adil", "*****@*****.**")
        self.assertEqual("Adil", client.getName(), "Clent created successfully")
    
    #@unittest.skip("skipping adding a position")
    #@unittest.expectedFailure
    def test_add_position(self):
        self.client.addPosition(Position("GOOG", 100, datetime.datetime.now()))
        self.assertEqual(100, self.client.getPosition("GOOG").getQuantity())
        self.client.addPosition(Position("GOOG", 100, datetime.datetime.now()))
        self.assertEqual(200, self.client.getPosition("GOOG").getQuantity())
 def setUp(self):
     self.yahoo = YahooServer('../trades.conf')
     self.alpha = Alphavantage('../alpha.conf')
     mock = ServerMock.MockAlphaServer()
     self.price_server=PriceServer(mock)
     
     self.json_regex=re.compile(r"^\{.*\}$", RegexFlag.DOTALL)
     self.url_regex=re.compile(r"https://.*/.*?", RegexFlag.DOTALL)
     
     self.client = Client(1, "Adil", "*****@*****.**")
    def setUp(self):
        """Sets URL to connect to the Yahoo and Alphavanatage servers. """
        self.yahoo = YahooServer('../trades.conf')
        self.alpha = Alphavantage('../alpha.conf')
        mock = ServerMock.MockAlphaServer()
        self.price_server = PriceServer(mock)

        self.json_regex = re.compile(
            r"^\{.*\}$",
            re.DOTALL)  #match everything from the start to the end
        self.url_regex = re.compile(
            r"https://.*/.*?", re.DOTALL)  #match everything including the //

        self.client = Client(1, "Adil",
                             "*****@*****.**")  #example client
Exemple #5
0
    def __init__(self,  config_file_name, stocks_file_name):
        '''
        Uses the (tab delimited) stocks file to retrieve securities details
        '''
        
        self.price_srvr = PriceServer(Alphavantage(config_file_name))        
  
        self.securities = {}

        with open(stocks_file_name, "r") as securities_file :
            #First read the line containing the header
            securities_file.readline()
            for line in securities_file :
                line = line.rstrip()
                symbol, name, sector, industry = line.split("\t")
                sec = Security(symbol, name, sector, industry)
                self.securities[symbol] = sec
    def __init__(self, config_file_name, transactions_file_name):
        """Constructor for TradingApplication takes arguments for configuration and transaction setup.
        
        alpha.conf is set in the PriceServer, and files that are read from the file
        are stored in a dictionary called transactions.
        
        Arguments
        ---------
        config_file_name: takes name of configuration filename alpha.conf
        transaction_file_name: takes name of transaction filename transactions.txt
        
        """
        self.price_srvr = PriceServer(Alphavantage(config_file_name))
        self.transactions_file_name = transactions_file_name
        self.broker = OrderBroker.getInstance()

        self.transactions = {}  #create a dictionary named transactions

        with open(self.transactions_file_name, "r") as transactions_file:
            for line in transactions_file:
                line = line.rstrip()  #remove any trailing spaces

                (trans_date, clt_id, tran_type, symbol, price,
                 qty) = line.split("|")
                transaction = Transaction()
                transaction.clientID = int(clt_id)
                transaction.date = datetime.datetime.strptime(
                    trans_date, Transaction.DATE_FORMAT)
                transaction.trans_type = TransType(int(tran_type))
                transaction.symbol = symbol
                transaction.price = float(price)
                transaction.quantity = int(qty)

                self.transactions[
                    transaction.
                    date] = transaction  #insert each transaction object as value for key transaction.date
Exemple #7
0
class SecurityManager(Application):
    '''
    classdocs
    '''
    instance = None    
    symbol , name, sector, industry = (Security.getSymbol(),Security.getName(),Security.getSector(), Security.getIndustry()) 

    @staticmethod
    def getInstance():
        if not SecurityManager.instance :
            config_file_name = Application.getConfigFileName()
            stocks_file_name = Application.getCompaniesFileName()
            SecurityManager.instance = SecurityManager(config_file_name, stocks_file_name)
        return SecurityManager.instance

    def __init__(self,  config_file_name, stocks_file_name):
        '''
        Uses the (tab delimited) stocks file to retrieve securities details
        '''
        
        self.price_srvr = PriceServer(Alphavantage(config_file_name))        
  
        self.securities = {}

        with open(stocks_file_name, "r") as securities_file :
            #First read the line containing the header
            securities_file.readline()
            for line in securities_file :
                line = line.rstrip()
                symbol, name, sector, industry = line.split("\t")
                sec = Security(symbol, name, sector, industry)
                self.securities[symbol] = sec
       
                
               
    
    def retrieveSecSymbol(self, companyName):
        #
        # A function retrieves a client the clients' dictionary based on client_id
        # raises an exception if client_id deos not exist
        #
        if companyName in self.securities :
            return self.securities[str(companyName)]
        else :
            raise SecurityException("company does not exist")
        
        
     
    def getCurrentMarketValue(self,symbol): 
        # A function return current market value
        
        current_value = self.price_srvr.getLastRecordedPriceBySymbol(symbol.upper())  
        return current_value
       

    def checkSecurityBySymbol(self, symbol):
        """Returns true f symbol exists"""
        
        return True if symbol in self.securities else False
    
    
    def checkSymbolBySecurity(self, companyName):
        """Returns true f symbol exists"""
        
        return True if companyName in self.securities else False
    
    def getSecurityInfoBySymbol(self, symbol):
        """Returns a dictionary of security details containing "SYMBOL", "NAME", "SECTOR" and "INDUSTRY" """
        
        return self.securities[symbol] if symbol in self.securities else None
    
    
    def listSecurities(self):
        for secList in self.securities.values() :
            print(str(secList))
class MarketDataTest(unittest.TestCase):
    """Made up of testcase function for market data test."""
    def setUp(self):
        """Sets URL to connect to the Yahoo and Alphavanatage servers. """
        self.yahoo = YahooServer('../trades.conf')
        self.alpha = Alphavantage('../alpha.conf')
        mock = ServerMock.MockAlphaServer()
        self.price_server = PriceServer(mock)

        self.json_regex = re.compile(
            r"^\{.*\}$",
            re.DOTALL)  #match everything from the start to the end
        self.url_regex = re.compile(
            r"https://.*/.*?", re.DOTALL)  #match everything including the //

        self.client = Client(1, "Adil",
                             "*****@*****.**")  #example client

    def test_connect_to_Yahoo_server(self):
        """Get Yahoo server Url and check against REGEX for a match.
        
        if there is no match this test is failed
        """
        url = self.yahoo.getURL()
        self.assertRegex(url, self.url_regex,
                         'URL of server should match a REGEX')

    def test_connect_to_Alphavantage_server(self):
        """Get Yahoo server Url and check against REGEX for a match.
        
        if there is no match this test is failed
        """
        url = self.alpha.getURL()
        self.assertRegex(url, 'https://.*/.*?',
                         'URL of server should match a REGEX')

    #@unittest.skip("skipping yahoo json test")
    def test_get_Yahoo_data_as_json(self):
        self.assertTrue('chart' in self.yahoo.getDataAsJSON(),
                        'Data from server looks like a json object')

    #@unittest.skip("skipping yahoo text test")
    def test_get_Yahoo_data_as_text(self):
        self.assertRegex(self.yahoo.getDataAsText(), self.json_regex,
                         'Text from server looks like a json object')

    #@unittest.skip("skipping alpha json test")
    def test_get_Alphavantage_data_as_json(self):
        self.assertTrue('Meta Data' in self.alpha.getDataAsJSON(),
                        'Data from server looks like a json object')

    #@unittest.skip("skipping alpha text test")
    def test_get_Alphavantage_data_as_text(self):
        self.assertRegex(self.alpha.getDataAsText(), self.json_regex,
                         'Text from server looks like a json object')

    #@unittest.skip("skipping today's price  test")
    @unittest.expectedFailure(PriceUnavailableEx)
    def test_tody_price_by_symbol(self):
        """Checks todays price against '83.8700' for equality
        
        EXception:
            @raise PriceUnvailable exception
        """
        self.assertEqual(
            self.price_server.getTodaySecurityPriceBySymbol("MSFT"), '83.8700',
            'todays price')

    #@unittest.skip("skipping last recorded price  test")
    #@unittest.expectedFailure
    def test_last_recorded_price_by_symbol(self):
        """Checks todays price against '83.8700' for equality. 
        
        Note
        ----
        AN expected failure is possible if no price is recorder for symbol
        """
        self.assertEqual(
            self.price_server.getLastRecordedPriceBySymbol("MSFT"), '83.8700',
            'todays price')

    #@unittest.skip("skipping creating a client test")
    #@unittest.expectedFailure
    def test_create_client(self):
        """Test create client and print success message"""
        client = Client(1, "Adil", "*****@*****.**")
        self.assertEqual("Adil", client.get_name(),
                         "Clent created successfully")

    #@unittest.skip("skipping adding a position")
    #@unittest.expectedFailure
    def test_add_position(self):
        """Add position to symbol for client and check if quantity matches."""

        self.client.addPosition(Position("GOOG", 100, datetime.datetime.now()))
        self.assertEqual(100, self.client.getPosition("GOOG").getQuantity())
        self.client.addPosition(Position("GOOG", 100, datetime.datetime.now()))
        self.assertEqual(200, self.client.getPosition("GOOG").getQuantity())
class Security:
    """The security class stores data for each security read from the companyList file.
    
    it stores data for symbol,name,sector and industry. Other classes query the security class
    to get more information on the security symbol inputed.
    """
    def __init__(self, symbol, name, sector, industry):
        self.symbol = symbol
        self.name = name
        self.sector = sector
        self.industry = industry
        self.price_srvr = PriceServer(
            Alphavantage(Application.getConfigFileName()))

    def getCurrentMarketValue(self):
        """A function querying a security's price from Price Server.
        
        Return
        ------
        price of symbol 
        
        Note:
        A Data_Unavailable_Ex may be thrown
        """
        price = self.price_srvr.getLastRecordedPriceBySymbol(self.symbol)
        return price

    def getAveragePriceForADay(self):
        """returns average price for security symbol in a day"""
        averagePrice = self.price_srvr.getTodaysAveragePriceBySymbol(
            self.symbol)
        return averagePrice

    def getTotalVolumeForADay(self):
        """returns average volume for security symbol in a day"""
        totalVolume = self.price_srvr.getTodaysVolumeBySymbol(self.symbol)
        return totalVolume

    def getName(self):
        """returns name of company for security symbol"""
        return self.name

    def getSector(self):
        """returns sector for security symbol"""
        return self.sector

    def getIndustry(self):
        """returns industry for security symbol"""
        return self.industry

    def getSymbol(self):
        """returns security symbol"""
        return self.symbol

    def setSymbol(self, symbol):
        self.symbol = symbol

    def setName(self, name):
        """set name for security symbol"""
        self.name = name

    def setSector(self, sector):
        """set sector for security symbol"""
        self.sector = sector

    def setIndustry(self, industry):
        """set industry for security symbol"""
        self.industry = industry

    def __str__(self):
        # the format in which security  is printed in.
        return "%s %10s %s %21s %s %16s %s %52s" % (
            '\nSymbol:', self.symbol, '\nName:', self.name, '\nSector:',
            self.sector, '\nIndustry:', self.industry)