Ape Mithrandir on Nostr: ```python import yfinance import pandas as pd import numpy as np import datetime as ...
```python
import yfinance
import pandas as pd
import numpy as np
import datetime as dt
import pytz
import argparse
from dateutil.relativedelta import relativedelta
def get_returns(sInformation, T):
# Calculate the reference date
years = int(T) # Get the whole number of years
months = int((T - years) * 12) # Convert the fractional part to months
ref_dt = dt.datetime.now(pytz.timezone('America/New_York')) - relativedelta(years=years, months=months)
hist = sInformation.history(period='10y')
hist = hist[hist.index >= ref_dt]
f = hist.Close.tolist()[0]
m = hist.Close.mean()
l = hist.Close.tolist()[-1]
tot_lr = np.log(l/f) * 100.0
avg_lr = np.log(l/f)/T * 100.0
tot_ret = (l/f - 1) * 100.0
avg_ret = ((l/f) ** (1.0/T) - 1) * 100.0
# Using T / 2 to represent the average holding time of the avg price
tot_lr_m = np.log(l/m) * 100.0
avg_lr_m = np.log(l/m)/(T/2.0) * 100.0
tot_ret_m = (l/m - 1) * 100.0
avg_ret_m = ((l/m) ** (2.0/T) - 1) * 100.0
return f, m, l, tot_lr, avg_lr, tot_ret, avg_ret, tot_lr_m, avg_lr_m, tot_ret_m, avg_ret_m
def format_number(value):
if value == 0:
return "0" # Handle zero case
elif abs(value) < 1:
return f"{value:.3f}" # 3 decimal places for small values
elif abs(value) < 100:
return f"{value:.2f}" # 2 decimal places for medium values
elif abs(value) < 1000:
return f"{value:.1f}" # 1 decimal place for larger values
else:
return f"{value:,.0f}" # No decimal places for very large values
def print_stats(s, T, f, m, l, tot_lr, avg_lr, tot_ret, avg_ret, tot_lr_m, avg_lr_m, tot_ret_m, avg_ret_m):
print("=============================================")
print(f"{s} Price Stats:")
print("=============================================")
print(f"{T} years ago Price: {format_number(f)}")
print(f"{T} years avg Price: {format_number(m)}")
print(f"Current price: {format_number(l)}\n")
print(f"{s} Returns vs the {T} years old Price:")
print("=============================================")
print(f"Total {T} years log-returns: {format_number(tot_lr)}%")
print(f"Avg {T} years ann. log-returns: {format_number(avg_lr)}%")
print(f"Total {T} years simple-returns: {format_number(tot_ret)}%")
print(f"Avg {T} years ann. simple-returns: {format_number(avg_ret)}%\n")
print(f"{s} Returns vs the {T} years avg Price:")
print("=============================================")
print(f"Total {T} years log-returns: {format_number(tot_lr_m)}%")
print(f"Avg {T} years ann. log-returns: {format_number(avg_lr_m)}%")
print(f"Total {T} years simple-returns: {format_number(tot_ret_m)}%")
print(f"Avg {T} years ann. simple-returns: {format_number(avg_ret_m)}%\n")
def main():
#Create the parser
parser = argparse.ArgumentParser(description='Process some integers.')
# Add arguments
parser.add_argument('--s1', type=str, required=True, help='First Yahoo Finance Instrument')
parser.add_argument('--s2', type=str, help='Second Yahoo Finance Instrument')
parser.add_argument('--T', type=float, required=True, help='Time period in years')
# Parse the arguments
try:
args = parser.parse_args()
except SystemExit as e:
print("Error: Missing required arguments.")
parser.print_help()
return
s1Information = yfinance.Ticker(args.s1)
f1, m1, l1, tot_lr1, avg_lr1, tot_ret1, avg_ret1, tot_lr_m1, avg_lr_m1, tot_ret_m1, avg_ret_m1 = get_returns(s1Information, args.T)
print_stats(args.s1, args.T, f1, m1, l1, tot_lr1, avg_lr1, tot_ret1, avg_ret1, tot_lr_m1, avg_lr_m1, tot_ret_m1, avg_ret_m1)
if args.s2 is not None:
s2Information = yfinance.Ticker(args.s2)
f2, m2, l2, tot_lr2, avg_lr2, tot_ret2, avg_ret2, tot_lr_m2, avg_lr_m2, tot_ret_m2, avg_ret_m2 = get_returns(s2Information, args.T)
print_stats(args.s2, args.T, f2, m2, l2, tot_lr2, avg_lr2, tot_ret2, avg_ret2, tot_lr_m2, avg_lr_m2, tot_ret_m2, avg_ret_m2)
if __name__ == '__main__':
main()
```
Published at
2024-08-31 14:26:06Event JSON
{
"id": "0b1ef69776afd069dec48c667870bc015c62175373e1baf2c59ffbd67f5bc174",
"pubkey": "d361c522fc291b1d478b23bcdcc81838d06a061e1d6e66b46c328daab6fe887c",
"created_at": 1725114366,
"kind": 1,
"tags": [
[
"t",
"Create"
]
],
"content": "```python\nimport yfinance\nimport pandas as pd\nimport numpy as np\nimport datetime as dt\nimport pytz\nimport argparse\nfrom dateutil.relativedelta import relativedelta\n\ndef get_returns(sInformation, T):\n # Calculate the reference date\n years = int(T) # Get the whole number of years\n months = int((T - years) * 12) # Convert the fractional part to months\n ref_dt = dt.datetime.now(pytz.timezone('America/New_York')) - relativedelta(years=years, months=months)\n hist = sInformation.history(period='10y')\n hist = hist[hist.index \u003e= ref_dt]\n f = hist.Close.tolist()[0]\n m = hist.Close.mean()\n l = hist.Close.tolist()[-1]\n tot_lr = np.log(l/f) * 100.0\n avg_lr = np.log(l/f)/T * 100.0\n tot_ret = (l/f - 1) * 100.0\n avg_ret = ((l/f) ** (1.0/T) - 1) * 100.0\n # Using T / 2 to represent the average holding time of the avg price\n tot_lr_m = np.log(l/m) * 100.0\n avg_lr_m = np.log(l/m)/(T/2.0) * 100.0\n tot_ret_m = (l/m - 1) * 100.0\n avg_ret_m = ((l/m) ** (2.0/T) - 1) * 100.0\n return f, m, l, tot_lr, avg_lr, tot_ret, avg_ret, tot_lr_m, avg_lr_m, tot_ret_m, avg_ret_m\n\ndef format_number(value):\n if value == 0:\n return \"0\" # Handle zero case\n elif abs(value) \u003c 1:\n return f\"{value:.3f}\" # 3 decimal places for small values\n elif abs(value) \u003c 100:\n return f\"{value:.2f}\" # 2 decimal places for medium values\n elif abs(value) \u003c 1000:\n return f\"{value:.1f}\" # 1 decimal place for larger values\n else:\n return f\"{value:,.0f}\" # No decimal places for very large values\n\ndef print_stats(s, T, f, m, l, tot_lr, avg_lr, tot_ret, avg_ret, tot_lr_m, avg_lr_m, tot_ret_m, avg_ret_m):\n print(\"=============================================\")\n print(f\"{s} Price Stats:\")\n print(\"=============================================\")\n print(f\"{T} years ago Price: {format_number(f)}\")\n print(f\"{T} years avg Price: {format_number(m)}\")\n print(f\"Current price: {format_number(l)}\\n\")\n print(f\"{s} Returns vs the {T} years old Price:\")\n print(\"=============================================\")\n print(f\"Total {T} years log-returns: {format_number(tot_lr)}%\")\n print(f\"Avg {T} years ann. log-returns: {format_number(avg_lr)}%\")\n print(f\"Total {T} years simple-returns: {format_number(tot_ret)}%\")\n print(f\"Avg {T} years ann. simple-returns: {format_number(avg_ret)}%\\n\")\n print(f\"{s} Returns vs the {T} years avg Price:\")\n print(\"=============================================\")\n print(f\"Total {T} years log-returns: {format_number(tot_lr_m)}%\")\n print(f\"Avg {T} years ann. log-returns: {format_number(avg_lr_m)}%\")\n print(f\"Total {T} years simple-returns: {format_number(tot_ret_m)}%\")\n print(f\"Avg {T} years ann. simple-returns: {format_number(avg_ret_m)}%\\n\")\n\ndef main():\n #Create the parser\n parser = argparse.ArgumentParser(description='Process some integers.')\n \n # Add arguments\n parser.add_argument('--s1', type=str, required=True, help='First Yahoo Finance Instrument')\n parser.add_argument('--s2', type=str, help='Second Yahoo Finance Instrument')\n parser.add_argument('--T', type=float, required=True, help='Time period in years')\n\n # Parse the arguments\n try:\n args = parser.parse_args()\n except SystemExit as e:\n print(\"Error: Missing required arguments.\")\n parser.print_help()\n return\n\n s1Information = yfinance.Ticker(args.s1)\n f1, m1, l1, tot_lr1, avg_lr1, tot_ret1, avg_ret1, tot_lr_m1, avg_lr_m1, tot_ret_m1, avg_ret_m1 = get_returns(s1Information, args.T)\n print_stats(args.s1, args.T, f1, m1, l1, tot_lr1, avg_lr1, tot_ret1, avg_ret1, tot_lr_m1, avg_lr_m1, tot_ret_m1, avg_ret_m1)\n if args.s2 is not None:\n s2Information = yfinance.Ticker(args.s2)\n f2, m2, l2, tot_lr2, avg_lr2, tot_ret2, avg_ret2, tot_lr_m2, avg_lr_m2, tot_ret_m2, avg_ret_m2 = get_returns(s2Information, args.T)\n print_stats(args.s2, args.T, f2, m2, l2, tot_lr2, avg_lr2, tot_ret2, avg_ret2, tot_lr_m2, avg_lr_m2, tot_ret_m2, avg_ret_m2)\n\nif __name__ == '__main__':\n main()\n```",
"sig": "fc640012bb942ee790a522cce90b32c16ede205075f47dde2f6d8b218f39629787db432b34c28a30993d558582d856efe9ae2d089248e57da4c12ba236b95fb1"
}