timeseries-julia-python
random julia and python scripts analyzing stock timeseries data
walkthrough-talib.py
(3214B)
1 import pandas as pd
2 from datetime import datetime, timedelta
3 from dateutil.relativedelta import relativedelta
4 import talib
5 import matplotlib.pyplot as plt
6 from mplfinance.original_flavor import candlestick_ohlc
7 from matplotlib.pylab import date2num
8
9 # Get today's date as UTC timestamp
10 today = datetime.today().strftime("%d/%m/%Y")
11 today = datetime.strptime(today + " +0000", "%d/%m/%Y %z")
12 to = int(today.timestamp())
13 # Get date ten years ago as UTC timestamp
14 ten_yr_ago = today - relativedelta(years=10)
15 fro = int(ten_yr_ago.timestamp())
16
17
18 def get_price_hist(ticker):
19 # Put stock price data in dataframe
20 url = "https://query1.finance.yahoo.com/v7/finance/download/{" \
21 "ticker}?period1={fro}&period2={" \
22 "to}&interval=1d&events=history".format(ticker=ticker, fro=fro, to=to)
23 data = pd.read_csv(url)
24
25 # Convert date to timestamp and make index
26 data.index = data["Date"].apply(lambda x: pd.Timestamp(x))
27 data.drop("Date", axis=1, inplace=True)
28
29 return data
30
31
32 def get_indicators(data):
33 # Get MACD
34 data["macd"], data["macd_signal"], data["macd_hist"] = talib.MACD(
35 data['Close'])
36
37 # Get MA10 and MA30
38 data["ma10"] = talib.MA(data["Close"], timeperiod=10)
39 data["ma30"] = talib.MA(data["Close"], timeperiod=30)
40
41 # Get RSI
42 data["rsi"] = talib.RSI(data["Close"])
43 return data
44
45
46 def plot_chart(data, n, ticker):
47 # Filter number of observations to plot
48 data = data.iloc[-n:]
49
50 # Create figure and set axes for subplots
51 fig = plt.figure()
52 fig.set_size_inches((20, 16))
53 ax_candle = fig.add_axes((0, 0.72, 1, 0.32))
54 ax_macd = fig.add_axes((0, 0.48, 1, 0.2), sharex=ax_candle)
55 ax_rsi = fig.add_axes((0, 0.24, 1, 0.2), sharex=ax_candle)
56 ax_vol = fig.add_axes((0, 0, 1, 0.2), sharex=ax_candle)
57
58 # Format x-axis ticks as dates
59 ax_candle.xaxis_date()
60
61 # Get nested list of date, open, high, low and close prices
62 ohlc = []
63 for date, row in data.iterrows():
64 openp, highp, lowp, closep = row[:4]
65 ohlc.append([date2num(date), openp, highp, lowp, closep])
66
67 # Plot candlestick chart
68 ax_candle.plot(data.index, data["ma10"], label="MA10")
69 ax_candle.plot(data.index, data["ma30"], label="MA30")
70 candlestick_ohlc(ax_candle, ohlc, colorup="g", colordown="r", width=0.8)
71 ax_candle.legend()
72
73 # Plot MACD
74 ax_macd.plot(data.index, data["macd"], label="macd")
75 ax_macd.bar(data.index, data["macd_hist"] * 3, label="hist")
76 ax_macd.plot(data.index, data["macd_signal"], label="signal")
77 ax_macd.legend()
78
79 # Plot RSI
80 # Above 70% = overbought, below 30% = oversold
81 ax_rsi.set_ylabel("(%)")
82 ax_rsi.plot(data.index, [70] * len(data.index), label="overbought")
83 ax_rsi.plot(data.index, [30] * len(data.index), label="oversold")
84 ax_rsi.plot(data.index, data["rsi"], label="rsi")
85 ax_rsi.legend()
86
87 # Show volume in millions
88 ax_vol.bar(data.index, data["Volume"] / 1000000)
89 ax_vol.set_ylabel("(Million)")
90
91 # Save the chart as PNG
92 fig.savefig("charts/" + ticker + ".png", bbox_inches="tight")
93
94 plt.show()
95
96
97 nflx_df = get_price_hist("NFLX")
98 nflx_df2 = get_indicators(nflx_df)
99 plot_chart(nflx_df2, 180, "NFLX")