Python
The code consists of a Python function called view_stock_data() that uses the yfinance library to retrieve historical stock data from Yahoo Finance, clean and format it, and plot it using the matplotlib library.
Here is a breakdown of each step in the function:
Explanation of the code:
- The
yfinance
library is imported to get the historical stock prices, and thematplotlib
library is imported to plot the data. TheYahooFinancials
class is imported from theyahoofinancials
library to create aYahooFinancials
object for the ticker symbol. - The function
plot_historical_stock_prices
is defined that takes in three arguments: the ticker symbol, start date, and end date. - A
YahooFinancials
object is created for the specified ticker symbol. - The
get_historical_price_data
method is called on theYahooFinancials
object with the specified start date, end date, and frequency (daily) to get the historical stock prices for the specified date range. - The closing prices are extracted from the historical stock prices data by looping through each day’s data and appending the closing price to a list.
- The historical closing prices are plotted using
matplotlib
.
Let’s get started,
To install a library in Python, you can use the pip
command in the terminal or command prompt. Here are the steps:
- Open the terminal or command prompt.
- Type
pip install yfinance
andpip install matplotlib
andpip install yahoofinancials
and press Enter. - Wait for the installation to complete. You should see a message that says “Successfully installed library_name version_number”.
Alternatively, if you are using an integrated development environment (IDE) such as Anaconda, you can install libraries using the package manager provided by the IDE. The steps may vary depending on the IDE, but in general, you can search for the library in the package manager and click the “Install” button to install it.
This should produce a plot of the historical closing prices of AAPL for the specified date range.
Now, write the code below in your Python Console,
import yfinance as yf
import matplotlib.pyplot as plt
from yahoofinancials import YahooFinancials
def anomalies_historical_stock_prices(ticker, start_date, end_date):
# Create a YahooFinancials object for the specified ticker symbol
yahoo_financials = YahooFinancials(ticker)
# Get the historical stock prices for the specified date range
historical_stock_prices = yahoo_financials.get_historical_price_data(start_date, end_date, 'daily')
# Extract just the closing prices from the historical stock prices data
closing_prices = [day['close'] for day in historical_stock_prices[ticker]['prices']]
# Plot the historical closing prices
plt.plot(closing_prices)
plt.title('Historical Stock Prices for ' + ticker + ' from ' + start_date + ' to ' + end_date)
plt.xlabel('Time (days)')
plt.ylabel('Closing Price ($)')
plt.show()
Here is an example of how to use this function:
anomalies_historical_stock_prices('AAPL', '2013-01-01', '2013-03-31')
This will download and plot the historical stock data for Apple Inc. (AAPL) from January 1, 2013 to March 31, 2013.
R-Project
library(yahoo-finance)
library(ggplot2)
get_historical_stock_prices <- function(ticker, start_date, end_date) {
# Convert start_date and end_date to POSIXct format
start_date <- as.POSIXct(start_date)
end_date <- as.POSIXct(end_date)
# Retrieve historical stock prices using yahoo.finance API
stock_prices <- yahoo.finance::yahoo_series(ticker, start_date, end_date, "day")
# Extract closing prices from stock_prices data
closing_prices <- stock_prices$close
# Return closing_prices data
return(closing_prices)
}
# Example usage
aapl_prices <- get_historical_stock_prices("AAPL", "2015-01-01", "2022-04-09")
# Plot the historical closing prices
ggplot(data = data.frame(closing_prices = aapl_prices), aes(x = seq_along(closing_prices), y = closing_prices)) +
geom_line() +
labs(title = "Anomalies Post - Historical Stock Prices for Apple Inc.",
x = "Time (days)",
y = "Closing Price ($)")
This function uses the yahoo.finance
package in R to retrieve historical stock prices for a given stock ticker and time period. It first converts the start_date and end_date parameters to POSIXct
format, and then retrieves the stock prices using the yahoo_series
function. It then extracts the closing prices from the stock prices data, and returns it as a vector. Finally, it plots the historical closing prices using ggplot2
.
To use this function, simply call it with the desired stock ticker, start date, and end date parameters. The function will return a vector of closing prices for the given stock ticker and time period, which can then be plotted using ggplot2
.
You must log in to post a comment.