type
status
date
slug
summary
tags
category
icon
password
 
page icon
Objective:Lay the groundwork by introducing the stock market basics and getting familiar with handling financial data programmatically.

 

1.1 What is a Stock Market?

  • Definition: A marketplace where buyers and sellers trade shares of public companies.
  • Key Terms to Know:
    • Stock: A representation of ownership in a company.
    • Exchange: A platform where stocks are traded (e.g., NYSE, NASDAQ).
    • Ticker Symbol: A unique identifier for a company's stock (e.g., AAPL for Apple).
    • Price: Current value of a stock determined by supply and demand.
    • Volume: Number of shares traded during a given period.

1.2 Types of Stock Data

  • OHLC Data:
    • Open: Price at market opening.
    • High: Highest price of the stock during the day.
    • Low: Lowest price of the stock during the day.
    • Close: Price at market close.
    • Volume: Total shares traded.
  • Time Frames: Intraday, Daily, Weekly, Monthly.

1.3 Setting Up Python Environment

  • Install Python and essential libraries:

    1.4 Fetching and Handling Stock Data

    • Using Yahoo Finance API (via yfinance):
       
      这里利用vscode的插件 DataWrangler 还能看到数据的分布情况
      notion image
       
      • Understanding the Output:
        • The data DataFrame includes columns like Open, High, Low, Close, Volume.

      1.5 Visualizing Stock Data

      • Plotting Stock Prices:
         
        notion image

         
        如果想画常看到的蜡烛图(K线图):
        notion image
         

        Insights and Explanation

        1. Why Stock Data Matters:
          1. Understanding stock data is the foundation of quantitative investment. It forms the input for all analysis and strategy development.
        1. Key Takeaway from Visualization:
          1. A simple price plot provides a visual understanding of trends and fluctuations, which is the first step towards identifying patterns.

        Extra Reading and Resources

        1. The Intelligent Investor by Benjamin Graham (Chapter 1-3).
        1. Introduction to Stock Markets (Investopedia).
        1. Official Yahoo Finance API Documentation.
        1. Python for Finance by Yves Hilpisch (Chapter 2).

         

        课后作业

        Homework for Unit 1: Introduction to Stock Markets and Data Handling

        To reinforce the concepts and skills learned in Unit 1, here are the homework tasks:

        Task 1: Explore Stock Market Basics

        1. Research and define the following terms:
            • Market capitalization
            • Dividend yield
            • Price-to-Earnings (P/E) ratio
        1. Write a short paragraph explaining how stock prices are determined by supply and demand.

        Task 2: Fetch and Analyze Stock Data

        1. Use the yfinance library to fetch daily stock data for any three companies of your choice over the past two years. Example companies:
            • Technology: Microsoft (MSFT)
            • Healthcare: Johnson & Johnson (JNJ)
            • Retail: Amazon (AMZN)
        1. Save the data for each company to a CSV file using the code

        Task 3: Visualize Stock Trends

        1. Plot the closing prices of your chosen stocks on a single graph for comparison. Include:
            • A legend indicating which line corresponds to each stock.
            • Labels for the X-axis (Date) and Y-axis (Price in USD).
            • Customize the plot by:
              • Adding a title.
              • Displaying a grid for better readability.
              • Using different colors or line styles for each stock.

        Task 4: Interpret Insights

        Answer the following based on your visualizations:
        1. Which stock showed the most consistent upward trend over the selected period?
        1. Did any stock experience significant price volatility? What might have caused this (hint: research news or events)?

        Task 5: Bonus Challenge (Optional)

        1. Calculate the daily percentage change for one of the stocks and add it as a new column to the DataFrame. Use the formula: Code example:
          1. Plot the daily percentage changes over time.

          Submission Format

          • Submit a Jupyter Notebook or Python script (.py file) with:
              1. Code implementations for each task.
              1. Plots and any additional visualizations.
              1. Written answers to the interpretive questions (Task 4).
          Let me know if you need clarifications or additional hints for these tasks!
           
           

          我自己做的答案:

          Task 1: Explore Stock Market Basics

          1. Research and define the following terms:
          • Market capitalization:公司的市值,等于当前股价 乘以 所有股数
          • Dividend yield: 股息率是衡量一家公司派发股息相对于其股价的比例,是投资者评估股票收益的重要指标之一。它用来表示每年从股息中获得的收益与股票价格的比值,公式如下:
            • 例如,如果某公司股票的当前股价为50元,而每年每股派发股息为2元,那么其股息率为:4%。
              意义:
            • 高股息率通常意味着投资者可以从股息中获得较高的现金回报,但可能也反映公司增长潜力有限(因为它更倾向于派发利润而非再投资)。
            • 低股息率可能意味着公司选择将更多利润用于再投资以推动增长,但现金回报较低。
          • Price-to-Earnings (P/E) ratio: 市盈率,是衡量股票估值的一个重要指标,它表示投资者为每单位的公司盈利支付的价格。公式为:
            • 我们在平时看一个股票中,常常还会有动态PE和静态PE两个指标,而且两个指标往往不相同。静态PE和动态PE的分母都是当前股价。静态PE的分子是过去12个月的每股收益。动态PE是分析师对未来12个月或者下一个财年的盈利预测数据下的预期每股收益。动态PE更适用于成长型公司,投资者希望通过它了解未来的增长空间。静态PE适合评价成熟公司,尤其是稳定盈利的企业,能直观反映当前估值水平。
            • EPS的实际意义: 投资者通常会结合EPS和市盈率(P/E)等指标,评估股票是否值得购买。 在比较同行业公司时,EPS是判断盈利能力的一个核心维度,但需要结合公司规模、行业特性等综合分析,避免单纯依赖该指标。
          1. Write a short paragraph explaining how stock prices are determined by supply and demand.
            1. 在股市当中要明白一个道理,当前股价是由边际交易决定的。假设十万个人持有某股票C,该股票今天被100个人交易,这100个人认为这个股值多少钱,这个股今天就会在涨跌幅区间内按照这个价格去波动。然而一百人仅占十万人的千分之一。这就是边际交易决定当前股价。但是,长期来看,股价的走势和金额和筹码的供需程度决定的。当一个公司有很好的预期,业绩也很好时,更多人愿意买入,这个时候市场上卖出的少,买入的多,价格就容易被抬升。反之亦然。所以我们要坚持长期持有,买股票并不是买筹码,而是真正的参与到公司的成长中,获得成长的收益。虽说如此,我们仍然要给我们的买入价格留取足够的安全边际,价格不能太高。但是我们无法保证在买入的节点一定是一个底价,所以要分批建仓,按时间、按幅度动态调整。
              记住,股价的波动不是亏损。要有耐心和公司成长
           

          Task 2: Fetch and Analyze Stock Data

          1. Use the yfinance library to fetch daily stock data for any three companies of your choice over the past two years. Example companies:
              • Technology: Microsoft (MSFT)
              • Healthcare: Johnson & Johnson (JNJ)
              • Retail: Amazon (AMZN)
          1. Save the data for each company to a CSV file using the code:
          notion image
           

          Task 3: Visualize Stock Trends

          1. Plot the closing prices of your chosen stocks on a single graph for comparison. Include:
              • A legend indicating which line corresponds to each stock.
              • Labels for the X-axis (Date) and Y-axis (Price in USD).
              Customize the plot by:
              • Adding a title.
              • Displaying a grid for better readability.
              • Using different colors or line styles for each stock.
           
          notion image
           

          Task 4: Interpret Insights

          Answer the following based on your visualizations:
          1. Which stock showed the most consistent upward trend over the selected period?
          According to the calculation
          we have
          Ticker AAPL 123.768456 GOOG 89.378853 MSFT 235.711731 Name: 2023-01-03 00:00:00, dtype: float64 Ticker AAPL 250.419998 GOOG 190.440002 MSFT 421.500000 Name: 2024-12-31 00:00:00, dtype: float64 Ticker AAPL 2.023294 GOOG 2.130705 MSFT 1.788201 dtype: float64
           
          which indicates the AAPL showed the most consistent upward trend over the selected period.
           
          1. Did any stock experience significant price volatility? What might have caused this (hint: research news or events)?
          It seems Microsoft experienced the fast down 2024-07 — 2024-08,
          消息面上,微软股价走低的背景,是其新近发布的财报。
          北京时间7月31日凌晨,微软发布了截至6月30日的2024财年第四财季财报。财报显示,微软第四财季总营收为647亿美元,同比增长15%,好于预期为643.9亿美元;净利润为220.36亿美元,同比增长10%,每股收益2.95美元,略高于预期的2.93美元。
          尽管总体上看,微软业绩表现稳健,新一季度总营收和利润增长都略微超预期,但同比营收增速明显放缓。这也是市场对微软财报不买单的原因之一。
          与此同时,出人意料的是,微软智能云(含Azure业务)的季度营收不及预期,为285.2亿美元,同比增长19%,低于分析师预期286.8亿美元。本季度,Azure和其他云服务的收入增长了29%,低于平均预期的30.6%。相比上季度降低了2个百分点。市场对Azure云服务业绩的担忧也直接体现在股价上:盘后交易中,微软股价急剧震荡,一度最多下跌8.52%至386.875美元。
          尽管Azure的云服务增长正在放缓,但微软管理层预计,2025财年的资本支出将增加。这也意味着,对于微软而言,AI基础设施支出的投资回报率仍是一个未解之谜。
           
           

          Task 5: Bonus Challenge (Optional)

          1. Calculate the daily percentage change for one of the stocks and add it as a new column to the DataFrame. Use the formula:
          notion image
           
          这里如果用普通的matplotlib 来画图:
          notion image
           
           
          但我们如果想用plotly来做交互式的可视化,代码如下
          notion image
           

          下节课预告

          For Unit 2, we will expand on calculating basic indicators (like moving averages) and delve deeper into preprocessing stock data.
           
           
          认识你自己,才是这件事的最终乐趣 — 抄录用GPT4学量化投资 — 设计思路和课程大纲
          Loading...
          Yixin Huang
          Yixin Huang
          一个热爱生活的算法工程师
          Latest posts
          时间序列论文阅读 — TimeCMA(AAAI 2025)
          2025-4-23
          时间序列论文阅读-ChatTime: A Unified Multimodal Time Series Foundation Model Bridging
          2025-4-23
          VLM系列论文阅读-Mixed Preference Optimization (MPO)
          2025-2-6
          VLM系列论文阅读 — Flamingo
          2025-2-6
          认识你自己,才是这件事的最终乐趣 — 抄录
          2025-2-5
          用GPT4学量化投资 — Junior Level - Unit 1: Introduction to Stock Markets and Data Handling
          2025-1-23
          Announcement
          🎉NotionNext 4.5已经上线🎉
          -- 感谢您的支持 ---
          👏欢迎更新体验👏