I made a script to get stock information for a stock list. For the shares involved (group in group) I need to calculate the MACD.
In order not to mix the price for one stock with another, I use the pandas group.
import pandas as pd
from pandas.io.data import DataReader
import numpy as np
import time
from io import StringIO
runstart = time.time()
stocklist = ['nflx','mmm']
tickers = []
days_backtest=102
end = pd.Timestamp.utcnow()
start = end - days_backtest * pd.tseries.offsets.BDay()
def GetStock(stocklist, start, end, csv_file_all='alltickers_ohlc.csv'):
'''
Fetches stock-info for analysis of each ticker in stocklist
'''
print('\nGetting Stock-info from Yahoo-Finance')
for ticker in stocklist:
r = DataReader(ticker, "yahoo",
start = start, end = end)
r['Ticker'] = ticker
tickers.append(r)
df_all = pd.concat(tickers)
df_all['Adj_Close'] = df_all['Adj Close']
df_all = df_all[['Ticker','Adj_Close','Volume']]
df_all['Adj_Close'] = np.round(df_all['Adj_Close'], decimals=2)
df_all.reset_index().sort(['Ticker', 'Date'], ascending=[1,1]).set_index('Ticker').to_csv(csv_file_all, date_format='%Y/%m/%d')
print('========= Picked up new stockinfo (df_all) \n')
print(70 * '-')
return df_all
def moving_average(group, n=9, type='simple'):
"""
compute an n period moving average.
type is 'simple' | 'exponential'
"""
group = np.asarray(df_['Adj_Close'])
if type == 'simple':
weights = np.ones(n)
else:
weights = np.exp(np.linspace(-1., 0., n))
weights /= weights.sum()
a = np.convolve(group, weights, mode='full')[:len(group)]
a[:n] = a[n]
return a
def moving_average_convergence(group, nslow=26, nfast=12):
"""
compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg'
return value is emaslow, emafast, macd which are len(x) arrays
"""
emaslow = moving_average(group, nslow, type='exponential')
emafast = moving_average(group, nfast, type='exponential')
return pd.DataFrame({'emaSlw': emaslow,
'emaFst': emafast,
'MACD': emafast - emaslow})
if __name__ == '__main__':
df_all = GetStock(stocklist, start, end)
df_all.reset_index().sort(['Ticker', 'Date'], ascending=[1,1]).set_index('Ticker')
df_ = df_all.set_index('Ticker', append=True)
''' Calculating all the KPIs via groupby (filtering pr ticker)'''
grouped = df_.groupby(level=1).Adj_Close
nslow = 26
nfast = 12
nema = 9
df_[['emaSlw', 'emaFst', 'MACD']] = df_.groupby(level=1).Adj_Close.apply(moving_average_convergence)
df_['MCD_Sign'] = df_.groupby(level=1).Adj_Close.apply(moving_average)
print ('(Output df)\n',df_,'\n')
df = df_.reset_index('Ticker')
df_test = df.groupby('Ticker').tail(1).reset_index().set_index('Date')
print ('df_test (summary from df) (Output)\n',df_test,'\n')
Obviously, I am not getting any column results for all MACD numbers. So somewhere the calculation goes south. I have no idea what is going wrong ...
Output line pr-ticker:
df_test (summary from df) (Output)
Ticker Adj_Close Volume emaSlw emaFst MACD MCD_Sign
Date
2016-07-07 nflx 95.10 9902700 NaN NaN NaN NaN
2016-07-07 mmm 174.87 1842300 NaN NaN NaN NaN
Any of you guys ... the tip !?