OnurKerimoglu commited on
Commit
cc15f2b
·
0 Parent(s):

introduced nb/technical_analysis_with_ta.ipynb

Browse files
notebooks/technical_analysis_with_ta.ipynb ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "import datetime as dt\n",
10
+ "import yfinance as yf\n",
11
+ "\n",
12
+ "ticker = 'TSLA'\n",
13
+ "period_start = dt.datetime.now() - dt.timedelta(weeks=8)\n",
14
+ "try:\n",
15
+ " print(f'Fetching price data for {ticker}')\n",
16
+ " data = yf.download(\n",
17
+ " ticker,\n",
18
+ " start=period_start,\n",
19
+ " end=dt.datetime.now(),\n",
20
+ " interval='1d'\n",
21
+ " )\n",
22
+ "except Exception as e:\n",
23
+ " print(f'Error fetching price data for {ticker}: {str(e)}')\n",
24
+ "\n",
25
+ "data.head()"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "execution_count": null,
31
+ "metadata": {},
32
+ "outputs": [],
33
+ "source": [
34
+ "# get rid of the redundant ticker column\n",
35
+ "df= data.copy()\n",
36
+ "df.columns = df.columns.droplevel('Ticker')\n",
37
+ "df.head()"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": null,
43
+ "metadata": {},
44
+ "outputs": [],
45
+ "source": [
46
+ "import matplotlib.pyplot as plt\n",
47
+ "import matplotlib.dates as mdates\n",
48
+ "\n",
49
+ "def plot_stock_metrics_ax(\n",
50
+ " ax,\n",
51
+ " dataset,\n",
52
+ " df,\n",
53
+ " colstoplot):\n",
54
+ " print(f'plotting {colstoplot} in {dataset}')\n",
55
+ " colorcycle = ['black', 'blue', 'red', 'green', 'orange']\n",
56
+ " for i, col in enumerate(colstoplot):\n",
57
+ " ax.plot(\n",
58
+ " df.index,\n",
59
+ " df[col],\n",
60
+ " color=colorcycle[i],\n",
61
+ " label=col,\n",
62
+ " linewidth=2)\n",
63
+ " # Format major ticks with year\n",
64
+ " # Set major ticks (every Monday with labels)\n",
65
+ " ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=mdates.MO))\n",
66
+ " ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))\n",
67
+ " # Set minor ticks (every day, but without labels)\n",
68
+ " ax.xaxis.set_minor_locator(mdates.DayLocator())\n",
69
+ " \n",
70
+ " ax.set_title(dataset)\n",
71
+ " ax.set_xlabel('Date')\n",
72
+ " ax.set_ylabel(dataset)\n",
73
+ " if len(colstoplot) > 1:\n",
74
+ " ax.legend()\n",
75
+ " if dataset in ['Index', 'Indices']:\n",
76
+ " ax.set_ylim([0, 100])\n",
77
+ " # Add a transparent shaded region between y=30 and y=70\n",
78
+ " ax.fill_between(df.index, 30, 70, color='gray', alpha=0.3)\n",
79
+ " if dataset in ['Price', 'Prices']:\n",
80
+ " # Add a transparent shaded region between y=30 and y=70\n",
81
+ " ax.fill_between(df.index, df['Low'], df['High'], color='gray', alpha=0.3)\n",
82
+ " ax.grid(True, linestyle='--', alpha=0.7)\n",
83
+ "\n",
84
+ "def plot_stock_metrics(\n",
85
+ " df,\n",
86
+ " datasets={\n",
87
+ " 'Volume': ['Volume'],\n",
88
+ " 'Price': ['Close'] # 'High','Low'\n",
89
+ " }\n",
90
+ " ):\n",
91
+ " numax = len(datasets)\n",
92
+ " fig, axes = plt.subplots(\n",
93
+ " nrows=numax,\n",
94
+ " ncols=1,\n",
95
+ " figsize=(10, 5*numax))\n",
96
+ " for i, ax in enumerate(axes.flat):\n",
97
+ " dataset = list(datasets.keys())[i]\n",
98
+ " colstoplot = datasets[dataset]\n",
99
+ " plot_stock_metrics_ax(\n",
100
+ " ax,\n",
101
+ " dataset,\n",
102
+ " df,\n",
103
+ " colstoplot)\n",
104
+ " plt.tight_layout()\n",
105
+ " plt.show()\n",
106
+ "plot_stock_metrics(df)"
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "execution_count": null,
112
+ "metadata": {},
113
+ "outputs": [],
114
+ "source": [
115
+ "from ta.volume import volume_weighted_average_price\n",
116
+ "from ta.momentum import RSIIndicator, StochasticOscillator\n",
117
+ "from ta.trend import MACD \n",
118
+ "\n",
119
+ "# Price Indicators\n",
120
+ "# Volume-Weighted Average Price (VWAP)\n",
121
+ "# https://chartschool.stockcharts.com/table-of-contents/technical-indicators-and-overlays/technical-overlays/volume-weighted-average-price-vwap\n",
122
+ "df['VWAP'] = volume_weighted_average_price(\n",
123
+ " high=df['High'],\n",
124
+ " low=df['Low'],\n",
125
+ " close=df['Close'],\n",
126
+ " volume=df['Volume'],\n",
127
+ ")\n",
128
+ "\n",
129
+ "# Indices\n",
130
+ "# RSI:\n",
131
+ "# https://www.investopedia.com/terms/r/rsi.asp\n",
132
+ "df['RSI'] = RSIIndicator(\n",
133
+ " df['Close'],\n",
134
+ " window=14).rsi()\n",
135
+ "# Stochastic Oscillator: \n",
136
+ "# https://chartschool.stockcharts.com/table-of-contents/technical-indicators-and-overlays/technical-indicators/stochastic-oscillator-fast-slow-and-full\n",
137
+ "df['StochOsc'] = StochasticOscillator(\n",
138
+ " df['High'],\n",
139
+ " df['Low'],\n",
140
+ " df['Close'],\n",
141
+ " window=14).stoch()\n",
142
+ "\n",
143
+ "# Trend signals\n",
144
+ "# Moving Average Convergence Divergence (MACD):\n",
145
+ "# https://chartschool.stockcharts.com/table-of-contents/technical-indicators-and-overlays/technical-indicators/macd-moving-average-convergence-divergence-oscillator\n",
146
+ "macd = MACD(\n",
147
+ " df['Close'],\n",
148
+ " window_slow=26,\n",
149
+ " window_fast=12,\n",
150
+ " window_sign=9)\n",
151
+ "df['MACD'] = macd.macd()\n",
152
+ "df['MACDsig'] = macd.macd_signal()\n",
153
+ "df['MACDdif'] = macd.macd_diff()\n",
154
+ "\n",
155
+ "plot_stock_metrics(\n",
156
+ " df,\n",
157
+ " datasets={\n",
158
+ " 'Volume': ['Volume'],\n",
159
+ " 'Prices': ['Close', 'VWAP'], # 'High','Low', \n",
160
+ " 'Indices': ['RSI', 'StochOsc'],\n",
161
+ " 'Trend': ['MACD', 'MACDsig', 'MACDdif']}\n",
162
+ " )"
163
+ ]
164
+ }
165
+ ],
166
+ "metadata": {
167
+ "kernelspec": {
168
+ "display_name": "finagents_py311",
169
+ "language": "python",
170
+ "name": "python3"
171
+ },
172
+ "language_info": {
173
+ "codemirror_mode": {
174
+ "name": "ipython",
175
+ "version": 3
176
+ },
177
+ "file_extension": ".py",
178
+ "mimetype": "text/x-python",
179
+ "name": "python",
180
+ "nbconvert_exporter": "python",
181
+ "pygments_lexer": "ipython3",
182
+ "version": "3.11.1"
183
+ }
184
+ },
185
+ "nbformat": 4,
186
+ "nbformat_minor": 2
187
+ }