stock market

How to Calculate Simple Buy And Hold Strategy in Python

This Python script loads historical stock or index data (like the Nifty index) from a CSV file, processes it to calculate daily logarithmic returns, and visualizes both the raw prices and derived returns using plots and histograms. It then computes cumulative returns to simulate the performance of a long-term investment. Through the use of pandas, numpy, and matplotlib, it offers both numerical insights and clear visualizations to help analyze the asset’s behavior over time.

1.Importing Libraries

  • pandas (pd) is used for data manipulation and analysis.
  • numpy (np) adds support for numerical computations.
  • matplotlib.pyplot (plt) is used for plotting graphs.

2. Reading the Data

  • Loads sample.csv into a DataFrame df.
  • parse_dates=["Date"]: converts the “Date” column to datetime format.
  • index_col="Date": sets the “Date” column as the index for time series analysis.
  • df by itself would display the DataFrame.
  • df.info() gives a quick summary: datatypes, non-null counts, and memory usage.

3. Plotting the Data

  • Plots all numerical columns in df.
  • The plot size is 12×8 inches, with a title and readable font.
  • plt.show() renders the plot.

4. Calculating Logarithmic Returns

  • Computes logarithmic returns for each column.
  • df.shift(1): shifts values down by one row (previous day’s price).
  • df.div(...): element-wise division (today’s price / yesterday’s).
  • np.log(...): takes the natural logarithm to compute returns.

5. Cleaning Data

  • Removes any rows with NaN values (likely from the first row after .shift(1)).

6. Visualizing Returns

  • Plots a histogram of daily returns with 100 bins to show distribution shape.

7. Cumulative Return Calculations

  • Calculates the cumulative return over time using log returns.
  • Alternative method: compares final price to initial price (only works if price column exists!).
  • Cumulative sum of log returns and converted back to normal scale using exp().

8. Adding and Plotting Cumulative Returns

  • Adds a new column creturns for cumulative returns.
  • Plots the performance over time—like tracking your investment value if you held the asset throughout.

Example: full program to calculate stock returns

Leave a Reply

Your email address will not be published. Required fields are marked *

RkdigitalSchool