如何使用Python发送库存更新

As a way to identify new companies to invest in, I like to watch out for the biggest market movers each day. However, there are thousands of stocks out there, and checking the news for each one would take forever.

作为确定要投资的新公司的一种方式,我喜欢每天注意最大的市场推动者。 但是,那里有成千上万的股票,要检查每只股票的消息将是永远的。

Luckily, we have Python which can do this in minutes. Not only is Python great for crunching data, its versatility allows it to send important emails, automating the entire workflow in one step. Rather than waiting hours or days, people can receive vital information in minutes.

幸运的是,我们拥有可以在几分钟内完成此操作的Python。 Python不仅非常适合处理数据,它的多功能性还使其能够发送重要的电子邮件,从而一步一步实现了整个工作流程的自动化。 人们无需等待数小时或数天,而可以在几分钟内收到重要信息。

For this article, I’d like to focus on how to both use Python to calculate daily price changes for each stock in the Nasdaq 100 and S&P 500 and then to send an email with a list of the biggest movers in the market automatically.

在本文中,我想重点介绍如何同时使用Python计算Nasdaq 100和S&P 500中每只股票的每日价格变化,然后自动发送一封电子邮件,列出市场上最大的推动者。

使用Python计算每日价格变化 (Using Python to Calculate Daily Price Changes)

Python has several financial packages that make pulling financial data extremely easy. yfinance and ffn are two that I’ve used, and I’ll use yfinance for this article.

Python有几个财务软件包,这些软件包使提取财务数据非常容易。 y 财务ffn是我使用的两个,在本文中我将使用yfinance。

In addition to needing yfinance as way to pull data for a stock, we also need a way to programmatically pull information for each stock in the S&P 500 and Nasdaq 100. Typing each stock out is just not going to cut it. Therefore, we’ll also be using requests and pandas to get and read stock market symbols from the web.

除了需要财务来提取股票数据之外,我们还需要一种方法来以编程方式提取S&P 500和Nasdaq 100中每只股票的信息。键入每只股票不会削减它。 因此,我们还将使用请求和熊猫从网上获取和读取股票市场代码。

To get started, let’s import the following packages:

首先,让我们导入以下软件包:

import requests
import pandas as pd
import yfinance as yf
import time

Next, we’ll pull a list of stock tickers from Wikipedia and plug them into python, so that it can calculate the daily change for each stock:

接下来,我们将从Wikipedia中提取股票行情清单,并将其插入python,以便它可以计算每种股票的每日变化:

#Read data from Wikiweb_data = requests.get('https://en.wikipedia.org/wiki/NASDAQ-100#Changes_in_2020').text#Put data into Pandas to easily create a list of tickers to loop throughnasdaq_df = pd.read_html(web_data)#Finds the Wiki table with tickers and stores them in Pandas Data Framenasdaq_df = nasdaq_df[2]#Creates a list of tickers from Data Frame to loop throughnasdaq_tickers = list(nasdaq_df['Ticker'])

We’ll repeat the process for stocks in the S&P 500:

我们将对标准普尔500指数中的股票重复此过程:

#Repeat process for S&P tickers
url = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'data = requests.get(url).textsp_df = pd.read_html(data)sp_df = sp_df[0]sp_tickers = list(sp_df['Symbol'])

We now have our list of stocks for which we’ll calculate prices changes. To calculate the price change, we’ll loop through the lists and use yfinance to pull price data over specified interval and pandas to calculate the change in price. This will take a minute or two to run:

现在,我们有了要计算其价格变化的库存清单。 为了计算价格变化,我们将遍历列表,并使用yfinance提取指定时间间隔内的价格数据,并使用熊猫来计算价格变化。 这需要一两分钟才能运行:

df = pd.DataFrame(columns=['Symbol', 'Percent_Change'])for ticker in nasdaq_tickers:
stock = yf.Ticker(ticker)
data = stock.history(period='2d')
first = data['Open'].iloc[0]
last = data['Close'].iloc[-1]
chg = ((last - first)/first)*100
chg = "{:.2f}".format(chg) df = df.append(dict(zip(df.columns,[ticker, chg])), ignore_index=True)print("Nasdaq Completed")for ticker in sp_tickers:
stock = yf.Ticker(ticker)
data = stock.history(period='2d')
if data.empty == True:
print(f"{ticker}: not found")
else:
first = data['Open'].iloc[0]
last = data['Close'].iloc[-1]
chg = ((last - first)/first)*100
chg = "{:.2f}".format(chg)
df = df.append(dict(zip(df.columns,[ticker, chg])), ignore_index=True)
print("S&P Completed")

After calculating the change for each stock, we need to filter our data to look for stocks that stood out. I personally set a filter that filters for stocks that have gained at least 5%, but feel free to play around with that and adjust it to your needs:

在计算完每只股票的变动之后,我们需要过滤数据以寻找突出的股票。 我个人设置了一个过滤器,用于过滤那些涨幅至少为5%的股票,但是可以随意尝试并根据您的需要进行调整:

df['Percent_Change'] = df['Percent_Change'].astype(float)
df_filtered = df.query("Percent_Change>=5")

After filtering the data, we need to save the results to a file in order to send them in email. In this example, I’ve saved them to a text file because Excel and csv files give me issues every now and then. Feel free to choose a file format that best suits your needs:

过滤数据后,我们需要将结果保存到文件中,以便通过电子邮件发送。 在此示例中,我将它们保存到文本文件中,因为Excel和csv文件时不时会给我一些问题。 随意选择最适合您需要的文件格式:

import os
os.chdir('Specify a file location to save the file in')#This allows today's date to be added without hardcoding it
today = pd.datetime.now().date()df_filtered.to_csv("Nasdaq and S&P Daily Gainers " + str(today) +".txt", index=False)

自动发送结果 (Sending the Results Automatically)

Now that we’ve created a file of our market movers, we’ll send it out on a schedule. Python has a package, schedule, that allows jobs to be completed at a specified time. It requires a function that performs a certain task, say sending an email, to be created, and the schedule package subsequently calls that function at a specified time.

现在,我们已经创建了一个有关市场动向的文件,我们将按计划将其发送出去。 Python有一个schedule包,它允许作业在指定的时间完成。 它需要执行某项任务的功能(例如,发送电子邮件),然后计划包随后在指定的时间调用该功能。

We’ll first create a function that sends an email:

我们首先创建一个发送电子邮件的函数:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encodersdef send_email():
today = pd.datetime.now().date()
email_sender = 'INSERT YOUR EMAIL'
email_recipient = "INSERT RECIPEINT EMAIL"
msg = MIMEMultipart()
email_message = "Attached are today's market movers"
attachment_location= "FILE LOCATION + FILE NAME" msg['From'] = email_sender
msg['To'] = email_recipient
msg['Subject'] = "Weekly Stocks"
msg.attach(MIMEText(email_message, 'plain')) if attachment_location != '':
filename = os.path.basename(attachment_location)
attachment = open(attachment_location, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename=%s" % filename) msg.attach(part)
try:
server = smtplib.SMTP('smtp-mail.outlook.com', 587)
server.ehlo()
server.starttls()
server.login('YOUR EMAIL ADDRESS', 'YOUR PASSWORD')
text = msg.as_string()
server.sendmail(email_sender, email_recipient, text)
print('email sent')
server.quit()
except:
print("Connection Error") #return schedule.CancelJob schedules the job only once.
return schedule.CancelJob

After creating our email function, we’ll create the schedule to send an email every day at 5PM.

创建电子邮件功能后,我们将创建时间表,以每天下午5点发送电子邮件。

import schedule
schedule.every().day.at("17:00").do(send_email)while schedule.jobs:
# Checks whether a scheduled task is pending to run or not
schedule.run_pending()
time.sleep(1)

结语 (Wrapping Up)

In this article, we saw how Python can quickly and efficiently identify trending stocks. Gathering and sending important data in a timely way can make all the difference. In this case, it can come down to quickly being able to spot a new investment opportunity or missing the boat.

在本文中,我们了解了Python如何快速有效地识别趋势股票。 及时收集和发送重要数据可以发挥作用。 在这种情况下,可以归结为Swift找到新的投资机会或错过机会。

翻译自: https://medium.com/python-in-plain-english/sending-stock-updates-with-python-c63a54a63f10

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值