我想知道是否可以通过一键/快捷方式执行我制作的Python脚本。
即我不想打开终端或 VS code 来执行它,而是“直接运行它”。
这可能吗?
最好的, 安德斯
import yfinance as yf
from datetime import datetime, timedelta
import locale
import smtplib
import ssl
stocks_dict = {
"YOU": 'About You Holding SE',
"CSIQ": 'Canadian Solar'
}
def format_currency(value):
return '{:.2f}'.format(value).replace('.', ',')
def get_stock_data(ticker, name):
stock = yf.Ticker(ticker)
end_date = datetime.now()
start_date = end_date - timedelta(days=2)
history = stock.history(start=start_date, end=end_date)
current_price = stock.history(period='1d')['Close'].iloc[-1]
current_price = round(current_price, 2)
if len(stock.history(period='2d')) >= 2:
previous_close = stock.history(period='2d')['Close'].iloc[-2]
price_change_percent = ((current_price - previous_close) / previous_close) * 100
else:
price_change_percent = float('nan')
highest_price_last_year = stock.history(period='1y')['Close'].max()
highest_price_last_year = round(highest_price_last_year, 2)
highest_price_last_5_years = stock.history(period='5y')['Close'].max()
highest_price_last_5_years = round(highest_price_last_5_years,2)
return (f"{name} ({ticker})\n"
f"Kursudvikling de sidste 24 timer: {'N/A' if price_change_percent is None else f'{round(price_change_percent, 2)}%'}\n"
f"Nuværende kurs: {format_currency(current_price)} USD\n"
f"Højeste kurs sidste år: {format_currency(highest_price_last_year)} USD\n"
f"Højeste kurs sidste 5 år: {format_currency(highest_price_last_5_years)} USD\n\n")
def send_mail(subject, body, sender_email, recipient_email, password):
context = ssl.create_default_context()
smtp_server = "smtp.simply.com"
smtp_port = 587
email_message = f"From: {sender_email}\n"
email_message += f"To: {recipient_email}\n"
email_message += f"Subject: {subject}\n\n{body}"
email_message = email_message.encode("utf-8")
try:
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls(context=context)
server.login(sender_email, password)
server.sendmail(sender_email, recipient_email, email_message)
print(f"E-mail sendt til {recipient_email}!")
except smtplib.SMTPException as e:
print(f"Fejl i send_mail: {e}")
except Exception as e:
print(f"Generel fejl i send_mail: {e}")
sender_email = "..."
recipient_email = "..."
password = "..."
email_subject = "Stock Data Overview"
email_body = ""
for ticker, name in stocks_dict.items():
email_body += get_stock_data(ticker, name)
send_mail(email_subject, email_body, sender_email, recipient_email, password)
我尝试过研究快捷方式和自动化程序。 Automator“工作”,但它不允许“import yfinance as yf”并抛出错误。
根据您的输入,我设法使用 Automator 运行该文件。一切都好(除了它抛出一个错误(send_mail:[SSL:CERTIFICATE_VERIFY_FAILED]证书验证失败:无法获取本地颁发者证书(_ssl.c:997),但我会调查这一点) - 谢谢:)