Skip to content

Instantly share code, notes, and snippets.

@suebtas
Forked from shaan-shah/candles1.ipynb
Created April 20, 2022 07:59
Show Gist options
  • Save suebtas/9edafb2ff011159dcaab082ef418961b to your computer and use it in GitHub Desktop.
Save suebtas/9edafb2ff011159dcaab082ef418961b to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from datetime import date\n",
"from nsepy import get_history\n",
"import pandas as pd"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def obtain_data(ticker,start,end):\n",
"# Enter the start and end dates using the method date(yyyy,m,dd) \n",
" stock=get_history(symbol=ticker,start=start,end=end)\n",
" df=stock.copy()\n",
" df=df.reset_index()\n",
" df=df.drop(['Series','Prev Close','Last','Turnover','%Deliverble','Trades'],axis=1)\n",
" df=df.rename({'Open':'open_price','Close':'close_price','High':'high','Low':'low','Volume':'volume'},axis='columns')\n",
" df.index=df.Date\n",
" return df"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import pandas as pd"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"\"\"\"This cell defineds the plot_candles function\"\"\"\n",
"\n",
"def plot_candles(pricing, title=None, volume_bars=False, color_function=None, technicals=None):\n",
" \"\"\" Plots a candlestick chart using quantopian pricing data.\n",
" \n",
" Author: Daniel Treiman\n",
" \n",
" Args:\n",
" pricing: A pandas dataframe with columns ['open_price', 'close_price', 'high', 'low', 'volume']\n",
" title: An optional title for the chart\n",
" volume_bars: If True, plots volume bars\n",
" color_function: A function which, given a row index and price series, returns a candle color.\n",
" technicals: A list of additional data series to add to the chart. Must be the same length as pricing.\n",
" \"\"\"\n",
" def default_color(index, open_price, close_price, low, high):\n",
" return 'r' if open_price[index] > close_price[index] else 'g'\n",
" color_function = color_function or default_color\n",
" technicals = technicals or []\n",
" open_price = pricing['open_price']\n",
" close_price = pricing['close_price']\n",
" low = pricing['low']\n",
" high = pricing['high']\n",
" oc_min = pd.concat([open_price, close_price], axis=1).min(axis=1)\n",
" oc_max = pd.concat([open_price, close_price], axis=1).max(axis=1)\n",
" \n",
" if volume_bars:\n",
" fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, gridspec_kw={'height_ratios': [3,1]},figsize=(7,7))\n",
" else:\n",
" fig, ax1 = plt.subplots(1, 1)\n",
" if title:\n",
" ax1.set_title(title)\n",
" fig.tight_layout()\n",
" x = np.arange(len(pricing))\n",
" candle_colors = [color_function(i, open_price, close_price, low, high) for i in x]\n",
" candles = ax1.bar(x, oc_max-oc_min, bottom=oc_min, color=candle_colors, linewidth=0)\n",
" lines = ax1.vlines(x , low, high, color=candle_colors, linewidth=1)\n",
" ax1.xaxis.grid(True)\n",
" ax1.yaxis.grid(True)\n",
" ax1.xaxis.set_tick_params(which='major', length=3.0, direction='in', top='off')\n",
" ax1.set_yticklabels([])\n",
" # Assume minute frequency if first two bars are in the same day.\n",
" frequency = 'minute' if (pricing.index[1] - pricing.index[0]).days == 0 else 'day'\n",
" time_format = '%d-%m-%Y'\n",
" if frequency == 'minute':\n",
" time_format = '%H:%M'\n",
" # Set X axis tick labels.\n",
" #plt.xticks(x, [date.strftime(time_format) for date in pricing.index], rotation='vertical')\n",
" for indicator in technicals:\n",
" ax1.plot(x, indicator)\n",
" \n",
" if volume_bars:\n",
" volume = pricing['volume']\n",
" volume_scale = None\n",
" scaled_volume = volume\n",
" if volume.max() > 1000000:\n",
" volume_scale = 'M'\n",
" scaled_volume = volume / 1000000\n",
" elif volume.max() > 1000:\n",
" volume_scale = 'K'\n",
" scaled_volume = volume / 1000\n",
" ax2.bar(x, scaled_volume, color=candle_colors)\n",
" volume_title = 'Volume'\n",
" if volume_scale:\n",
" volume_title = 'Volume (%s)' % volume_scale\n",
" #ax2.set_title(volume_title)\n",
" ax2.xaxis.grid(True)\n",
" ax2.set_yticklabels([])\n",
" ax2.set_xticklabels([])\n",
" return fig "
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.8.1"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment