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