I'll recommend several super practical quantitative Python libraries, along with code examples. You'll definitely enjoy watching and using them!

1. NumPy

The "pillar" of our quantitative analysis, array operations are so satisfying, and matrix operations are blazing fast.

Code Example 1: Simple Array Operations

1
2
3
4
5
6
7
8
9
10
11
12
13
import numpy as np

# Create a price array
prices = np.array([100, 102, 101, 105, 108])
print(f"Stock prices: {prices}")

# Calculate simple returns
returns = np.diff(prices) / prices[:-1]
print(f"Simple returns: {returns}")

# Calculate average return
avg_return = np.mean(returns)
print(f"Average return: {avg_return:.2%}")

Code Example 2: Matrix Dot Product

1
2
3
4
5
6
7
8
9
10
11
import numpy as np

# Create two matrices
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(f"Matrix A:\n{a}")
print(f"Matrix b:\n{b}")

# Calculate matrix dot product
dot_product = np.dot(a, b)
print(f"Matrix dot product:\n{dot_product}")

2. Pandas

The "magic tool" for financial time series analysis that can organize messy data perfectly.

Code Example 1: Creating Financial Data DataFrame

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import pandas as pd

# Create financial data dictionary
data = {
'Open': [100, 101, 102],
'High': [103, 104, 105],
'Low': [99, 100, 101],
'Close': [102, 103, 104],
'Volume': [10000, 15000, 12000]
}

# Convert dictionary to DataFrame
df = pd.DataFrame(data)
print(f"Financial Data DataFrame:\n{df}")

# Add date index
df['Date'] = pd.date_range(start='2024-01-01', periods=3)
df.set_index('Date', inplace=True)
print(f"DataFrame with date index:\n{df}")

Code Example 2: Calculating Rolling Window Mean

1
2
3
4
5
6
7
8
9
10
11
12
13
import pandas as pd

# Create price data
data = {'Price': [100, 102, 101, 105, 108, 106, 107]}
df = pd.DataFrame(data)

# Calculate 3-day rolling mean
df['3-day MA'] = df['Price'].rolling(window=3).mean()
print(f"3-day rolling mean:\n{df}")

# Calculate 5-day rolling mean
df['5-day MA'] = df['Price'].rolling(window=5).mean()
print(f"5-day rolling mean:\n{df}")

3. Matplotlib

Our "secret weapon" for drawing charts that transforms boring data into gorgeous visualizations, making analysis results crystal clear.

Code Example 1: Plotting Price Time Series

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib.pyplot as plt

# Stock price data
prices = [100, 102, 101, 105, 108, 106, 107, 109, 112, 110]
dates = list(range(1, 11)) # Simple date index

# Plot price time series
plt.plot(dates, prices, marker='o', linestyle='-', color='b', label='Stock Price')
plt.title('Stock Price Trend')
plt.xlabel('Date')
plt.ylabel('Price')
plt.grid(True)
plt.legend()
plt.show()

Code Example 2: Plotting Bar Chart

1
2
3
4
5
6
7
8
9
10
11
12
13
import matplotlib.pyplot as plt

# Data categories and values
categories = ['Stocks', 'Bonds', 'Gold', 'Forex']
values = [10, 15, 7, 12]

# Plot bar chart
plt.bar(categories, values, color=['blue', 'green', 'orange', 'purple'])
plt.title('Portfolio Distribution')
plt.xlabel('Asset Class')
plt.ylabel('Investment Ratio')
plt.grid(axis='y')
plt.show()

4. TA-Lib

The "ultimate weapon" for technical analysis with all kinds of technical indicators available. It's so satisfying to use.

Code Example 1: Calculating RSI (Relative Strength Index)

1
2
3
4
5
6
7
8
9
10
11
import talib as ta
import numpy as np

# Generate random price data
np.random.seed(42)
prices = np.random.random(100) * 100 # Generate 100 random prices, range 0-100
print(f"Random price data:\n{prices}")

# Calculate RSI
rsi = ta.RSI(prices, timeperiod=14)
print(f"RSI indicator:\n{rsi}")

Code Example 2: Calculating Moving Averages

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import talib as ta
import numpy as np

# Generate random price data
np.random.seed(42)
prices = np.random.random(100) * 100 # Generate 100 random prices, range 0-100

# Calculate Simple Moving Average (SMA)
sma = ta.SMA(prices, timeperiod=10)
print(f"Simple Moving Average:\n{sma}")

# Calculate Exponential Moving Average (EMA)
ema = ta.EMA(prices, timeperiod=10)
print(f"Exponential Moving Average:\n{ema}")

5. Zipline

The "professional" for backtesting that lets you easily simulate trading strategies to see if they actually work.

Code Example 1: Simple Buy Strategy

from zipline import run_algorithm
from zipline.api import order, symbol

# Initialize function
def initialize(context):
    context.asset = symbol('AAPL')  # Set target stock to Apple

# Daily handle function
def handle_data(context, data):


## 🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 **AI 编程实战课** 帮你从零上手!

- 👉 **课程报名**:[点击这里报名,前3讲免费试听](https://r7up9.xetslk.com/s/1uP5YW)
- 👉 **免费试看**:[B站免费试看前3讲,先看看适不适合自己](https://www.bilibili.com/cheese/play/ss982042944)