安装 Python 3.10+
安装 VSCode + Python 插件
新建一个文件夹:crypto_quant
创建虚拟环境
python -m venv env
激活虚拟环境
Windows
env\\Scripts\\activate
macOS
source env/bin/activate
安装必要库
pip install numpy pandas matplotlib ccxt
创建 test_ccxt.py
import ccxt
import pandas as pd
exchange = ccxt.binance()
ohlcv = exchange.fetch_ohlcv('BTC/USDT', timeframe='1h', limit=100)
df = pd.DataFrame(ohlcv, columns=['timestamp','open','high','low','close','volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
print(df.head())
在指令行输入
python test_ccxt.py
# --- Python Basics (Day 2) ---
# 变量 & 类型
a = 10
b = 3.5
name = "crypto"
is_ok = True
print(a, b, name, is_ok)
# list
nums = [1, 2, 3, 4, 5]
print("nums:", nums)
# dict
person = {"name": "bebeca", "role": "quant learner"}
print("person:", person)
# for loop
for i in range(5):
print("loop:", i)
# if
x = 7
if x > 5:
print("x 大于 5")
else:
print("x 不大于 5")
# 函数
def square(n):
return n * n
print("square(5) =", square(5))
# --- 手写 SMA 函数 ---
def SMA(values, window):
"""
values: list or array
window: int
"""
if len(values) < window:
return None
return sum(values[-window:]) / window
# 测试:
close_prices = [10, 11, 12, 13, 14, 15]
print("SMA(3):", SMA(close_prices, 3))
# --- Day 3: Pandas Basics ---
import pandas as pd
# 示例数据 DataFrame
df = pd.DataFrame({
"open": [100, 102, 101, 105],
"high": [103, 104, 102, 106],
"low": [99, 101, 100, 103],
"close":[102, 101, 105, 104],
})
print("head:")
print(df.head())
print("\\ndescribe:")
print(df.describe())
# 取列
print("\\nclose column:")
print(df["close"])
# 简单图
df["close"].plot(title="Example Close Price")
请新建一个 Python 文件:generate_data.py
import pandas as pd
import numpy as np
# 1. 设置随机种子,保证你和我生成的“随机数”是一样的,方便对答案
np.random.seed(42)
# 2. 生成 100 个交易日期
dates = pd.date_range(start="2023-01-01", periods=100, freq="D")
# 3. 模拟股价波动 (随机游走)
# 假设初始价格 100,每天涨跌幅在 -2% 到 +2% 之间
returns = np.random.uniform(low=-0.02, high=0.02, size=100)
price_path = 100 * (1 + returns).cumprod() # 计算累积乘积得到价格路径
# 4. 基于收盘价,随机生成 High/Low/Open
# Open: 在 Close 附近波动
# High: 一定比 Open 和 Close 都高
# Low: 一定比 Open 和 Close 都低
data = {
"close": price_path,
"open": price_path * (1 + np.random.uniform(-0.005, 0.005, 100)),
"high": price_path * (1 + np.random.uniform(0.005, 0.015, 100)),
"low": price_path * (1 - np.random.uniform(0.005, 0.015, 100)),
"volume": np.random.randint(1000, 5000, 100) # 成交量 1000-5000 之间
}
# 5. 组装成 DataFrame
df = pd.DataFrame(data, index=dates)
# 6. 保存为 CSV 文件
df.to_csv("sample_kline.csv")
print("✅ 成功生成文件: sample_kline.csv")
print("前 3 行数据预览:")
print(df.head(3))