Skip to content

Instantly share code, notes, and snippets.

@guicaulada
Last active January 7, 2026 12:58
Show Gist options
  • Select an option

  • Save guicaulada/a409f133930b0e56770f60357dd1a1b1 to your computer and use it in GitHub Desktop.

Select an option

Save guicaulada/a409f133930b0e56770f60357dd1a1b1 to your computer and use it in GitHub Desktop.
Rebalance your shares
#!/bin/bash
# Script to calculate the number of shares to buy/sell for rebalancing.
# Formula: ((market_value * target_percentage / current_percentage) - market_value) / last_price
# Percentages can be provided as decimals (e.g., 0.20 for 20%) or integers (e.g., 20 for 20%).
# The script assumes consistent format for both percentages.
usage() {
echo "Usage: $0 market_value target_percentage current_percentage last_price"
echo ""
echo "Arguments:"
echo " last_price Current price per share (e.g., 50)"
echo " market_value Current market value of the asset (e.g., 10000)"
echo " current_percentage Current actual percentage (e.g., 15 or 0.15)"
echo " target_percentage Desired target percentage (e.g., 20 or 0.20)"
echo ""
echo "Options:"
echo " -h, --help Display this help message"
echo ""
echo "Example:"
echo " $0 50 10000 15 20"
echo " This calculates shares needed to rebalance from 15% to 20%."
echo ""
echo "Note: A positive result means shares to buy; negative means shares to sell."
exit 0
}
# Check for help flag
if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
usage
fi
# Check if exactly 4 arguments are provided
if [ $# -ne 4 ]; then
echo "Error: Incorrect number of arguments."
usage
fi
last_price="$1"
market_value="$2"
current_percentage="$3"
target_percentage="$4"
# Validate inputs are numbers (basic check)
if ! [[ "$market_value" =~ ^[0-9]+(\.[0-9]+)?$ ]] ||
! [[ "$target_percentage" =~ ^[0-9]+(\.[0-9]+)?$ ]] ||
! [[ "$current_percentage" =~ ^[0-9]+(\.[0-9]+)?$ && "$current_percentage" != "0" ]] ||
! [[ "$last_price" =~ ^[0-9]+(\.[0-9]+)?$ && "$last_price" != "0" ]]; then
echo "Error: All arguments must be positive numbers. Current percentage and price cannot be zero."
exit 1
fi
# Perform the calculation with bc
result=$(echo "scale=6; (($market_value * $target_percentage / $current_percentage) - $market_value) / $last_price" | bc -l)
echo "$result"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment