Determining the best return on investiment (60 day periods)

Using historical closing prices of MSFT when was a good time to buy and sell based on the return on investment metric.

Return on investment:

(sold_price – purchase_price) / purchase_price

For example, if you buy 20 shares of Joe's Pizza for $10 a share, your investment cost is $200. 
If you sell those shares for $250, then your ROI is ($250-200)/$200 for a total of 0.25 or 25%. 



In [3]:
import pandas as pd
import datetime

%matplotlib inline

Q. Using all the historical closing prices of MSFT shares calculate which 60 day periods yielded a return on investment greater than 25%.


In [4]:
ls *.csv


 Volume in drive C is Windows
 Volume Serial Number is 6AD0-5968

 Directory of C:\Users\nafagg\Documents\GitHub\notebooks\Introductions

30/04/2015  07:26 PM           430,328 msft.csv
               1 File(s)        430,328 bytes
               0 Dir(s)  411,151,962,112 bytes free

In [5]:
stock = pd.read_csv('msft.csv', parse_dates=['Date']).set_index('Date').sort()
stock.tail()


Out[5]:
Open High Low Close Volume Adj Close
Date
2015-04-20 41.73 43.17 41.68 42.91 45738800 42.91
2015-04-21 43.00 43.15 42.53 42.64 25932200 42.64
2015-04-22 42.67 43.13 42.55 42.99 24856600 42.99
2015-04-23 42.89 43.61 42.80 43.34 45029600 43.34
2015-04-24 45.66 48.14 45.65 47.87 127995200 47.87

In [6]:
stock["Open"].plot(figsize=(15, 5));



In [7]:
def ROI(series):
    """Return on investiment"""
    return (series[-1] - series[0]) / series[0]

In [8]:
days = 60 
stock["ROI"] = pd.rolling_apply(stock["Close"], days, ROI)
stock.tail()


Out[8]:
Open High Low Close Volume Adj Close ROI
Date
2015-04-20 41.73 43.17 41.68 42.91 45738800 42.91 -0.090504
2015-04-21 43.00 43.15 42.53 42.64 25932200 42.64 -0.092959
2015-04-22 42.67 43.13 42.55 42.99 24856600 42.99 0.007736
2015-04-23 42.89 43.61 42.80 43.34 45029600 43.34 0.052197
2015-04-24 45.66 48.14 45.65 47.87 127995200 47.87 0.139491

In [9]:
good_times = stock[stock.ROI > 0.25]
good_times.tail()


Out[9]:
Open High Low Close Volume Adj Close ROI
Date
2013-06-03 34.92 35.63 34.83 35.59 51252600 33.89887 0.271071
2013-06-04 35.62 35.74 34.77 34.99 65529500 33.32738 0.255472
2013-06-06 34.84 35.11 34.49 34.96 37618500 33.29881 0.252149
2013-06-07 35.25 35.78 35.06 35.67 40757300 33.97507 0.267591
2013-06-10 35.51 35.65 35.14 35.47 35994500 33.78457 0.264979

In [10]:
ax = stock["Close"].plot(figsize=(15, 5));
ax.plot(good_times.index, good_times["Close"], 'or', alpha=0.3);


Q. Can you form a cost function to maximize ROI? Using scipy.optimize.


In [ ]: