Browse Source

implemented pse automatic fetching of pse data

pull/8381/head
jbpcasoy 4 weeks ago
parent
commit
930e9590c4
  1. 3
      .gitignore
  2. 74
      START-GHOSTFOLIO.md
  3. 19
      docker/docker-compose.yml
  4. 86
      docker/pse-sync.sh
  5. 135
      get-pse-history.ps1

3
.gitignore

@ -49,3 +49,6 @@ testem.log
# System Files
.DS_Store
Thumbs.db
/pse-history

74
START-GHOSTFOLIO.md

@ -0,0 +1,74 @@
# Starting and Stopping Ghostfolio
Ghostfolio runs in Docker on this PC. Open it at <http://localhost:3333> and log in with your security token.
## Start
1. Open **Docker Desktop** and wait until it says it is running.
2. Go to <http://localhost:3333>. The containers normally come back on their own, so it may already be up.
3. If the page does not load, open a terminal in `D:\Documents\GitHub\ghostfolio` and run:
```powershell
docker compose -f docker/docker-compose.yml up -d
```
4. Wait about 30 seconds, then reload the page.
To skip step 1 after a reboot, turn on **Start Docker Desktop when you sign in** in Docker Desktop's settings.
## Stop
Run this from `D:\Documents\GitHub\ghostfolio`:
```powershell
docker compose -f docker/docker-compose.yml stop
```
Your data is kept. After a manual stop, Ghostfolio stays off, even after a reboot, until you run the `up -d` command again.
> **Warning:** Do not add `-v` to a `docker compose down` command. It deletes your portfolio database.
## Stock prices
Ghostfolio fetches stock prices about once an hour, and only while it is running. If it has been off, prices catch up at the next update.
### PSE price history
You don't need to do anything to update PSE prices. A fourth container, `gf-pse-sync`, starts and stops with Ghostfolio. Each time it starts, it downloads all closing prices since July 1, 2026 from PSE EDGE and updates them in Ghostfolio. This takes about a minute; reload the page to see the new prices.
- If you leave Ghostfolio running, it updates again each day at 6:00 PM Manila time.
- Days when Ghostfolio was off are filled in by the next update.
- A ticker shows `FAIL` if its prices don't reach back to July 1, 2026. Its existing prices stay as they are.
- If an update fails, it tries again an hour later.
See what the last update did. Each ticker's line starts with `OK` or `FAIL`:
```powershell
docker logs --tail 25 gf-pse-sync
```
To update prices right away:
```powershell
docker restart gf-pse-sync
```
To add a ticker, add it to the list at the top of `docker/pse-sync.sh`, then run the restart command above. Its name must match the asset's name in Ghostfolio.
## If something is wrong
Run these from `D:\Documents\GitHub\ghostfolio`.
Check that all four containers (`ghostfolio`, `gf-postgres`, `gf-redis`, `gf-pse-sync`) are running:
```powershell
docker compose -f docker/docker-compose.yml ps
```
See the most recent app logs:
```powershell
docker logs --tail 50 ghostfolio
```
If you see an error about connecting to Docker, Docker Desktop is not running yet. Start it and try again.

19
docker/docker-compose.yml

@ -72,5 +72,24 @@ services:
timeout: 5s
retries: 5
pse-sync:
image: docker.io/library/postgres:15-alpine
container_name: gf-pse-sync
restart: unless-stopped
init: true
security_opt:
- no-new-privileges:true
env_file:
- ../.env
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
volumes:
- ./pse-sync.sh:/pse-sync.sh:ro
# tr keeps the script working if Git checks it out with Windows line endings.
command: ['sh', '-c', "tr -d '\\r' < /pse-sync.sh | sh"]
volumes:
postgres:

86
docker/pse-sync.sh

@ -0,0 +1,86 @@
#!/bin/sh
# Runs in the pse-sync container. Updates PSE closing prices in Ghostfolio's
# database when the container starts, then daily while it keeps running.
# Assets are matched by name because the MANUAL data source identifies them by
# a generated UUID. To add a ticker, add "TICKER:cmpy_id" below (the number after
# "cmpy_id=" on edge.pse.com.ph); the ticker must match the asset's name in Ghostfolio.
COMPANIES="AC:57 AREIT:679 CNPF:652 CNVRG:680 CREIT:691 DDMPR:681 DNL:639 FILRT:683
JFC:86 MBT:128 MER:118 MONDE:682 OGP:704 PGOLD:629 RCR:684 SGP:166 SMC:154 URC:124"
# Every update covers this date up to today. A ticker fails, and nothing is written
# for it, if its data doesn't reach back to LATEST_FIRST_DAY (allows for market holidays).
HISTORY_START=07-01-2026
LATEST_FIRST_DAY=20260703
UA="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36"
TO_SQL_VALUES='[.chartData[] | "(\($q)\(.CHART_DATE | strptime("%b %d, %Y %H:%M:%S") | strftime("%Y-%m-%d"))\($q),\(.CLOSE | tonumber))"] | unique_by(.[0:13]) | join(",")'
export PGPASSWORD="$POSTGRES_PASSWORD"
export REDISCLI_AUTH="$REDIS_PASSWORD"
sync_ticker() {
symbol=$1
cmpy_id=$2
page_url="https://edge.pse.com.ph/companyPage/stockData.do?cmpy_id=$cmpy_id"
jar=/tmp/cookies
# Open the Stock Data page first (gets a session cookie and the security_id).
page=$(curl -fsS --max-time 60 -A "$UA" -c "$jar" "$page_url" | tr -d '\r\n') || return 1
options=$(echo "$page" | grep -oE '<option[^>]*value="[0-9]+"[^>]*>[[:space:]]*[^<]+' |
sed -E 's/.*value="([0-9]+)"[^>]*>[[:space:]]*/\1 /')
security_id=$(echo "$options" | awk -v s="$symbol" '$2 == s { print $1; exit }')
[ -n "$security_id" ] || security_id=$(echo "$options" | awk 'NR == 1 { print $1 }')
[ -n "$security_id" ] || { echo "no security_id found"; return 1; }
end=$(date +%m-%d-%Y)
values=$(curl -fsS --max-time 60 -A "$UA" -b "$jar" -H "Content-Type: application/json" \
-H "X-Requested-With: XMLHttpRequest" -H "Referer: $page_url" -H "Origin: https://edge.pse.com.ph" \
-d "{\"cmpy_id\":\"$cmpy_id\",\"security_id\":\"$security_id\",\"startDate\":\"$HISTORY_START\",\"endDate\":\"$end\"}" \
https://edge.pse.com.ph/common/DisclosureCht.ax |
jq -r --arg q "'" "$TO_SQL_VALUES") || return 1
[ -n "$values" ] || { echo "no price data returned"; return 1; }
first=$(echo "$values" | cut -c3-12 | tr -d -)
[ "$first" -le "$LATEST_FIRST_DAY" ] || { echo "$symbol history starts at $first, too late"; return 1; }
count=$(echo "$values" | grep -o "),(" | wc -l)
count=$((count + 1))
sql="INSERT INTO \"MarketData\" (id, \"dataSource\", symbol, date, \"marketPrice\", state)
SELECT gen_random_uuid()::text, a.\"dataSource\", a.symbol, v.d::timestamp, v.price::double precision, 'CLOSE'
FROM (VALUES $values) AS v(d, price)
JOIN \"SymbolProfile\" a ON a.name = '$symbol' AND a.\"dataSource\" = 'MANUAL'
ON CONFLICT (\"dataSource\", symbol, date) DO UPDATE
SET \"marketPrice\" = EXCLUDED.\"marketPrice\", state = EXCLUDED.state;"
result=$(echo "$sql" | psql -h postgres -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1) || return 1
[ "$result" = "INSERT 0 $count" ] || { echo "expected $count rows, database said: $result"; return 1; }
echo "OK $symbol $count days"
}
sync_all() {
failed=0
for company in $COMPANIES; do
symbol=${company%:*}
sync_ticker "$symbol" "${company#*:}" || { echo "FAIL $symbol"; failed=$((failed + 1)); }
sleep 2 # be polite to the PSE server
done
# Drop cached portfolio calculations so the next page load uses the new prices.
redis-cli -h redis --scan --pattern 'portfolio-snapshot-*' | xargs -r redis-cli -h redis del >/dev/null
echo "$(date) Done with $failed failure(s)."
[ "$failed" -eq 0 ]
}
until apk add --quiet --no-cache curl jq redis; do sleep 30; done
until pg_isready --quiet -h postgres; do sleep 5; done
while true; do
now=$(date +%s)
if sync_all; then
# Next 18:00 Manila time (10:00 UTC). Short sleeps so a laptop's sleep can't delay it much.
next=$((now / 86400 * 86400 + 36000))
[ "$next" -gt "$now" ] || next=$((next + 86400))
else
next=$((now + 3600))
fi
while [ "$(date +%s)" -lt "$next" ]; do sleep 300; done
done

135
get-pse-history.ps1

@ -0,0 +1,135 @@
# get-pse-history.ps1
# Downloads daily closing prices from PSE EDGE and saves them in the
# "date;marketPrice" format that Ghostfolio's market data import accepts, then
# updates those prices in Ghostfolio's database. Existing dates are overwritten
# with the latest values; no other data is touched.
#
# HOW TO USE
# 1. Fill in the cmpy_id for each ticker below. Find it on edge.pse.com.ph:
# search the company, open it, and copy the number after "cmpy_id=" in the address bar.
# Tickers left at 0 are skipped.
# 2. Right-click this file > "Run with PowerShell"
# (or in a terminal: powershell -ExecutionPolicy Bypass -File .\get-pse-history.ps1)
# 3. Files appear in a "pse-history" folder next to this script, one per ticker.
# Ghostfolio must be running for the database update (see START-GHOSTFOLIO.md).
#
# You normally don't need this: the pse-sync container (docker/pse-sync.sh) updates
# prices whenever Ghostfolio starts. Use this script to also get the text files.
# Runs are logged to pse-history\sync.log.
$Companies = [ordered]@{
"AC" = 57
"AREIT" = 679
"CNPF" = 652
"CNVRG" = 680
"CREIT" = 691
"DDMPR" = 681
"DNL" = 639
"FILRT" = 683
"JFC" = 86
"MBT" = 128
"MER" = 118
"MONDE" = 682
"OGP" = 704
"PGOLD" = 629
"RCR" = 684
"SGP" = 166
"SMC" = 154
"URC" = 124
}
# Date range (MM-dd-yyyy): July 1, 2026 up to today. A ticker fails, and nothing is
# written for it, if its data doesn't reach back to $LatestFirstDay (allows for market holidays).
$EndDate = (Get-Date).ToString("MM-dd-yyyy")
$StartDate = "07-01-2026"
$LatestFirstDay = "2026-07-03"
$OutDir = Join-Path $PSScriptRoot "pse-history"
New-Item -ItemType Directory -Force -Path $OutDir | Out-Null
$Culture = [System.Globalization.CultureInfo]::InvariantCulture
$UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36"
$Failed = 0
Start-Transcript -Path (Join-Path $OutDir "sync.log") -Append | Out-Null
function Finish([int]$ExitCode) {
Stop-Transcript | Out-Null
Read-Host "Press Enter to close" | Out-Null
exit $ExitCode
}
# Upserts one ticker's prices. Assets are matched by name because the MANUAL
# data source identifies them by a generated UUID, not by the ticker.
function Update-GhostfolioPrices([string]$Symbol, [string[]]$Rows) {
$Values = ($Rows | ForEach-Object { $p = $_ -split ";"; "('$($p[0])',$($p[1]))" }) -join ","
$Sql = @"
INSERT INTO "MarketData" (id, "dataSource", symbol, date, "marketPrice", state)
SELECT gen_random_uuid()::text, a."dataSource", a.symbol, v.d::timestamp, v.price::double precision, 'CLOSE'
FROM (VALUES $Values) AS v(d, price)
JOIN "SymbolProfile" a ON a.name = '$Symbol' AND a."dataSource" = 'MANUAL'
ON CONFLICT ("dataSource", symbol, date) DO UPDATE
SET "marketPrice" = EXCLUDED."marketPrice", state = EXCLUDED.state;
"@
$Result = $Sql | docker exec -i gf-postgres sh -c 'psql -v ON_ERROR_STOP=1 -U $POSTGRES_USER -d $POSTGRES_DB'
if ($LASTEXITCODE -ne 0) { throw "database update failed" }
if ("$Result" -ne "INSERT 0 $($Rows.Count)") { throw "expected $($Rows.Count) rows, database said: $Result" }
}
docker exec gf-postgres true 2>$null
if ($LASTEXITCODE -ne 0) {
Write-Host "FAIL Ghostfolio's database is not running. Nothing was updated." -ForegroundColor Red
Finish 1
}
foreach ($Symbol in $Companies.Keys) {
$CmpyId = $Companies[$Symbol]
if (-not $CmpyId) { Write-Host "SKIP $Symbol (no cmpy_id filled in)" -ForegroundColor DarkGray; continue }
try {
# Open the Stock Data page first (gets a session cookie and the security_id).
$PageUrl = "https://edge.pse.com.ph/companyPage/stockData.do?cmpy_id=$CmpyId"
$Page = Invoke-WebRequest -Uri $PageUrl -SessionVariable Session -UserAgent $UA -UseBasicParsing
# Find the security_id: prefer the option whose label is the ticker, else the first option.
$SecurityId = $null
$Options = [regex]::Matches($Page.Content, '<option[^>]*value="(\d+)"[^>]*>\s*([^<]+?)\s*</option>')
foreach ($o in $Options) { if ($o.Groups[2].Value -eq $Symbol) { $SecurityId = $o.Groups[1].Value; break } }
if (-not $SecurityId -and $Options.Count -gt 0) { $SecurityId = $Options[0].Groups[1].Value }
if (-not $SecurityId) { throw "could not find security_id on the Stock Data page" }
# Ask for the chart data (same request the page makes when you click 1year).
$Body = @{ cmpy_id = "$CmpyId"; security_id = "$SecurityId"; startDate = $StartDate; endDate = $EndDate } | ConvertTo-Json -Compress
$Headers = @{ "X-Requested-With" = "XMLHttpRequest"; "Referer" = $PageUrl; "Origin" = "https://edge.pse.com.ph" }
$Data = Invoke-RestMethod -Uri "https://edge.pse.com.ph/common/DisclosureCht.ax" -Method Post `
-ContentType "application/json" -Body $Body -Headers $Headers -WebSession $Session -UserAgent $UA
if (-not $Data.chartData -or $Data.chartData.Count -eq 0) { throw "no price data returned" }
$Lines = $Data.chartData | ForEach-Object {
$d = [datetime]::ParseExact($_.CHART_DATE, "MMM dd, yyyy HH:mm:ss", $Culture)
[pscustomobject]@{ Date = $d; Close = $_.CLOSE }
} | Sort-Object Date -Unique | ForEach-Object {
"{0};{1}" -f $_.Date.ToString("yyyy-MM-dd"), $_.Close.ToString($Culture)
}
$FirstDay = @($Lines)[0].Substring(0, 10)
if ($FirstDay -gt $LatestFirstDay) { throw "history starts at $FirstDay, too late" }
$OutFile = Join-Path $OutDir "$Symbol-history.txt"
Set-Content -Path $OutFile -Value (@("date;marketPrice") + $Lines) -Encoding UTF8
Update-GhostfolioPrices $Symbol $Lines
Write-Host ("OK {0,-6} {1} days (security_id {2})" -f $Symbol, $Lines.Count, $SecurityId) -ForegroundColor Green
}
catch {
Write-Host "FAIL $Symbol : $($_.Exception.Message)" -ForegroundColor Red
$Failed++
}
Start-Sleep -Seconds 2 # be polite to the PSE server
}
# Drop cached portfolio calculations so the next page load uses the new prices.
docker exec gf-redis sh -c "export REDISCLI_AUTH=`$REDIS_PASSWORD; redis-cli --scan --pattern 'portfolio-snapshot-*' | xargs -r redis-cli del" | Out-Null
Write-Host "`nDone with $Failed failure(s). Files are in: $OutDir"
Finish $(if ($Failed) { 1 } else { 0 })
Loading…
Cancel
Save