Unlock Stock Insights: An Apple Price Analysis with NumPy
This tutorial walks through loading Apple stock CSV data with NumPy, computing basic statistics like mean, median, variance, weighted average, daily returns, volatility, and handling dates, while demonstrating essential NumPy functions and code snippets for practical financial data analysis.
We demonstrate how to read the AAPL.csv file using numpy.loadtxt to extract closing prices and volumes, then compute simple statistics such as arithmetic mean, weighted average (VWAP), maximum, minimum, range, median, and variance.
Basic Statistics
import numpy as np
c, v = np.loadtxt('AAPL.csv', delimiter=',', usecols=(1,2), unpack=True)
mean_c = np.mean(c)
print(mean_c) # 172.614918033
vwap = np.average(c, weights=v)
print(vwap) # 170.950010035
print(np.max(c)) # 181.72
print(np.min(c)) # 155.15
print(np.ptp(c)) # 26.57
print(np.median(c)) # 174.35
print(np.var(c)) # 37.5985528621Daily Returns and Volatility
Daily returns are calculated as the negative difference of consecutive closing prices divided by the previous price, and their standard deviation indicates volatility.
returns = -np.diff(c) / c[1:]
print(np.std(returns)) # 0.0150780328454
positive_days = np.where(returns > 0)
print(positive_days)Log Returns and Annualized Volatility
Log returns are computed using np.log, and historical volatility is derived from the standard deviation of log returns, scaled by the square root of the number of trading days (252).
logreturns = -np.diff(np.log(c))
volatility = np.std(logreturns) / np.mean(logreturns)
annual_volatility = volatility / np.sqrt(1./252.)
print(volatility) # 100.096757388
print(annual_volatility) # 1588.98676256Date Handling
Since numpy.loadtxt expects numeric data, a custom converter transforms byte‑encoded date strings into weekday numbers.
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)Weekly Average Closing Prices
Using the weekday indices, we compute the average closing price for each day of the week and identify the highest and lowest averages.
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} avg={averages[i]}")
top = np.max(averages)
top_index = np.argmax(averages)
bot = np.min(averages)
bot_index = np.argmin(averages)
print(f"highest:{top}, top day is {top_index}")
print(f"lowest:{bot}, bottom day is {bot_index}")Additional useful NumPy functions such as clip for value limiting and compress for conditional filtering are also shown.
a = np.arange(5)
print(a.clip(1,3)) # [1 1 2 3 3]
print(a.compress(a > 2)) # [3 4]The article emphasizes that NumPy provides a rich set of low‑level functions for data manipulation, serving as a foundation before moving to higher‑level libraries.
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.
