예제 #1
0
 def StockScreener_click(self):
     tickers_dict_eps = dict()
     tickers_dict_debt = dict()
     marketcap_high = self.textTicker2.get()
     marketcap_low = self.textTicker3.get()
     beta_high = self.textTicker4.get()
     beta_low = self.textTicker5.get()
     dividend_high = self.textTicker6.get()
     dividend_low = self.textTicker7.get()
     sector = self.textTicker8.get()
     industry = self.textTicker9.get()
     exchange = self.textTicker10.get()
     entered_years = self.buttonYears_var.get()
     print(
         '\n---- CLICK EVENT StockScreener_click ---- Selected criteria are are: '
         + marketcap_high + ' ' + marketcap_low + ' ' + beta_high + ' ' +
         beta_low + ' ' + dividend_high + ' ' + dividend_low + ' ' +
         sector + ' ' + industry + ' ' + exchange)
     Quote = Analyses('stockscreener',
                      period=entered_years,
                      api_key=self.apikey,
                      statistic=' ')
     criteria_list = [
         marketcap_high, marketcap_low, beta_high, beta_low, dividend_high,
         dividend_low, sector, industry, exchange
     ]
     Quote.Stock_screener(criteria_list)
예제 #2
0
 def YieldSearch_click(self):
     marketcap_high = self.textTicker2.get()
     marketcap_low = self.textTicker3.get()
     beta_high = self.textTicker4.get()
     beta_low = self.textTicker5.get()
     dividend_high = self.textTicker6.get()
     dividend_low = self.textTicker7.get()
     sector = self.textTicker8.get()
     industry = self.textTicker9.get()
     exchange = self.textTicker10.get()
     targetYield = self.textYield.get()
     entered_years = self.buttonYears_var.get()
     print(
         '\n---- CLICK EVENT Yeld finder click ---- Selected criteria are are: '
         + marketcap_high + ' ' + marketcap_low + ' ' + beta_high + ' ' +
         beta_low + ' ' + dividend_high + ' ' + dividend_low + ' ' +
         sector + ' ' + industry + ' ' + exchange)
     Quote = Analyses('stockscreener',
                      period=entered_years,
                      api_key=self.apikey,
                      statistic=' ')
     criteria_list = [
         marketcap_high, marketcap_low, beta_high, beta_low, dividend_high,
         dividend_low, sector, industry, exchange
     ]
     Quote.Stock_screener(criteria_list, 1,
                          targetYield)  #YIELD function is enabled
예제 #3
0
 def Ticker_list_click(self):  #TO DO
     print(
         '\n---- CLICK EVENT Ticker_list_click : Ticker list will be listed /saved_data/Ticker_list.csv  ---- '
     )
     entered_years = self.buttonYears_var.get()
     Quote = Analyses('list',
                      period=entered_years,
                      api_key=self.apikey,
                      statistic=' ')
     Quote.Ticker_list()  #Get the ticker list
예제 #4
0
파일: instance.py 프로젝트: jeremygw/silky
    def __init__(self, session_path, instance_id=None):

        self._coms = None
        self._dataset = None
        self._filepath = None
        self._analyses = Analyses()
        self._em = EngineManager()

        self._session_path = session_path

        self._em.add_results_listener(self._on_results)

        settings = Settings.retrieve()
        settings.sync()

        if instance_id is not None:
            self._instance_id = instance_id
        else:
            self._instance_id = str(uuid.uuid4())
            print("created " + self._instance_id)

        self._instance_path = os.path.join(self._session_path, self._instance_id)
        os.makedirs(self._instance_path, exist_ok=True)
        self._buffer_path = os.path.join(self._instance_path, 'buffer')

        self._em.start(self._session_path)

        Instance.instances[self._instance_id] = self
예제 #5
0
 def ANALYZE_click(self):
     tickers_dict_eps = dict()
     tickers_dict_debt = dict()
     entered_tickers = self.textTicker.get()
     entered_years = self.buttonYears_var.get()
     print('\n---- CLICK EVENT ANALYZE ---- Selected ticker is/are: ' +
           entered_tickers)
     ticker_list = entered_tickers.split(',')
     for ticker in ticker_list:
         print('---- Collecting data for ' + str(ticker))
         a = Analyses(ticker=entered_tickers,
                      period=entered_years,
                      api_key=self.apikey,
                      statistic='')
         #a.title_data = ['Earning Per Share','netIncomeRatio']
         (date, eps,
          netIncomeRatio) = a.Get_document_for(ticker,
                                               'epsdiluted',
                                               'netIncomeRatio',
                                               document='income_statement')
         (date_2, bookValuePerShare,
          roe) = a.Get_document_for(ticker,
                                    'bookValuePerShare',
                                    'roe',
                                    document='metrics')
         (date_2, dividendYield,
          roe) = a.Get_document_for(ticker,
                                    'dividendYield',
                                    'roe',
                                    document='metrics')
         tickers_dict_eps[ticker] = {
             'x': date,
             'y1': eps,
             'y2': dividendYield
         }
         tickers_dict_debt[ticker] = {
             'x': date_2,
             'y1': bookValuePerShare,
             'y2': roe
         }
     a.title_data = [
         'Earning Per Share Diluted =\n (NetIncome - PreferredDividends)/SharesOutstanding',
         'dividendYield %',
         'bookValuePerShare =\n (TotalEquity-PreferredEquity)/SharesOutstanding',
         'ROE =\n NetIncome/SharholdersEquity'
     ]
     print(
         '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'
     )
     click_data = ['EPS', 'netIncomeRatio', 'BVPS', 'ROE']
     plot = a.Multiple_plots(ticker_list, tickers_dict_eps,
                             tickers_dict_debt, 'Analyze')
예제 #6
0
 def CashFlow_click(self):
     tickers_dict_eps = dict()
     tickers_dict_debt = dict()
     entered_tickers = self.textTicker.get()
     entered_years = self.buttonYears_var.get()
     print('\n---- CLICK EVENT CashFlow ---- Selected ticker is/are: ' +
           entered_tickers)
     ticker_list = entered_tickers.split(',')
     print('-- You selected ' + str(len(ticker_list)) + ' tickers \n')
     for ticker in ticker_list:
         print('---- Collecting data for ' + str(ticker))
         CashFlow = Analyses(ticker=entered_tickers,
                             period=entered_years,
                             api_key=self.apikey,
                             statistic=' ')
         (date, netCashProvidedByOperating,
          netCashUsedForInvesting) = CashFlow.Get_document_for(
              ticker,
              'netCashProvidedByOperatingActivities',
              'netCashUsedForInvestingActivites',
              document='cash_flow')
         (date_2, netCashUsedProvidedByFinancing,
          netChangeInCash) = CashFlow.Get_document_for(
              ticker,
              'netCashUsedProvidedByFinancingActivities',
              'netChangeInCash',
              document='cash_flow')
         tickers_dict_eps[ticker] = {
             'x': date,
             'y1': netCashProvidedByOperating,
             'y2': netCashUsedForInvesting
         }
         tickers_dict_debt[ticker] = {
             'x': date_2,
             'y1': netCashUsedProvidedByFinancing,
             'y2': netChangeInCash
         }
         #print(tickers_dict_eps
     CashFlow.title_data = [
         'netCashProvidedByOperatingActivities',
         'netCashUsedProvidedByForInvestingActivities',
         'netCashUsedProvidedByFinancingActivities', 'netChangeInCash'
     ]
     plot = CashFlow.Multiple_plots(ticker_list, tickers_dict_eps,
                                    tickers_dict_debt, 'CashFlow')
예제 #7
0
 def Profitability_click(self):
     tickers_dict_eps = dict()
     tickers_dict_debt = dict()
     entered_tickers = self.textTicker.get()
     entered_years = self.buttonYears_var.get()
     print(
         '\n---- CLICK EVENT Profitability ---- Selected ticker is/are: ' +
         entered_tickers)
     ticker_list = entered_tickers.split(',')
     #print('-- You selected '+str(len(ticker_list))+' tickers \n')
     for ticker in ticker_list:
         print('---- Collecting data for ' + str(ticker))
         IncomeStatement = Analyses(ticker=entered_tickers,
                                    period=entered_years,
                                    api_key=self.apikey,
                                    statistic='%')
         (date, grossProfitRatio,
          operatingIncome) = IncomeStatement.Get_document_for(
              ticker,
              'grossProfitRatio',
              'operatingIncomeRatio',
              document='income_statement')
         (date_2, returnOnTangibleAssets,
          roic) = IncomeStatement.Get_document_for(ticker,
                                                   'returnOnTangibleAssets',
                                                   'roic',
                                                   document='metrics')
         tickers_dict_eps[ticker] = {
             'x': date,
             'y1': grossProfitRatio,
             'y2': operatingIncome
         }
         tickers_dict_debt[ticker] = {
             'x': date_2,
             'y1': returnOnTangibleAssets,
             'y2': roic
         }
     IncomeStatement.title_data = [
         'grossProfitRatio', 'operatingIncomeRatio',
         'returnOnTangibleAssets', 'roic '
     ]
     plot = IncomeStatement.Multiple_plots(ticker_list, tickers_dict_eps,
                                           tickers_dict_debt,
                                           'Profitability')
예제 #8
0
 def DebtFigures_click(self):
     tickers_dict_eps = dict()
     tickers_dict_debt = dict()
     entered_tickers = self.textTicker.get()
     entered_years = self.buttonYears_var.get()
     print('\n---- CLICK EVENT DebtFigures ---- Selected ticker is/are: ' +
           entered_tickers)
     ticker_list = entered_tickers.split(',')
     #print('-- You selected '+str(len(ticker_list))+' tickers \n')
     for ticker in ticker_list:
         print('---- Collecting data for ' + str(ticker))
         DebtFigures = Analyses(ticker=entered_tickers,
                                period=entered_years,
                                api_key=self.apikey,
                                statistic='  ')
         (date, Current_ratio,
          Debt_to_Assets) = DebtFigures.Get_document_for(ticker,
                                                         'currentRatio',
                                                         'debtToAssets',
                                                         document='metrics')
         (date_2, bookValuePerShare,
          debtToEquity) = DebtFigures.Get_document_for(ticker,
                                                       'netDebtToEBITDA',
                                                       'debtToEquity',
                                                       document='metrics')
         tickers_dict_eps[ticker] = {
             'x': date,
             'y1': Current_ratio,
             'y2': Debt_to_Assets
         }
         tickers_dict_debt[ticker] = {
             'x': date_2,
             'y1': bookValuePerShare,
             'y2': debtToEquity
         }
     DebtFigures.title_data = [
         'CurrentRatio =\n CurrentAssets/CurrentLiabilities',
         'DebtToAssets =\n STDebts+LTDebts/TotalAssets',
         'netDebtToEBITDA =\n TotalDebt - Cash&Equivalents / EBITDA',
         'debtToEquity =\n TotalLiabilities/ShareholdersEquity'
     ]
     plot = DebtFigures.Multiple_plots(ticker_list, tickers_dict_eps,
                                       tickers_dict_debt, 'DebtFigures')
예제 #9
0
 def BalanceSheet_click(self):
     tickers_dict_eps = dict()
     tickers_dict_debt = dict()
     entered_tickers = self.textTicker.get()
     entered_years = self.buttonYears_var.get()
     print('\n---- CLICK EVENT BalanceSheet ---- Selected ticker is/are: ' +
           entered_tickers)
     ticker_list = entered_tickers.split(',')
     print('-- You selected ' + str(len(ticker_list)) + ' tickers \n')
     for ticker in ticker_list:
         print('---- Collecting data for ' + str(ticker))
         BalanceSheet = Analyses(ticker=entered_tickers,
                                 period=entered_years,
                                 api_key=self.apikey,
                                 statistic='log')
         (date, totalCurrentLiabilities,
          totalCurrentAssets) = BalanceSheet.Get_document_for(
              ticker, 'totalCurrentLiabilities', 'totalCurrentAssets',
              'balance_sheet')
         (date_2, shortTermDebt,
          longTermDebt) = BalanceSheet.Get_document_for(
              ticker,
              'shortTermDebt',
              'longTermDebt',
              document='balance_sheet')
         tickers_dict_eps[ticker] = {
             'x': date,
             'y1': totalCurrentLiabilities,
             'y2': totalCurrentAssets
         }
         tickers_dict_debt[ticker] = {
             'x': date_2,
             'y1': shortTermDebt,
             'y2': longTermDebt
         }
         #print(tickers_dict_eps
     BalanceSheet.title_data = [
         'totalCurrentLiabilities', 'totalCurrentAssets', 'shortTermDebt',
         'longTermDebt'
     ]
     plot = BalanceSheet.Multiple_plots(ticker_list, tickers_dict_eps,
                                        tickers_dict_debt, 'BalanceSheet')
예제 #10
0
 def Growth_click(self):
     tickers_dict_eps = dict()
     tickers_dict_debt = dict()
     entered_tickers = self.textTicker.get()
     entered_years = self.buttonYears_var.get()
     print('\n---- CLICK EVENT Growth_click ---- Selected ticker is/are: ' +
           entered_tickers)
     ticker_list = entered_tickers.split(',')
     print('-- You selected ' + str(len(ticker_list)) + ' tickers \n')
     for ticker in ticker_list:
         print('---- Collecting data for ' + str(ticker))
         Growth = Analyses(ticker=entered_tickers,
                           period=entered_years,
                           api_key=self.apikey,
                           statistic='%')
         (date, revenueGrowth,
          operatingIncomeGrowth) = Growth.Get_document_for(
              ticker, 'revenueGrowth', 'operatingIncomeGrowth',
              'financial-growth')
         (date_2, netIncomeGrowth,
          epsdilutedGrowth) = Growth.Get_document_for(
              ticker,
              'netIncomeGrowth',
              'epsdilutedGrowth',
              document='financial-growth')
         tickers_dict_eps[ticker] = {
             'x': date,
             'y1': revenueGrowth,
             'y2': operatingIncomeGrowth
         }
         tickers_dict_debt[ticker] = {
             'x': date_2,
             'y1': netIncomeGrowth,
             'y2': epsdilutedGrowth
         }
         #print(tickers_dict_eps
     Growth.title_data = [
         'revenueGrowth', 'operatingIncomeGrowth', 'netIncomeGrowth',
         'epsdilutedGrowth'
     ]
     plot = Growth.Multiple_plots(ticker_list, tickers_dict_eps,
                                  tickers_dict_debt, 'Growth')
예제 #11
0
 def IncomeStatement_click(self):
     tickers_dict_eps = dict()
     tickers_dict_debt = dict()
     entered_tickers = self.textTicker.get()
     entered_years = self.buttonYears_var.get()
     print(
         '\n---- CLICK EVENT IncomeStatement ---- Selected ticker is/are: '
         + entered_tickers)
     ticker_list = entered_tickers.split(',')
     print('-- You selected ' + str(len(ticker_list)) + ' tickers \n')
     for ticker in ticker_list:
         print('---- Collecting data for ' + str(ticker))
         IncomeStatement = Analyses(ticker=entered_tickers,
                                    period=entered_years,
                                    api_key=self.apikey,
                                    statistic='log')
         (date, Revenue, NetIncome) = IncomeStatement.Get_document_for(
             ticker, 'revenue', 'netIncome', document='income_statement')
         (date_2, operatingIncome,
          ebitda) = IncomeStatement.Get_document_for(
              ticker,
              'operatingIncome',
              'ebitda',
              document='income_statement')
         tickers_dict_eps[ticker] = {
             'x': date,
             'y1': Revenue,
             'y2': NetIncome
         }
         tickers_dict_debt[ticker] = {
             'x': date_2,
             'y1': operatingIncome,
             'y2': ebitda
         }
     IncomeStatement.title_data = [
         'Revenue', 'NetIncome', 'OperatingIncome', 'Ebitda '
     ]
     plot = IncomeStatement.Multiple_plots(ticker_list, tickers_dict_eps,
                                           tickers_dict_debt,
                                           'IncomeStatement')
예제 #12
0
 def NOW_click(self):
     tickers_quote = dict()
     entered_tickers = self.textTicker.get()
     entered_years = self.buttonYears_var.get()
     print('\n---- CLICK EVENT  NOW_click ---- Selected ticker is/are: ' +
           entered_tickers)
     ticker_list = entered_tickers.split(',')
     print('---- You selected ' + str(len(ticker_list)) + ' tickers')
     for ticker in ticker_list:
         print('---- Collecting data for ' + str(ticker))
         Quote = Analyses(ticker,
                          period=entered_years,
                          api_key=self.apikey,
                          statistic=' ')
         price, priceAvg50, priceAvg200, eps, sharesOutstanding, marketCap = Quote.Get_quote_for(
             ticker)
         today = Quote.today
         #Thoise values are evaluated at the latest date
         currentRatio, quickRatio, cashRatio, grossProfitMargin, operatingProfitMargin, netProfitMargin, returnOnAssets, returnOnEquity, unused_0, unused_1, operatingCashFlowPerShare, freeCashFlowPerShare = Quote.Ratios(
         )  #return 12 strings
         latest_ratio_date = Quote.today
         bookValuePerShare, debtToAssets, debtToEquity, enterpriseValue, enterpriseValueOverEBITDA, freeCashFlowPerShare, researchAndDdevelopementToRevenue, roe, roic = Quote.Metrics(
         )
         beta, volAvg, lastDiv, dcf, ipoDate, industry, sector = Quote.Profile(
         )
         tickers_quote[ticker] = {
             'Today': today,
             'beta': beta,
             'volAvg': volAvg,
             'lastDiv': lastDiv,
             'dcf': dcf,
             'ipoDate': ipoDate,
             'industry': industry,
             'sector': sector,
             'marketCap': marketCap,
             'price': price,
             'priceAvg50': priceAvg50,
             'priceAvg200': priceAvg200,
             'EPS': eps,
             'bookValuePerShare': bookValuePerShare,
             'roe': roe,
             'roic': roic,
             'sharesOutstanding': sharesOutstanding,
             'Latest report date': latest_ratio_date,
             'currentRatio': currentRatio,
             'quickRatio': quickRatio,
             'debtToAssets': debtToAssets,
             'debtToEquity': debtToEquity,
             'cashRatio': cashRatio,
             'grossProfitMargin': grossProfitMargin,
             'operatingProfitMargin': operatingProfitMargin,
             'netProfitMargin': netProfitMargin,
             'returnOnAssets': returnOnAssets,
             'returnOnEquity': returnOnEquity,
             'researchAndDdevelopementToRevenue':
             researchAndDdevelopementToRevenue,
             'operatingCashFlowPerShare': operatingCashFlowPerShare,
             'freeCashFlowPerShare': freeCashFlowPerShare,
             'enterpriseValue': enterpriseValue,
             'enterpriseValueOverEBITDA': enterpriseValueOverEBITDA
         }
     index_for_dataframe = Quote.title_data = [
         'Today', 'beta', 'volAvg', 'lastDiv', 'dcf', 'ipoDate', 'industry',
         'sector', 'marketCap', 'price', 'priceAvg50', 'priceAvg200', 'EPS',
         'bookValuePerShare', 'roe', 'roic', 'sharesOutstanding',
         'Latest report date', 'currentRatio', 'quickRatio', 'debtToAssets',
         'debtToEquity', 'cashRatio', 'grossProfitMargin',
         'operatingProfitMargin', 'netProfitMargin', 'returnOnAssets',
         'returnOnEquity', 'researchAndDdevelopementToRevenue',
         'operatingCashFlowPerShare', 'freeCashFlowPerShare',
         'enterpriseValue', 'enterpriseValueOverEBITDA'
     ]
     #print('Dict is '+str(tickers_quote))
     mydict = tickers_quote
     #with open('dict.csv', 'w') as csv_file:
     #	writer = csv.writer(csv_file)
     #	for key, value in mydict.items():
     #		writer.writerow([key, value])
     frame = pd.DataFrame(tickers_quote,
                          columns=entered_tickers.split(","),
                          index=index_for_dataframe)
     print('Frame is ' + str(frame))
     if (len(entered_tickers) > 1):
         f = open(
             "saved_data/dataframe/" + entered_tickers.replace(',', '_') +
             "_now_click.log", "w")
         print(frame, file=f)
         frame.to_csv(r'saved_data/csv/' +
                      entered_tickers.replace(',', '_') + '_now_click.csv',
                      index=index_for_dataframe)
     print('-- NOW_click printed on files for: ' + entered_tickers)
     Quote.Get_Industry_Ratios(industry)
예제 #13
0
파일: instance.py 프로젝트: jeremygw/silky
class Instance:

    instances = { }

    @staticmethod
    def get(instance_id):
        return Instance.instances.get(instance_id)

    def __init__(self, session_path, instance_id=None):

        self._coms = None
        self._dataset = None
        self._filepath = None
        self._analyses = Analyses()
        self._em = EngineManager()

        self._session_path = session_path

        self._em.add_results_listener(self._on_results)

        settings = Settings.retrieve()
        settings.sync()

        if instance_id is not None:
            self._instance_id = instance_id
        else:
            self._instance_id = str(uuid.uuid4())
            print("created " + self._instance_id)

        self._instance_path = os.path.join(self._session_path, self._instance_id)
        os.makedirs(self._instance_path, exist_ok=True)
        self._buffer_path = os.path.join(self._instance_path, 'buffer')

        self._em.start(self._session_path)

        Instance.instances[self._instance_id] = self

    @property
    def id(self):
        return self._instance_id

    def set_coms(self, coms):
        self._coms = coms

    def get_path_to_resource(self, resourceId):
        resource_path = os.path.join(self._instance_path, resourceId)
        return resource_path

    def on_request(self, request):
        if type(request) == silkycoms.CellsRequest:
            self._on_cells(request)
        elif type(request) == silkycoms.OpenRequest:
            self._on_open(request)
        elif type(request) == silkycoms.SaveRequest:
            self._on_save(request)
        elif type(request) == silkycoms.InfoRequest:
            self._on_info(request)
        elif type(request) == silkycoms.SettingsRequest:
            self._on_settings(request)
        elif type(request) == silkycoms.AnalysisRequest:
            self._on_analysis(request)
        elif type(request) == silkycoms.FSRequest:
            self._on_fs_request(request)
        else:
            print('unrecognised request')
            print(request.payloadType)

    def _on_results(self, results, request, complete):
        complete = (results.status == silkycoms.AnalysisStatus.ANALYSIS_COMPLETE)
        self._coms.send(results, self._instance_id, request, complete)

    def _on_fs_request(self, request):
        location = request.path

        if location.startswith('{{Documents}}'):
            location = location.replace('{{Documents}}', Dirs.documents_dir())
        if location.startswith('{{Desktop}}'):
            location = location.replace('{{Desktop}}', Dirs.desktop_dir())
        if location.startswith('{{Home}}'):
            location = location.replace('{{Home}}', Dirs.home_dir())

        response = silkycoms.FSResponse()

        try:
            contents = os.scandir(location)

            for direntry in contents:
                entry = silkycoms.FSEntry()
                entry.path = direntry.path
                if direntry.is_dir():
                    entry.type = silkycoms.FSEntry.Type.FOLDER
                else:
                    entry.type = silkycoms.FSEntry.Type.FILE
                response.contents.append(entry)

        except Exception as e:
            print(e)
            response.errorMessage = str(e)

        self._coms.send(response, self._instance_id, request)

    def _on_save(self, request):
        print('saving ' + request.filename)

        FileIO.write(self._dataset, request.filename)

        self._filepath = request.filename
        response = silkycoms.SaveProgress()
        self._coms.send(response, self._instance_id, request)

        self._add_to_recents(request.filename)

    def _on_open(self, request):
        print('opening ' + request.filename)

        mm = MemoryMap.create(self._buffer_path, 65536)
        dataset = DataSet.create(mm)

        try:
            FileIO.read(dataset, request.filename)
            self._dataset = dataset
            self._filepath = request.filename

            self._coms.send(None, self._instance_id, request)

            self._add_to_recents(request.filename)

        except Exception as e:
            base    = os.path.basename(request.filename)
            message = 'Could not open {}'.format(base)
            cause = e.strerror

            self._coms.send_error(message, cause, self._instance_id, request)

    def _open_callback(self, task, progress):
        response = silkycoms.ComsMessage()
        response.open.status = silkycoms.Status.IN_PROGRESS
        response.open.progress = progress
        response.open.progress_task = task

        self._coms.send(response, self._instance_id)

    def _on_analysis(self, request):

        if 'options' not in request:

            try:
                analysis = self._analyses.create(request.analysisId, request.name, request.ns)
                analysisId = request.analysisId
                options = json.dumps(analysis.options)

                response = silkycoms.AnalysisResponse()
                response.analysisId = analysisId
                response.options = options
                response.status = silkycoms.AnalysisStatus.ANALYSIS_NONE

                self._coms.send(response, self._instance_id, request, False)

                request.datasetId = self._instance_id
                request.analysisId = analysisId
                request.options = options
                self._em.send(request)

            except Exception as e:

                print('Could not create analysis: ' + str(e))
                self._coms.discard(request)

                # We should handle this properly at some point, something like:
                #
                # response = silkycoms.AnalysisResponse()
                # response.status = silkycoms.AnalysisStatus.ANALYSIS_ERROR
                # response.error.message = 'Could not create analysis: ' + str(e)
                #
                # self._coms.send(response, self._instance_id, request)

        else:
            analysisId = request.analysisId
            options = request.options

            request.datasetId = self._instance_id
            request.analysisId = analysisId
            request.options = options
            self._em.send(request)

    def _on_info(self, request):

        response = silkycoms.InfoResponse()

        hasDataSet = self._dataset is not None
        response.hasDataSet = hasDataSet

        if hasDataSet:
            response.filePath = self._filepath
            response.rowCount = self._dataset.row_count
            response.columnCount = self._dataset.column_count

            for column in self._dataset:

                field = silkycoms.InfoResponse.Schema.Field()
                field.name = column.name
                field.measureType = silkycoms.InfoResponse.Schema.Field.MeasureType(column.type)
                field.width = 100

                if column.type is MeasureType.CONTINUOUS:
                    field.dps = column.dps
                elif column.type is MeasureType.NOMINAL_TEXT:
                    for level in column.labels:
                        levelEntry = silkycoms.VariableLevel()
                        levelEntry.label = level[1]
                        field.levels.append(levelEntry)
                elif column.type is MeasureType.NOMINAL or column.type is MeasureType.ORDINAL:
                    for level in column.labels:
                        levelEntry = silkycoms.VariableLevel()
                        levelEntry.value = level[0]
                        levelEntry.label = level[1]
                        field.levels.append(levelEntry)

                response.schema.fields.append(field)

        self._coms.send(response, self._instance_id, request)

    def _on_cells(self, request):

        if self._dataset is None:
            return None

        rowStart = request.rowStart
        colStart = request.columnStart
        rowEnd   = request.rowEnd
        colEnd   = request.columnEnd
        rowCount = rowEnd - rowStart + 1
        colCount = colEnd - colStart + 1

        response = silkycoms.CellsResponse()

        response.request.rowStart    = rowStart
        response.request.columnStart = colStart
        response.request.rowEnd      = rowEnd
        response.request.columnEnd   = colEnd

        dataset = self._dataset

        for c in range(colStart, colStart + colCount):
            column = dataset[c]

            colRes = silkycoms.CellsResponse.Column()

            if column.type == MeasureType.CONTINUOUS:
                for r in range(rowStart, rowStart + rowCount):
                    value = column[r]
                    colRes.doubles.values.append(value)
            elif column.type == MeasureType.NOMINAL_TEXT:
                for r in range(rowStart, rowStart + rowCount):
                    value = column[r]
                    colRes.strings.values.append(value)
            else:
                for r in range(rowStart, rowStart + rowCount):
                    value = column[r]
                    colRes.ints.values.append(value)

            response.columns.append(colRes)

        self._coms.send(response, self._instance_id, request)

    def _add_to_recents(self, path):

        settings = Settings.retrieve('backstage')
        recents  = settings.get('recents', [ ])

        for recent in recents:
            if path == recent['path']:
                recents.remove(recent)
                break

        name = os.path.basename(path)
        location = os.path.dirname(path)

        documents_dir = Dirs.documents_dir()
        home_dir = Dirs.home_dir()
        desktop_dir = Dirs.desktop_dir()

        if location.startswith(documents_dir):
            location = location.replace(documents_dir, '{{Documents}}')
        if location.startswith(desktop_dir):
            location = location.replace(desktop_dir, '{{Desktop}}')
        if location.startswith(home_dir):
            location = location.replace(home_dir, '{{Home}}')

        recents.insert(0, { 'name': name, 'path': path, 'location': location })
        recents = recents[0:5]

        settings.set('recents', recents)
        settings.sync()

        for instanceId, instance in Instance.instances.items():
            instance._on_settings()

    def _on_settings(self, request=None):

        settings = Settings.retrieve('backstage')

        localFSRecents = settings.get('localFSRecents')
        if localFSRecents is None:
            localFSRecents = [
                { 'name': '{{Documents}}', 'path': '{{Documents}}' },
                { 'name': '{{Desktop}}',   'path': '{{Desktop}}' } ]

        recents = settings.get('recents', [ ])

        response = silkycoms.SettingsResponse()

        for recent in recents:
            recentEntry = silkycoms.DataSetEntry()
            recentEntry.name = recent['name']
            recentEntry.path = recent['path']
            recentEntry.location = recent['location']

            response.recents.append(recentEntry)

        for localFSRecent in localFSRecents:
            recent = silkycoms.DataSetEntry()
            recent.name = localFSRecent['name']
            recent.path = localFSRecent['path']

            response.localFSRecents.append(recent)

        self._coms.send(response, self._instance_id, request)
예제 #14
0
 def CashFlowCalculator(self):
     tickers_quote = dict()
     entered_tickers = self.textTicker.get()
     entered_years = self.buttonYears_var.get()
     print('\n----   CashFlowCalculator ---- Selected ticker is/are: ' +
           entered_tickers)
     ticker_list = entered_tickers.split(',')
     print('---- You selected ' + str(len(ticker_list)) + ' tickers')
     for ticker in ticker_list:
         print('---- Collecting data for ' + str(ticker))
         Quote = Analyses(ticker,
                          period=entered_years,
                          api_key=self.apikey,
                          statistic=' ')
         price, priceAvg50, priceAvg200, eps, sharesOutstanding, marketCap = Quote.Get_quote_for(
             ticker)
         #Thoise values are evaluated at the latest date
         revenue, netIncome, ebitda, depreciationAndAmortization, interestExpense, incomeTaxExpense, operatingIncome, date, period = Quote.IncomeStatement(
             history_year='latest')  #return 12 strings
         date, period, totalAssets, totalLiabilities, totalCurrentAssets, totalCurrentLiabilities, totalNonCurrentAssets, shortTermDebt, longTermDebt, cashAndShortTermInvestments, retainedEarnings, propertyPlantEquipmentNet = Quote.BalanceSheet(
             history_year='latest')  #return 14 strings
         date, period, operatingCashFlow, capitalExpenditure, dividendsPaid, commonStockRepurchased, changeInWorkingCapital, netCashProvidedByOperatingActivities, commonStockIssued, capitalExpenditure, freeCashFlow = Quote.CashFlowStatement(
             history_year='latest')  #return 14 strings
         latest_ratio_date = Quote.today
         tickers_quote[ticker] = {
             'date': date,
             'period': period,
             'price': price,
             'sharesOutstanding': sharesOutstanding,
             'revenue': revenue,
             'netIncome': netIncome,
             'ebitda': ebitda,
             'depreciationAndAmortization': depreciationAndAmortization,
             'interestExpense': interestExpense,
             'incomeTaxExpense': incomeTaxExpense,
             'operatingIncome': operatingIncome,
             'totalAssets': totalAssets,
             'totalLiabilities': totalLiabilities,
             'totalCurrentAssets': totalCurrentAssets,
             'totalCurrentLiabilities': totalCurrentLiabilities,
             'totalNonCurrentAssets': totalNonCurrentAssets,
             'shortTermDebt': shortTermDebt,
             'longTermDebt': longTermDebt,
             'cashAndShortTermInvestments': cashAndShortTermInvestments,
             'retainedEarnings': retainedEarnings,
             'operatingCashFlow': operatingCashFlow,
             'capitalExpenditure': capitalExpenditure,
             'dividendsPaid': dividendsPaid,
             'commonStockRepurchased': commonStockRepurchased,
             'changeInWorkingCapital': changeInWorkingCapital,
             'netCashProvidedByOperatingActivities':
             netCashProvidedByOperatingActivities,
             'commonStockIssued': commonStockIssued,
             'capitalExpenditure': capitalExpenditure,
             'freeCashFlow': freeCashFlow,
             'propertyPlantEquipmentNet': propertyPlantEquipmentNet
         }
     index_for_dataframe = Quote.title_data = [
         'date', 'period', 'price', 'sharesOutstanding', 'revenue',
         'netIncome', 'ebitda', 'depreciationAndAmortization',
         'interestExpense', 'incomeTaxExpense', 'operatingIncome',
         'totalAssets', 'totalLiabilities', 'totalCurrentAssets',
         'totalCurrentLiabilities', 'totalNonCurrentAssets',
         'shortTermDebt', 'longTermDebt', 'cashAndShortTermInvestments',
         'retainedEarnings', 'operatingCashFlow', 'capitalExpenditure',
         'dividendsPaid', 'commonStockRepurchased',
         'changeInWorkingCapital', 'netCashProvidedByOperatingActivities',
         'commonStockIssued', 'capitalExpenditure', 'freeCashFlow',
         'propertyPlantEquipmentNet'
     ]
     mydict = tickers_quote
     frame = pd.DataFrame(tickers_quote,
                          columns=entered_tickers.split(","),
                          index=index_for_dataframe)
     print('Frame is ' + str(frame))
     if (len(entered_tickers) > 1):
         f = open(
             "saved_data/dataframe/" + entered_tickers.replace(',', '_') +
             "_cashflowcalculator.log", "w")
         print(frame, file=f)
         frame.to_csv(r'saved_data/csv/' +
                      entered_tickers.replace(',', '_') +
                      '_cashflowcalculator.csv',
                      index=index_for_dataframe)
     print('-- CashFlowCalculator printed on files for: ' + entered_tickers)