Dollar cost average stocks based on Yahoo Finance API

2 min read Original article ↗
#!/bin/bash
# Default values for tickers and DCA thresholds
tickers=("^GSPC" "AAPL" "AMZN" "GOOG" "MSFT" "NVDA" "PLTR" "TSLA")
dca_low=0.80
dca_high=0.95
# Function to display help
display_help() {
echo "Usage: $(basename "$0") [options]"
echo
echo "Options:"
echo " -t, --tickers Comma-separated list of stock tickers (e.g., \"AAPL,GOOG,MSFT\")"
echo " -l, --low Low DCA threshold as a fraction of 52-week high (default: 0.80)"
echo " -h, --high High DCA threshold as a fraction of 52-week high (default: 0.95)"
echo " --help Display this help message"
echo
exit 1
}
# Function to check for dependencies
check_dependencies() {
local dependencies=("jq" "curl")
for dep in "${dependencies[@]}"; do
if ! command -v $dep &> /dev/null; then
echo "Error: $dep is not installed."
echo "Please install $dep to run this script."
echo "For example, you can install it using:"
echo " sudo apt-get install $dep"
exit 1
fi
done
}
# Parse command line arguments
while [[ "$1" != "" ]]; do
case $1 in
-t | --tickers ) shift
IFS=',' read -r -a tickers <<< "$1"
;;
-l | --low ) shift
dca_low=$1
;;
-h | --high ) shift
dca_high=$1
;;
--help ) display_help
;;
* ) display_help
;;
esac
shift
done
# Check for dependencies
check_dependencies
# Function to determine buying strategy
determine_strategy() {
TICKER=$1
ONE_YEAR_AGO=$(date -v-1y "+%s" 2>/dev/null || date -d '1 year ago' "+%s" 2>/dev/null)
RESPONSE=$(curl -s "https://query1.finance.yahoo.com/v8/finance/chart/$TICKER?period2=$(date +%s)&period1=$ONE_YEAR_AGO&interval=1d")
HIGH_52_WEEK=$(echo $RESPONSE | jq '[.chart.result[0].indicators.quote[0].high[]] | max')
DAILY_HIGH=$(echo $RESPONSE | jq '.chart.result[0].meta.regularMarketDayHigh')
THRESHOLD_AGGRESSIVE=$(echo "$HIGH_52_WEEK * $dca_low" | bc)
THRESHOLD_NORMAL=$(echo "$HIGH_52_WEEK * $dca_high" | bc)
if (( $(echo "$DAILY_HIGH < $THRESHOLD_AGGRESSIVE" | bc -l) )); then
STRATEGY="Buy aggressively"
elif (( $(echo "$DAILY_HIGH < $THRESHOLD_NORMAL" | bc -l) )); then
STRATEGY="Buy normally"
else
STRATEGY="Don't buy"
fi
# Adjusted printf statement for better alignment
printf "| %-8s | %12.2f | %18.2f | %12.2f | %12.2f | %-18s |\n" "$TICKER" "$DAILY_HIGH" "$HIGH_52_WEEK" "$THRESHOLD_AGGRESSIVE" "$THRESHOLD_NORMAL" "$STRATEGY"
}
# Print header with adjusted spacing
printf "| %-8s | %-12s | %-18s | %-12s | %-12s | %-18s |\n" "Ticker" "Daily High" "Year High" "High x $dca_low" "High x $dca_high" "Strategy"
printf "| %-8s | %-12s | %-18s | %-12s | %-12s | %-18s |\n" "--------" "------------" "------------------" "------------" "------------" "------------------"
# Loop through each ticker and determine strategy
for ticker in "${tickers[@]}"; do
determine_strategy $ticker
done