Data Driven Solutions

                   Data driven solutions


During the 2008 financial crisis, many major financial institutions suffered because of fragmented, siloed information technology (IT) and data architectures. These legacy systems left firms blind to their true aggregate exposures, counterparty risks, and toxic asset concentrations.

JPMorgan Chase (JPM) navigated the crisis more successfully than most of its Wall Street peers due to a combination of disciplined risk data aggregation, conservative IT strategies, and rigorous operational controls.

Unified Risk Aggregation and Reporting Systems

Prior to and during the crash, many banks could not answer a fundamental question: "What is our total exposure to subprime mortgages or a specific counterparty across all trading desks?" Data was trapped in business-unit silos.

Firm-Wide Data Integration: JPM had heavily invested in centralized database structures and risk-reporting frameworks that allowed leadership to view risk across investment banking, commercial banking, and retail divisions simultaneously.

Rapid Stress Testing: Because their data was more consolidated, JPM could run enterprise-wide stress tests on their mortgage-backed securities and leveraged loan portfolios much faster than competitors, allowing them to proactively write down assets and hedge risks before the panic peaked.

The 2008 financial crisis serves as a textbook masterclass in the dangers of over-concentration. When financial institutions, rating agencies, and investors put all their eggs in one basket—or in correlated, overlapping baskets—a single localized shock cascades into a global systemic collapse.


JP Morgan

AI Impact on Banking

Balancing Caution and Adoption: While expressing market caution, Jamie Dimon noted that JPMorgan is actively deploying AI to speed up client services.

Workforce Shifts: The bank is evaluating how AI intersects with employee roles as automation encroaches on traditional tasks.

Private Credit Risks

Market Vulnerability: Dimon cautioned that high market valuations mean banks are not totally immune to an upcoming credit cycle or potential "cockroach" events (referencing corporate blowups like Tricolor and First Brands).

Conservative Strategy: Unlike peers like Morgan Stanley who are heavily underwriting data centers and large projects, JPMorgan maintains a relatively more cautious approach to risk exposure.

JPMorgan's Strategic Outlook

Broad Ambitions vs. Niches: Dimon expects JPMorgan to win in 75 out of 100 areas and lose in 25, acknowledging that while they aim to dominate multiple sectors, niche competitors will excel in specific segments.

Pre-Crisis Parallels: He warned against aggressive lending practices (which boost net interest income) reminiscent of the era before the Great Financial Crisis.

CEO Succession Planning

No Hard Timeline: Dimon offered his familiar stance on succession, stating he will remain CEO as long as he and the board agree, potentially transitioning to executive chairman later.

Deep Bench, Aging Leadership: Shareholders continue to look for a defined succession line, especially given that Dimon is the longest-serving big bank CEO (having served before the financial crisis). Despite his hand surgery cast, analysts noted he looks healthy, and the bank maintains a deep bench of talent.


Sector Concentration

During the crisis, over-concentration manifested across several critical dimensions:

 Asset Class Concentration (The Real Estate Monoculture)

The Problem: Wall Street and global banks became dangerously over-concentrated in a single asset class: U.S. residential real estate and mortgage-backed debt.

The Flaw: Risk models assumed that housing prices across different geographic regions (e.g., California, Florida, Ohio) were uncorrelated—meaning if prices dropped in Miami, they would rise or hold steady in Phoenix.

The Fallout: When the housing bubble burst nationally, every single mortgage-backed security across the globe suffered simultaneous, correlated losses. There was nowhere to hide because the entire financial sector was betting on the exact same outcome.

Counterparty Credit Concentration (The Interbank Web)

The Problem: Major financial institutions were excessively exposed to a small handful of interconnected counterparties through Over-the-Counter (OTC) derivatives like Credit Default Swaps (CDS).

The Flaw: Banks assumed that giants like AIG or fellow investment banks like Lehman Brothers were "too big to fail" and would always be good for their obligations. They didn't adequately monitor or cap how much risk they held with a single counterparty.

The Fallout: When Lehman Brothers went bankrupt and AIG verged on collapse, it triggered a domino effect. Because every major bank was tied to them through complex financial webs, the failure of one core node threatened to instantly take down the entire global banking network.

Funding and Liquidity Concentration (Wholesale Short-Term Debt)

The Problem: Investment banks relied heavily on overnight and short-term wholesale funding markets (such as commercial paper and repurchase agreements or "repos") to finance long-term, illiquid assets like mortgage bonds.

The Flaw: They concentrated their funding models on the assumption that short-term credit would always be available to roll over day after day at low interest rates.

The Fallout: When trust evaporated in September 2008, the overnight lending market froze completely. Because banks couldn't roll over their short-term debt, even solvent institutions faced immediate, fatal liquidity crises.

Geographic and Sectoral Concentration in Lending

The Problem: Regional and commercial banks concentrated their commercial real estate (CRE) and residential portfolios in specific geographic hotspots (like the Sunbelt states and California) where the housing boom was most aggressive.

The Fallout: When local economies cooled and defaults spiked, these regional banks lacked portfolio diversification. Without a national or international balance sheet to absorb local losses, hundreds of regional community banks collapsed or were forced into emergency mergers.

Institutional Reliance on Ratings (Oligopoly Concentration)

The Problem: The entire machinery of securitization relied on just three credit rating agencies—Moody's, Standard & Poor's, and Fitch—to assess risk.

The Flaw: This created a dangerous single point of failure (and a conflict of interest, as issuers paid the rating agencies). When these three agencies stamped thousands of toxic subprime CDOs with AAA ratings, the entire global institutional investor base—pension funds, municipalities, and insurance companies—blindly trusted them.

The Fallout: When those AAA ratings proved to be catastrophically wrong overnight, institutional investors holding strict mandate-bound rules suddenly found themselves holding multi-billion-dollar blocks of junk assets.

The Modern Takeaway

The post-2008 regulatory framework (including Dodd-Frank and Basel III capital standards) was built specifically to dismantle these concentrations. Today, regulators enforce stricter capital buffers, stress testing (CCAR), and limits on counterparty exposures to ensure that a localized failure in one asset class or institution can never again threaten to pull down the entire global financial ecosystem.

Sector balance


Pension and Insurance funds need balance. They have payment obligations that people depend on. Investing for growth needs to be made within the parameters of delivering cash flow and keeping assets secure.


Look at Space Exploration Technologies Corp. (SPCX) for example.


Potential for growth makes it look like an attractive investment.


But it pays no dividend and loses money every quarter EPS -1.10 per share.




.

PepsiCo, Inc. (PEP) on the other hand makes money and pays a nice quarterly dividend




It is valued at 1/10 the price of SPCX 

earns $7.63 cents per share

Has a PE Ratio of 16.76

Pays a dividend per share of $5.92 vents per share

Dividend yield is $4.61% as of 9/29/26


Before we dive into metrics lets look at how we would avoid the pitfalls of over concentration.


Let's take the S&P 500 for example.



Sector

S&P 500 Weight

Technology

38.69%

Financial Services

12.06%

Communication Services

9.50%

Consumer Cyclical

9.31%

Healthcare

9.28%

Industrials

7.75%

Consumer Defensive

4.46%

Energy

3.48%

Utilities

1.98%

Real Estate

1.80%

Basic Materials

1.68%


Learning lessons from the crash of 2008 investors need to stay within percentages of certain sectors to avoid the dangers of over concentration.


Investors who lost 90% of their investment in Citibank stock during the crash would limit their losses if they did not over concentrate on financials.


Most Defensive Sectors

Consumer Staples

Why they outperformed: People still needed to buy groceries, household goods, and personal care items regardless of how bad the economy or banking system looked.

Standouts: Discount retailers, warehouse clubs, and low-cost consumer brands (like Walmart) saw relative stability because consumers actively traded down from luxury or mid-tier brands to discount alternatives.

Healthcare

Why they outperformed: Medical care, pharmaceuticals, and essential treatments are non-discretionary expenses. People cannot easily cut healthcare out of their budgets during a recession. While pharmaceutical and biotech stocks still dropped, they experienced far lower drawdowns than tech, industrials, or financials.

Utilities

Why they outperformed: Electricity, water, and gas are mandatory utilities. Furthermore, utility companies traditionally offer stable, high dividend yields, which attracted investors looking for shelter from the violent volatility tearing through growth and financial equities.

Other sectors performed better like Food, healthcare and Utilities because people need them to carry on with their lives.


Building a balanced portfolio


A balanced stock portfolio would invest in each sector and keep percentages within the sector percentages limiting over concentration risk.


Also, not having single stock risk in one sector so buying multiple stocks per sector to ensure that one stock can’t hurt the entire portfolio.


Data driven metrics


Lets ask Gemini


What are the primary yfinance fields that should be focused on when deciding what stock to buy?


For the purpose of a simple example lets just focus on one set of metrics for valuation.


Primary yfinance Fields by Category

Valuation Metrics (Is the stock priced fairly relative to earnings/assets?)


forwardPE & trailingPE: Price-to-Earnings ratios. Comparing forwardPE (expected 12-month earnings) to trailingPE (past 12 months) indicates whether analysts expect earnings growth or contraction.

The Price-to-Earnings (P/E) ratio is one of the most widely used valuation metrics in investing. Put simply, it tells you how much investors are willing to pay for every $1 of a company's earnings.

If a stock has a P/E of 20, it means investors are paying $20 for every $1 of annual profit the company generates.

The two primary variations of this metric—Trailing P/E and Forward P/E—look at the "E" (earnings) through different lenses: the rearview mirror versus the windshield.

Trailing P/E (Historical)

What it is: Trailing P/E calculates the ratio using historical, actual earnings from the past 12 months (often called Trailing Twelve Months or TTM).

The Formula:
TrailingP/E=CurrentStockPriceTrailing12-MonthEarningsPerShare(EPS)

Pros & Cons: It is grounded in hard, audited financial facts rather than guesses. However, because it looks backward, it can be misleading if a company's past profits do not reflect its current or future business reality.

Forward P/E (Projected)

What it is: Forward P/E replaces past earnings with analyst consensus estimates for the company’s profits over the next 12 months.

The Formula:
ForwardP/E=CurrentStockPriceEstimatedNext12-MonthEarningsPerShare(EPS)

Pros & Cons: It is forward-looking, making it useful for evaluating high-growth companies or businesses undergoing rapid transformation. The drawback is that forecasts are just educated guesses and can be wrong.

Practical Example: PepsiCo (PEP)

Applying these concepts to PepsiCo (PEP) illustrates how they work in practice:

Current Stock Price: $128.50

Trailing EPS (TTM): $7.63 (actual audited earnings over the past year)

Estimated Forward EPS: $8.00 - $8.90 (what Wall Street analysts project PEP will earn over the next 12 months)

Calculating PepsiCo's Ratios:

Trailing P/E Calculation:
Trailing P/E = $128.50\$7.63 approx 16.8x

Meaning: Investors are paying roughly $16.84 for every dollar of profit PepsiCo actually generated over the last year.

Forward P/E Calculation:
Using a consensus forward earnings estimate of roughly $8.90 per share:
Forward P/E = $128.50\$8.90 14.4x

Meaning: Investors are paying roughly $14.40 for every dollar of profit PepsiCo is expected to earn over the coming year.

How to Use Them Together

If a company's Forward P/E is lower than its Trailing P/E (as seen in the PepsiCo example), it implies that analysts expect earnings to grow over the next year, making the stock effectively "cheaper" on a forward-looking basis.

If a company's Forward P/E is much higher than its Trailing P/E, it usually means earnings are expected to drop, or the stock is a high-growth tech/disruptor where investors are heavily pricing in future expansion.


pegRatio: Price/Earnings-to-Growth ratio. A PEG ratio under 1.0 often suggests a stock may be undervalued relative to its earnings growth rate.

The Price/Earnings-to-Growth (PEG) ratio is a financial metric that builds upon the standard P/E ratio by factoring in a company's expected earnings growth rate.

While a traditional P/E ratio tells you how expensive a stock is relative to its current profits, it has a blind spot: it doesn't tell you how fast those profits are growing. A stock with a high P/E might look expensive at first glance, but if its earnings are skyrocketing by 40% a year, it could actually be a bargain. Conversely, a low P/E stock with zero growth might actually be overpriced. The PEG ratio bridges that gap.

The Formula



(Note: In the denominator, the growth rate is typically expressed as a whole number rather than a decimal—e.g., use 5 for a 5% growth rate, not 0.05).

PepsiCo (PEP) Example

Applying the PEG ratio framework to PepsiCo (PEP) illustrates how it evaluates a slow-and-steady consumer defensive stock versus a high-growth tech stock:

P/E Ratio (Trailing): 16.8x

Expected Annual Earnings Growth Rate (Next 5 Years): 4.3% to 4.5%

Calculating PepsiCo's PEG Ratio:


PEGRatio=16.84.53.7

(Live market trackers using slightly different rolling growth metrics or forward estimates often place PepsiCo's PEG ratio in the 2.9 to 3.5 range).

How to Interpret the PEG Ratio

PEG = 1.0 (Fairly Valued): Traditionally, a PEG ratio of 1.0 indicates that a stock's price is perfectly aligned with its earnings growth rate (e.g., a P/E of 20 paired with a 20% growth rate).

PEG < 1.0 (Potentially Undervalued): A ratio below 1.0 suggests that the stock may be underpriced relative to how fast its earnings are growing ("growth is on sale").

PEG > 1.0 (Growth is Expensive): A ratio significantly above 1.0 implies that investors are paying a steep premium relative to the actual speed of earnings growth.

Why PepsiCo’s PEG is Higher than 1.0

With a PEG ratio hovering above 3.0, PepsiCo looks "expensive" strictly from a growth-adjusted perspective. However, this is common for Consumer Staples giants:

Investors aren't buying PepsiCo for explosive 20% annual earnings growth.

Instead, they pay a premium for stability, recession resilience, and reliable dividend growth (PepsiCo is a classic Dividend King).

Because the PEG ratio penalizes slow-growing companies, it is most effective when comparing companies within the same sector (e.g., comparing PepsiCo directly to Coca-Cola or Keurig Dr Pepper) rather than cross-sector comparisons between a consumer defensive stock and a high-flying technology stock.




priceToBook (p/b): Price-to-Book ratio. Compares market value to balance sheet net asset value (crucial for capital-intensive sectors and banking).

What is the Price-to-Book (P/B) Ratio?

The Price-to-Book (P/B) ratio compares a company’s market valuation (its stock price) to its book value (its net asset value on the balance sheet).

The Book Value: This represents total assets minus total liabilities. In theory, it is what shareholders would receive if the company liquidated all its physical assets and paid off all its debts today.

The Formula:

  • P/BRatio=CurrentStockPriceBookValuePerShare(BVPS)

A P/B ratio of 2.0, for instance, means investors are paying $2.00 for every $1.00 of net assets the company owns.

Practical Example: PepsiCo (PEP)

Applying the P/B framework to PepsiCo (PEP) illustrates how the ratio behaves for a massive, asset-backed consumer goods enterprise:

Current Stock Price: $128.00

Book Value Per Share (BVPS): $16.30 (calculated as total stockholders' equity divided by shares outstanding)

Calculating PepsiCo's P/B Ratio:

P/B Ratio = $128.00\$16.30 = 7.9

This means the stock market values PepsiCo at roughly 7.9 times the net accounting value of its physical assets.

How to Interpret the P/B Ratio

P/B below 1.0: The stock is trading for less than the accounting value of its net assets. This can signal a deep bargain, but it can also indicate a "value trap"—a company with structural problems, burning cash, or holding toxic assets that accounting rules haven't yet written down (common in troubled banks).

P/B above 1.0: The market values the company at a premium over its baseline net assets because of its ability to generate high returns on equity (ROE) and profits.

Why PepsiCo’s P/B is Relatively High (~7.9x)

At first glance, a P/B ratio near 8.0 might look expensive, but context is essential:

Intangible Assets: Traditional accounting rules prevent companies from placing their most valuable assets—like world-class brand names (Pepsi, Gatorade, Frito-Lay)—on the balance sheet at their true economic worth.

Asset-Light vs. Capital-Intensive: Highly profitable, cash-generative consumer staple companies often maintain low physical book values relative to their massive market power, naturally pushing their P/B ratios higher than asset-heavy industries like manufacturing or utilities.

enterpriseToEbitda: Enterprise Value to EBITDA. Neutralizes differing debt structures across industry competitors.

The Enterprise Value-to-EBITDA (EV/EBITDA) ratio is one of the most robust valuation multiples used by professional analysts. While the standard P/E ratio only looks at a company’s share price relative to net income, EV/EBITDA evaluates the entire total value of the business relative to its core cash earnings before accounting for debt, taxes, and capital structure.

Breaking Down the Components

To understand the ratio, you have to look at its two parts:

Numerator: Enterprise Value (EV)
Enterprise Value=Market Capitalization+Total Debt−Cash and Cash Equivalents

Think of EV as the true "cost" to buy out an entire company. If you bought all its shares (Market Cap), you would also have to pay off its debts, but you would get to keep its cash pile.

Denominator: EBITDA Earnings Before Interest, Taxes, Depreciation, and Amortization. This measures a company's raw operating profitability, stripping away the effects of financing decisions (interest/taxes) and non-cash accounting write-offs (depreciation/amortization).

Practical Example: PepsiCo (PEP)

Applying this framework to PepsiCo (PEP) illustrates how the calculation works using current operational scale:

Enterprise Value (EV): ≈$218.6 billion (Market cap plus net debt load)

Trailing EBITDA: ≈$18.6 billion (Core operating earnings over the past 12 months)

Calculating PepsiCo's EV/EBITDA Ratio:

EV/EBITDA=$18.6 billion$218.6 billion​≈11.7x

What this means: Investors are paying roughly $11.70 for every $1.00 of core operating cash earnings generated by PepsiCo's snack and beverage empire.

Why EV/EBITDA is Often Preferred Over P/E

Capital Structure Neutral: Two companies might have identical operating businesses, but one might be heavily loaded with debt while the other holds a massive cash reserve. A standard P/E ratio can be skewed by the interest expenses and tax differences resulting from that debt. EV/EBITDA strips that away, showing how efficiently the core business generates cash regardless of how it is financed.

Accounts for Debt: If a company has a low P/E ratio because its stock is cheap, but it is drowning in billions of hidden debt, the P/E ratio can look deceptively attractive. EV/EBITDA immediately flags this because the total debt is added directly into the numerator (Enterprise Value).

Cross-Border and Cross-Industry Comparisons: Because it ignores differing tax jurisdictions (taxes vary wildly by country or state) and depreciation methods (which depend on how aggressively a company buys equipment), it allows for cleaner comparisons between international peers.


Additional definitions.


Debt-to-Equity ratio is a fundamental financial health and leverage metric that compares a company’s total liabilities (debt) to the capital supplied by its shareholders (equity).

Put simply, it answers the question: How much of the company's operations are being funded by borrowed money versus money put in by owners and earned as retained profits?


Debt-to-EquityRatio=TotalLiabilitiesTotalShareholders'Equity

Total Liabilities: Everything the company owes, including short-term loans, accounts payable, bonds, and long-term debt.

Total Shareholders' Equity: The net worth of the company (Total Assets minus Total Liabilities). This represents the capital belonging to the shareholders.

What is Dividend Yield?

The dividend yield is a financial ratio that measures how much cash flow (dividends) a company pays out each year relative to its current share price. Expressed as a percentage, it tells investors the cash return they are generating from dividend distributions alone for every dollar invested.

DividendYield=AnnualDividendsPerShareCurrentSharePrice100

Annual Dividends Per Share: The total amount of cash dividends paid out per share over a 12-month period (calculated either retrospectively using the trailing four quarters or forward-looking by multiplying the most recent quarterly payout by four).

Current Share Price: The prevailing market price of a single share of stock.

(FCF) measures the actual cash a company generates after accounting for the money spent to maintain or expand its physical assets (like property, plants, equipment, and technology).

Unlike net income—which includes accounting adjustments like depreciation and non-cash revenue—free cash flow represents pure, unencumbered cash liquidity. It is the money left over that a company can freely deploy to pay dividends, buy back stock, reduce debt, or fund new acquisitions.

FreeCashFlow=OperatingCashFlow(OCF)-CapitalExpenditures(CapEx)

Operating Cash Flow (OCF): The cash generated directly from a company’s normal daily business operations (found on the Statement of Cash Flows).

Capital Expenditures (CapEx): The cash spent to purchase, upgrade, or maintain physical assets and infrastructure.

What are Gross Margins?

The gross margin is a profitability metric that shows the percentage of revenue that exceeds the direct costs associated with producing or delivering a company's goods and services.

Put simply, it tells you how much money a company keeps from each dollar of sales after paying off the direct expenses required to make its products (such as raw materials, factory labor, and manufacturing overhead).

Total Revenue: The total top-line money brought in from sales.

Cost of Goods Sold (COGS): The direct costs tied specifically to creating the product (e.g., aluminum cans, corn syrup, packaging, and factory assembly line wages for a beverage company). It excludes indirect overhead like corporate salaries, marketing, and R&D.

What is Net Interest Margin (NIM)?

is a profitability and efficiency metric used primarily in the banking and financial services sector. It measures how successfully a bank is managing its interest-earning assets versus its interest-bearing liabilities.

Put simply, NIM is the bank's "net profit margin" on lending money: it calculates the difference between the interest a bank earns on loans (like mortgages, car loans, and commercial debt) and the interest it pays out to depositors and lenders, expressed as a percentage of its earning assets.

NetInterestMargin(NIM)=InterestIncomeGenerated-InterestPaidonDeposits/DebtAverageEarningAssets

Interest Income Generated: The total interest collected from loans, mortgages, and securities held by the bank.

Interest Paid: The interest paid out to customers on savings accounts, certificates of deposit (CDs), and borrowed funds.

Average Earning Assets: The average value of all interest-generating assets (loans and investments) over the period.

What are Operating Margin and Net Margin?

While gross margin only looks at the direct cost of making a product, operating margin and net margin step further down the income statement to reveal how efficiently a company manages all its overhead, administrative expenses, taxes, and interest obligations.

Operating Margin (EBIT Margin) measures the percentage of revenue left over after paying for both the direct costs of production (COGS) and the indirect operating expenses required to keep the business running day-to-day (such as salaries, rent, research and development, and marketing).


What it tells you: It evaluates management's core operational efficiency. It strips out financing choices (debt interest) and tax structures, focusing strictly on how much profit the primary business operations generate from sales.

Example: If a company has an operating margin of 15%, it keeps 15 cents of operating profit for every dollar of sales after covering all operational costs.

Net Margin (Net Profit Margin) is the ultimate bottom-line profitability metric. It measures the percentage of revenue that remains as pure profit after every single expense—including COGS, operating expenses, interest on debt, taxes, and one-off costs—has been completely paid off.



What it tells you: This is what shareholders truly care about. It accounts for the entire financial picture, showing how much of every top-line dollar actually trickles down to net earnings.

Example: If a company reports a net margin of 10%, it means $0.10 of every dollar earned in sales becomes actual net profit for the company.

The dividend payout ratio is a critical financial metric that measures the percentage of a company’s net income that is paid out to shareholders as dividends.

Put simply, it answers the question: Out of every dollar of net profit a company generates, how many cents are being handed directly back to investors as cash dividends, and how much is being kept inside the business?

The payout ratio can be calculated using either total company figures or on a per-share basis:

Dividends Per Share: The total cash dividend paid out per share over the course of the year.

Earnings Per Share (EPS): The company’s net income divided by its total shares outstanding.

Regulatory capital is the minimum amount of loss-absorbing capital that financial regulators (such as the Federal Reserve, the FDIC, or international bodies like the Basel Committee) require banks and financial institutions to hold.

Put simply, it is the financial safety buffer a bank must maintain to absorb unexpected losses from bad loans, market crashes, or operational failures without collapsing or requiring a taxpayer-funded bailout.

Regulatory Capital Matters

Before the 2008 financial crisis, many major investment banks operated with dangerously thin cushions of their own money—borrowing heavily (sometimes leveraging 30-to-1) to buy toxic assets. When those assets lost value, the banks instantly became insolvent.

Post-crisis regulatory frameworks (like Basel III and the Dodd-Frank Act) dramatically strengthened these requirements, forcing banks to hold higher-quality capital and maintain strict safety buffers.

The Tiers of Regulatory Capital

Regulators divide a bank's capital into distinct categories based on how reliably and quickly that capital can absorb losses:

Tier 1 Capital (Core Capital):

This is the highest-quality, most reliable capital a bank owns. It consists primarily of common stock, disclosed reserves, and retained earnings.

Tier 1 capital absorbs losses immediately while the bank continues to operate normally, keeping the lights on and protecting depositor funds.

Tier 2 Capital (Supplementary Capital):

This is secondary capital, including subordinated debt and certain hybrid financial instruments.

It is less reliable than Tier 1 because it primarily absorbs losses only if the bank enters liquidation or bankruptcy, providing a secondary layer of protection for senior creditors and depositors.

Return on Equity (ROE) is one of the most important profitability metrics in investing. It measures how efficiently a company uses the money invested by its shareholders to generate net profit.

Put simply, it answers the question: For every dollar of equity (net worth) that shareholders have put into the business, how many cents of profit does management successfully generate in return?


ROE=NetIncomeShareholders'Equity100

Net Income: The company’s total bottom-line profit after all expenses, taxes, and interest have been paid over a 12-month period.

Shareholders' Equity: The net worth of the company (Total Assets minus Total Liabilities). This represents the capital contributed by investors plus retained earnings accumulated over time.

Return on Invested Capital (ROIC) is widely considered by institutional investors and fundamental analysts to be the gold standard of profitability metrics.

While metrics like Return on Equity (ROE) look strictly at shareholder money, ROIC measures how well a company allocates all of its available capital—both equity from shareholders and debt from lenders—into profitable, money-making business investments.

Put simply, it answers the question: For every dollar of total capital tied up in the business, how much pure operating profit does management generate?



ROIC=NetOperatingProfitAfterTaxes(NOPAT)InvestedCapital100


NOPAT (Net Operating Profit After Taxes): The core operating profit a company generates from its normal operations, adjusted as if it had no debt financing costs (no interest expense) and adjusted for taxes. It is pure operating earnings.

Invested Capital: The total amount of money actively put to work in the business.


 It is generally calculated as:



(By subtracting excess cash, ROIC penalizes companies that hoard idle cash rather than putting it to productive use).

Revenue growth measures the percentage increase (or decrease) in a company's total sales—often called the "top-line"—over a specific period, such as year-over-year (YoY) or quarter-over-quarter (QoQ).

Put simply, it answers the question: Is customer demand for the company’s products or services expanding, and is the business successfully scaling its market presence?


Current Period Revenue: Total sales generated over the most recent timeframe (e.g., this quarter or this year).

Prior Period Revenue: Total sales generated over the comparable historical timeframe (e.g., the same quarter last year).


Sector by Sector decisions


Different economic sectors possess vastly different business models, capital structures, and earnings drivers. Because of this, certain financial metrics carry much more weight depending on the sector you are analyzing.

Sector-by-Sector Metric Prioritization

Information Technology

Primary Focus: Growth & Future Valuation

Key Metrics: Revenue Growth, PEG Ratio, Forward P/E, and Free Cash Flow.

Why: Tech companies often reinvest heavily rather than paying high dividends. Investors focus on how fast top-line revenues are scaling and whether high valuations are justified by future earnings growth.

Financial Services

Primary Focus: Asset Quality, Profitability & Solvency

Key Metrics: Price-to-Book (P/B), Return on Equity (ROE), and Net Interest Margin / Regulatory Capital.

Why: Traditional debt-to-equity ratios don't apply well to banks because holding debt (deposits and leverage) is their core business model. Instead, P/B measures asset valuation, and ROE tracks how efficiently they generate profit from shareholder equity.

Communication Services

Primary Focus: Cash Generation & Subscriber Growth

Key Metrics: Free Cash Flow, EV/EBITDA, and Revenue Growth.

Why: Ranging from telecom giants to media/streaming firms, these businesses require massive capital expenditures (e.g., 5G rollouts, content creation). EV/EBITDA and Free Cash Flow reveal their true operating cash health after heavy infrastructure investments.

Consumer Cyclical (Discretionary)

Primary Focus: Economic Sensitivity & Margins

Key Metrics: Operating/Net Margins, Revenue Growth (YoY), and Trailing/Forward P/E.

Why: These companies sell non-essential goods (autos, luxury items, apparel) that boom and bust with consumer confidence. Monitoring margin compression during downturns is critical.

Healthcare

Primary Focus: Innovation R&D and Cash Stability

Key Metrics: Free Cash Flow, Forward P/E, and Gross Margins.

Why: Biotechnology and pharmaceutical firms spend heavily on R&D with long pipelines. Stable cash flows and strong gross margins help determine which firms can fund drug trials independently versus those reliant on volatile debt or dilution.

Industrials

Primary Focus: Operational Efficiency & Capital Intensity

Key Metrics: EV/EBITDA, Free Cash Flow, Debt-to-Equity, and Return on Invested Capital (ROIC).

Why: Aerospace, defense, machinery, and transportation companies manage heavy physical asset bases. EV/EBITDA neutralizes differences in debt structures across capital-heavy competitors.

Consumer Defensive (Staples)

Primary Focus: Shareholder Returns & Pricing Power

Key Metrics: Dividend Yield, Payout Ratio, Gross Margins, and Trailing P/E.

Why: Companies like PepsiCo or Walmart offer stable, slow growth. Investors prioritize dividend reliability, low payout risk, and stable gross margins (indicating pricing power against inflation).

Energy

Primary Focus: Commodity-Cycle Cash Flow & Leverage

Key Metrics: EV/EBITDA, Free Cash Flow, and Debt-to-Equity.

Why: Energy companies experience wild cash-flow swings tied to oil and gas prices. Free cash flow generation during commodity upswings is vital for paying down debt and funding dividends.

Utilities

Primary Focus: Dividend Safety & Regulated Leverage

Key Metrics: Dividend Yield, Payout Ratio, and Debt-to-Equity.

Why: Utilities operate as regulated monopolies with steady, predictable revenues. Investors treat them like bond proxies, looking closely at dividend safety and how they manage long-term infrastructure debt.

Real Estate (REITs)

Primary Focus: Asset Valuation & Cash Yield

Key Metrics: Dividend Yield, Price-to-Book (P/B), and Debt-to-Equity.

Why: Real estate investment trusts distribute most of their earnings as dividends. While standard accounting metrics like P/E can be distorted by property depreciation, asset backing (P/B) and leverage are critical risk indicators.

Basic Materials

Primary Focus: Cyclical Efficiency & Debt Management

Key Metrics: EV/EBITDA, Debt-to-Equity, and Free Cash Flow.

Why: Mining, chemicals, and metal producers are heavily exposed to global economic cycles. Monitoring debt-to-equity prevents over-leveraging during commodity price downturns.




Field dump


#!/usr/bin/env python3.12

import sqlalchemy

import csv

import yfinance as yf

from google.cloud.sql.connector import Connector


# --- SECTION 1: DATABASE CONNECTION SETUP ---

connector = Connector()


def getconn():

    conn = connector.connect(

        "sentiment-analysis-379200:us-east1:fintech",

        "pymysql",

        user="root",

        password="Uconnstamford1!",

        db="jiacovacci",

        enable_iam_auth=False

    )

    return conn


# Create the SQLAlchemy engine pool

pool = sqlalchemy.create_engine(

    "mysql+pymysql://",

    creator=getconn,

    pool_pre_ping=True,

)


# --- SECTION 2: FETCH YFINANCE METRICS ---

def get_yfinance_metrics(ticker):

    """Fetches key financial ratios and metrics from yfinance for a given ticker."""

    metrics = {

        "forwardPE": None,

        "trailingPE": None,

        "priceToBook": None,

        "pegRatio": None,

        "ebitda": None,

        "debtToEquity": None,

        "dividendYield": None,

        "freeCashflow": None,

        "grossMargins": None,

        "operatingMargins": None,

        "profitMargins": None,

        "payoutRatio": None,

        "returnOnEquity": None,

        "returnOnAssets": None,

        "revenueGrowth": None,

    }

   

    if not ticker:

        return metrics


    try:

        stock = yf.Ticker(ticker.strip())

        info = stock.info

       

        # Map yfinance info keys safely

        for key in metrics.keys():

            metrics[key] = info.get(key, None)

           

    except Exception as e:

        # Silently handle rate limits or missing tickers during batch iteration

        pass

       

    return metrics


# --- SECTION 3: MULTI-TABLE JOIN & CSV EXPORT ---

def join_and_export_to_csv():

    """Joins database tables, fetches yfinance metrics per ticker, and saves to a CSV file."""

   

    sql_query = """

        SELECT

            -- Security Fields

            s.figi,

            s.name AS security_name,

            s.ticker,

            s.exchCode,

            s.securityType,

            s.marketSector,

            s.shareClassFIGI,

            s.securityType2,

            s.securityDescription,

           

            -- Company Fields

            c.Comp_Name,

            c.Comp_Street,

            c.Comp_City,

            c.Comp_State,

            c.Comp_Zip,

            c.Comp_Country,

            c.Sector AS company_sector,

            c.Industry,

           

            -- Sector Fields

            sec.sec_name,

            sec.sec_percentage,

            sec.sec_desc

           

        FROM security s

        JOIN company c ON s.ticker = c.Ticker

        LEFT JOIN sector sec ON c.Sector = sec.sec_name;

    """

   

    try:

        with pool.connect() as db_conn:

            result = db_conn.execute(sqlalchemy.text(sql_query))

           

            db_column_names = list(result.keys())

            rows = result.fetchall()


            if not rows:

                print("No matching records found across the joined tables.")

                return


            # Define yfinance metric header names to append

            yf_metric_keys = [

                "forwardPE", "trailingPE", "priceToBook", "pegRatio", "ebitda",

                "debtToEquity", "dividendYield", "freeCashflow", "grossMargins",

                "operatingMargins", "profitMargins", "payoutRatio", "returnOnEquity",

                "returnOnAssets", "revenueGrowth"

            ]

           

            # Combine SQL columns and yfinance metric columns for headers

            all_column_names = db_column_names + yf_metric_keys

            ticker_idx = db_column_names.index("ticker")


            processed_data = []

            print(f"Processing {len(rows)} records with yfinance...")


            for row in rows:

                row_list = list(row)

                ticker = row_list[ticker_idx]

               

                # Fetch yfinance metrics for this ticker

                yf_data = get_yfinance_metrics(ticker)

               

                # Append yfinance values in order

                for key in yf_metric_keys:

                    row_list.append(yf_data.get(key))


                processed_data.append(row_list)


            # Write to CSV

            filename = "enriched_security_company.csv"

            with open(filename, mode='w', newline='', encoding='utf-8') as f:

                writer = csv.writer(f)

                writer.writerow(all_column_names)

                writer.writerows(processed_data)

           

            print(f"Successfully exported {len(processed_data)} enriched records to {filename}")


    except Exception as e:

        print(f"Database Error: {e}")

    finally:

        connector.close()


# --- Main Execution ---

if __name__ == "__main__":

    join_and_export_to_csv()


Simple Strategy lowest PE


Take $100,000 and buy the lowest trailing PE per sector, 3 stocks per sector


change program to buy 3 stocks per each sector based on the lowest trailingPE, spend $100,000 and use sector percentage for the dollar value purchased in each sector, split buys evenly, strategy will be PE, use yfinance to get stock price buy shares based upon the total value of buy per stock  create transactions and holdings records - desc transactions;

+------------------+--------------------+------+-----+---------+----------------+

| Field            | Type               | Null | Key | Default | Extra          |

+------------------+--------------------+------+-----+---------+----------------+

| transaction_id   | int                | NO   | PRI | NULL    | auto_increment |

| strategy         | varchar(50)        | YES  | MUL | NULL    |                |

| ticker           | varchar(10)        | YES  |     | NULL    |                |

| transaction_date | date               | YES  |     | NULL    |                |

| transaction_type | enum('BUY','SELL') | YES  |     | NULL    |                |

| quantity         | decimal(19,4)      | YES  |     | NULL    |                |

| price_per_share  | decimal(19,2)      | YES  |     | NULL    |                |

+------------------+--------------------+------+-----+---------+----------------+

7 rows in set (0.01 sec)


mysql> Field            | Type          | Null | Key | Default | Extra |

+------------------+---------------+------+-----+---------+-------+

| Holding_strategy | varchar(50)   | NO   | PRI | NULL    |       |

| Holdings_date    | date          | NO   | PRI | NULL    |       |

| Holdings_ticker  | varchar(20)   | NO   | PRI | NULL    |       |

| purchase_price   | decimal(12,2) | YES  |     | NULL    |       |

| holdings_amount  | int           | YES  |     | NULL    |       |

| purchase_date    | date          | YES  |     | NULL    |       |

| purchase_cost    | decimal(19,4) | YES  |     | NULL    |       |

+-------------


Here is the updated Python program. It queries your database to join security, company, and sector tables, filters valid tickers using live stock prices and trailing P/E ratios from yfinance, allocates the $100,000 capital pool based on the defined sector percentages, splits buys evenly among the top 3 lowest P/E stocks per sector, calculates the share quantities, and inserts the resulting records directly into both your transactions and holdings tables in MySQL. 


pe_strategy.py


#!/usr/bin/env python3.12

import datetime

import sqlalchemy

import yfinance as yf

from google.cloud.sql.connector import Connector


# --- SECTION 1: DATABASE CONNECTION SETUP ---

connector = Connector()


def getconn():

    conn = connector.connect(

        "sentiment-analysis-379200:us-east1:fintech",

        "pymysql",

        user="root",

        password="Uconnstamford1!",

        db="jiacovacci",

        enable_iam_auth=False

    )

    return conn


pool = sqlalchemy.create_engine(

    "mysql+pymysql://",

    creator=getconn,

    pool_pre_ping=True,

)


# --- SECTION 2: PORTFOLIO EXECUTION & DB INSERTION ---

def execute_pe_portfolio_strategy():

    TOTAL_CAPITAL = 100000.00

    STRATEGY_NAME = "PE"

    TODAY = datetime.date.today()


    # 1. Pull sector allocation percentages and company/security mappings from database

    sql_query = """

        SELECT

            s.ticker,

            c.Sector AS sector_name,

            sec.sec_percentage

        FROM security s

        JOIN company c ON s.ticker = c.Ticker

        JOIN sector sec ON c.Sector = sec.sec_name

        WHERE sec.sec_percentage IS NOT NULL AND sec.sec_percentage > 0;

    """


    try:

        with pool.connect() as db_conn:

            result = db_conn.execute(sqlalchemy.text(sql_query))

            rows = result.fetchall()


            if not rows:

                print("No records found with valid sector percentages.")

                return


            # Group stocks by sector

            sectors_data = {}

            for row in rows:

                ticker = row[0]

                sector = row[1]

                try:

                    percentage = float(row[2])

                except (TypeError, ValueError):

                    continue

               

                if sector not in sectors_data:

                    sectors_data[sector] = {

                        "percentage": percentage,

                        "tickers": []

                    }

                if ticker not in sectors_data[sector]["tickers"]:

                    sectors_data[sector]["tickers"].append(ticker)


            print(f"Fetched {len(rows)} database records across {len(sectors_data)} sectors.")


            # 2. Evaluate Trailing PE and current price via yfinance for each stock

            sector_rankings = {}

            for sector, data in sectors_data.items():

                stock_metrics = []

                print(f"Evaluating tickers for sector: {sector}...")

               

                for ticker in data["tickers"]:

                    try:

                        clean_ticker = ticker.strip()

                        tk = yf.Ticker(clean_ticker)

                        info = tk.info

                       

                        trailing_pe = info.get("trailingPE")

                        current_price = info.get("currentPrice") or info.get("regularMarketPrice") or info.get("previousClose")


                        if trailing_pe is not None and current_price is not None:

                            pe_val = float(trailing_pe)

                            price_val = float(current_price)

                           

                            if pe_val > 0 and price_val > 0:

                                stock_metrics.append({

                                    "ticker": clean_ticker.upper(),

                                    "trailingPE": pe_val,

                                    "price": price_val

                                })

                    except Exception as e:

                        pass


                # Sort by lowest trailing PE and pick top 3

                stock_metrics.sort(key=lambda x: x["trailingPE"])

                top_3 = stock_metrics[:3]

               

                if top_3:

                    sector_rankings[sector] = {

                        "percentage": data["percentage"],

                        "selected_stocks": top_3

                    }


            # 3. Calculate capital allocation and share quantities

            transaction_records = []

            holding_records = []


            print("\n--- Portfolio Allocation Breakdown ---")

            for sector, details in sector_rankings.items():

                sec_percentage = details["percentage"]

                sec_capital = TOTAL_CAPITAL * (sec_percentage / 100.0)

                stocks = details["selected_stocks"]

               

                num_stocks = len(stocks)

                if num_stocks == 0:

                    continue

               

                capital_per_stock = sec_capital / num_stocks


                print(f"\nSector: {sector} | Allocation: {sec_percentage}% (${sec_capital:,.2f}) split across {num_stocks} stock(s):")


                for stock in stocks:

                    ticker = stock["ticker"]

                    price = stock["price"]

                    pe = stock["trailingPE"]

                   

                    quantity = capital_per_stock / price

                    actual_cost = quantity * price


                    print(f"  > Ticker: {ticker} | Trailing PE: {pe:.2f} | Price: ${price:.2f} | Invested: ${actual_cost:,.2f} | Shares: {quantity:.4f}")


                    # Prepare transaction tuple

                    transaction_records.append({

                        "strategy": STRATEGY_NAME,

                        "ticker": ticker,

                        "transaction_date": TODAY,

                        "transaction_type": "BUY",

                        "quantity": round(quantity, 4),

                        "price_per_share": round(price, 2)

                    })


                    # Prepare holding tuple

                    holding_records.append({

                        "Holding_strategy": STRATEGY_NAME,

                        "Holdings_date": TODAY,

                        "Holdings_ticker": ticker,

                        "purchase_price": round(price, 2),

                        "holdings_amount": int(round(quantity)),

                        "purchase_date": TODAY,

                        "purchase_cost": round(actual_cost, 4)

                    })


            # 4. Insert records into MySQL database

            if not transaction_records:

                print("\nNo valid stock selections made. Aborting database insertion.")

                return


            print("\nInserting strategy, transactions, and holdings into MySQL database...")

           

            # Ensure the strategy exists in the parent strategy table first

            strategy_insert_sql = sqlalchemy.text("""

                INSERT IGNORE INTO strategy (Strategy_name) VALUES (:strategy);

            """)

            db_conn.execute(strategy_insert_sql, {"strategy": STRATEGY_NAME})


            # Insert Transactions

            trans_insert_sql = sqlalchemy.text("""

                INSERT INTO transactions (strategy, ticker, transaction_date, transaction_type, quantity, price_per_share)

                VALUES (:strategy, :ticker, :transaction_date, :transaction_type, :quantity, :price_per_share);

            """)

            db_conn.execute(trans_insert_sql, transaction_records)


            # Insert Holdings

            hold_insert_sql = sqlalchemy.text("""

                INSERT INTO holdings (Holding_strategy, Holdings_date, Holdings_ticker, purchase_price, holdings_amount, purchase_date, purchase_cost)

                VALUES (:Holding_strategy, :Holdings_date, :Holdings_ticker, :purchase_price, :holdings_amount, :purchase_date, :purchase_cost)

                ON DUPLICATE KEY UPDATE

                    purchase_price = VALUES(purchase_price),

                    holdings_amount = holdings_amount + VALUES(holdings_amount),

                    purchase_cost = purchase_cost + VALUES(purchase_cost);

            """)

            db_conn.execute(hold_insert_sql, holding_records)


            # Commit the transaction on the active connection

            db_conn.commit()

            print("Successfully committed strategy, transactions, and holdings to database!")


    except Exception as e:

        print(f"Database Execution Error: {e}")

    finally:

        connector.close()


if __name__ == "__main__":

    execute_pe_portfolio_strategy()



$ cd openFIGI/

$ python pe_strategy.py

Fetched 503 database records across 11 sectors.

Evaluating tickers for sector: Basic Materials...

Evaluating tickers for sector: Communication Services...

Evaluating tickers for sector: Consumer Cyclical...

Evaluating tickers for sector: Consumer Defensive...

Evaluating tickers for sector: Energy...

Evaluating tickers for sector: Financial Services...

Evaluating tickers for sector: Healthcare...

Evaluating tickers for sector: Industrials...

Evaluating tickers for sector: Real Estate...

Evaluating tickers for sector: Technology...

Evaluating tickers for sector: Utilities...


--- Portfolio Allocation Breakdown ---


Sector: Basic Materials | Allocation: 1.68% ($1,680.00) split across 3 stock(s):

  > Ticker: CF | Trailing PE: 8.57 | Price: $115.71 | Invested: $560.00 | Shares: 4.8397

  > Ticker: NEM | Trailing PE: 14.64 | Price: $117.09 | Invested: $560.00 | Shares: 4.7826

  > Ticker: CRH | Trailing PE: 14.80 | Price: $84.53 | Invested: $560.00 | Shares: 6.6249


Sector: Communication Services | Allocation: 9.5% ($9,500.00) split across 3 stock(s):

  > Ticker: TTD | Trailing PE: 0.15 | Price: $12.05 | Invested: $3,166.67 | Shares: 262.7939

  > Ticker: CHTR | Trailing PE: 2.90 | Price: $110.67 | Invested: $3,166.67 | Shares: 28.6136

  > Ticker: CMCSA | Trailing PE: 6.92 | Price: $21.60 | Invested: $3,166.67 | Shares: 146.6049


Sector: Consumer Cyclical | Allocation: 9.31% ($9,310.00) split across 3 stock(s):

  > Ticker: LULU | Trailing PE: 8.28 | Price: $96.87 | Invested: $3,103.33 | Shares: 32.0361

  > Ticker: NCLH | Trailing PE: 8.65 | Price: $14.80 | Invested: $3,103.33 | Shares: 209.6847

  > Ticker: CCL | Trailing PE: 9.96 | Price: $25.11 | Invested: $3,103.33 | Shares: 123.5895


Sector: Consumer Defensive | Allocation: 4.46% ($4,460.00) split across 3 stock(s):

  > Ticker: MKC | Trailing PE: 8.05 | Price: $48.40 | Invested: $1,486.67 | Shares: 30.7163

  > Ticker: STZ | Trailing PE: 10.75 | Price: $112.77 | Invested: $1,486.67 | Shares: 13.1832

  > Ticker: DLTR | Trailing PE: 14.23 | Price: $113.30 | Invested: $1,486.67 | Shares: 13.1215


Sector: Energy | Allocation: 3.48% ($3,480.00) split across 3 stock(s):

  > Ticker: EXE | Trailing PE: 7.35 | Price: $84.18 | Invested: $1,160.00 | Shares: 13.7800

  > Ticker: APA | Trailing PE: 8.90 | Price: $42.19 | Invested: $1,160.00 | Shares: 27.4947

  > Ticker: DVN | Trailing PE: 10.15 | Price: $46.60 | Invested: $1,160.00 | Shares: 24.8927


Sector: Financial Services | Allocation: 12.06% ($12,060.00) split across 3 stock(s):

  > Ticker: ALL | Trailing PE: 4.56 | Price: $225.42 | Invested: $4,020.00 | Shares: 17.8334

  > Ticker: SYF | Trailing PE: 7.33 | Price: $71.72 | Invested: $4,020.00 | Shares: 56.0513

  > Ticker: ACGL | Trailing PE: 7.43 | Price: $95.12 | Invested: $4,020.00 | Shares: 42.2624


Sector: Healthcare | Allocation: 9.28% ($9,280.00) split across 3 stock(s):

  > Ticker: UHS | Trailing PE: 7.18 | Price: $175.73 | Invested: $3,093.33 | Shares: 17.6028

  > Ticker: SOLV | Trailing PE: 10.95 | Price: $89.32 | Invested: $3,093.33 | Shares: 34.6320

  > Ticker: CI | Trailing PE: 11.24 | Price: $275.26 | Invested: $3,093.33 | Shares: 11.2379


Sector: Industrials | Allocation: 7.75% ($7,750.00) split across 3 stock(s):

  > Ticker: HON | Trailing PE: 8.13 | Price: $210.13 | Invested: $2,583.33 | Shares: 12.2940

  > Ticker: UAL | Trailing PE: 10.44 | Price: $112.65 | Invested: $2,583.33 | Shares: 22.9324

  > Ticker: PNR | Trailing PE: 13.68 | Price: $53.47 | Invested: $2,583.33 | Shares: 48.3137


Sector: Real Estate | Allocation: 1.8% ($1,800.00) split across 3 stock(s):

  > Ticker: VICI | Trailing PE: 8.99 | Price: $23.20 | Invested: $600.00 | Shares: 25.8621

  > Ticker: SPG | Trailing PE: 14.43 | Price: $204.28 | Invested: $600.00 | Shares: 2.9371

  > Ticker: HST | Trailing PE: 15.06 | Price: $22.44 | Invested: $600.00 | Shares: 26.7380


Sector: Technology | Allocation: 38.69% ($38,690.00) split across 3 stock(s):

  > Ticker: FIS | Trailing PE: 5.12 | Price: $33.35 | Invested: $12,896.67 | Shares: 386.7066

  > Ticker: FSLR | Trailing PE: 10.66 | Price: $176.93 | Invested: $12,896.67 | Shares: 72.8914

  > Ticker: LDOS | Trailing PE: 11.43 | Price: $123.10 | Invested: $12,896.67 | Shares: 104.7658


Sector: Utilities | Allocation: 1.98% ($1,980.00) split across 3 stock(s):

  > Ticker: EIX | Trailing PE: 5.31 | Price: $53.56 | Invested: $660.00 | Shares: 12.3226

  > Ticker: AES | Trailing PE: 5.57 | Price: $14.86 | Invested: $660.00 | Shares: 44.4145

  > Ticker: PCG | Trailing PE: 8.58 | Price: $12.18 | Invested: $660.00 | Shares: 54.1872


Inserting strategy, transactions, and holdings into MySQL database...

Successfully committed strategy, transactions, and holdings to database!

john_iacovacci1@cloudshell:~/openFIGI (sentiment-analysis-379200)$ 



mysql> select * from holdings;

+------------------+---------------+-----------------+----------------+-----------------+---------------+---------------+

| Holding_strategy | Holdings_date | Holdings_ticker | purchase_price | holdings_amount | purchase_date | purchase_cost |

+------------------+---------------+-----------------+----------------+-----------------+------

| PE  | 2026-09-30    | ACGL |     95.12 |  42 | 2026-09-30    |     4020.0000 |

| PE  | 2026-09-30    | AES    |     14.86 |  44 | 2026-09-30    |      660.0000 |

| PE  | 2026-09-30    | ALL    |   225.42 |  18 | 2026-09-30    |     4020.0000 |

| PE  | 2026-09-30    | APA    |     42.19 |  27 | 2026-09-30    |     1160.0000 |

| PE  | 2026-09-30    | CCL    |     25.11 | 124 | 2026-09-30   |     3103.3333 |

| PE | 2026-09-30    | CF        |   115.71 |     5 | 2026-09-30    |      560.0000 |

| PE | 2026-09-30    | CHTR   |   110.67 |   29 | 2026-09-30   |    3166.6667 |

| PE | 2026-09-30    | CI         |   275.26 |   11 | 2026-09-30    |    3093.3333 |

| PE | 2026-09-30    | CMCSA  | 21.60 |  147 | 2026-09-30    |    3166.6667 |

| PE | 2026-09-30    | CRH     |   84.53 |      7 | 2026-09-30    |      560.0000 |

| PE | 2026-09-30    | DLTR   |  113.30 |    13 | 2026-09-30    |    1486.6667 |

| PE | 2026-09-30    | DVN     |   46.60 |    25 | 2026-09-30    |     1160.0000 |

| PE | 2026-09-30    | EIX      |    53.56 |    12 | 2026-09-30    |      660.0000 |

| PE | 2026-09-30    | EXE    |     84.18 |    14 | 2026-09-30    |    1160.0000 |

| PE | 2026-09-30    | FIS      |    33.35 |   387 | 2026-09-30    |  12896.6667 |

| PE | 2026-09-30    | FSLR  |   176.93 |    73 | 2026-09-30    |  12896.6667 |

| PE | 2026-09-30    | HON    |  210.13 |    12 | 2026-09-30    |    2583.3333 |

| PE | 2026-09-30    | HST    |     22.44 |    27 | 2026-09-30    |      600.0000 |

| PE | 2026-09-30    | LDOS  |   123.10 |  105 | 2026-09-30    | 12896.6667 |

| PE | 2026-09-30    | LULU  |      96.87 |    32 | 2026-09-30    |   3103.3333 |

| PE | 2026-09-30    | MKC   |      48.40 |    31 | 2026-09-30    |   1486.6667 |

| PE | 2026-09-30    | NCLH  |     14.80 |  210 | 2026-09-30    |   3103.3333 |

| PE | 2026-09-30    | NEM    |    117.09 |     5 | 2026-09-30    |     560.0000 |

| PE | 2026-09-30    | PCG    |      12.18 |   54 | 2026-09-30    |     660.0000 |

| PE | 2026-09-30    | PNR    |       53.47 |  48 | 2026-09-30    |    2583.3333 |

| PE | 2026-09-30    | SOLV  |      89.32 |   35 | 2026-09-30    |    3093.3333 |

| PE | 2026-09-30    | SPG    |    204.28 |     3 | 2026-09-30    |      600.0000 |

| PE | 2026-09-30    | STZ     |    112.77 |   13 | 2026-09-30    |    1486.6667 |

| PE | 2026-09-30    | SYF   |   71.72 |      56 | 2026-09-30    |     4020.0000 |

| PE | 2026-09-30    | TTD   |  12.05 |     263 | 2026-09-30    |     3166.6667 |

| PE | 2026-09-30    | UAL  |  112.65 |      23 | 2026-09-30    |     2583.3333 |

| PE | 2026-09-30    | UHS  |  175.73 |      18 | 2026-09-30    |     3093.3333 |

| PE | 2026-09-30    | VICI       23.20 |       26 | 2026-09-30    |      600.0000 |

+------------------+---------------+-----------------+----------------+-----------------+------

34 rows in set (0.00 sec)


mysql> 

 transaction_id | strategy    | ticker | transaction_date | transaction_type | quantity | price_per_share |

+----------------+-------------+--------+------------------+------------------+----------+-----

35 | PE          | CF     | 2026-09-30       | BUY         |   4.8397 |          115.71 |

36 | PE          | NEM    | 2026-09-30       | BUY       |   4.7826 |          117.09 |

37 | PE          | CRH    | 2026-09-30       | BUY        |   6.6249 |           84.53 |

38 | PE          | TTD    | 2026-09-30       | BUY       | 262.7939 |           12.05 |

39 | PE          | CHTR   | 2026-09-30       | BUY     |  28.6136 |          110.67 |

40 | PE          | CMCSA  | 2026-09-30       | BUY   | 146.6049 |           21.60 |

41 | PE          | LULU   | 2026-09-30       | BUY      |  32.0361 |           96.87 |

42 | PE          | NCLH   | 2026-09-30       | BUY     | 209.6847 |           14.80 |

43 | PE          | CCL    | 2026-09-30       | BUY       | 123.5895 |           25.11 |

44 | PE          | MKC    | 2026-09-30       | BUY       |  30.7163 |           48.40 |

45 | PE          | STZ    | 2026-09-30       | BUY       |  13.1832 |          112.77 |

46 | PE          | DLTR   | 2026-09-30       | BUY      |  13.1215 |          113.30 |

47 | PE          | EXE    | 2026-09-30       | BUY        |  13.7800 |           84.18 |

48 | PE          | APA    | 2026-09-30       | BUY        |  27.4947 |           42.19 |

49 | PE          | DVN    | 2026-09-30       | BUY       |  24.8927 |           46.60 |

50 | PE          | ALL    | 2026-09-30       | BUY       |  17.8334 |          225.42 |

51 | PE          | SYF    | 2026-09-30       | BUY        |  56.0513 |           71.72 |

52 | PE          | ACGL   | 2026-09-30       | BUY      |  42.2624 |           95.12 |

53 | PE          | UHS    | 2026-09-30       | BUY      |  17.6028 |          175.73 |

54 | PE          | SOLV   | 2026-09-30       | BUY      |  34.6320 |           89.32 |

55 | PE          | CI     | 2026-09-30       | BUY          |  11.2379 |          275.26 |

56 | PE          | HON    | 2026-09-30       | BUY      |  12.2940 |          210.13 |

57 | PE          | UAL    | 2026-09-30       | BUY       |  22.9324 |          112.65 |

58 | PE          | PNR    | 2026-09-30       | BUY       |  48.3137 |           53.47 |

59 | PE          | VICI   | 2026-09-30       | BUY         |  25.8621 |           23.20 |

60 | PE          | SPG    | 2026-09-30       | BUY       |   2.9371 |          204.28 |

61 | PE          | HST    | 2026-09-30       | BUY        |  26.7380 |           22.44 |

62 | PE          | FIS    | 2026-09-30       | BUY        | 386.7066 |           33.35 |

63 | PE          | FSLR   | 2026-09-30       | BUY      |  72.8914 |          176.93 |

64 | PE          | LDOS   | 2026-09-30       | BUY    | 104.7658 |          123.10 |

65 | PE          | EIX    | 2026-09-30       | BUY         |  12.3226 |           53.56 |

66 | PE          | AES    | 2026-09-30       | BUY       |  44.4145 |           14.86 |

67 | PE          | PCG    | 2026-09-30       | BUY       |  54.1872 |           12.18 |

+-------------+--------+------------------+------------------+----------+-----------------+

34 rows in set (0.01 sec)


mysql> 


No comments:

Post a Comment

Assignment #4 due 9/30/26

Build a cloud run application https://googleclouduconn.blogspot.com/p/google-cloud-run.html That takes the data from the screen of stock tic...