Photo by Igor Shabalin

Python For Finance: Improve Your Stock Trading Performance with Scripting

Yuli Vasiliev
Level Up Coding
Published in
5 min readJul 29, 2020

--

If you search for ways to improve your stock investment skills, you’ll definitely find ‘do some research’ among other things.

The decision on whether to buy, sell, or hold the stock is often taken based on emotions, which is definitely not the best strategy. To make balanced choices, you need to raise your logic and decrease your emotions by weighing up the pros and cons of any possible decision. The ability to make informed decisions can help you get ahead of your competition. This article gives a quick overview of some techniques you can use to improve your stock investment skills, using Python scripting language.

When To Buy?

This is perhaps one of the most important questions for those who are involved in stock trading. It is known that the most significant price fluctuations of a stock typically occur on the day before, on the day of, and the next day of an event related to a company, say, the company’s annual general meeting or quarterly earnings report.

To play with the idea suggested here, you’ll need to have a kind of earnings calendar that includes information about the most significant events for known companies. You’ll find one at https://markets.businessinsider.com/earnings-calendar. The following screenshot includes a fragment of the earnings calendar you should see in your browser:

It is important to note that the stock may react to events that are not in the earning calendar but are significant for the company nevertheless. For example, it can be changing the CEO or a large acquiring, etc. Typically, such events do not go unnoticed by the press. So analyzing news coverage can directly or indirectly indicate what to expect from the market. We’ll touch upon financial news sentiment analysis in the Checking with News Coverage section later in this article.

Exploring Stock Data

If you’ve looked through the list of events in the earnings calendar introduced in the previous section, you might already choose an event for the last month, related to a certain company. Say, Q2 2020 Earnings for Pfizer Inc scheduled for 7/28. So, let’s now explore the stock prices for this company for 7/27 and 7/28 to check if the stock has reacted to the event.

With Python, playing with stock prices for a certain company can be implemented using an API like Yahoo Finance API.

import yfinance as yf
pfe = yf.Ticker('PFE')
hist = pfe.history(period="5d")
pfe_close = hist[['Close']]
pfe_close.sort_values(by = 'Date', ascending=False).head(2)
Close
Date
2020–07–28 39.02
2020–07–27 37.54

As you can see, the stock shows a growth of approximately 4% in one day.

Was Your Investment Really Profitable?

The answer to this question may seem very obvious at first glance: If you’ve managed to f you managed to sell for more than you bought, then the operation can be considered profitable. In real life however, no one uses such straightforward logic. What if the profit you got is similar to what you’d have if invested in any other stock? Can you still consider your investment profitable? Perhaps, an investment can be considered profitable if it let you earn higher returns than, say, S&P500 index figures.

Checking with S&P500 Index

So, checking with S&P500 index is a good way to measure the profitability of your stock operations. To start with, how can you obtain the index figures? The following code address this issue, obtaining the S&P500 figures for the last month:

import pandas_datareader.data as pdr
from datetime import date, timedelta, datetime
end = date.today()
start = datetime(year=end.year, month=end.month-1, day=end.day )
spx_index = pdr.get_data_stooq('^SPX', start, end)

To see the S&P500 index last month figures on a plot, you can generate one as follows:

import matplotlib.pyplot as plt
plt.title(‘The last month price history for S&P500 Index’)
plt.plot(spx_index[‘Close’])
plt.show()

Let’s now look at how the S&P500 index changes correlate with the Pfizer stock price changes for this same period (last month):

import yfinance as yf
pfe = yf.Ticker('PFE')
hist = pfe.history(period="1mo")
pfe_close = hist[['Close']]

For convenience, it would be interesting to join the figures into a single dataframe:

stock_vs_snp = pfe_close.join(spx_index[‘Close’], how=’left’, lsuffix='_stock', rsuffix='_index').dropna()
stock_vs_snp.sort_values(by = 'Date', ascending=False).head(5)
Close_stock Close_index
Date
2020–07–28 39.02 3218.44
2020–07–27 37.54 3239.41
2020–07–24 37.66 3215.63
2020–07–23 38.41 3235.66
2020–07–22 38.56 3276.02

The following plot shows that the growth of stock prices is comparable with the index:

import matplotlib.pyplot as plt
import seaborn as sns
ax=sns.lineplot(data=stock_vs_snp['Close_index'], color="r",label='S&P500 close figures')
ax2 = plt.twinx()
sns.lineplot(data=stock_vs_snp['Close_stock'], color="g", ax=ax2, label='Pfizer stock price figures')
plt.show()

For a more comprehensive discussion on S&P500 index, you might also want to look at this article.

Stock Or Gold?

Using S&P 500 and Dow Jones indexes is not the only way you can employ to measure the profitability of your stock investments. Gold is another alternative. With the Quandl library, you can request the prices for gold in London, which are globally considered as the international standard for pricing of gold.

import quandl
from datetime import date, timedelta, datetime
end = date.today()
start = datetime(year=end.year, month=end.month-1, day=end.day )
london_fixing_gold_price = quandl.get("LBMA/GOLD",start_date=start, end_date=end, authtoken=<your auth token>)
import matplotlib.pyplot as plt
london_fixing_gold_price[‘USD (AM)’].plot(title="Gold Price: in USD(AM price)")
plt.show();

You can impose the stock curve on the above graph in the way you did it for the S&P500 index in the previous section.

Checking with News Coverage

Sentiment analysis is a text processing technique. When it comes to investing, you may analyze sentiment of financial news articles, trying to predict market movements. As a Python user, you can take advantage of the News API (), which lets you get the most relevant news articles in accordance with your request, say, ‘stock’ for articles about stocks in general or, for example, ‘Apple’ to obtain articles about a certain company.

Once you obtain a set of relevant articles, you can automatically figure out whether their sentiment is positive, negative, or neutral. Since sentiment is expressed in figures, you’ll be able to compare it with, for example, S&P500 index to understand how it is related to real market.

The implementation details can be found in this comprehensive article. Also, of you’re interested in natural language processing techniques with Python scripts, check out this repository.

Conclusion

As mentioned in the beginning however, this article provided just a quick overview of some techniques you can use to improve your stock investment skills, using Python scripting language. If you want to look at a more detailed discussion, I would recommend you to check out this series.

--

--