python 股票预警_如何使用python建立股价预警

python 股票预警

There can be a million reasons why you would invest in stocks. You want to be rich like Warren Buffet, you want to save up for retirement, or you just don’t want to miss out on the rising stock market ride.

您可能有上百万个理由投资股票。 您想像沃伦·巴菲特(Warren Buffet)这样的富人,想为退休储蓄,或者只是不想错过股市上涨的机会。

Whatever your reason might be, you need to be aware of the price of the stock you’re interested in. Here is a simple guide to set up an email alert to notify when a stock reaches the price you desire.

无论您是出于何种原因,都需要了解自己感兴趣的股票价格。这是一个简单的指南,用于设置电子邮件警报,以在股票达到所需价格时发出通知。

在设备上设置Python(如果已设置,请跳过) (Setting up Python on your device (skip if you have it set up already))

If you’re reading this article I will assume that you have Python installed and have your favorite code editor set up.

如果您正在阅读本文,我将假定您已经安装了Python并已设置了您喜欢的代码编辑器。

If not, here is a great guide to get you started, come back after you review it to follow along.

如果没有,这是一个很好的入门指南,请仔细阅读后再回来。

采取的步骤: (Steps to take:)

  • Get API key from Alpha Vantage

    从Alpha Vantage获取API密钥
  • Import relevant packages

    导入相关包
  • Pull the data from Alpha Vantage

    从Alpha Vantage提取数据
  • Picking the relevant data

    挑选相关数据
  • Setting up an email notification

    设置电子邮件通知
  • Notes

    笔记

从Alpha Vantage获取API密钥 (Get API key from Alpha Vantage)

Alpha Vantage provides free stock data. They were build to democratize the access to data for the purpose of using in projects such as this.

Alpha Vantage提供免费的库存数据。 建立它们的目的是使对数据的访问民主化,以用于诸如此类的项目。

Normally you would have to go through a paid service or scrape the data off of Yahoo Finance or another service.

通常,您将不得不通过付费服务或从Yahoo Finance或其他服务中抓取数据

To pull your data from Alpha Vantage, you will need to receive an API key. Follow this link to their website which looks like this:

要从Alpha Vantage中提取数据,您需要接收一个API密钥。 通过此链接访问其网站,如下所示:

Image for post
https://www.alphavantage.co by the Author https://www.alphavantage.co的屏幕截图

Click on the “Get your free API key today”

点击“立即获取免费的API密钥”

Image for post
Image credit by Author
图片版权归作者所有

Once you fill the little form above, you will be given an API key which will enable you to pull data from Alpha Vantage. Take a note of the API key and let’s jump into our Code editor.

填写上面的小表格后,您将获得一个API密钥,该密钥使您能够从Alpha Vantage中提取数据。 记下API密钥,然后进入代码编辑器。

导入相关包 (Import relevant packages)

To get started with our project we need to make sure that we have all the relevant packages installed and imported. If you don’t know how to install packages you can learn it from here:

要开始我们的项目,我们需要确保已经安装并导入了所有相关的软件包。 如果您不知道如何安装软件包,可以从这里学习:

import pandas as pd #data manipulation and analysis packagefrom alpha_vantage.timeseries import TimeSeries #enables data pull from Alpha Vantageimport matplotlib.pyplot as plt #if you want to plot your findingsimport timeimport smtplib #enables you to send emails

从Alpha Vantage提取数据 (Pulling the data from Alpha Vantage)

Here we will use the API key we just obtained from above, on the example below you will find the one I used while building the project initially:

在这里,我们将使用刚刚从上面获得的API密钥,在下面的示例中,您将找到我在最初构建项目时使用的密钥:

#Getting the data from alpha_vantagets = TimeSeries(key='CZK4PSW4EWOIOSUG', output_format='pandas')data, meta_data = ts.get_intraday(symbol='MSFT',interval='1min', outputsize='full')

On the first line, you are creating a time-series data frame and telling python to have the format as a pandas data frame.

在第一行,您将创建一个时间序列数据框,并告诉python将其格式设置为pandas数据框。

In this case, I have used Microsoft or MSFT but you can use your own stocks. A couple of examples would be:

在这种情况下,我使用了Microsoft或MSFT,但您可以使用自己的股票。 以下是几个示例:

  • AAPL — Apple

    AAPL-苹果
  • AMZN — Amazon

    AMZN-亚马逊
  • FB — Facebook

    FB-Facebook

If you’re unsure about the ticker of your stock, you can go to Yahoo Finance and type in the company you’re interested in. It will display the stock ticker for you.

如果不确定股票代码,可以转到Yahoo Finance并输入您感兴趣的公司。它将为您显示股票代码。

Another input that you can specify is the interval in which you want the program to pull data. I have specified 1min for the interval. A couple of other options include:

您可以指定的另一个输入是希望程序提取数据的时间间隔。 我为间隔指定了1min 。 其他几个选项包括:

  • 1min, 5min, 15min, 30min, 60min

    1min5min15min30min60min

To try and explore more options I recommend you read the Alpha Vantage documentation here.

为了尝试探索更多选项,我建议您在此处阅读Alpha Vantage文档。

选择正确的数据 (Picking the right data)

Alpha Vantage will by default output the following information for a stock.

默认情况下,Alpha Vantage将输出股票的以下信息。

For the purposes of this project, we will only use the close column which indicates the closing price of the stock.

对于这个项目的目的,我们将只使用close柱这表明股票的收盘价。

Other columns if you’re interested: open, high, low, close, volume

如果您有兴趣open, high, low, close, volume还可以选择其他栏目: open, high, low, close, volume

#We are currently interested in the latest priceclose_data = data['4. close'] #The close data column
last_price = close_data[0] #Selecting the last price from the close_data column#Check if you're getting a correct value
print(last_price)

The output was:$ 220.9 as of Aug 26, 20:00

输出为:$ 220.9截至8月26日,20:00

设置电子邮件通知 (Setting up the email notification)

Now that we are able to pull the latest prices of the stock we desire. We can set up an email alert to notify us when the time is right.

现在我们可以拉出我们想要的股票的最新价格。 我们可以设置电子邮件警报以在适当的时候通知我们。

#Set the desired message you want to see once the stock price is at a certain levelsender_email = "youremail@email.com" #The sender emailrec_email = "receivingemail@email.com" #The receiver emailpassword = ("password")#The password to the sender emailmessage = "MSFT STOCK ALERT!!! The stock is at above price you set " + "%.6f" % last_price  #The message you want to send

Below we will set up the condition and the trigger that will cause the email to be sent to us when the time is right.

在下面,我们将设置条件和触发条件,以便在适当的时候将电子邮件发送给我们。

Let’s assume that you own a bunch of MSFT stock and you want to sell it when the time is right. the target_sell_price variable enables you to set the limit you want.

假设您拥有大量MSFT股票,并且想在适当的时候出售它。 使用target_sell_price变量可以设置所需的限制。

For example, if you believe that the stock price is too high right now and want to get out / believe that you have sufficient profits at the $220.00 price level, you can use that limit. It is totally up to you to enter your desired number.

例如,如果您认为股票价格现在太高了,并且想出去/认为您在$ 220.00的价格水平上有足够的利润,则可以使用该限制。 输入所需的号码完全取决于您。

target_sell_price = 220 #enter the price you want to sell atif last_price > target_sell_price:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, password) #logs into your email account
print("Login Success")#confirms that you have logged in succesfully
server.sendmail(sender_email, rec_email, message)#send the email with your custom mesage
print("Email was sent") #confirms that the email was sentYou’re DONE! If everything went as planned you should expect to find an email like this:
Image for post
Image credit Author
图片信用作者

Here is the full code for your reference:

这是完整的代码供您参考:

import pandas as pd #data manipulation and analysis package
from alpha_vantage.timeseries import TimeSeries #enables data pull from Alpha Vantage
import matplotlib.pyplot as plt #if you want to plot your findings
import time
import smtplib #enables you to send emails#Getting the data from alpha_vantagets = TimeSeries(key='CZK4PSW4EWOIOSUG', output_format='pandas')data, meta_data = ts.get_intraday(symbol='MSFT',interval='1min', outputsize='full')#We are currently interested in the latest priceclose_data = data['4. close'] #The close data column
last_price = close_data[0] #Selecting the last price from the close_data column#Check if you're getting a correct value
print(last_price)#Set the desired message you want to see once the stock price is at a certain levelsender_email = "youremail@email.com" #The sender emailrec_email = "receivingemail@email.com" #The receiver emailpassword = ("password")#The password to the sender emailmessage = "MSFT STOCK ALERT!!! The stock is at above price you set " + "%.6f" % last_price #The message you want to sendtarget_sell_price = 220 #enter the price you want to sell atif last_price > target_sell_price:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls() server.login(sender_email, password) #logs into your email account
print("Login Success")#confirms that you have logged in succesfully server.sendmail(sender_email, rec_email, message)#send the email with your custom mesage
print("Email was sent") #confirms that the email was sent

笔记 (Notes)

  • If you copy and paste the full code above DO NOT forget to enter your own email and password information.

    如果您复制并粘贴上面的完整代码,请不要忘记输入您自己的电子邮件和密码信息。
  • Make sure to use your own API key obtained by Alpha Vantage

    确保使用Alpha Vantage获得的自己的API密钥
  • By no means is this a trading or stock investment advice

    绝不是交易或股票投资建议
  • If you get an error saying your password is rejected, you might want to configure the “Less secure apps” settings on (assuming you use a Gmail account) Gmail account here. This will enable your program to access your google account and send an email on your behalf, otherwise, Google will reject the request from your program.

    如果您收到错误消息,提示您的密码被拒绝,则可能要在此处 (假设您使用Gmail帐户)Gmail帐户上配置“缺少安全应用”设置。 这将使您的程序可以访问您的Google帐户并代表您发送电子邮件,否则,Google将拒绝您程序的请求。

几个改进思路 (A couple of improvement ideas)

  • You can add more stocks to your tracker and set buy/sell targets

    您可以将更多股票添加到跟踪器并设置买/卖目标
  • You can make the email look better and create an email service (or have fun with your friends. To format your Python emails check this out.

    您可以使电子邮件看起来更好,并创建电子邮件服务(或与朋友一起玩耍。要格式化Python电子邮件,请检查此)

  • You can create more sophisticated indicators such as: change_in_price to seek volatility.

    您可以创建更复杂的指标,例如: change_in_price以寻求波动性。

I hope that this simple walkthrough helps you dip your toes in the water. Even if you’re not a coder I hope you were able to follow through. Happy coding!!

我希望这个简单的演练可以帮助您将脚趾浸入水中。 即使您不是编码人员,我也希望您能够继续学习。 编码愉快!!

翻译自: https://medium.com/illumination/how-to-build-a-stock-price-alert-using-python-d7d61ec12f2

python 股票预警

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值