DEV Community

Bahman Shadmehr
Bahman Shadmehr

Posted on

Financial Insights: NumPy Magic with Yahoo Finance Data

In the realm of financial analysis, extracting meaningful insights from historical stock price data is a cornerstone of decision-making. In this blog post, we'll embark on a journey into the world of financial data manipulation using NumPy, a powerful Python library, with real-world data fetched from Yahoo Finance. We'll perform an array of calculations, visualize trends, and uncover key metrics that empower us to understand the dynamics of stock prices.

1. Setting the Stage: Fetching Historical Stock Prices

To begin our exploration, let's fetch historical stock prices from Yahoo Finance using the yfinance library. We'll focus on Apple Inc. stock as our example.

import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt

# Define the stock symbol and the time range for historical data
stock_symbol = "AAPL"
start_date = "2022-01-01"
end_date = "2022-12-31"

# Fetch historical stock prices from Yahoo Finance
stock_data = yf.download(stock_symbol, start=start_date, end=end_date)

# Extract Date and Close Price columns
dates = stock_data.index.strftime('%Y-%m-%d')
close_prices = stock_data['Close'].values
Enter fullscreen mode Exit fullscreen mode

2. NumPy in Action: Basic Data Manipulations

Now that we have our historical stock prices, let's perform some basic data manipulations using NumPy.

# Calculate daily returns
daily_returns = np.diff(close_prices) / close_prices[:-1]

# Calculate 50-day and 200-day moving averages
moving_average_50 = np.convolve(close_prices, np.ones(50)/50, mode='valid')
moving_average_200 = np.convolve(close_prices, np.ones(200)/200, mode='valid')

# Calculate percentage changes
percentage_changes = np.diff(close_prices) / close_prices[:-1] * 100

# Calculate cumulative returns
cumulative_returns = np.cumprod(1 + daily_returns) - 1
Enter fullscreen mode Exit fullscreen mode

3. Visualizing Financial Trends: Matplotlib Comes into Play

Let's bring Matplotlib into the mix to visualize the trends we've calculated.

# Plotting
plt.figure(figsize=(12, 6))

plt.subplot(2, 1, 1)
plt.plot(stock_data.index, close_prices, label='Close Price')
plt.plot(stock_data.index[49:], moving_average_50, label='50-day Moving Average')
plt.plot(stock_data.index[199:], moving_average_200, label='200-day Moving Average')
plt.title('Stock Prices and Moving Averages')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()

plt.subplot(2, 1, 2)
plt.plot(stock_data.index, cumulative_returns, label='Cumulative Returns')
plt.title('Cumulative Returns Over Time')
plt.xlabel('Date')
plt.ylabel('Cumulative Return')
plt.legend()

plt.tight_layout()
plt.show()
Enter fullscreen mode Exit fullscreen mode

4. Deriving Insights: Beyond Numbers

The visualizations provide a compelling narrative:

  • Stock Prices and Moving Averages: The interplay between daily closing prices and moving averages helps identify trends and potential turning points.

  • Cumulative Returns Over Time: Observing the cumulative returns over time provides insights into the overall performance of the stock.

5. Conclusion: NumPy's Role in Financial Analysis

NumPy's prowess in handling numerical operations, combined with real-world financial data, empowers analysts to delve deeper into market trends. From daily returns to moving averages and cumulative returns, the toolkit NumPy provides is vast and versatile.

As you embark on your journey into financial data analysis, may NumPy be your trusted companion, unraveling the intricacies of stock prices and guiding you towards more informed decision-making. The financial markets are dynamic, and with the right tools, you're well-equipped to navigate their complexities. Happy coding and may your financial analyses be as insightful as the trends you uncover!

Top comments (0)