Example #1
0
def ret_annual(ticker, begdate, enddte):
    x = getData(ticker, begdate, enddate, asobject=True, adjusted=True)
    logret = sp.log(x.aclose[1:] / x.aclose[:-1])
    date = []
    d0 = x.date
    for i in range(0, sp.size(logret)):
        date.append(d0[i].strftime("%Y"))
    y = pd.DataFrame(logret, date, columns=[ticker])
    return sp.exp(y.groupby(y.index).sum()) - 1
def ret_monthly(ticker):  #	function 1
    x = getData(ticker, (begYear, 1, 1), (endYear, 12, 31),
                asobject=True,
                adjusted=True)
    logret = np.log(x.aclose[1:] / x.aclose[:-1])
    date = []
    d0 = x.date
    for i in range(0, np.size(logret)):
        date.append(''.join([d0[i].strftime("%Y"), d0[i].strftime("%m")]))
    y = pd.DataFrame(logret, date, columns=[ticker])
    return y.groupby(y.index).sum()
def sharpeRatio(ticker, begdate=(2012, 1, 1), enddate=(2016, 12, 31)):
    """Objective: estimate Sharpe ratio for stock
        ticker  : stock symbol 
        begdate : beginning date
        enddate : ending date
        
       Example #1: sharpeRatio("ibm")
                     0.0068655583807256159
        
       Example #2: date1=(1990,1,1)
                   date2=(2015,12,23)
                   sharpeRatio("ibm",date1,date2)
                     0.027831010497755326
    """
    import scipy as sp
    from matplotlib.finance import quotes_historical_yahoo_ochl as getData
    p = getData(ticker, begdate, enddate, asobject=True, adjusted=True)
    ret = p.aclose[1:] / p.aclose[:-1] - 1
    return sp.mean(ret) / sp.std(ret)
Example #4
0
"""
  Name     : c11_09_normality_test_MSFT.py
  Book     : Python for Finance (2nd ed.)
  Publisher: Packt Publishing Ltd. 
  Author   : Yuxing Yan
  Date     : 6/6/2017
  email    : [email protected]
             [email protected]
"""

import numpy as np
from scipy import stats
from matplotlib.finance import quotes_historical_yahoo_ochl as getData
#
ticker = 'MSFT'
begdate = (2012, 1, 1)
enddate = (2016, 12, 31)
#
p = getData(ticker, begdate, enddate, asobject=True, adjusted=True)
ret = (p.aclose[1:] - p.aclose[:-1]) / p.aclose[1:]
print 'ticker=', ticker, 'W-test, and P-value'
print(stats.shapiro(ret))
print(stats.anderson(ret))
Example #5
0
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, WeekdayLocator
from matplotlib.dates import HourLocator, DayLocator, MONDAY
from matplotlib.finance import candlestick_ohlc, plot_day_summary_oclh
from matplotlib.finance import quotes_historical_yahoo_ochl as getData
#
date1 = (2013, 10, 20)
date2 = (2013, 11, 10)
ticker = 'IBM'
mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
alldays = DayLocator()  # minor ticks on the days
weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
dayFormatter = DateFormatter('%d')  # e.g., 12
quotes = getData(ticker, date1, date2)
if len(quotes) == 0:
    raise SystemExit
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
ax.xaxis.set_minor_formatter(dayFormatter)
plot_day_summary_oclh(ax, quotes, ticksize=3)
candlestick_ohlc(ax, quotes, width=0.6)
ax.xaxis_date()
ax.autoscale_view()
plt.setp(plt.gca().get_xticklabels(), rotation=80, horizontalalignment='right')
plt.figtext(0.35, 0.45, '10/29: Open, High, Low, Close')
plt.figtext(0.35, 0.42, ' 177.62, 182.32, 177.50, 182.12')
"""
  Name     : c8_04_retrieve_daily_from_Yahoo.py
  Book     : Python for Finance (2nd ed.)
  Publisher: Packt Publishing Ltd. 
  Author   : Yuxing Yan
  Date     : 6/6/2017
  email    : [email protected]
             [email protected]
"""

from matplotlib.finance import quotes_historical_yahoo_ochl as getData
x = getData("IBM", (2016, 1, 1), (2016, 1, 21), asobject=True, adjusted=True)
print(x[0:4])
Example #7
0
def ret_f(ticker, begdate, enddte):
    x = getData(ticker, begdate, enddate, asobject=True, adjusted=True)
    ret = x.aclose[1:] / x.aclose[:-1] - 1
    return ret
  email    : [email protected]
             [email protected]
"""
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.finance import quotes_historical_yahoo_ochl as getData
# Step 1: input area
ticker = 'MSFT'  # input value 1
begdate = (1926, 1, 1)  # input value 2
enddate = (2013, 12, 31)  # input value 3
n_simulation = 5000  # input value 4

# Step 2: retrieve price data and estimate log returns
x = getData(ticker, begdate, enddate, asobject=True)
logret = sp.log(x.aclose[1:] / x.aclose[:-1])

# Step 3: estimate annual returns
date = []
d0 = x.date
for i in range(0, sp.size(logret)):
    date.append(d0[i].strftime("%Y"))

y = pd.DataFrame(logret, date, columns=['logret'])
ret_annual = sp.exp(y.groupby(y.index).sum()) - 1
ret_annual.columns = ['ret_annual']
n_obs = len(ret_annual)

# Step 4: estimate distribution with replacement
sp.random.seed(123577)
def dailyRet(ticker, begdate, enddate):
    p = getData(ticker, begdate, enddate, asobject=True, adjusted=True)
    return p.aclose[1:] / p.aclose[:-1] - 1
Example #10
0
def ret_f(ticker):  #	function 1
    x = getData(ticker, begdate, enddate, asobject=True, adjusted=True)
    ret = x.aclose[1:] / x.aclose[:-1] - 1
    ddate = x['date'][1:]
    y = pd.DataFrame(ret, columns=[ticker], index=ddate)
    return y.groupby(y.index).sum()
def ret_f(ticker, begdate, enddate):
    p = getData(ticker, begdate, enddate, asobject=True, adjusted=True)
    ret = p.aclose[1:] / p.aclose[:-1] - 1
    date_ = p.date
    return pd.DataFrame(data=ret, index=date_[1:], columns=['ret'])
# -*- coding: utf-8 -*-
"""
  Name     : c4_07_first_one.py
  Book     : Python for Finance (2nd ed.)
  Publisher: Packt Publishing Ltd. 
  Author   : Yuxing Yan
  Date     : 6/6/2017
  email    : [email protected]
             [email protected]
"""

from matplotlib.finance import quotes_historical_yahoo_ochl as getData
p = getData("IBM", (2015, 1, 1), (2015, 12, 31), asobject=True, adjusted=True)
print(p[0:5])
Example #13
0
def ret_f(ticker, begdate, enddte):
    x = getData(ticker, begdate, enddate, asobject=True, adjusted=True)
    ret = x.aclose[1:] / x.aclose[:-1] - 1
    d0 = x.date[1:]
    return pd.DataFrame(ret, index=d0, columns=[ticker])
Example #14
0
def ret_f(ticker, begdate, enddate):
    p = getData(ticker, begdate, enddate, asobject=True, adjusted=True)
    ret = p.aclose[1:]
    ret = p.aclose[1:] / p.aclose[:-1] - 1
    return (ret)