Files
YoteInvest/README.md
T
2026-11-17 20:07:31 +01:00

304 lines
18 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Yote-In-Vest
A dark-themed investing dashboard and bot for six markets: Euronext Amsterdam (AEX),
Euronext Paris, Xetra (Frankfurt), London, the US (NYSE and Nasdaq) and crypto. A trend
strategy finds entries, a news filter (several sources, judged by DeepSeek) can veto or shrink
a buy, hard risk rules decide, and a paper broker executes.
No real money is involved unless you deliberately change that.
## Quick start: the demo
The demo runs on its own with **real prices and real news but fake money** (€10,000).
No broker, no TradingView and no API keys are needed.
```bash
docker compose -f docker-compose.demo.yml up -d --build
```
Open http://localhost:8000. What happens:
- Every 15 minutes Yote-In-Vest fetches the latest 1-hour candles for all 117 markets from
Yahoo Finance (free, no account). Prices in dollars and pounds are converted to euros with
live rates, so the fake account is one clean euro balance.
- The same trend strategy as the TradingView script runs on each new closed candle.
- On a buy signal it gathers news (see below) and judges it. With a `DEEPSEEK_API_KEY` in
`.env`, DeepSeek judges the headlines; without one, a simple keyword score does (cruder, so
it only blocks buys when the news is clearly negative).
- The usual risk rules apply (€50 per buy, max 4 positions, daily loss limit, exchange must be
open), and the trade is booked on the fake account.
Be patient: on 1-hour candles a trend signal may take hours or days to appear, and a share
only trades while its exchange is open. To see the whole flow working within minutes, run it
on made-up prices instead:
```bash
DEMO_DATA=simulated docker compose -f docker-compose.demo.yml up -d --build
```
The **Reset demo** button wipes the fake account and starts over. It asks for the webhook
secret (`demo` by default; set `WEBHOOK_SECRET` to change it). To run the demo on your server
behind Traefik instead, use the normal `docker-compose.yml` with `DEMO_MODE=true` in `.env`.
Yahoo Finance's price endpoint is free but unofficial: it can rate-limit or change. If it
fails, the dashboard shows the error per market and Yote-In-Vest simply retries next time.
## Is it working? The Health panel
In demo mode the dashboard has a **Health** panel (it refreshes by itself every 10 seconds):
- **Price feeds:** how many of the markets deliver prices, when the last check ran and when the next
one is due. A market is flagged *error* if Yahoo failed for it, or *stale* if its exchange is open
but no new candle has arrived for a while.
- **In an uptrend / closest to a buy:** how many markets are trending up, and which one is nearest to
a signal, with what it still lacks.
- **Per market, five checks:** trend (fast average above slow), price above the fast average, volume
above average, trend strength (ADX), and a fresh start. A buy needs all five at once. Hover a check
for its value. These are the same rules the bot uses, and a test makes sure the panel and the bot
never disagree.
No trades in a falling market is normal: with no market in an uptrend, no buys are expected.
## Tracking the money you put in
The **Your money** panel at the top of the dashboard answers "how much did I put in, and what is
it worth?". Press *Add money*, enter an amount and the secret. Put in €50 now and €50 next week
and it shows `Put in €100`, `Worth now €120`, `Gain +€20`. A deposit is never counted as a gain,
and a negative amount records a withdrawal (limited to the cash that is free).
- For real tracking, set `PAPER_START_CASH=0` in `.env` before the first start, so that only
your deposits count. The default of 10,000 is the demo's fake starting balance and counts as
money put in.
- The scorecard's return is measured against the same total. Its "worst drop" can show a
withdrawal as a dip, because it is taken from the account value over time.
- With Alpaca connected, the deposit is recorded here but you move the money at Alpaca yourself.
- The same data is available at `GET /api/money`; `POST /api/deposits` adds one.
## Scorecard and backtest
Two tools to answer "is this actually any good?" before you trust it with money. Both are on
the dashboard.
**Scorecard** (always on). Worked out from what the bot has really done in the demo or on paper:
- Return since start next to *just holding all markets equally* over the same period, the
worst drop from a peak, finished trades, win rate, average win and loss, profit factor
(money won divided by money lost) and return on the money actually invested.
- A table of what the price did **6, 24 and 72 candles after each buy signal**, split by what the
bot did with it: bought, skipped because of bad news, skipped by another rule. If skipped-for-news
signals tend to go down afterwards, the news filter is earning its keep; if they go up, it is
costing you. This needs weeks of data before it says anything.
- Plain warnings when the sample is too small (under 30 days or under 30 finished trades).
Treat the numbers as noise until those warnings are gone.
The scorecard records every candle price and an account snapshot at each update, in the same
database, and **Reset demo** clears them.
**Backtest** (on demand). Replays the exact same trading rules over years of real price history
for all markets, with fees and slippage, and compares with buy-and-hold. Press *Run backtest* on the
dashboard (needs the secret; takes a minute or two), or from the terminal:
```bash
docker compose run --rm yote-in-vest python -m app.backtest --interval 1d --years 5
docker compose run --rm yote-in-vest python -m app.backtest --interval 1h --symbols BTCUSD,ASML,SPY
```
It reports the 60% / 40% split (the last 40% is "unseen" data, a check against settings that only
fit the past), a table of slightly different settings (a strategy that swings wildly between them
is fragile), and a plain-language verdict.
What a backtest cannot tell you, and the report says so: it has no news filter (there is no free
archive of old headlines), no currency effects, no daily loss limit and no €50 cap (it invests 10% of a
€10,000 account). Hourly history only goes back about two years on Yahoo. Past results do not predict
future ones, and more settings tried means more chance one looks good by luck. This is why the
bot does not "learn" from a month of demo: it has no memory. The honest use is to check the rules
on history first, then use the scorecard to see whether live behaviour matches.
## The exchanges
Chosen for depth and for being practical from the Netherlands: big and liquid, quoted in
euros, dollars or pounds, and open at hours that overlap with Amsterdam. This is a judgement
call, not a ranking. The biggest exchanges by value (several are in China) are left out
because foreign retail investors can barely reach them. Tokyo, Hong Kong or Zurich can be
added later with one entry in `app/exchanges.py`.
| Exchange | Hours (local) | Markets | Currency | Orders go to |
|---|---|---|---|---|
| Euronext Amsterdam | 09:00–17:30 | 24: ASML, Adyen, ING, Philips, Ahold Delhaize, Heineken, Unilever, Wolters Kluwer, Prosus, Akzo Nobel, ArcelorMittal, NN Group, ASM Intl, BESI, IMCD, SBM Offshore, Randstad, DSM-Firmenich, KPN, RELX, ABN AMRO, Exor, ASR, Aalberts | EUR | Built-in simulator |
| Euronext Paris | 09:00–17:30 | 20: LVMH, TotalEnergies, L'Oréal, Sanofi, Airbus, BNP Paribas, Schneider, Air Liquide, AXA, Hermès, Kering, Vinci, Safran, Danone, EssilorLuxottica, Stellantis, Orange, Capgemini, Société Générale, Crédit Agricole | EUR | Built-in simulator |
| Xetra (Frankfurt) | 09:00–17:30 | 17: SAP, Siemens, Allianz, Deutsche Telekom, Mercedes-Benz, BMW, BASF, Bayer, Adidas, Infineon, Munich Re, Deutsche Bank, Volkswagen, DHL, RWE, E.ON, Henkel | EUR | Built-in simulator |
| London | 08:00–16:30 | 17: Shell, AstraZeneca, HSBC, BP, Unilever, GSK, Rio Tinto, Diageo, BAT, LSEG, Barclays, Lloyds, Vodafone, National Grid, RELX, Glencore, Compass | GBP (quoted in pence) | Built-in simulator |
| NYSE and Nasdaq | 09:30–16:00 New York | 30: SPY, QQQ, IWM, DIA and 26 large US companies (Apple, Microsoft, Nvidia, Amazon, Alphabet, Meta, Tesla, ...) | USD | Alpaca paper account |
| Crypto | 24/7 | 9: BTC, ETH, SOL, DOGE, AVAX, LINK, LTC, DOT, BCH | USD | Alpaca paper account |
The full list is `_STOCKS` and `_CRYPTO` in `app/config.py`: one line per market. Yahoo symbols were
not all checked live (the build environment could not reach Yahoo). A wrong one shows as an error
in the Health panel and the rest keep working.
What "connected" means here, honestly:
- **Prices:** all six come from Yahoo Finance. No account needed.
- **Orders:** only crypto and US stocks can reach a real (paper) broker account, through
Alpaca. Alpaca does not offer Euronext, and its Xetra access is for broker partners, so
European shares use the built-in simulator. Trading European shares with real money would
need another broker, for example Interactive Brokers, and an adapter for it, which is not
built yet.
- **Hours:** a buy is skipped while the share's exchange is closed (Mon to Fri, regular
hours). Public holidays and early closes are not modelled; on a holiday no new candles
arrive, so the strategy stays quiet by itself.
Shares listed on several exchanges (ASML, SAP, Shell, AstraZeneca) appear once, on the
exchange in the table. Make the TradingView alert on that exchange: `EURONEXT:ASML`,
`XETR:SAP`, `LSE:SHEL`.
## News sources
Each buy signal is checked against recent news. Sources, all free:
| Source | What it gives | Used for |
|---|---|---|
| Google News | Headlines about the company or coin | Every asset |
| European Central Bank | Press releases and speeches | Euronext, Xetra, crypto |
| Federal Reserve | Press releases | US stocks, crypto |
| Finnhub (optional, free key) | Company news, crypto news | US stocks, crypto |
The model treats central-bank news as background only: it can raise or lower its confidence
but never overrides clear news about the asset itself. London has no central-bank source yet
(no Bank of England feed). Switch sources on or off with `NEWS_SOURCES` in `.env`. If one source
fails, the others still count and the failure shows on the dashboard; if all fail, buys are
blocked rather than made blind. The dashboard shows which sources fed each decision, with the
headlines behind it.
Why not Reuters, Bloomberg or Dow Jones directly? Their real-time feeds are licensed
products that cost thousands per month and forbid redistribution. That is out of proportion
for a bot that acts on hourly candles and uses news as a filter, not as a trigger.
Things to keep in mind:
- News only ever vetoes or shrinks a buy. It cannot start a trade, and sells are never blocked by it.
- Headlines are untrusted text from the internet. The prompt tells the model to treat them as
material to judge, never as instructions, and its answer is validated (a sentiment word and a
number) before use, so a planted headline cannot do more than nudge sentiment.
- Language models misread sarcasm, old stories and rumours. Treat the verdict as one input.
- A calendar of earnings dates and central-bank meetings (to avoid buying right before them)
would probably add more than more headlines. It is not built yet.
## How the full version works
```
TradingView strategy ──webhook──▶ this server ──▶ news filter
│ (Google News, ECB, Fed, Finnhub → DeepSeek)
▼ │
risk rules ◀──────── verdict
│
┌─────────────────┴────────────────┐
▼ ▼
Alpaca paper (US stocks + crypto) built-in paper broker (European shares)
```
## What it does
| Step | Rule |
|---|---|
| Entry signal | Fast EMA (21) above slow EMA (55), price above fast EMA, volume 1.2x above average, ADX ≥ 20 |
| Exit signal | Fast EMA crosses below slow EMA, or a 3x ATR trailing stop is hit |
| News filter | Bearish news at ≥ 60% confidence **blocks** a buy. Mildly bearish = half size, neutral = 75%, bullish = full size |
| Position size | 10% of equity per trade, **never more than €50 per buy** (`MAX_ORDER_EUR`). News scaling applies on top of the cap |
| Limits | Max 4 open positions per account; no new buys after −3% on the day; kill switch on the dashboard |
| Exchange hours | Buys only while the exchange is open (`ENFORCE_MARKET_HOURS`). US stocks on Alpaca use Alpaca's own clock, which knows holidays |
| Safety | Sells are never blocked. If the news filter fails, buys are blocked. Live trading is off unless `ALPACA_LIVE=true` |
**US trading hours** are 15:30–22:00 Amsterdam time (shifting by an hour for a few weeks in
spring and autumn, when the US and Europe change clocks on different dates). A strategy on
daily candles fires when the day's candle closes, which is after the market has closed, so
those buys would always be skipped. Either run charts on 1h or 4h candles, or, for US stocks
only, set `US_AFTER_HOURS=queue` to buy at the next opening price instead.
## Run on your server with Docker Compose + Traefik
**Using Portainer:** you don't need a `.env` file. Create the stack from the repository (or
upload the project folder so it can build the image), and under *Environment variables* add
`WEBHOOK_SECRET` and `DASHBOARD_AUTH` (required) plus anything from `.env.example` you want to
change, such as `DEEPSEEK_API_KEY` or `PAPER_START_CASH=0`. Everything not set uses the default.
When updating the stack, leave "Re-pull image" off: the image is built here, not downloaded.
Paste `DASHBOARD_AUTH` as the plain `admin:$2y$...` hash; if the login is refused, double every
`$` in it (`$$`). A stack typed into Portainer's web editor cannot build the image; use the
repository option, or build the image once, and replace `build: .` and `pull_policy: build` with `image: yote-in-vest:latest`.
The Compose file assumes you already run Traefik with an external Docker network and a
certificate resolver. It creates two routes on one domain:
- `https://BOT_DOMAIN/webhook`, open so TradingView can reach it (it checks `WEBHOOK_SECRET`).
- Everything else (the dashboard), behind a basic-auth password.
1. Point a DNS record at your server. The compose file defaults to `yoteinvest.dv3.app`; set
`BOT_DOMAIN` in `.env` to use another name.
2. Create the settings file and a dashboard password:
```bash
cp .env.example .env
docker run --rm httpd:2.4-alpine htpasswd -nbB admin 'your-password'
```
Paste the output into `.env` as `DASHBOARD_AUTH='admin:$2y$05$...'`, inside **single quotes**.
Set `BOT_DOMAIN`, your keys, and a long `WEBHOOK_SECRET`. If your Traefik uses other
names than `traefik` / `websecure` / `letsencrypt`, change `TRAEFIK_NETWORK`,
`TRAEFIK_ENTRYPOINT` and `TRAEFIK_CERTRESOLVER`.
3. Start it:
```bash
docker compose up -d --build
docker compose logs -f
```
4. Open `https://yoteinvest.dv3.app` and log in. With `DEMO_MODE=true` (the default in
`.env.example`) it runs the demo; set `DEMO_MODE=false` to use TradingView signals and Alpaca.
Your webhook URL for TradingView is `https://yoteinvest.dv3.app/webhook`.
The database lives in the `yote-in-vest-data` volume, so it survives restarts and rebuilds.
Optional: `docker-compose.yml` has a commented-out IP allowlist so only TradingView's
servers can reach `/webhook`. Check TradingView's current IP list before enabling it.
## Run without Docker
```bash
pip install -r requirements.txt
cp .env.example .env
python -m pytest -q # tests, no keys needed
python -m app.backtest --years 5 # backtest from the terminal
uvicorn app.main:app --host 0.0.0.0 --port 8000
```
For a quick test with TradingView, `ngrok http 8000` gives you a public https URL.
## Add the strategy in TradingView
You need a paid plan with webhooks, and 2FA turned on.
1. Pine Editor → paste `pine/trend_strategy.pine` → Add to chart.
2. In the strategy settings, set **Webhook secret** to the same value as in `.env`.
3. Check the Strategy Tester tab to see how it did historically on that chart.
4. Create an alert: condition = the strategy, message = `{{strategy.order.alert_message}}`,
webhook URL = `https://yoteinvest.dv3.app/webhook`.
5. Repeat for each chart, on the exchange listed in the table above.
There are 117 markets, so up to 117 alerts. That is more than most TradingView plans allow; the built-in demo does not need alerts at all, and for real use you can pick the markets you care about. Check how many alerts your TradingView plan allows,
and that cheaper plans expire alerts after a while. Check your alert list regularly, or the
bot silently stops getting signals.
## Things to know
- The built-in paper broker fills at the alert price with a 0.15% fee. Real fills will differ.
- The news filter caches verdicts for 15 minutes per asset to keep DeepSeek costs low.
- Without Alpaca keys, crypto and US stocks run on the built-in paper account too, so euro
and dollar amounts share one simulated balance. Fine for testing, not precise accounting.
- The €50 cap is converted to dollars for Alpaca with `EUR_USD_RATE`. Keep it roughly current.
- The daily loss limit resets at midnight UTC.
- Alpaca paper accounts are open to anyone. Whether you can open a live Alpaca account
from the Netherlands is a separate question to check with Alpaca.
- The Yahoo, Google News, ECB, Federal Reserve and Finnhub connections were tested against
saved sample responses, not live, because the build environment could not reach them.
If a feed address has moved, the dashboard shows the error; the ECB and Fed addresses can
be changed with `NEWS_ECB_URL` and `NEWS_FED_URL`.
## Before you ever consider real money
Run it on paper for at least a few months across different market conditions. Compare it
to simply holding the assets. If it doesn't clearly beat that after fees, it isn't worth
the risk. This software is a tool, not financial advice.