{"id":2150,"date":"2023-09-29T11:58:46","date_gmt":"2023-09-29T11:58:46","guid":{"rendered":"https:\/\/eodhd.com\/financial-academy\/?p=2150"},"modified":"2025-02-05T13:07:26","modified_gmt":"2025-02-05T13:07:26","slug":"algorithmic-trading-with-williams-r-in-python","status":"publish","type":"post","link":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python","title":{"rendered":"Algorithmic Trading with Williams %R in\u00a0Python"},"content":{"rendered":"\n<p id=\"8890\">While having a look at the list of most popular momentum indicators that consists of the Relative Strength Index, and the Stochastic Oscillator, the one we are going to discuss today also joins the list when considering its usage and efficiency in the real world market. It\u2019s an indicator known as Williams %R.<\/p>\n\n\n\n<p id=\"796e\">In this article, we are going to explore what Williams %R is all about, the math behind this indicator, and how a trading strategy based on it can be built with the help of Python. As a bonus step, we will compare the returns of our Williams %R strategy returns with the returns of SPY ETF (an ETF specifically designed to track the movement of the S&amp;P 500 Index) to get an idea of how well our strategy performs in the real-world market and can be considered as a step to evaluate the strategy. Considering your curiosity piqued, let\u2019s dive into the article!<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a class=\"maxbutton-1 maxbutton maxbutton-subscribe-to-api external-css btn\" href=\"https:\/\/eodhd.com\/register\"><span class='mb-text'>Register &amp; Get Data<\/span><\/a><\/p>\n\n\n\n\n\n\n<h1 class=\"wp-block-heading\" id=\"6fbd\">Williams %R<\/h1>\n\n\n\n<p id=\"9c85\">Founded by Larry Williams, the Williams %R is a momentum indicator whose values oscillate between 0 to -100. This indicator is most similar to the Stochastic Oscillator, but differs in its calculation. Traders use this indicator to spot potential entry and exit points for trades by constructing two levels of overbought and oversold. Before moving on, a word on overbought and oversold levels: A stock is said to be overbought when the market\u2019s trend seems to be extremely bullish and bound to consolidate. Similarly, a stock reaches an oversold region when the market\u2019s trend seems to be extremely bearish and has the tendency to bounce. The traditional threshold for overbought and oversold levels are 20 and 80 respectively but there aren&#8217;t any prohibitions in taking other values too.<\/p>\n\n\n\n<p id=\"10a8\">In order to calculate the values of Williams %R with the traditional setting of 14 as the lookback period, first, the highest high and the lowest low for each period over a fourteen-day timeframe is determined. Then, the two differences are taken: The closing price from the highest high, and the lowest low from the highest high. Finally, the first difference is divided by the second difference and multiple by -100 to obtain the values of Williams %R. The calculation can be mathematically represented as follows:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>W%R 14<\/strong> = [ <strong>H.HIGH<\/strong> - <strong>C.PRICE<\/strong> ] \/ [ <strong>L.LOW<\/strong> - <strong>C.PRICE<\/strong> ] * (<strong> - 100<\/strong> )\n\nwhere,\nW%R 14 = 14-day Williams %R of the stock\nH.HIGH = 14-day Highest High of the stock\nL.LOW = 14-day Lowest Low of the stock\nC.PRICE = Closing price of the stock<\/pre>\n\n\n\n<p id=\"697e\">The underlying idea of this indicator is that the stock will keep reaching new highs when it is a strong uptrend and similarly, the stock will reach new lows when it follows a sturdy downtrend. With that being said, let\u2019s discuss the trading strategy we are going to implement in this article.<\/p>\n\n\n\n<p id=\"ee19\"><strong>About our trading strategy:<\/strong>&nbsp;There are a lot of Williams %R-based trading strategies that can be implemented in the real world market but the one we are going to discuss today is a strategy based on the overbought and oversold levels. The strategy reveals a buy signal whenever the previous reading of the Williams %R is below -20 and the current reading is above -20. Likewise, a sell signal is generated whenever the previous reading of the Williams %R is above -80 and the current reading is below -80. Our trading strategy can be represented as follows:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\">IF <strong>PREV.W%R<\/strong> &lt; [<strong> - 20 <\/strong>] AND <strong>CURRENT.W%R<\/strong> &gt; [<strong> - 20<\/strong> ] ==&gt; <strong>BUY SIGNAL<\/strong><br>IF <strong>PREV.W%R<\/strong> &gt; [ <strong>- 80<\/strong> ] AND <strong>CURRENT.W%R<\/strong> &lt; [ <strong>- 80<\/strong> ] ==&gt; <strong>SELL SIGNAL<\/strong><\/pre>\n\n\n\n<p id=\"69b3\">This concludes our theory part on Williams %R, its calculation, and the trading strategy. Now, let\u2019s build this indicator from scratch in Python, construct the trading strategy we discussed, backtest it on the Netflix data, and compare the returns with those of the SPY ETF. Without further ado, let\u2019s do some coding!&nbsp;<strong>Before moving on, a note on disclaimer: This article\u2019s sole purpose is to educate people and must be considered as an information piece but not as investment advice.<\/strong><\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"98ff\">Implementation in Python<\/h1>\n\n\n\n<p id=\"fe52\">The coding part is classified into various steps as follows:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>1. Importing Packages<\/strong>\n<strong>2. API Key Activation\n2. Extracting Historical Stock Data\n3. Williams %R Calculation\n4. Williams %R Indicator Plot\n5. Creating the Trading Strategy\n6. Plotting the Trading Lists\n7. Creating our Position\n8. Backtesting\n9. SPY ETF Comparison<\/strong><\/pre>\n\n\n\n<p id=\"aadf\">We will be following the order mentioned in the above list and buckle up your seat belts to follow every upcoming coding part.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ddd7\">Step-1: Importing Packages<\/h2>\n\n\n\n<p id=\"65f4\">Importing the required packages into the Python environment is a non-skippable step. The primary packages are going to be eodhd for extracting historical stock data, Pandas for data formatting and manipulations, NumPy to work with arrays and for complex functions, and Matplotlib for plotting purposes. The secondary packages are going to be Math for mathematical functions and Termcolor for font customization (optional).<\/p>\n\n\n\n<p id=\"b9a0\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\"># IMPORTING PACKAGES\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom termcolor import colored as cl\nfrom math import floor\nfrom eodhd import APIClient\n\nplt.rcParams['figure.figsize'] = (20,10)\nplt.style.use('fivethirtyeight')<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"6a56\">With the required packages imported into Python, we can proceed to fetch historical data for Netflix using EODHD&#8217;s <code>eodhd<\/code> Python library. Also, if you haven\u2019t installed any of the imported packages, make sure to do so using the&nbsp;<code>pip<\/code>&nbsp;command in your terminal.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"a9f4\">Step-2: API Key Activation<\/h2>\n\n\n\n<p id=\"c710\">It is essential to register the EODHD API key with the package in order to use its functions. If you don\u2019t have an EODHD API key, firstly, head over to their&nbsp;<a href=\"https:\/\/eodhistoricaldata.com\/?utm_source=medium&amp;utm_medium=post&amp;utm_campaign=a_python_package_to_retrieve_financial_data_part2\" rel=\"noreferrer noopener\" target=\"_blank\">website<\/a>, then, finish the&nbsp;<a href=\"https:\/\/eodhistoricaldata.com\/register?utm_source=medium&amp;utm_medium=post&amp;utm_campaign=a_python_package_to_retrieve_financial_data_part2\" rel=\"noreferrer noopener\" target=\"_blank\">registration<\/a>&nbsp;process to create an EODHD account, and finally, navigate to the \u2018<a href=\"https:\/\/eodhistoricaldata.com\/cp\/settings?utm_source=medium&amp;utm_medium=post&amp;utm_campaign=a_python_package_to_retrieve_financial_data_part2\" rel=\"noreferrer noopener\" target=\"_blank\">Settings<\/a>\u2019 page where you could find your secret EODHD API key. It is important to ensure that this secret API key is not revealed to anyone. You can activate the API key by following this code:<\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">api_key = '&lt;YOUR API KEY&gt;'\nclient = APIClient(api_key)<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"fd3d\">The code is pretty simple. In the first line, we are storing the secret EODHD API key into the&nbsp;<code>api_key<\/code>&nbsp;and then in the second line, we are using the&nbsp;<code>APIClient<\/code>&nbsp;class provided by the&nbsp;<code>eodhd<\/code>&nbsp;package to activate the API key and stored the response in the&nbsp;<code>client<\/code>&nbsp;variable.<\/p>\n\n\n\n<p id=\"4634\">Note that you need to replace&nbsp;<code>&lt;YOUR API KEY&gt;<\/code>&nbsp;with your secret EODHD API key. Apart from directly storing the API key with text, there are other ways for better security such as utilizing environmental variables, and so on.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a class=\"maxbutton-1 maxbutton maxbutton-subscribe-to-api external-css btn\" href=\"https:\/\/eodhd.com\/register\"><span class='mb-text'>Register &amp; Get Data<\/span><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"8568\">Step-3: Extracting Historical Data<\/h2>\n\n\n\n<p id=\"ac40\">Before heading into the extraction part, it is first essential to have some background about historical or end-of-day data. In a nutshell, historical data consists of information accumulated over a period of time. It helps in identifying patterns and trends in the data. It also assists in studying market behavior. Now, you can easily extract the historical data of any tradeable assets using the&nbsp;<code>eod<\/code>&nbsp;package by following this code:<\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\"># EXTRACTING HISTORICAL DATA\n\ndef extract_historical_data(ticker, start_date):\n    json_resp = client.get_eod_historical_stock_market_data(symbol = ticker, period = 'd', from_date = start_date, order = 'a')\n    df = pd.DataFrame(json_resp)\n    df = df.set_index('date')\n    df.index = pd.to_datetime(df.index)\n    return df\n\nnflx = get_historical_data('NFLX', '2020-01-01')\nnflx.tail()<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"c103\">In the above code, we are using the&nbsp;<code>get_eod_historical_stock_market_data<\/code>&nbsp;function provided by the <code>eod<\/code> package to extract the split-adjusted historical stock data of Netflix. The function consists of the following parameters:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>the&nbsp;<code>ticker<\/code>&nbsp;parameter where the symbol of the stock we are interested in extracting the data should be mentioned<\/li>\n\n\n\n<li>the&nbsp;<code>period<\/code>&nbsp;refers to the time interval between each data point (one-day interval in our case).<\/li>\n\n\n\n<li>the&nbsp;<code>from_date<\/code>&nbsp;and&nbsp;<code>to_date<\/code>&nbsp;parameters which indicate the starting and ending date of the data respectively. The format of the input should be \u201cYYYY-MM-DD\u201d<\/li>\n\n\n\n<li>the&nbsp;<code>order<\/code>&nbsp;parameter which is an optional parameter that can be used to order the dataframe either in ascending (<code>a<\/code>) or descending (<code>d<\/code>). It is ordered based on the dates.<\/li>\n<\/ul>\n\n\n\n<p id=\"a294\">After extracting the historical data, we are performing some data-wrangling processes to clean and format the data. The final dataframe looks like this:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"856\" height=\"458\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-25.png\" alt=\"\" class=\"wp-image-2153\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"e764\">Step-3: Williams %R Calculation<\/h2>\n\n\n\n<p id=\"a625\">In this step, we are going to calculate the values of Williams %R by following the formula we discussed before.<\/p>\n\n\n\n<p id=\"945e\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">def get_wr(high, low, close, lookback):\n    highh = high.rolling(lookback).max() \n    lowl = low.rolling(lookback).min()\n    wr = -100 * ((highh - close) \/ (highh - lowl))\n    return wr\n\nnflx['wr_14'] = get_wr(nflx['high'], nflx['low'], nflx['close'], 14)\nnflx = nflx.dropna()\nnflx.head()<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"c427\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1041\" height=\"460\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-27.png\" alt=\"\" class=\"wp-image-2155\"\/><\/figure>\n\n\n\n<p id=\"acde\"><strong>Code Explanation:<\/strong>&nbsp;We are first defining a function named \u2018get_wr\u2019 that takes a stock\u2019s high price data (\u2018high\u2019), low price data (\u2018low\u2019), closing price data (\u2018close\u2019), and the lookback period (\u2018period\u2019) as parameters. Inside the function, we are first determining the highest high over a specific lookback period timeframe with the help of the \u2018rolling\u2019 and \u2018max\u2019 functions provided by the Pandas package and stored it into the \u2018highh\u2019 variable. What the \u2018rolling\u2019 function performs is that it will take into account the n-period timeframe we specify and the \u2018max\u2019 function filters the maximum values present in the given dataframe.<\/p>\n\n\n\n<p id=\"0a9f\">Next, we are defining a variable named \u2018lowl\u2019 to store the lowest low over a specified lookback period timeframe which we determined using the \u2018rolling\u2019 and \u2018min\u2019 function (as the name suggests, filters the minimum values in the given dataframe) provided by the Pandas package.<\/p>\n\n\n\n<p id=\"4d2e\">Then, we are substituting the determined highest high and lowest low values into the formula we discussed before to calculate the values of Williams %R and stored it into the \u2018wr\u2019 variable. Finally, we are returning and calling the created function to store Netflix\u2019s Williams %R readings with 14 as the lookback period.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"f476\">Step-4: Williams %R Plot<\/h2>\n\n\n\n<p id=\"6650\">In this step, we are going to plot the calculated Williams %R values of Netflix to make more sense of them. The main aim of this part is not on the coding section but instead to observe the plot to gain a solid understanding of the Williams %R technical indicator.<\/p>\n\n\n\n<p id=\"8715\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">ax1 = plt.subplot2grid((11,1), (0,0), rowspan = 5, colspan = 1)<br>ax2 = plt.subplot2grid((11,1), (6,0), rowspan = 5, colspan = 1)<br>ax1.plot(nflx['close'], linewidth = 2)<br>ax1.set_title('NFLX CLOSING PRICE')<br>ax2.plot(nflx['wr_14'], color = 'orange', linewidth = 2)<br>ax2.axhline(-20, linewidth = 1.5, linestyle = '--', color = 'grey')<br>ax2.axhline(-80, linewidth = 1.5, linestyle = '--', color = 'grey')<br>ax2.set_title('NFLX WILLIAMS %R 14')<br>plt.show()<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"f05a\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1818\" height=\"884\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-28.png\" alt=\"\" class=\"wp-image-2156\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p id=\"5e24\">The above chart is divided into two panels: The upper panel with the closing price of Netflix\u2019s stock data and the lower panel with the values of Netflix\u2019s 14-day readings of Williams %R. Now, the chart can be utilized in two ways. The first way is using the chart as a tool to identify overbought and oversold states of the market. You could observe that there are two horizontal grey lines plotted above and below the market which are the overbought and oversold levels plotted at a threshold of -20 and -80 respectively. You can consider that the market is in the state of overbought if the Williams %R has a reading of above the upper line or the overbought line. Similarly, you can assume that the market is in the state of oversold if the Williams %R has a reading of below the lower line or the oversold line.<\/p>\n\n\n\n<p id=\"ce2c\">The second way of using Williams %R is to identify false momentum in the market. During a sturdy uptrend, the readings of Williams %R tend to reach above -20 frequently. If the indicator falls and struggles to reach above -20 before the next fall, indicates that the market\u2019s momentum is not authentic and possible to follow a tremendous downtrend. Likewise, during a healthy downtrend, the readings of Williams %R bound to go below -80 frequently. If the indicator rises and fails to reach -80 before the next rise, reveals that the market is going to follow a positive trend.<\/p>\n\n\n\n<p id=\"fd17\">Since Williams %R is a directional indicator (an indicator whose movement is directly proportional to that of the actual market), traders also use this indicator to find and confirm strong uptrends or downtrends in a market and trade along with it. Some indicators are not of much use while utilized for identifying or confirming market trends as they might be lagging in nature (an indicator that takes into account the historical data points to determine the current reading) but Williams %R is an effective one because it is a leading indicator (an indicator that takes into account the previous data points to predict the future movements).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"8adc\">Step-5: Creating the trading strategy<\/h2>\n\n\n\n<p id=\"d587\">In this step, we are going to implement the discussed Williams %R trading strategy in Python.<\/p>\n\n\n\n<p id=\"6bc0\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">def implement_wr_strategy(prices, wr):    \n    buy_price = []\n    sell_price = []\n    wr_signal = []\n    signal = 0\n\n    for i in range(len(wr)):\n        if wr[i-1] &gt; -80 and wr[i] &lt; -80:\n            if signal != 1:\n                buy_price.append(prices[i])\n                sell_price.append(np.nan)\n                signal = 1\n                wr_signal.append(signal)\n            else:\n                buy_price.append(np.nan)\n                sell_price.append(np.nan)\n                wr_signal.append(0)\n        elif wr[i-1] &lt; -20 and wr[i] &gt; -20:\n            if signal != -1:\n                buy_price.append(np.nan)\n                sell_price.append(prices[i])\n                signal = -1\n                wr_signal.append(signal)\n            else:\n                buy_price.append(np.nan)\n                sell_price.append(np.nan)\n                wr_signal.append(0)\n        else:\n            buy_price.append(np.nan)\n            sell_price.append(np.nan)\n            wr_signal.append(0)\n            \n    return buy_price, sell_price, wr_signal\n            \nbuy_price, sell_price, wr_signal = implement_wr_strategy(nflx['close'], nflx['wr_14'])<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"742e\"><strong>Code Explanation:<\/strong>&nbsp;First, we are defining a function named \u2018implement_wr_strategy\u2019 which takes the stock prices (\u2018prices\u2019), and the values of Williams %R indicator (\u2018wr\u2019) as parameters.<\/p>\n\n\n\n<p id=\"a427\">Inside the function, we are creating three empty lists (buy_price, sell_price, and wr_signal) in which the values will be appended while creating the trading strategy.<\/p>\n\n\n\n<p id=\"1921\">After that, we are implementing the trading strategy through a for-loop. Inside the for-loop, we are passing certain conditions, and if the conditions are satisfied, the respective values will be appended to the empty lists. If the condition to buy the stock gets satisfied, the buying price will be appended to the \u2018buy_price\u2019 list, and the signal value will be appended as 1 representing to buy the stock. Similarly, if the condition to sell the stock gets satisfied, the selling price will be appended to the \u2018sell_price\u2019 list, and the signal value will be appended as -1 representing to sell the stock.<\/p>\n\n\n\n<p id=\"1949\">Finally, we are returning the lists appended with values. Then, we are calling the created function and stored the values into their respective variables. The list doesn\u2019t make any sense unless we plot the values. So, let\u2019s plot the values of the created trading lists.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2d74\">Step-6: Plotting the trading signals<\/h2>\n\n\n\n<p id=\"11c6\">In this step, we are going to plot the created trading lists to make sense of them.<\/p>\n\n\n\n<p id=\"a9b0\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">ax1 = plt.subplot2grid((11,1), (0,0), rowspan = 5, colspan = 1)\nax2 = plt.subplot2grid((11,1), (6,0), rowspan = 5, colspan = 1)\nax1.plot(nflx['close'], linewidth = 2)\nax1.plot(nflx.index, buy_price, marker = '^', markersize = 12, linewidth = 0, color = 'green', label = 'BUY SIGNAL')\nax1.plot(nflx.index, sell_price, marker = 'v', markersize = 12, linewidth = 0, color = 'r', label = 'SELL SIGNAL')\nax1.legend()\nax1.set_title('NFLX TRADING SIGNALS')\nax2.plot(nflx['wr_14'], color = 'orange', linewidth = 2)\nax2.axhline(-20, linewidth = 1.5, linestyle = '--', color = 'grey')\nax2.axhline(-80, linewidth = 1.5, linestyle = '--', color = 'grey')\nax2.set_title('NFLX WILLIAMS %R 14')\nplt.show()<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"8b2e\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1818\" height=\"884\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-29.png\" alt=\"\" class=\"wp-image-2157\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p id=\"2e19\"><strong>Code Explanation:<\/strong>&nbsp;We are plotting the readings of Williams %R along with the buy and sell signals generated by the trading strategy. We can observe that whenever the Williams %R line crosses from below to above -20 and, a green-colored buy signal is plotted in the chart. Similarly, whenever the Williams %R line crosses from above to below -80 and, a red-colored sell signal is plotted in the chart.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"97ab\">Step-7: Creating our Position<\/h2>\n\n\n\n<p id=\"8b42\">In this step, we are going to create a list that indicates 1 if we hold the stock or 0 if we don\u2019t own or hold the stock.<\/p>\n\n\n\n<p id=\"9923\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">position = []\nfor i in range(len(wr_signal)):\n    if wr_signal[i] &gt; 1:\n        position.append(0)\n    else:\n        position.append(1)\n        \nfor i in range(len(nflx['close'])):\n    if wr_signal[i] == 1:\n        position[i] = 1\n    elif wr_signal[i] == -1:\n        position[i] = 0\n    else:\n        position[i] = position[i-1]\n        \nclose_price = nflx['close']\nwr = nflx['wr_14']\nwr_signal = pd.DataFrame(wr_signal).rename(columns = {0:'wr_signal'}).set_index(nflx.index)\nposition = pd.DataFrame(position).rename(columns = {0:'wr_position'}).set_index(nflx.index)\n\nframes = [close_price, wr, wr_signal, position]\nstrategy = pd.concat(frames, join = 'inner', axis = 1)\n\nstrategy.head()<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"44a5\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"871\" height=\"464\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-30.png\" alt=\"\" class=\"wp-image-2158\"\/><\/figure>\n\n\n\n<p id=\"b6db\"><strong>Code Explanation:<\/strong>&nbsp;First, we are creating an empty list named \u2018position\u2019. We are passing two for-loops, one is to generate values for the \u2018position\u2019 list to just match the length of the \u2018signal\u2019 list. The other for-loop is the one we are using to generate actual position values. Inside the second for-loop, we are iterating over the values of the \u2018signal\u2019 list, and the values of the \u2018position\u2019 list get appended concerning which condition gets satisfied. The value of the position remains 1 if we hold the stock or remains 0 if we sold or don\u2019t own the stock. Finally, we are doing some data manipulations to combine all the created lists into one dataframe.<\/p>\n\n\n\n<p id=\"4ad4\">From the output being shown, we can see that in the first row our position in the stock has remained 1 (since there isn\u2019t any change in the Williams %R signal) but our position suddenly turned to -1 as we sold the stock when the Williams %R trading signal represents a sell signal (-1). Our position will remain 0 until some changes in the trading signal occur. Now it\u2019s time to do implement some backtesting process!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6ea5\">Step-8: Backtesting<\/h2>\n\n\n\n<p id=\"1d00\">Before moving on, it is essential to know what backtesting is. Backtesting is the process of seeing how well our trading strategy has performed on the given stock data. In our case, we are going to implement a backtesting process for our Williams %R trading strategy over the Netflix stock data.<\/p>\n\n\n\n<p id=\"0f0e\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">nflx_ret = pd.DataFrame(np.diff(nflx['close'])).rename(columns = {0:'returns'})\nwr_strategy_ret = []\n\nfor i in range(len(nflx_ret)):\n    returns = nflx_ret['returns'][i]*strategy['wr_position'][i]\n    wr_strategy_ret.append(returns)\n    \nwr_strategy_ret_df = pd.DataFrame(wr_strategy_ret).rename(columns = {0:'wr_returns'})\ninvestment_value = 100000\nwr_investment_ret = []\n\nfor i in range(len(wr_strategy_ret_df['wr_returns'])):\n    number_of_stocks = floor(investment_value\/nflx['close'][i])\n    returns = number_of_stocks*wr_strategy_ret_df['wr_returns'][i]\n    wr_investment_ret.append(returns)\n\nwr_investment_ret_df = pd.DataFrame(wr_investment_ret).rename(columns = {0:'investment_returns'})\ntotal_investment_ret = round(sum(wr_investment_ret_df['investment_returns']), 2)\nprofit_percentage = floor((total_investment_ret\/investment_value)*100)\nprint(cl('Profit gained from the W%R strategy by investing $100k in NFLX : {}'.format(total_investment_ret), attrs = ['bold']))\nprint(cl('Profit percentage of the W%R strategy : {}%'.format(profit_percentage), attrs = ['bold']))<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"1fff\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>Profit gained from the W%R strategy by investing $100k in NFLX : 57772.45<\/strong><br><strong>Profit percentage of the W%R strategy : 57%<\/strong><\/pre>\n\n\n\n<p id=\"fee3\"><strong>Code Explanation:<\/strong>&nbsp;First, we are calculating the returns of the Netflix stock using the \u2018diff\u2019 function provided by the NumPy package and we have stored it as a dataframe into the \u2018nflx_ret\u2019 variable. Next, we are passing a for-loop to iterate over the values of the \u2018nflx_ret\u2019 variable to calculate the returns we gained from our Williams %R trading strategy, and these returns values are appended to the \u2018wr_strategy_ret\u2019 list. Next, we are converting the \u2018wr_strategy_ret\u2019 list into a dataframe and stored it into the \u2018wr_strategy_ret_df\u2019 variable.<\/p>\n\n\n\n<p id=\"3901\">Next comes the backtesting process. We are going to backtest our strategy by investing a hundred thousand USD into our trading strategy. So first, we are storing the amount of investment into the \u2018investment_value\u2019 variable. After that, we are calculating the number of Netflix stocks we can buy using the investment amount. You can notice that I\u2019ve used the \u2018floor\u2019 function provided by the Math package because, while dividing the investment amount by the closing price of Netflix stock, it spits out an output with decimal numbers. The number of stocks should be an integer but not a decimal number. Using the \u2018floor\u2019 function, we can cut out the decimals. Remember that the \u2018floor\u2019 function is way more complex than the \u2018round\u2019 function. Then, we are passing a for-loop to find the investment returns followed by some data manipulation tasks.<\/p>\n\n\n\n<p id=\"b392\">Finally, we are printing the total return we got by investing a hundred thousand into our trading strategy and it is revealed that we have made an approximate profit of fifty-seven thousand USD in one year. That\u2019s not bad! Now, let\u2019s compare our returns with SPY ETF (an ETF designed to track the S&amp;P 500 stock market index) returns.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ef26\">Step-9: SPY ETF Comparison<\/h2>\n\n\n\n<p id=\"476f\">This step is optional but it is highly recommended as we can get an idea of how well our trading strategy performs against a benchmark (SPY ETF). In this step, we are going to extract the data of the SPY ETF using the \u2018get_historical_data\u2019 function we created and compare the returns we get from the SPY ETF with our Williams %R trading strategy returns on Netflix.<\/p>\n\n\n\n<p id=\"a90e\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">def get_benchmark(start_date, investment_value):\n    spy = get_historical_data('SPY', start_date)['close']\n    benchmark = pd.DataFrame(np.diff(spy)).rename(columns = {0:'benchmark_returns'})\n    \n    investment_value = investment_value\n    benchmark_investment_ret = []\n    \n    for i in range(len(benchmark['benchmark_returns'])):\n        number_of_stocks = floor(investment_value\/spy[i])\n        returns = number_of_stocks*benchmark['benchmark_returns'][i]\n        benchmark_investment_ret.append(returns)\n\n    benchmark_investment_ret_df = pd.DataFrame(benchmark_investment_ret).rename(columns = {0:'investment_returns'})\n    return benchmark_investment_ret_df\n\nbenchmark = get_benchmark('2020-01-01', 100000)\n\ninvestment_value = 100000\ntotal_benchmark_investment_ret = round(sum(benchmark['investment_returns']), 2)\nbenchmark_profit_percentage = floor((total_benchmark_investment_ret\/investment_value)*100)\nprint(cl('Benchmark profit by investing $100k : {}'.format(total_benchmark_investment_ret), attrs = ['bold']))\nprint(cl('Benchmark Profit percentage : {}%'.format(benchmark_profit_percentage), attrs = ['bold']))\nprint(cl('W%R Strategy profit is {}% higher than the Benchmark Profit'.format(profit_percentage - benchmark_profit_percentage), attrs = ['bold']))<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"6a13\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>Benchmark profit by investing $100k : 22431.5<\/strong><br><strong>Benchmark Profit percentage : 22%<\/strong><br><strong>W%R Strategy profit is 35% higher than the Benchmark Profit<\/strong><\/pre>\n\n\n\n<p><strong>Code Explanation:<\/strong>&nbsp;The code used in this step is almost similar to the one used in the previous backtesting step but, instead of investing in Netflix, we are investing in SPY ETF by not implementing any trading strategies. From the output, we can see that our Williams %R trading strategy has outperformed the SPY ETF by 35%. That\u2019s great!<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a class=\"maxbutton-1 maxbutton maxbutton-subscribe-to-api external-css btn\" href=\"https:\/\/eodhd.com\/register\"><span class='mb-text'>Register &amp; Get Data<\/span><\/a><\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"0d3c\">Final Thoughts!<\/h1>\n\n\n\n<p>After a long process of crushing both theory and coding parts on Williams %R, we have successfully built a profitable trading strategy that exceeds the returns of SPY ETF. That\u2019s great but, that isn&#8217;t enough. When I ran a separate backtest process to gain more insights on the performance of our trading strategy, I came to know that our Williams %R-based strategy returns are less than that of the actual Netflix stock return. The foremost reason behind this might be strategy optimization.<\/p>\n\n\n\n<p>What is strategy optimization? It is the process of tuning a trading strategy to perform to its best. The best way to tune a strategy, especially a leading indicator trading strategy is to add another technical indicator as a filter. This filter acts as a gauge to ensure that the trading signals being revealed by the strategy are authentic but not false. This part should be considered essential while using Williams %R since this indicator is prone to revealing many false signals which ultimately ends up resulting in us making bad trades. Coming back to strategy optimization, it is not only about adding another technical indicator but also includes efficient risk management steps, and a better trading environment.<\/p>\n\n\n\n<p>If you manage to achieve these things, you will have a robust trading algorithm in your hand that is ready to make some better trades in the real-world market. So I highly recommend you to try these things out. You might question me on why I haven&#8217;t touched upon these topics in the article because the sole incentive of the article is not to encourage people to create profitable trading strategies and mint money from the market but to educate people about a powerful trading indicator. That\u2019s it! You\u2019ve reached the end of the article. Hope you learned something new and useful from this article.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>While having a look at the list of most popular momentum indicators that consists of the Relative Strength Index, and the Stochastic Oscillator, the one we are going to discuss today also joins the list when considering its usage and efficiency in the real world market. It\u2019s an indicator known as Williams %R. In this [&hellip;]<\/p>\n","protected":false},"author":18,"featured_media":2151,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[65,59,61],"tags":[],"coding-language":[30],"ready-to-go-solution":[56],"qualification":[31,32],"financial-apis-category":[36],"financial-apis-manuals":[39,38,40],"class_list":["post-2150","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-backtesting-strategies-examples","category-technical-analysis-examples","category-trading-indicators-implimentations","coding-language-python","ready-to-go-solution-eodhd-python-financial-library","qualification-experienced","qualification-guru","financial-apis-category-stock-market-prices","financial-apis-manuals-end-of-day","financial-apis-manuals-intraday","financial-apis-manuals-technical-indicators","has_thumb"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v21.9 (Yoast SEO v26.7) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Algorithmic Trading with Williams %R in Python: A Comprehensive Guide | EODHD APIs Academy<\/title>\n<meta name=\"description\" content=\"Learn about algorithmic trading with Williams %R indicator using Python. Explore the power of coding and automate your trading strategies.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Algorithmic Trading with Williams %R in\u00a0Python\" \/>\n<meta property=\"og:description\" content=\"Learn about algorithmic trading with Williams %R indicator using Python. Explore the power of coding and automate your trading strategies.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python\" \/>\n<meta property=\"og:site_name\" content=\"Financial Academy\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/eodhistoricaldata\" \/>\n<meta property=\"article:published_time\" content=\"2023-09-29T11:58:46+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-02-05T13:07:26+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-24.png\" \/>\n\t<meta property=\"og:image:width\" content=\"828\" \/>\n\t<meta property=\"og:image:height\" content=\"552\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Nikhil Adithyan\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@EOD_data\" \/>\n<meta name=\"twitter:site\" content=\"@EOD_data\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Nikhil Adithyan\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"15 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#article\",\"isPartOf\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python\"},\"author\":{\"name\":\"Nikhil Adithyan\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/67681e71050cf7d8d0efb91fee5f0402\"},\"headline\":\"Algorithmic Trading with Williams %R in\u00a0Python\",\"datePublished\":\"2023-09-29T11:58:46+00:00\",\"dateModified\":\"2025-02-05T13:07:26+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python\"},\"wordCount\":3181,\"publisher\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#organization\"},\"image\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#primaryimage\"},\"thumbnailUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-24.png\",\"articleSection\":[\"Backtesting Strategies Examples\",\"Technical Analysis Examples\",\"Trading Indicators Implimentations\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python\",\"name\":\"Algorithmic Trading with Williams %R in Python: A Comprehensive Guide | EODHD APIs Academy\",\"isPartOf\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#primaryimage\"},\"image\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#primaryimage\"},\"thumbnailUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-24.png\",\"datePublished\":\"2023-09-29T11:58:46+00:00\",\"dateModified\":\"2025-02-05T13:07:26+00:00\",\"description\":\"Learn about algorithmic trading with Williams %R indicator using Python. Explore the power of coding and automate your trading strategies.\",\"breadcrumb\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#primaryimage\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-24.png\",\"contentUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-24.png\",\"width\":828,\"height\":552,\"caption\":\"Algorithmic Trading with Williams %R in\u00a0Python\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/eodhd.com\/financial-academy\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Algorithmic Trading with Williams %R in\u00a0Python\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#website\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/\",\"name\":\"Financial APIs Academy | EODHD\",\"description\":\"Financial Stock Market Academy\",\"publisher\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/eodhd.com\/financial-academy\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#organization\",\"name\":\"EODHD (EOD Historical Data)\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/12\/EODHD-Logo.png\",\"contentUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/12\/EODHD-Logo.png\",\"width\":159,\"height\":82,\"caption\":\"EODHD (EOD Historical Data)\"},\"image\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/eodhistoricaldata\",\"https:\/\/x.com\/EOD_data\",\"https:\/\/www.reddit.com\/r\/EODHistoricalData\/\",\"https:\/\/eod-historical-data.medium.com\/\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/67681e71050cf7d8d0efb91fee5f0402\",\"name\":\"Nikhil Adithyan\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/eb53ce41bde412555cee22b8b4c09c2ff51625fff05ba3696b20cac7a7c0d938?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/eb53ce41bde412555cee22b8b4c09c2ff51625fff05ba3696b20cac7a7c0d938?s=96&d=mm&r=g\",\"caption\":\"Nikhil Adithyan\"},\"description\":\"Founder at BacktestZone | Streamlit Student Ambassador | FinTech &amp; Quantitative Finance enthusiast\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/author\/nikhiladithyan\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Algorithmic Trading with Williams %R in Python: A Comprehensive Guide | EODHD APIs Academy","description":"Learn about algorithmic trading with Williams %R indicator using Python. Explore the power of coding and automate your trading strategies.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python","og_locale":"en_US","og_type":"article","og_title":"Algorithmic Trading with Williams %R in\u00a0Python","og_description":"Learn about algorithmic trading with Williams %R indicator using Python. Explore the power of coding and automate your trading strategies.","og_url":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python","og_site_name":"Financial Academy","article_publisher":"https:\/\/www.facebook.com\/eodhistoricaldata","article_published_time":"2023-09-29T11:58:46+00:00","article_modified_time":"2025-02-05T13:07:26+00:00","og_image":[{"width":828,"height":552,"url":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-24.png","type":"image\/png"}],"author":"Nikhil Adithyan","twitter_card":"summary_large_image","twitter_creator":"@EOD_data","twitter_site":"@EOD_data","twitter_misc":{"Written by":"Nikhil Adithyan","Est. reading time":"15 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#article","isPartOf":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python"},"author":{"name":"Nikhil Adithyan","@id":"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/67681e71050cf7d8d0efb91fee5f0402"},"headline":"Algorithmic Trading with Williams %R in\u00a0Python","datePublished":"2023-09-29T11:58:46+00:00","dateModified":"2025-02-05T13:07:26+00:00","mainEntityOfPage":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python"},"wordCount":3181,"publisher":{"@id":"https:\/\/eodhd.com\/financial-academy\/#organization"},"image":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#primaryimage"},"thumbnailUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-24.png","articleSection":["Backtesting Strategies Examples","Technical Analysis Examples","Trading Indicators Implimentations"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python","url":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python","name":"Algorithmic Trading with Williams %R in Python: A Comprehensive Guide | EODHD APIs Academy","isPartOf":{"@id":"https:\/\/eodhd.com\/financial-academy\/#website"},"primaryImageOfPage":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#primaryimage"},"image":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#primaryimage"},"thumbnailUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-24.png","datePublished":"2023-09-29T11:58:46+00:00","dateModified":"2025-02-05T13:07:26+00:00","description":"Learn about algorithmic trading with Williams %R indicator using Python. Explore the power of coding and automate your trading strategies.","breadcrumb":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#primaryimage","url":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-24.png","contentUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-24.png","width":828,"height":552,"caption":"Algorithmic Trading with Williams %R in\u00a0Python"},{"@type":"BreadcrumbList","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/algorithmic-trading-with-williams-r-in-python#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/eodhd.com\/financial-academy\/"},{"@type":"ListItem","position":2,"name":"Algorithmic Trading with Williams %R in\u00a0Python"}]},{"@type":"WebSite","@id":"https:\/\/eodhd.com\/financial-academy\/#website","url":"https:\/\/eodhd.com\/financial-academy\/","name":"Financial APIs Academy | EODHD","description":"Financial Stock Market Academy","publisher":{"@id":"https:\/\/eodhd.com\/financial-academy\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/eodhd.com\/financial-academy\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/eodhd.com\/financial-academy\/#organization","name":"EODHD (EOD Historical Data)","url":"https:\/\/eodhd.com\/financial-academy\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/eodhd.com\/financial-academy\/#\/schema\/logo\/image\/","url":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/12\/EODHD-Logo.png","contentUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/12\/EODHD-Logo.png","width":159,"height":82,"caption":"EODHD (EOD Historical Data)"},"image":{"@id":"https:\/\/eodhd.com\/financial-academy\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/eodhistoricaldata","https:\/\/x.com\/EOD_data","https:\/\/www.reddit.com\/r\/EODHistoricalData\/","https:\/\/eod-historical-data.medium.com\/"]},{"@type":"Person","@id":"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/67681e71050cf7d8d0efb91fee5f0402","name":"Nikhil Adithyan","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/eb53ce41bde412555cee22b8b4c09c2ff51625fff05ba3696b20cac7a7c0d938?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/eb53ce41bde412555cee22b8b4c09c2ff51625fff05ba3696b20cac7a7c0d938?s=96&d=mm&r=g","caption":"Nikhil Adithyan"},"description":"Founder at BacktestZone | Streamlit Student Ambassador | FinTech &amp; Quantitative Finance enthusiast","url":"https:\/\/eodhd.com\/financial-academy\/author\/nikhiladithyan"}]}},"jetpack_featured_media_url":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-24.png","jetpack_shortlink":"https:\/\/wp.me\/pdOdVT-yG","jetpack_sharing_enabled":true,"acf":[],"_links":{"self":[{"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts\/2150","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/users\/18"}],"replies":[{"embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/comments?post=2150"}],"version-history":[{"count":10,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts\/2150\/revisions"}],"predecessor-version":[{"id":6275,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts\/2150\/revisions\/6275"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/media\/2151"}],"wp:attachment":[{"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/media?parent=2150"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/categories?post=2150"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/tags?post=2150"},{"taxonomy":"coding-language","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/coding-language?post=2150"},{"taxonomy":"ready-to-go-solution","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/ready-to-go-solution?post=2150"},{"taxonomy":"qualification","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/qualification?post=2150"},{"taxonomy":"financial-apis-category","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/financial-apis-category?post=2150"},{"taxonomy":"financial-apis-manuals","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/financial-apis-manuals?post=2150"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}