Skip to content

Commit

Permalink
acquire yahoo finance session (fixes #33)
Browse files Browse the repository at this point in the history
  • Loading branch information
pstadler committed Apr 20, 2023
1 parent 9cb765a commit 38be480
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ $ watch -n 5 -t -c ./ticker.sh AAPL MSFT GOOG BTC-USD
$ while true; do clear; ./ticker.sh AAPL MSFT GOOG BTC-USD; sleep 5; done
```

Please note that ticker.sh may require periodic updates of its session with Yahoo Finance. During these instances, the script may take slightly longer to complete.

This script works well with [GeekTool](https://www.tynsoe.org/v2/geektool/) and similar software:

```sh
Expand Down
29 changes: 26 additions & 3 deletions ticker.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ set -e
LANG=C
LC_NUMERIC=C

SESSION_DIR="${TMPDIR}pstadler-ticker-sh"
COOKIE_FILE="${SESSION_DIR}/cookies.txt"
CRUMB_FILE="${SESSION_DIR}/crumb.txt"

SYMBOLS=("$@")

if ! $(type jq > /dev/null 2>&1); then
Expand All @@ -30,8 +34,27 @@ fi
symbols=$(IFS=,; echo "${SYMBOLS[*]}")
fields=$(IFS=,; echo "${FIELDS[*]}")

results=$(curl --silent "$API_ENDPOINT&fields=$fields&symbols=$symbols" \
| jq '.quoteResponse .result')
[ ! -d "$SESSION_DIR" ] && mktemp -q -d "$SESSION_DIR"

preflight () {
curl --silent --output /dev/null --cookie-jar "$COOKIE_FILE" "https://finance.yahoo.com" \
-H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8"
curl --silent -b "$COOKIE_FILE" "https://query1.finance.yahoo.com/v1/test/getcrumb" \
> "$CRUMB_FILE"
}

fetch_quotes () {
curl --silent -b "$COOKIE_FILE" "$API_ENDPOINT&fields=$fields&symbols=$symbols&crumb=$(cat "$CRUMB_FILE")"
}

[ ! -f "$COOKIE_FILE" -o ! -f "$CRUMB_FILE" ] && preflight
results=$(fetch_quotes)
if $(echo "$results" | grep -q '"code":"Unauthorized"'); then
preflight
results=$(fetch_quotes)
fi

results=$(echo $results | jq '.quoteResponse .result')

query () {
echo $results | jq -r ".[] | select(.symbol == \"$1\") | .$2"
Expand Down Expand Up @@ -82,4 +105,4 @@ for symbol in $(IFS=' '; echo "${SYMBOLS[*]}" | tr '[:lower:]' '[:upper:]'); do
printf "$color%10.2f%12s$COLOR_RESET" $diff $(printf "(%.2f%%)" $percent)
printf " %s\n" "$nonRegularMarketSign"
fi
done
done

0 comments on commit 38be480

Please sign in to comment.