# Daily Returns

## Daily Returns

![](https://463299088-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3wXpaYFUfPiqG2WRb2%2F-M3wY0wnXPvGBdZ6_Cbt%2F-M3wYJOUqu9xjbBjBWYD%2Fdaily-returns.png?generation=1585858873945000\&alt=media)

## Python code to implement daily returns

```
import os
import pandas as pd
import matplotlib.pyplot as plt

def symbol_to_path(symbol, base_dir="data"):
    """Return CSV file path given ticker symbol."""
    return os.path.join(base_dir, "{}.csv".format(str(symbol)))

def get_data(symbols, dates):
    """Read stock data (adjusted close) for given symbols from CSV files."""
    df = pd.DataFrame(index=dates)
    if 'SPY' not in symbols:  # add SPY for reference, if absent
        symbols.insert(0, 'SPY')

    for symbol in symbols:
        df_temp = pd.read_csv(symbol_to_path(symbol), index_col='Date',
                              parse_dates=True, usecols=['Date', 'Adj Close'], na_values=['nan'])
        df_temp = df_temp.rename(columns={'Adj Close': symbol})
        df = df.join(df_temp)
        if symbol == 'SPY':  # drop dates SPY did not trade
            df = df.dropna(subset=["SPY"])

    return df

def plot_data(df, title="Stock prices", xlabel="Date", ylabel="Price"):
    """Plot stock prices with a custom title and meaningful axis labels."""
    ax = df.plot(title=title, fontsize=12)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    plt.show()

def compute_daily_returns(df):
    """Compute and return the daily return values."""
    daily_returns = df.pct_change()
    # Daily return values for the first date cannot be calculated. Set these to zero.
    daily_returns.ix[0, :] = 0

    # Alternative method
    # daily_returns = (df / df.shift(1)) - 1
    # daily_returns.ix[0, :] = 0

    # Another alternative method
    # daily_returns = df.copy()
    # compute daily returns for row 1 onwards
    # daily_returns[1:] = (daily_returns[1:] / daily_returns[-1:].values) - 1
    # daily_returns.ix[0, :] = 0 # set daily returns for row 0 to 0

    return daily_returns

def test_run():
    # Read data
    dates = pd.date_range('2012-07-01', '2012-07-31')  # one month only
    symbols = ['SPY', 'XOM']
    df = get_data(symbols, dates)
    plot_data(df)

    # Compute daily returns
    daily_returns = compute_daily_returns(df)
    plot_data(daily_returns, title="Daily returns", ylabel="Daily returns")

if __name__ == "__main__":
    test_run()
```

Here are the two charts.

![](https://463299088-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3wXpaYFUfPiqG2WRb2%2F-M3wY0wnXPvGBdZ6_Cbt%2F-M3wYJOX3FnlLJZeSrLT%2Fdaily-return-prices.png?generation=1585858866606672\&alt=media)

Observe that SPY and XOM stocks are somehow connected. It seems that SPY is following XOM stock changes.

![](https://463299088-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3wXpaYFUfPiqG2WRb2%2F-M3wY0wnXPvGBdZ6_Cbt%2F-M3wYJOZjgXZ9g_x0D_u%2Fdaily-returns-daily-returns.png?generation=1585858866417721\&alt=media)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ondrej-kvasnovsky-2.gitbook.io/handbook-of-hidden-data-scientist-python/statistical-analysis/daily-returns.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
