In [7]:
import yahooFinance as yf
In [8]:
yf.getQuote(['TSLA','AAPL'])
Out[8]:
In [9]:
tesla = yf.getHistoricData('TSLA',(2012,1,1))
print tesla.tail(20)
In [10]:
tesla.tail(2)['close']
Out[10]:
In [28]:
figsize(15,9)
from pandas import rolling_min, rolling_max, Series
# last n data point of tesla
n = 150
price = [el for el in tesla.tail(n)['close']]
x = range(n)
plot(x,price,'.')
# moving average
import numpy
def movingaverage(interval, window_size):
window= numpy.ones(int(window_size))/float(window_size)
return numpy.convolve(interval, window, 'same')
# generate moving average
window = 7
y_av = movingaverage(price, window)
min_av = rolling_min(Series(price), window)
max_av = rolling_max(Series(price), window)
mins = set(min_av)
maxs = set(min_av)
plot(x, min_av, "r")
plot(x, max_av, "r")
plot(x, y_av, "b")
#Series(price).plot()
#plot(x, price, "b")
#plot(mins, maxs, "b")
xlim(window, n-window)
Out[28]:
In [14]:
# find when to buy and sell
import trendy
import tradingWithPython as twp
order=trendy.iterlines(price, window = 25, charts = True)
order=[el*100 for el in order]
In [21]:
import tradingWithPython.lib.yahooFinance as yahoo
import pandas as pd
price = yahoo.getHistoricData('TSLA')['adj_close'][-n:]
price.plot()
Out[21]:
In [22]:
# create a stratgy
strategy = pd.Series(index=price.index)
for i, idx in enumerate(price.index):
if order[i]!=0:
strategy[idx] = order[i]
#print idx,order[i]
# force sell at the end
order[-1] = 0
# generate backtest
bt = twp.Backtest(price, strategy, initialCash=100)
bt.plotTrades()
figure()
bt.pnl.plot()
title('pnl')
figure()
bt.data.plot()
title('all strategy data')
Out[22]:
In [40]:
trendy.minitrends(y, window = 30, charts = True);
In [ ]: