Stocks with Python
If all of this sounds familiar. It is because it is actually familiar.
API’s I was using with R/Stocks 📌
- PriceR
- QuantDL - API required
- QuantMod
- yfR - yahoo finance in R
PyStocks
For user authentication: clear/supabase/logto…
- https://clerk.com/docs
- https://github.com/clerk/clerk-sdk-python/blob/main/README.md
- https://www.reddit.com/r/Supabase/comments/1dvabn6/what_is_the_best_solution_to_use_supabase_auth/
- https://www.reddit.com/r/nextjs/comments/1bvda9r/officially_hate_supabase_auth/?rdt=40537
- https://www.reddit.com/r/Supabase/comments/xaxecr/authentication_with_supabase_is_easy_almost/
- _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.
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
- Data Load Tool - https://github.com/dlt-hub/dlt
the open-source Python library for data loading
- How to inspect a SQL DB with AI (without knowing much about it…)
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:
- Operating Cash Flow: Cash generated from core business activities.
- Investing Cash Flow: Cash used in or generated by investments in assets.
- Financing Cash Flow: Cash used for or received from debt, equity, and dividends.
Aspect | Net Income | Net Cash Flow |
---|---|---|
Definition | Profit or loss from operations (accounting basis) | Actual cash generated or used (cash basis) |
Non-cash items | Includes non-cash items (e.g., depreciation) | Excludes non-cash items, tracks cash only |
Timing | Accrual-based accounting | Tracks when cash is received or spent |
Use | Measures profitability | Measures 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
Interesting Software for Finances
Financial Freedom
is an open-source financial management tool.
- https://github.com/serversideup/financial-freedom
- It serves as an alternative to commercial apps like Mint and YNAB.
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
Interesting Financial Data WebSites
- https://www.multpl.com/
- it has Sp500 PE Ratios, 10y treausry rates…
- https://www.wallstreetmojo.com/trailing-pe-vs-forward-pe/
- https://stockanalysis.com/ esta es buena para stocks, etfs no
- https://www.justetf.com/uk/ esta es un screener de ETFs muy bueno, además están todas las variantes monetarias de cada ETF
- https://divvydiary.com/en/?via=elisa&gad_source=1&gclid=Cj0KCQiA0fu5BhDQARIsAMXUBOIN8XXGkoEZZbfhufMr55Y2kSIuAGXDP4Lb1LYgLlRMnezpTUl2tkAaAp2kEALw_wcB esta la encontré el otro día, ofrece datos históricos de stocks y algún ETF (FUSD te lo da pero IDUS no), pero mola que me da el ISIN rápido, entonces veo rápidamente en qué país cotiza
- https://tools.mhinvest.com/mhichart una web app que tiene una idea muy parecida a la que pensamos en su momento, pero no considera seguir metiendo gasolina, parte de una cantidad inicial y listo.
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]