Use This Method to Rate Stocks For Better Investing
Using Python to Create a Scorecard For Stocks Using FMP Data
Stock ratings based on technical indicators involve analyzing various aspects of a stock’s price movements and trading volume to predict future price movements. Technical analysts use charts and statistical indicators to assess trends and patterns in stock prices, aiming to make informed decisions about buying, selling, or holding stocks.. This article shows how to import stock data from FMP and rate them with different recommendations.
Quick Introduction to Technical Analysis
Technical analysis is a method used by traders and investors to evaluate securities and forecast future price movements based on historical price and volume data. It involves studying charts and applying various statistical indicators to identify patterns and trends in market prices.
Moving averages are one of the fundamental tools in technical analysis. They smooth out price data by creating a constantly updated average price over a specific period, such as 10 days, 50 days, or 200 days. Moving averages help traders identify trends by filtering out short-term fluctuations in price, making it easier to spot the direction of the overall trend.
✨ Important note
In this article, we will be using different moving averages to rate the stocks as either Buy, Neutral, or Sell.
For example, a simple moving average calculates the average price over a specified period by adding up the closing prices for each day and dividing by the number of days.
Traders use moving averages in various ways, such as identifying trend reversals, determining support and resistance levels, and generating buy or sell signals when moving average lines cross over each other or the stock price. Moving averages provide valuable insights into market trends and help traders make informed decisions about when to buy or sell securities.
✨ Important note
The simplest way to determine a market trend is to assume that a market trading above its moving average is in a bullish regime, while a market trading below its moving average is in a bearish regime.
A market regime refers to the prevailing characteristics or conditions of a financial market during a particular period. These conditions can encompass a wide range of factors, including volatility levels, trend direction, trading volume, and investor sentiment. Market regimes can be classified into different types based on these characteristics, such as bull markets, bear markets, and neutral (ranging) markets.
The following chart shows EURUSD’s daily values across time. In green, the market is in a bullish regime, in grey, the market seems to be ranging (neutral), and in red, the market seems to be in a bearish regime:
✨ Important note
The first step to analyzing a market is to determine its current regime. If a market is in a bullish regime, then it may be interesting to look for buying opportunities.
Quick Introduction to FMP
Financial Modeling Prep (FMP) API provides real time stock price, company financial statements, major index prices, stock historical data, forex real time rate and cryptocurrencies.
FMP stock price API is in real time, the company reports can be found in quarter or annual format, and goes up to 30 years back in history. This article will show one way to use the API to import key financial metrics and evaluate them using theoretical financial analysis.
Creating the Rating System
The main objective of the algorithm we are about to create is to calculate the average positions of the stock relative to its different moving averages following these steps:
Import the historical stock price data of a certain company (e.g. Apple).
Calculate the 10, 20, 50, 100, 200, and 300-day moving averages.
Calculate the number of moving averages that are above or below the market. If the market is above more than three moving averages, the recommendation is BUY, if the market is below more than three moving averages, the recommendation is SELL. Otherwise, the recommendation is NEUTRAL.
FMP allows you to download the historical OHLC data of the stock price, which is really helpful when analyzing trends and momentum.
Use the following code to create the task:
#!/usr/bin/env python
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
import certifi
import json
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def get_jsonparsed_data(url):
"""
Receive the content of ``url``, parse it as JSON and return the object.
Parameters
----------
url : str
Returns
-------
dict
"""
response = urlopen(url, cafile=certifi.where())
data = response.read().decode("utf-8")
return json.loads(data)
url_1 = ("https://financialmodelingprep.com/api/v3/historical-chart/1hour/AAPL?apikey=f31f6886eaea1332d01938423b8a9c5d")
stock_data_AAPL = get_jsonparsed_data(url_1)
values_array = []
# Loop through each dictionary
for i in stock_data_AAPL:
# Get the first value of the dictionary and append it to the array
first_value = list(i.values())[1]
values_array.append(first_value)
values_array = np.array(values_array)
values_array = np.reshape(values_array[::-1], (-1, 1))
def add_column(data, times):
for i in range(1, times + 1):
new = np.zeros((len(data), 1), dtype = float)
data = np.append(data, new, axis = 1)
return data
def ma(data, lookback, close, position):
data = add_column(data, 1)
for i in range(len(data)):
try:
data[i, position] = (data[i - lookback + 1:i + 1, close].mean())
except IndexError:
pass
return data
values_array = ma(values_array, 10, 0, 1)
values_array = ma(values_array, 20, 0, 2)
values_array = ma(values_array, 50, 0, 3)
values_array = ma(values_array, 100, 0, 4)
values_array = ma(values_array, 200, 0, 5)
values_array = ma(values_array, 300, 0, 6)
rating = []
if values_array[-1, 0] > values_array[-1, 1]:
print('Price > MA10')
rating = np.append(rating, 1)
else:
print('Price < MA10')
rating = np.append(rating, 0)
if values_array[-1, 0] > values_array[-1, 2]:
print('Price > MA20')
rating = np.append(rating, 1)
else:
print('Price < MA20')
rating = np.append(rating, 0)
if values_array[-1, 0] > values_array[-1, 3]:
print('Price > MA50')
rating = np.append(rating, 1)
else:
print('Price < MA50')
rating = np.append(rating, 0)
if values_array[-1, 0] > values_array[-1, 4]:
print('Price > MA100')
rating = np.append(rating, 1)
else:
print('Price < MA100')
rating = np.append(rating, 0)
if values_array[-1, 0] > values_array[-1, 5]:
print('Price > MA200')
rating = np.append(rating, 1)
else:
print('Price < MA200')
rating = np.append(rating, 0)
if values_array[-1, 0] > values_array[-1, 6]:
print('Price > MA300')
rating = np.append(rating, 1)
else:
print('Price < MA300')
rating = np.append(rating, 0)
if np.sum(rating) > 3:
print('Technical Recommendation: BUY')
elif np.sum(rating) == 3:
print('Technical Recommendation: NEUTRAL')
else:
print('Technical Recommendation: SELL')
plt.plot(values_array[:, 0], label = 'APPLE')
plt.plot(values_array[:, 1], label = 'MA10')
plt.plot(values_array[:, 2], label = 'MA20')
plt.plot(values_array[:, 3], label = 'MA50')
plt.plot(values_array[:, 4], label = 'MA100')
plt.plot(values_array[:, 5], label = 'MA200')
plt.plot(values_array[:, 6], label = 'MA300')
plt.legend()
plt.grid()
The output is as follows:
Price > MA10
Price > MA20
Price > MA50
Price < MA100
Price < MA200
Price < MA300
Technical Recommendation: NEUTRAL
The following shows Apple’s stock price with its moving averages:
✨ Important note
You have to create an account and get your API key and replace it in the appropriate place in the previous code. I highly recommend this as it takes no longer than a few minutes.
Link for the FMP site here:
Pricing Plans - Financial Modeling Prep API
Claim free stock market database API. Get API key for real-time stock market dataintelligence.financialmodelingprep.com
Let’s do the same task on NVIDIA’s stock price:
The output is as follows:
Price < MA10
Price < MA20
Price > MA50
Price > MA100
Price > MA200
Price > MA300
Technical Recommendation: BUY
It seems that the current bullish momentum of NVIDIA favors more upside as seen by the simple technical recommendation model.
Link for the FMP site here:
Pricing Plans - Financial Modeling Prep API
Claim free stock market database API. Get API key for real-time stock market dataintelligence.financialmodelingprep.com