Unlock Stock Insights: Analyzing Apple Prices with NumPy in Python
This tutorial shows how to load Apple stock data from a CSV file using NumPy, then compute basic statistics such as mean, weighted average, min/max, variance, daily returns, volatility, and weekday‑based price averages, illustrating essential data‑analysis functions for finance.
This article demonstrates how to use NumPy to read a CSV file containing Apple stock data and perform basic statistical analysis such as mean, weighted average, min/max, variance, daily returns, volatility, and weekday aggregation.
Reading CSV Data
Use np.loadtxt to load the closing price and volume columns from AAPL.csv.
import numpy as np
c, v = np.loadtxt('AAPL.csv', delimiter=',', usecols=(1,2), unpack=True)
print(c)
print(v)Simple Statistics
Compute arithmetic mean, weighted average (VWAP), maximum, minimum, range, and variance.
mean_c = np.mean(c)
print(mean_c)
vwap = np.average(c, weights=v)
print(vwap)
max_price = np.max(c)
min_price = np.min(c)
range_price = np.ptp(c)
print(max_price, min_price, range_price)
var_c = np.var(c)
print(var_c)Daily Returns and Volatility
Calculate daily returns, their standard deviation, and annualized volatility using logarithmic returns.
returns = -np.diff(c) / c[1:]
print(returns)
std_ret = np.std(returns)
print(std_ret)
logreturns = -np.diff(np.log(c))
volatility = np.std(logreturns) / np.mean(logreturns)
annual_volatility = volatility / np.sqrt(1/252)
print(volatility)
print(annual_volatility)Date Handling and Weekday Analysis
Convert byte‑encoded date strings to datetime objects, extract weekdays, and compute average closing price for each weekday.
import datetime
def datestr2num(bytedate):
return datetime.datetime.strptime(bytedate.decode('utf-8'), '%Y/%m/%d').date().weekday()
dates, c = np.loadtxt('AAPL.csv', delimiter=',', usecols=(0,1), converters={0: datestr2num}, unpack=True)
averages = np.zeros(5)
for i in range(5):
idx = np.where(dates == i)
prices = np.take(c, idx)
averages[i] = np.mean(prices)
print(f"Day {i} prices:{prices}, avg={averages[i]}")
top = np.max(averages)
top_day = np.argmax(averages)
bot = np.min(averages)
bot_day = np.argmin(averages)
print(f"highest:{top}, top day is {top_day}")
print(f"lowest:{bot}, bottom day is {bot_day}")Additional NumPy Utilities
Demonstrate np.clip for value limiting and np.compress for conditional filtering.
a = np.arange(5)
print(a.clip(1,3)) # [1 1 2 3 3]
print(a.compress(a > 2)) # [3 4]These examples provide a quick overview of essential NumPy functions for financial data analysis.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
