You are previewing Mastering pandas for Finance.
O'Reilly logo
Mastering pandas for Finance

Book Description

Master pandas, an open source Python Data Analysis Library, for financial data analysis

In Detail

This book will teach you to use Python and the Python Data Analysis Library (pandas) to solve real-world financial problems.

Starting with a focus on pandas data structures, you will learn to load and manipulate time-series financial data and then calculate common financial measures, leading into more advanced derivations using fixed- and moving-windows. This leads into correlating time-series data to both index and social data to build simple trading algorithms. From there, you will learn about more complex trading algorithms and implement them using open source back-testing tools. Then, you will examine the calculation of the value of options and Value at Risk. This then leads into the modeling of portfolios and calculation of optimal portfolios based upon risk. All concepts will be demonstrated continuously through progressive examples using interactive Python and IPython Notebook.

By the end of the book, you will be familiar with applying pandas to many financial problems, giving you the knowledge needed to leverage pandas in the real world of finance.

What You Will Learn

  • Modeling and manipulating financial data using the pandas DataFrame

  • Indexing, grouping, and calculating statistical results on financial information

  • Time-series modeling, frequency conversion, and deriving results on fixed and moving windows

  • Calculating cumulative returns and performing correlations with index and social data

  • Algorithmic trading and backtesting using momentum and mean reversion strategies

  • Option pricing and calculation of Value at Risk

  • Modeling and optimization of financial portfolios

  • Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

    Table of Contents

    1. Mastering pandas for Finance
      1. Table of Contents
      2. Mastering pandas for Finance
      3. Credits
      4. About the Author
      5. About the Reviewers
        1. Support files, eBooks, discount offers, and more
          1. Why subscribe?
          2. Free access for Packt account holders
      7. Preface
        1. What this book covers
        2. What you need for this book
        3. Who this book is for
        4. Conventions
        5. Reader feedback
        6. Customer support
          1. Downloading the example code
          2. Errata
          3. Piracy
          4. Questions
      8. 1. Getting Started with pandas Using
        1. What is Wakari?
        2. Creating a Wakari cloud account
          1. Updating existing packages
          2. Installing new packages
        3. Installing the samples in Wakari
        4. Summary
      9. 2. Introducing the Series and DataFrame
        1. Notebook setup
        2. The main pandas data structures – Series and DataFrame
          1. The Series
          2. The DataFrame
        3. The basics of the Series and DataFrame objects
          1. Creating a Series and accessing elements
          2. Size, shape, uniqueness, and counts of values
          3. Alignment via index labels
          4. Creating a DataFrame
          5. Example data
          6. Selecting columns of a DataFrame
          7. Selecting rows of a DataFrame using the index
            1. Slicing using the [] operator
            2. Selecting rows by the index label and location – .loc[] and .iloc[]
            3. Selecting rows by the index label and/or location – .ix[]
            4. Scalar lookup by label or location using .at[] and .iat[]
          8. Selecting rows using the Boolean selection
          9. Arithmetic on a DataFrame
        4. Reindexing the Series and DataFrame objects
        5. Summary
      10. 3. Reshaping, Reorganizing, and Aggregating
        1. Notebook setup
        2. Loading historical stock data
          1. Organizing the data for the examples
        3. Reorganizing and reshaping data
          1. Concatenating multiple DataFrame objects
          2. Merging DataFrame objects
          3. Pivoting
          4. Stacking and unstacking
          5. Melting
        4. Grouping and aggregating
          1. Splitting
          2. Aggregating
        5. Summary
      11. 4. Time-series
        1. Notebook setup
        2. Time-series data and the DatetimeIndex
        3. Creating time-series with specific frequencies
        4. Representing intervals of time using periods
        5. Shifting and lagging time-series data
        6. Frequency conversion of time-series data
        7. Resampling of time-series
        8. Summary
      12. 5. Time-series Stock Data
        1. Notebook setup
        2. Obtaining historical stock and index data
          1. Fetching historical stock data from Yahoo!
          2. Fetching index data from Yahoo!
        3. Visualizing financial time-series data
          1. Plotting closing prices
          2. Plotting volume-series data
          3. Combined price and volumes
          4. Plotting candlesticks
        4. Fundamental financial calculations
          1. Calculating simple daily percentage change
          2. Calculating simple daily cumulative returns
          3. Analyzing the distribution of returns
            1. Histograms
            2. Q-Q plots
            3. Box-and-whisker plots
          4. Comparison of daily percentage change between stocks
        5. Moving windows
        6. Volatility calculation
          1. Rolling correlation of returns
          2. Least-squares regression of returns
        7. Comparing stocks to the S&P 500
        8. Summary
      13. 6. Trading Using Google Trends
        1. Notebook setup
        2. A brief on Quantifying Trading Behavior in Financial Markets Using Google Trends
        3. Data collection
          1. The data from the paper
          2. Gathering our own DJIA data from Quandl
          3. Google Trends data
        4. Generating order signals
        5. Computing returns
        6. Cumulative returns and the result of the strategy
        7. Summary
      14. 7. Algorithmic Trading
        1. Notebook setup
        2. The process of algorithmic trading
          1. Momentum strategies
          2. Mean-reversion strategies
        3. Moving averages
          1. Simple moving average
          2. Exponentially weighted moving average
        4. Technical analysis techniques
          1. Crossovers
            1. Pairs trading
        5. Algo trading with Zipline
          1. Algorithm – buy apple
          2. Algorithm – dual moving average crossover
          3. Algorithm – pairs trade
        6. Summary
      15. 8. Working with Options
        1. Introducing options
        2. Notebook setup
          1. Options data from Yahoo! Finance
          2. Implied volatility
            1. Volatility smirks
        3. Calculating payoff on options
          1. The call option payoff calculation
          2. The put option payoff calculation
        4. Profit and loss calculation
          1. The call option profit and loss for a buyer
          2. The call option profit and loss for the seller
          3. Combined payoff charts
          4. The put option profit and loss for a buyer
          5. The put option profit and loss for the seller
        5. The pricing of options
          1. The pricing of options with Black-Scholes
            1. Deriving the model
              1. The value of the cash to buy
              2. The value of the stock received
            2. The formulas
              1. d1 and d2
          2. Black-Scholes using Mibian
          3. Charting option price change over time
          4. The Greeks
            1. Calculation and visualization
        6. Summary
      16. 9. Portfolios and Risk
        1. Notebook setup
        2. An overview of modern portfolio theory
          1. Concept
          2. Mathematical modeling of a portfolio
            1. Risk and expected return
            2. Diversification
            3. The efficient frontier
        3. Modeling a portfolio with pandas
        4. Constructing an efficient portfolio
          1. Gathering historical returns for a portfolio
          2. Formulation of portfolio risks
          3. The Sharpe ratio
          4. Optimization and minimization
        5. Constructing an optimal portfolio
        6. Visualizing the efficient frontier
        7. Value at Risk
        8. Summary
      17. Index