Jamyy's Weblog

BASH: 取得股票代碼與五年、五個月內歷史股價高低點

by Jamyy on 一月.21, 2015, under Coding


環境: bash, curl, utf-8

getstockid

#!/bin/bash

TMPFILE="/dev/shm/temp.dat"

if [ -z "${1}" ]; then
	echo "請輸入股票名稱"
	exit 1
fi

curl --silent -G --data-urlencode $(echo "query=${1}" | iconv -f utf8 -t big5) "https://tw.stock.yahoo.com/h/kimosel.php?search=1&cat=1&form=menu&form_id=stock_id&form_name=stock_name&domain=0" | iconv -f big5 -t utf8 > ${TMPFILE}

if [ -z "$(grep setid ${TMPFILE} | tail -n +2)" ]; then
	echo "查無 ${1}"
	exit 1
else
	grep setid ${TMPFILE} | tail -n +2 | head -n 1 | awk -F\' '{print $2,$4}'
fi


 
pricehistory

#!/bin/bash

TMPPATH="/dev/shm/"
TMPFILE="${TMPPATH}temp.dat"

if [ "${1}" == "" ]; then
        echo "請輸入股票代碼或股票名稱"
        exit 1
fi

ISNUM='^[0-9]+$'

if [[ ${1} =~ ${ISNUM} ]]; then
        stockid=${1}
else
        curl --silent -G --data-urlencode $(echo "query=${1}" | iconv -f utf8 -t big5) "https://tw.stock.yahoo.com/h/kimosel.php?search=1&cat=1&form=menu&form_id=stock_id&form_name=stock_name&domain=0" | iconv -f big5 -t utf8 > ${TMPFILE}
        if [ -z "$(grep setid ${TMPFILE} | tail -n +2)" ]; then
                echo "查無 ${1}"
                exit 1
        else
                stockid=$(grep setid ${TMPFILE} | tail -n +2 | head -n 1 | awk -F\' '{print $2}')
        fi
fi

CSVFILE="${TMPPATH}${stockid}.csv"
AWA=($(date --date 'now - 7 days' '+%-m %d %Y')) # A Week Ago
FYA=($(date --date 'now - 5 years' '+%-m 01 %Y')) # Five Years Ago

curl --silent "http://real-chart.finance.yahoo.com/table.csv?s=${stockid}.TW&a=$((${AWA[0]}-1))&b=${AWA[1]}&c=${AWA[2]}&d=&e=&f=&g=d&ignore=.csv" > ${TMPFILE}
curl --silent "http://real-chart.finance.yahoo.com/table.csv?s=${stockid}.TW&a=$((${FYA[0]}-1))&b=${FYA[1]}&c=${FYA[2]}&d=&e=&f=&g=m&ignore=.csv" | sed -e 's/-..,/,/g' > ${CSVFILE}
tail -n +2 ${TMPFILE} | head -n 1 | awk -F, '{print "昨收",$5}'
tail -n +2 ${CSVFILE} | sort -t, -k 3 -n | tail -n 1 | awk -F, '{print "五年內最高",$1,$3}'
tail -n +2 ${CSVFILE} | sort -t, -k 4 -n | head -n 1 | awk -F, '{print "五年內最低",$1,$4}'
tail -n +2 ${CSVFILE} | head -n 5 | sort -t, -k 3 -n | tail -n 1 | awk -F, '{print "五個月內最高",$1,$3}'
tail -n +2 ${CSVFILE} | head -n 5 | sort -t, -k 4 -n | head -n 1 | awk -F, '{print "五個月內最低",$1,$4}'


 
Ref:

延伸閱讀: 股票的鐘型曲線及波動風險



:,