Stocks with Python

Stocks with Python

December 23, 2024
ℹ️
After Weather Planning, there is also the financial aspects of travelling
ℹ️
The project source code - PyStocks 💻

If all of this sounds familiar. It is because it is actually familiar.

ℹ️
Sometime ago I was doing similar Project in R Shiny - R/Stocks
API’s I was using with R/Stocks 📌

PyStocks

For user authentication: clear/supabase/logto…

    • _index.md
      • _index.md
      • getting-started.md
        • _index.md
        • organize-files.md
      • _index.md
      • post-1.md
  • content
    ├── _index.md // <- /
    ├── docs
    │   ├── _index.md // <- /docs/
    │   ├── getting-started.md // <- /docs/getting-started/
    │   └── guide
    │       ├── _index.md // <- /docs/guide/
    │       └── organize-files.md // <- /docs/guide/organize-files/
    └── blog
        ├── _index.md // <- /blog/
        └── post-1.md // <- /blog/post-1/

    AI Features for PyStocks

    Chat with the pulled financial data thanks to LangChain.

    ℹ️
    I was exploring on this post and related repo, how to use LangChain as RAG with OpenAI API so that given a DB, we can use Natural Language to interact with it.

    Chat with a DB applied for finance - https://github.com/JAlcocerT/Data-Chat/tree/main/LangChain/PyStocksDB

    Conclusions

    This goes one step further than the previous project RStocks.

    And definitely much more than the older FlexDashboards in R.

    Stock Questions - Answered

    • Stocks overperforming SP500 in xyz period / last xyz months
    • YoC when I stopped investing at a certain point of time (Dave van Knapp made a all in approach, but it can serve to see what happens after a DCA strategy)

    Interesting Pkgs I got to learn

    the open-source Python library for data loading


    FAQ

    Interesting Financial Parameters / KPIs 📌

    Revenue:

    • Gross Revenue: Total income from sales.
    • Net Revenue: Gross revenue minus returns and discounts.

    Expenses:

    • Operating Expenses: Costs incurred during normal business operations.
    • COGS (Cost of Goods Sold): Direct costs of producing goods.
    • Non-operating Expenses: Costs not related to core operations (e.g., interest payments).

    Assets & Liabilities:

    • Current Assets: Cash or items convertible to cash within a year.
    • Long-term Assets: Assets held for more than a year (e.g., machinery).
    • Current Liabilities: Debts due within a year.
    • Long-term Liabilities: Debts payable over a longer period.

    Valuation Metrics:

    • EBITDA (Earnings Before Interest, Taxes, Depreciation, and Amortization): Indicates operational profitability.

    • Net Cash Flow: Difference between cash inflows and outflows.

    • Debt-to-Equity Ratio: Indicates the level of financial leverage.

    • Yield: Dividend return relative to share price; calculated as Dividends per Share / Market Price per Share.

    • Payout Ratio: Proportion of earnings paid out as dividends; calculated as Dividends / Net Income.

    • PER (Price-to-Earnings Ratio): A valuation measure comparing share price to earnings per share.

    • PEGI (Price/Earnings to Growth Index): PER adjusted for expected earnings growth; calculated as PER / Annual EPS Growth.

    • PEGY (Price/Earnings to Growth and Yield): PER adjusted for both expected earnings growth and dividend yield; calculated as PER / (Annual EPS Growth + Dividend Yield).

    %%{init: {"flowchart": {"htmlLabels": false}} }%%
    flowchart TD
        A["Net Cash Flow"] <--> B["Cash Inflows"]
        A <--> C["Cash Outflows"]
        B --> D["Revenue, Investments, Financing"]
        C --> E["Operating Expenses, Investments, Dividends"]
        E --> F["Dividends"]
        F --> G["Payout Ratio"]
        G --> H["Dividends / Net Income"]
        
        A -- "Positive Net Cash Flow supports" --> F
        A -- "Negative Net Cash Flow impacts ability to pay" --> F
        G -- "High Payout Ratio limits reinvestment" --> A
    Net Income vs Net Cash Flow 📌

    Net Income is not the same as Net Cash Flow.

    They are related but measure different aspects of a company’s financial health:

    Net Income:

    • Represents a company’s profit or loss during a specific period.
    • Found on the income statement.
    • Includes both cash and non-cash items:
      • Revenues minus all expenses, including non-cash expenses like depreciation and amortization.
      • Accrual-based (recognizes income/expenses when they are earned/incurred, not when cash changes hands).

    Net Cash Flow:

    • Measures the actual cash movement into and out of the company during a specific period.
    • Found on the cash flow statement.
    • Focuses on cash inflows and outflows, ignoring non-cash items!.
    • Composed of three parts:
      1. Operating Cash Flow: Cash generated from core business activities.
      2. Investing Cash Flow: Cash used in or generated by investments in assets.
      3. Financing Cash Flow: Cash used for or received from debt, equity, and dividends.
    AspectNet IncomeNet Cash Flow
    DefinitionProfit or loss from operations (accounting basis)Actual cash generated or used (cash basis)
    Non-cash itemsIncludes non-cash items (e.g., depreciation)Excludes non-cash items, tracks cash only
    TimingAccrual-based accountingTracks when cash is received or spent
    UseMeasures profitabilityMeasures liquidity and financial flexibility

    Relationship: Net Income is often the starting point for calculating Operating Cash Flow.

    Adjustments are made to add back non-cash expenses and account for changes in working capital.

    Both metrics are important:

    • Net Income: Indicates profitability.
    • Net Cash Flow: Shows the company’s ability to generate cash and stay solvent.

    A diagram is worth more than xyz words, right?

    %%{init: {"flowchart": {"htmlLabels": false}} }%%
    flowchart TD
        A["Company Financials"] --> B["Revenue"]
        A --> C["Expenses"]
        A --> D["Assets & Liabilities"]
        A --> E["Valuation Metrics"]
    
        B --> F["Gross Revenue"]
        B --> G["Net Revenue"]
        
        C --> H["Operating Expenses"]
        C --> I["Cost of Goods Sold (COGS)"]
        C --> J["Non-operating Expenses"]
        
        D --> K["Current Assets"]
        D --> L["Long-term Assets"]
        D --> M["Current Liabilities"]
        D --> N["Long-term Liabilities"]
        
        B --> O["`**EBITDA**`"]
        C --> O
        O --> Z["Revenue - Operating Expenses"]
    
        B --> P["`**Net Cash Flow**`"]
        C --> P
        P --> AA["Cash Inflows - Cash Outflows"]
        
        G --> Q["`**PER (Price-to-Earnings Ratio)**`"]
        Q --> BB["Market Price per Share / EPS"]
        
        D --> R["`**Debt-to-Equity Ratio**`"]
        R --> CC["Total Debt / Total Equity"]
        
        E --> S["`**Yield**`"]
        S --> DD["Dividends per Share / Market Price per Share"]
        
        E --> T["`**PEGI (Price/Earnings to Growth Index)**`"]
        T --> EE["PER / Annual EPS Growth"]
        
        E --> U["`**Payout Ratio**`"]
        U --> FF["Dividends / Net Income"]

    How to use AI LLM Agents to get posts with this program as Source

    ℹ️
    I was testing Automatic Posts creation with AIssistant here and with this related repo.

    Interesting Software for Finances

    Financial Freedom is an open-source financial management tool.

    More about Financial Freedom Software 📌

    This project addresses privacy concerns by allowing users to self-host their financial data.

    Users can run the application on any device with Docker support, enhancing control over their financial information.

    Key features:

    • Supports any bank: Integrate with various banking institutions.
    • Private synchronization: Ensures data privacy during synchronization.
    • Self-hosting: Run on AWS, Digital Ocean, or even Raspberry Pi.
    • Budgeting tools: Helps in managing cash flow and setting budgets.
    • Global currency support: Manages finances in multiple currencies.

    The project is actively being developed, inviting community involvement through contributions.

    Financial Freedom empowers users to manage finances privately and securely.

    Similar projects include Firefly III and GnuCash.

    Interesting Financial Stories

    ℹ️
    You can create an ebook like this one with AI. How? with an AIssistant

    Interesting Financial Data WebSites

    Financial Data Apps

    GSheets Tricks

    You can have a simple, yet useful Google Sheets with Stocks info:

    =GoogleFinance(S35;"eps")
    =GoogleFinance(S35;"pe")

    And if you need, you can also import info from other website sources:

    =VALOR(IZQUIERDA(importxml(CONCATENAR("https://ycharts.com/companies/";REGEXEXTRACT(S33;"[^:]*$");"/profit_margin");$AJ$28);3))/100
    #S33 is a ticker, NASDAQ:PEP, for example and AJ28 the XPATH
    # =importxml("https://ycharts.com/companies/"& REGEXEXTRACT("NASDAQ:PEP";"\:(.*)") & "/profit_margin";$AI$28)

    with xpath being /html/body/div[3]/div[2]/section[1]/div/div/div[1]/div[2]/ul/li[1]/span[2]

    ℹ️
    You can learn more about Scrapping as covered on this blog post and the Scrapping-Tools repo 💻