🔴
入学要求
💯
能力测试
🛣️
课程安排
🕹️
研究资源

第2讲:Python入门 (Introduction to Python)

💡

查看全集:💎Quantopia量化分析56讲

变量与基础类型

变量定义

变量是存储数据的容器,在Python中使用等号(=)进行赋值:

stock_price = 158.76      # 浮点数表示股价
company = "AAPL"          # 字符串表示公司代码
is_tech = True            # 布尔值表示是否科技股

数字类型

类型说明示例
整数(int)不带小数点的数字volume = 1_000_000
浮点数(float)带小数点的数字pe_ratio = 25.8
# 类型转换示例
print(int(3.9))    # 输出3(直接截断)
print(float(5))    # 输出5.0

字符串操作

# 1. f-string(推荐)
print(f"{company}当前股价:{stock_price}")

# 2. format方法
print("{}市盈率:{:.1f}".format(company, pe_ratio))

# 3. %格式化
print("是否科技股:%s" % is_tech)

数据结构

列表 vs 元组

特征列表(list)元组(tuple)
可变性✔️
语法[元素1, 元素2](元素1, 元素2)
适用场景需要修改的数据序列固定不变的数据集合
tech_stocks = ["AAPL", "MSFT", "GOOG"]  # 可修改的科技股列表
market_indexes = ("SPX", "DJI", "NDX")   # 不可变的指数元组

字典实战

股票数据存储示例:

stock_data = {
    "AAPL": {
        "price": 189.84,
        "volume": 45_123_000,
        "sector": "Technology"
    },
    "TSLA": {
        "price": 260.54,
        "volume": 102_345_000,
        "sector": "Automotive"
    }
}

# 获取特斯拉的交易量
print(stock_data["TSLA"]["volume"])

流程控制

条件判断进阶

def evaluate_stock(pe, sector):
    if pe < 15 and sector == "Finance":
        return "价值股"
    elif 15 <= pe <= 25 and sector in ["Technology", "Healthcare"]:
        return "成长股"
    else:
        return "需进一步分析"

print(evaluate_stock(18, "Technology"))  # 输出"成长股"

循环技巧

# 使用enumerate同时获取索引和值
stock_list = ["AAPL", "MSFT", "AMZN"]
for idx, ticker in enumerate(stock_list, 1):
    print(f"股票#{idx}: {ticker}")

# 字典推导式示例
sectors = ["Tech", "Auto", "Tech", "Retail"]
market_caps = [2.8, 0.7, 1.5, 0.3]
sector_cap = {s: sum(m for s1, m in zip(sectors, market_caps) if s1 == s)
              for s in set(sectors)}
print(sector_cap)  # 输出各行业市值总和

函数与模块

函数编写规范

def analyze_portfolio(holdings, market_data):
    """计算投资组合总价值
    Args:
        holdings (dict): 持仓字典 {股票代码: 股数}
        market_data (dict): 市场数据 {股票代码: 股价}

    Returns:
        float: 组合总价值
    """
    total = 0.0
    for ticker, shares in holdings.items():
        if ticker not in market_data:
            raise ValueError(f"缺少{ticker}的价格数据")
        total += shares * market_data[ticker]
    return total

# 使用示例
my_holdings = {"AAPL": 100, "MSFT": 50}
current_prices = {"AAPL": 189.84, "MSFT": 340.65}
print(f"组合价值:${analyze_portfolio(my_holdings, current_prices):,.2f}")

使用yfinance获取数据

import yfinance as yf
from datetime import datetime

def fetch_stock_data(tickers, period="1y"):
    """获取多只股票历史数据"""
    data = yf.download(tickers, period=period, group_by='ticker')
    return {ticker: data[ticker] for ticker in tickers}

# 示例使用
if __name__ == "__main__":
    tech_stocks = ["AAPL", "MSFT", "GOOG"]
    stock_data = fetch_stock_data(tech_stocks)

    # 展示苹果公司最近5个交易日的收盘价
    print(stock_data["AAPL"].tail()[['Close']])

综合练习

# 练习:编写动量策略分析函数
def momentum_strategy(tickers, lookback_days=60):
    """
    计算股票过去lookback_days天的收益率
    返回收益率最高的前3只股票
    """
    data = fetch_stock_data(tickers, period=f"{lookback_days+10}d")
    momentum = {}

    for ticker in tickers:
        closes = data[ticker]['Close']
        if len(closes) >= lookback_days:
            start_price = closes.iloc[-lookback_days]
            end_price = closes.iloc[-1]
            momentum[ticker] = (end_price - start_price) / start_price

    sorted_stocks = sorted(momentum.items(), key=lambda x: x[1], reverse=True)
    return [stock[0] for stock in sorted_stocks[:3]]

# 测试策略
print("推荐关注股票:", momentum_strategy(["AAPL", "MSFT", "TSLA", "NVDA", "AMZN"]))

学习要点总结:

  1. 理解变量类型及其转换方法
  1. 掌握列表/字典的操作和性能特点
  1. 熟练使用条件判断和循环结构
  1. 能够封装可复用的功能函数
  1. 掌握使用yfinance获取金融数据的方法

扩展学习建议:

附:练习合集