예제 #1
0
        public async Task <FinancialStatement> FileToFinancialStatement(string fileContent)
        {
            if (string.IsNullOrWhiteSpace(fileContent))
            {
                throw new ArgumentException(nameof(fileContent));
            }

            FinancialStatement result = new FinancialStatement();

            await Task.Run(() => {
                var currencyType = this.GetCurrency(fileContent);
                var account      = this.GetAccount(fileContent);
                var bankId       = this.GetBank(fileContent);

                result.BankId       = bankId;
                result.Account      = account;
                result.CurrencyType = currencyType;
            });

            await Task.Run(() => {
                var transactionContent = fileContent.Parse("<BANKTRANLIST>", "</BANKTRANLIST>");

                result.Transactions = this.GetTransactions(transactionContent.RemoveSpecialChars());
            });

            return(result);
        }
        private decimal CalculateRoic(FinancialStatement financialStatement)
        {
            var incomeBeforeTaxes = financialStatement.IncomeStatement.IncomeBeforeTaxes;

            if (incomeBeforeTaxes <= 0)
            {
                return(0);
            }
            var taxExpense      = financialStatement.IncomeStatement.TaxExpense;
            var taxRate         = taxExpense / incomeBeforeTaxes;
            var nopat           = financialStatement.IncomeStatement.Ebit * (1 - taxRate);
            var investedCapital = financialStatement.BalanceSheet.RealTotalEquity +
                                  financialStatement.BalanceSheet.TotalLongTermDebt +
                                  financialStatement.BalanceSheet.TotalShortTermDebt;
            var marketableSecurities = Math.Max(0,
                                                financialStatement.BalanceSheet.CashCashEquivalentAndShortTermInvestments -
                                                financialStatement.BalanceSheet.CashAndCashEquivalent);

            if (financialStatement.BalanceSheet.CashAndCashEquivalent <= 0)
            {
                marketableSecurities = 0;
            }
            investedCapital -= marketableSecurities;
            if (investedCapital <= 0)
            {
                return(0);
            }
            return(nopat / investedCapital * 100);
        }
예제 #3
0
        private List <FinancialStatement> ParseFinancialStatements(string jsonData, string frequency)
        {
            dynamic statements = JObject.Parse(jsonData);
            var     results    = new List <FinancialStatement>();

            if (statements != null && statements.result != null && statements.result.rows != null)
            {
                foreach (var row in statements.result.rows.Children())
                {
                    FinancialStatement statement = new FinancialStatement {
                        Source = frequency
                    };
                    foreach (var entry in row.values.Children())
                    {
                        string field = entry.field;
                        string value = entry.value;
                        if (Setters.ContainsKey(field) && value != null && value != "null")
                        {
                            Setters[field](statement, value);
                        }
                    }
                    results.Add(statement);
                }
            }
            return(results);
        }
        private void SaveStatements()
        {
            var factory = FinancialStatement.FinancialStatementFactory();

            using (IDbConnection db = factory.OpenDbConnection())
            {
                db.CreateTableIfNotExists <IncomeStatement>();
                db.CreateTableIfNotExists <BalanceSheet>();
                db.CreateTableIfNotExists <CashFlow>();

                foreach (string key in _statementCache.Keys)
                {
                    db.Delete <IncomeStatement>(statement => statement.HashKey == _statementCache[key].HashKey);
                    db.Delete <BalanceSheet>(statement => statement.HashKey == _statementCache[key].HashKey);
                    db.Delete <CashFlow>(statement => statement.HashKey == _statementCache[key].HashKey);
                }

                foreach (string key in _statementCache.Keys)
                {
                    db.Insert <IncomeStatement>(_statementCache[key].IncomeStatement);
                    db.Insert <BalanceSheet>(_statementCache[key].BalanceSheet);
                    db.Insert <CashFlow>(_statementCache[key].CashFlow);
                }
            }
        }
        private void AddToStatement(FactContext context, string elementName, string value)
        {
            double result = 0;

            if (!double.TryParse(value, out result))
            {
                return; // NaN
            }
            if (null == context)
            {
                return; // no time period
            }
            // look up financial statement, if there is one
            FinancialStatement statement;

            if (_statementCache.ContainsKey(context.HashKey))
            {
                statement = _statementCache[context.HashKey];
            }
            else
            {
                statement = new FinancialStatement {
                    StartDate = context.StartDate,
                    EndDate   = context.EndDate,
                    Ticker    = this._filing.Ticker,
                    Source    = StatementBase.SourceEdgar
                }
            };

            // try to set the value on the statement
            if (SetStatementValue(statement, elementName, result))
            {
                _statementCache[context.HashKey] = statement;
            }
        }
        private static bool SetStatementValue(FinancialStatement statement, string elementName, double value)
        {
            try
            {
                // set the property value if it exists in the cache
                if (BalanceSheetElements.ContainsKey(elementName))
                {
                    BalanceSheetElements[elementName].SetValue(statement.BalanceSheet, value);
                    return(true);
                }
                else if (CashFlowElements.ContainsKey(elementName))
                {
                    CashFlowElements[elementName].SetValue(statement.CashFlow, value);
                    return(true);
                }
                else if (IncomeStatementElements.ContainsKey(elementName))
                {
                    IncomeStatementElements[elementName].SetValue(statement.IncomeStatement, value);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                log.Error("Unable to set edgar value from attribute.", ex);
                return(false);
            }

            return(false);
        }
예제 #7
0
        private static void CalculateNcavAndDiscount(FinancialStatement latestStatement, Security security)
        {
            var ncav = latestStatement.BalanceSheet.TotalCurrentAssets -
                       latestStatement.BalanceSheet.TotalLiabilities;

            //Ncav
            var totalAsset        = latestStatement.BalanceSheet.TotalAssets;
            var totalEquity       = latestStatement.BalanceSheet.TotalStockHolderEquity;
            var cashAndEquivalent = latestStatement.BalanceSheet.CashAndCashEquivalent;

            if ((totalAsset - cashAndEquivalent) != 0)
            {
                security.DebtRatio = totalEquity / (totalAsset - cashAndEquivalent);
            }

            var nbShares = security.NbSharesOutstanding != 0
                ? security.NbSharesOutstanding
                : security.MarketCapitalisation / security.Last;

            if (nbShares <= 0)
            {
                throw new Exception(string.Format("Number of shares is null or negative for Security : {0}", security.Ticker));
            }
            security.NcavPerShare = ncav / nbShares;
            if (security.NcavPerShare > 0)
            {
                security.DiscountOnNcav = (ncav / nbShares - security.Last) / (ncav / nbShares);
            }
            security.DateOfLatestCalculusOnNav = DateTime.Today;
        }
 private decimal?GetGrossMargin(FinancialStatement financialStatement)
 {
     if (financialStatement.IncomeStatement.TotalRevenue == 0)
     {
         return(null);
     }
     return(100 * financialStatement.IncomeStatement.GrossProfit / financialStatement.IncomeStatement.TotalRevenue);
 }
 private decimal?GetNetMargin(FinancialStatement financialStatement)
 {
     if (financialStatement.IncomeStatement.TotalRevenue == 0)
     {
         return(null);
     }
     return(100 * financialStatement.IncomeStatement.NetIncome / financialStatement.IncomeStatement.TotalRevenue);
 }
예제 #10
0
 private decimal?GetLeverage(FinancialStatement financialStatement)
 {
     if (financialStatement.BalanceSheet.TotalAssets == 0)
     {
         return(null);
     }
     return(financialStatement.BalanceSheet.TotalLongTermDebt / financialStatement.BalanceSheet.TotalAssets);
 }
예제 #11
0
 private decimal?GetEquityLeverage(FinancialStatement financialStatement)
 {
     if (financialStatement.BalanceSheet.RealTotalEquity == 0)
     {
         return(null);
     }
     return(financialStatement.BalanceSheet.TotalLiabilities / financialStatement.BalanceSheet.RealTotalEquity);
 }
        public void FileToFinancialStatementTest_EmpytValues_TransactionValue()
        {
            var fileContent = Properties.Resources.extrato5;

            Action action = () => { FinancialStatement financialStatement = this._financialStatementService.FileToFinancialStatement(fileContent).Result; };

            action.Should().Throw <ConvertValueException>().WithMessage("Impossible convert value '' to the type Decimal.");
        }
예제 #13
0
 private decimal?GetAssetTurnover(FinancialStatement financialStatement)
 {
     if (financialStatement.BalanceSheet.TotalAssets == 0)
     {
         return(null);
     }
     return(100 * financialStatement.IncomeStatement.TotalRevenue / financialStatement.BalanceSheet.TotalAssets);
 }
예제 #14
0
 private decimal?GetQuickRatio(FinancialStatement financialStatement)
 {
     if (financialStatement.BalanceSheet.TotalCurrentLiabilities == 0)
     {
         return(null);
     }
     return(100 * financialStatement.BalanceSheet.CashCashEquivalentAndShortTermInvestments /
            financialStatement.BalanceSheet.TotalCurrentLiabilities);
 }
예제 #15
0
 private decimal?GetRoa(FinancialStatement financialStatement)
 {
     if (financialStatement.BalanceSheet.TotalAssets == 0)
     {
         return(null);
     }
     return(100 * financialStatement.IncomeStatement.NetIncomeApplicableToCommon /
            financialStatement.BalanceSheet.TotalAssets);
 }
예제 #16
0
 private decimal?GetCurrenRatio(FinancialStatement financialStatement)
 {
     if (financialStatement.BalanceSheet.TotalCurrentLiabilities == 0)
     {
         return(null);
     }
     return(100 * financialStatement.BalanceSheet.TotalCurrentAssets /
            financialStatement.BalanceSheet.TotalCurrentLiabilities);
 }
예제 #17
0
        /// <summary>
        /// Calculate a metric given a financial statement.
        /// </summary>
        /// <param name="statement"></param>
        /// <returns></returns>
        public FinancialMetric CalculateMetric(FinancialStatement statement)
        {
            FinancialMetric metric = new FinancialMetric
            {
                Source    = statement.Source,
                Ticker    = statement.Ticker,
                StartDate = statement.StartDate,
                EndDate   = statement.EndDate
            };

            bool   quarterly = statement.IsQuarterly;
            double divisor   = statement.IsQuarterly ? (statement.NumQuarters) : 4;

            // caclulate quarterly nets and normalize for calcs
            metric.NetIncome           = quarterly ? statement.IncomeStatement.NetIncome * 4 : statement.IncomeStatement.NetIncome;
            metric.CashFromOperations  = (statement.CashFlow.CashFromOperatingActivities / divisor) * 4;
            metric.CapitalExpenditures = (statement.CashFlow.CapitalExpenditures / divisor) * 4;
            metric.Revenue             = quarterly ? statement.IncomeStatement.TotalRevenue * 4 : statement.IncomeStatement.TotalRevenue;

            metric.FreeCashFlow = FinanceUtility.FreeCashFlow(metric.CashFromOperations, metric.CapitalExpenditures).Normalize();
            metric.CurrentReturnOnInvestmentCapital = FinanceUtility.CurrentReturnOnInvestmentCapital(metric.FreeCashFlow, statement.BalanceSheet.TotalEquity, statement.BalanceSheet.TotalLiabilities, statement.BalanceSheet.TotalCurrentLiabilities).Normalize();

            metric.ReceivablesPercentOfSales = FinanceUtility.ReceivablesPercentOfSales(metric.Revenue, statement.BalanceSheet.TotalReceivables).Normalize();
            metric.CurrentRatio = FinanceUtility.CurrentRatio(statement.BalanceSheet.TotalCurrentAssets, statement.BalanceSheet.TotalCurrentLiabilities).Normalize();

            metric.PlantPropertyValue       = FinanceUtility.PlantPropertyValue(statement.BalanceSheet.PropertyPlantEquipment, statement.BalanceSheet.Depreciation).Normalize();
            metric.GoodwillPercentAssets    = FinanceUtility.GoodwillPercentAssets(statement.BalanceSheet.Goodwill, statement.BalanceSheet.TotalAssets).Normalize();
            metric.IntangiblesPercentAssets = FinanceUtility.IntangiblePercentAssets(statement.BalanceSheet.Intangibles, statement.BalanceSheet.TotalAssets).Normalize();

            metric.ReturnOnAssets = FinanceUtility.ReturnOnAssets(metric.NetIncome, statement.BalanceSheet.TotalAssets).Normalize();

            metric.LiabilityToEquity = (statement.BalanceSheet.TotalLiabilities / statement.BalanceSheet.TotalEquity).Normalize();
            metric.DebtToEquity      = (statement.BalanceSheet.TotalDebt / statement.BalanceSheet.TotalEquity).Normalize();

            metric.ReturnOnEquity = (statement.IncomeStatement.NetIncome / statement.BalanceSheet.TotalEquity).Normalize();

            metric.TangibleBookValue = statement.BalanceSheet.TotalEquity - statement.BalanceSheet.Goodwill - statement.BalanceSheet.Intangibles;

            metric.FreeCashFlowPerShare = (metric.FreeCashFlow / statement.BalanceSheet.CommonSharesOutstanding).Normalize();

            metric.ResearchAndDevelopmentPercentOfRevenue = (statement.IncomeStatement.ResearchAndDevelopmentExpense / statement.IncomeStatement.TotalRevenue).Normalize();
            metric.SalesPercentRevenue = (statement.IncomeStatement.SalesAndMarketingExpenses / statement.IncomeStatement.TotalRevenue).Normalize();

            metric.Ncav = (statement.BalanceSheet.TotalCurrentAssets - statement.BalanceSheet.TotalLiabilities).Normalize();

            // company value if we liquidated everything today
            metric.LiquidationValue = statement.BalanceSheet.TotalAssets - 0.2 * statement.BalanceSheet.PropertyPlantEquipment - 0.5 * statement.BalanceSheet.TotalInventory
                                      - 0.5 * statement.BalanceSheet.AccountsReceivable - statement.BalanceSheet.Intangibles - statement.BalanceSheet.TotalLiabilities;

            metric.EarningsPerShareDiluted = statement.IncomeStatement.EarningsPerShareDiluted;
            metric.CashAndShortTerm        = statement.BalanceSheet.CashAndShortTerm;
            metric.CommonSharesOutstanding = statement.BalanceSheet.CommonSharesOutstanding;
            metric.TotalDebt = statement.BalanceSheet.TotalDebt;

            return(metric);
        }
        public async Task <FinancialStatement[]> GetFinancialStatementsAsync(string symbol, string filing_type)
        {
            EdgarSearch es = await EdgarSearch.CreateAsync(symbol, filing_type, null, EdgarSearchOwnershipFilter.exclude, EdgarSearchResultsPerPage.Entries40);

            //Get a list of the filings
            List <EdgarSearchResult> Results = new List <EdgarSearchResult>();

            foreach (EdgarSearchResult esr in es.Results)
            {
                if (esr.Filing.Trim().ToLower() == filing_type.Trim().ToLower())
                {
                    Results.Add(esr);
                }
            }

            //Make financial statments for each
            List <FinancialStatement> FinancialStatements = new List <FinancialStatement>();

            foreach (EdgarSearchResult esr in Results)
            {
                try
                {
                    Stream s = await esr.DownloadXbrlDocumentAsync();

                    XbrlInstanceDocument doc = XbrlInstanceDocument.Create(s);
                    FinancialStatement   fs  = doc.CreateFinancialStatement();
                    FinancialStatements.Add(fs);
                }
                catch
                {
                }
            }


            //Arrange from oldest to newest
            List <FinancialStatement> Arranged = new List <FinancialStatement>();

            do
            {
                FinancialStatement Winner = FinancialStatements[0];
                foreach (FinancialStatement fs in FinancialStatements)
                {
                    if (fs.PeriodEnd < Winner.PeriodEnd)
                    {
                        Winner = fs;
                    }
                }
                Arranged.Add(Winner);
                FinancialStatements.Remove(Winner);
            } while (FinancialStatements.Count > 0);


            return(Arranged.ToArray());
        }
예제 #19
0
파일: Program.cs 프로젝트: TimHanewich/Xbrl
        static void Main(string[] args)
        {
            EdgarSearch          es   = EdgarSearch.CreateAsync(args[0], "10-K").Result;
            EdgarSearchResult    esr  = es.GetFirstResultOfFilingType("10-K");
            Stream               s    = esr.DownloadXbrlDocumentAsync().Result;
            XbrlInstanceDocument doc  = XbrlInstanceDocument.Create(s);
            FinancialStatement   fs   = doc.CreateFinancialStatement();
            string               json = JsonConvert.SerializeObject(fs);

            Console.WriteLine(json);
        }
        public void FileToFinancialStatementTest_EmpytValues()
        {
            var fileContent = Properties.Resources.extrato6;

            FinancialStatement financialStatement = this._financialStatementService.FileToFinancialStatement(fileContent).Result;

            financialStatement.Should().NotBeNull();
            financialStatement.BankId.Should().Be(341);
            financialStatement.Account.Should().Be(7037300576);
            financialStatement.CurrencyType.Should().Be(CurrencyType.BRL);
            financialStatement.Transactions.Should().HaveCount(1);
        }
예제 #21
0
 private decimal CalculateRoe(FinancialStatement financialStatement)
 {
     if (financialStatement.IncomeStatement.NetIncomeApplicableToCommon <= 0)
     {
         return(0);
     }
     if (financialStatement.BalanceSheet.RealTotalEquity <= 0)
     {
         return(0);
     }
     return(financialStatement.IncomeStatement.NetIncomeApplicableToCommon / financialStatement.BalanceSheet.RealTotalEquity * 100);
 }
        public async Task FileToFinancialStatementTest_OrderChanged()
        {
            var fileContent = Properties.Resources.extrato2;

            FinancialStatement financialStatement = await this._financialStatementService.FileToFinancialStatement(fileContent);

            financialStatement.Should().NotBeNull();
            financialStatement.BankId.Should().Be(341);
            financialStatement.Account.Should().Be(7037300576);
            financialStatement.CurrencyType.Should().Be(CurrencyType.BRL);
            financialStatement.Transactions.Should().HaveCount(4);
        }
예제 #23
0
        private void button1_Click(object sender, EventArgs e)
        {
            var list = Dao.Dao.fakeAccountInfo.GetInfoReorganized();
            FinancialStatement finance = new FinancialStatement();

            finance.DataSource = list;

            finance.tableCell15.TextFormatString = timeSelectFlag == 0 ? "Quarter {0}" : "Month {0}";
            ReportPrintTool printTool = new ReportPrintTool(finance);

            //objectData
            printTool.ShowPreview();
        }
예제 #24
0
파일: Program.cs 프로젝트: TimHanewich/Xbrl
        static void TestSingleDocument()
        {
            string path = "C:\\Users\\tihanewi\\Downloads\\AAPL.xml";
            Stream s    = System.IO.File.OpenRead(path);
            XbrlInstanceDocument doc = XbrlInstanceDocument.Create(s);

            Console.WriteLine("Period context ref: '" + doc.PrimaryPeriodContextId + "'");
            Console.WriteLine("Instant context ref: '" + doc.PrimaryInstantContextId + "'");
            FinancialStatement fs   = doc.CreateFinancialStatement();
            string             json = JsonConvert.SerializeObject(fs);

            Console.WriteLine(json);
        }
예제 #25
0
        public async Task <bool> Handle(UpdateFinancialStatementsCommand message, CancellationToken cancellationToken)
        {
            var mandatoryReports = await _configurationService.GetEffective("financial-statements/mandatory-reports");

            JObject json = JObject.Parse(mandatoryReports);
            JArray  list = (JArray)json["mandatory-reports"];

            foreach (var involvedPartyItem in message.Application.InvolvedParties)
            {
                if (involvedPartyItem is OrganizationParty organization)
                {
                    var fslist = new List <FinancialStatement>();
                    organization.FinancialStatements = new List <FinancialStatement>();
                    foreach (var item in list)
                    {
                        JArray reports       = (JArray)item["reports"];
                        var    distinctYears = (from foo in reports
                                                select foo["year"]).Distinct().ToArray();
                        foreach (var year in distinctYears)
                        {
                            FinancialStatement statement = new FinancialStatement();
                            statement.Reports = new List <Report>();
                            statement.Year    = Convert.ToInt32(year);
                            foreach (var statementItem in reports)
                            {
                                if (Convert.ToInt32(statementItem["year"]) == Convert.ToInt32(year))
                                {
                                    FinancialStatementsData financialStatementsData = await _financialStatementsService.GetFinancialStatementAsync(organization.CustomerNumber, statementItem["report-type"].ToString(), statementItem["accounting-method"].ToString(), Convert.ToInt32(statementItem["year"]));

                                    Report r = new Report
                                    {
                                        ReportId         = (financialStatementsData.ReportId != 0) ? financialStatementsData.ReportId : null,
                                        ReportType       = statementItem["report-type"].ToString(),
                                        AccountingMethod = statementItem["accounting-method"].ToString(),
                                        ReportDate       = financialStatementsData.ReportDate
                                    };
                                    statement.Reports.Add(r);
                                }
                            }
                            fslist.Add(statement);
                        }
                    }
                    organization.FinancialStatements = fslist;
                }
            }

            _involvedPartyRepository.PublishFinancialStatementsChangeEvent(message.Application.ApplicationNumber,
                                                                           message.Application.CustomerNumber);
            return(true);
        }
예제 #26
0
파일: Program.cs 프로젝트: TimHanewich/Xbrl
        static void TestAll10Ks()
        {
            do
            {
                Console.WriteLine("Symbol?");
                string symbol = Console.ReadLine();

                EdgarSearch es = EdgarSearch.CreateAsync(symbol, "10-K").Result;

                foreach (EdgarSearchResult esr in es.Results)
                {
                    if (esr.Filing == "10-K")
                    {
                        if (esr.InteractiveDataUrl != null && esr.InteractiveDataUrl != "")
                        {
                            try
                            {
                                Stream s = esr.DownloadXbrlDocumentAsync().Result;
                                XbrlInstanceDocument doc = XbrlInstanceDocument.Create(s);
                                FinancialStatement   fs  = doc.CreateFinancialStatement();
                                string rev = "";
                                if (fs.Revenue.HasValue)
                                {
                                    rev = fs.Revenue.Value.ToString("#,##0");
                                }
                                else
                                {
                                    rev = "?";
                                }
                                Console.WriteLine(fs.PeriodEnd.Value.ToShortDateString() + " - " + rev);
                            }
                            catch
                            {
                                Console.WriteLine("Critical error (filed on " + esr.FilingDate.ToShortDateString());
                            }
                        }
                    }
                }
                Console.WriteLine();
            } while (true);
        }
예제 #27
0
 private decimal GetFreeCashFlows(FinancialStatement financialStatement)
 {
     return(financialStatement.CashFlowStatement.CashFromOperatingActivities
            - Math.Abs(financialStatement.CashFlowStatement.CapitalExpanditure));
 }
예제 #28
0
 private bool HasGoodAccrual(FinancialStatement statement)
 {
     return(statement.CashFlowStatement.CashFromOperatingActivities >
            statement.IncomeStatement.NetIncomeApplicableToCommon);
 }