From 4a0af59d54168f6297ab988f74f98d13dada856f Mon Sep 17 00:00:00 2001
From: Ajmal Sarwary <68126622+AjmalSarwary@users.noreply.github.com>
Date: Wed, 5 Apr 2023 14:33:52 +0200
Subject: [PATCH] Part 1 created in Colab
---
brent_predictor.ipynb | 816 ++++++++++++++++++++++++++++++++++++++++++
1 file changed, 816 insertions(+)
create mode 100644 brent_predictor.ipynb
diff --git a/brent_predictor.ipynb b/brent_predictor.ipynb
new file mode 100644
index 0000000..37d14da
--- /dev/null
+++ b/brent_predictor.ipynb
@@ -0,0 +1,816 @@
+{
+ "nbformat": 4,
+ "nbformat_minor": 0,
+ "metadata": {
+ "colab": {
+ "provenance": [],
+ "authorship_tag": "ABX9TyN71igwPAy2MDioDzo5fpta",
+ "include_colab_link": true
+ },
+ "kernelspec": {
+ "name": "python3",
+ "display_name": "Python 3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "view-in-github",
+ "colab_type": "text"
+ },
+ "source": [
+ ""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "from google.colab import drive\n",
+ "drive.mount('/content/drive')"
+ ],
+ "metadata": {
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ },
+ "id": "6kDDYN6n7q5q",
+ "outputId": "31d91381-08c7-4b1b-b826-b20590e05774"
+ },
+ "execution_count": null,
+ "outputs": [
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n"
+ ]
+ }
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "import sys\n",
+ "sys.path.append('/content/drive/MyDrive/my_packages')\n",
+ "import api_alphavantage as av"
+ ],
+ "metadata": {
+ "id": "l-VV33HX_7zw"
+ },
+ "execution_count": null,
+ "outputs": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "UyqYP65d0og3"
+ },
+ "outputs": [],
+ "source": [
+ "import requests\n",
+ "import json\n",
+ "import pandas as pd\n",
+ "\n",
+ "def alphavantage_get( symbol,dfrom, dto,interval,api_key):\n",
+ " \n",
+ " '''retrieves time series of prices for function in range dfrom to dto at interval with api_key'''\n",
+ " \n",
+ " interval = interval\n",
+ " dfrom=dfrom\n",
+ " dto=dto\n",
+ " api_key=api_key\n",
+ " \n",
+ " url = f'https://www.alphavantage.co/query?function={symbol}&interval={interval}&apikey={api_key}&outputsize=full'\n",
+ " \n",
+ " r = requests.get(url)\n",
+ " data = r.json()\n",
+ " \n",
+ " df = pd.DataFrame(data)\n",
+ " \n",
+ " df['date'] = df['data'].apply(lambda x: x['date'])\n",
+ " df['value'] = df['data'].apply(lambda x: x['value'])\n",
+ "\n",
+ " df.drop('data', axis=1, inplace=True)\n",
+ " df['date'] = pd.to_datetime(df['date'])\n",
+ " df.set_index('date', inplace=True)\n",
+ "\n",
+ " # filter data to specified time period\n",
+ " df = df[(df.index >= dfrom) & (df.index <= dto)]\n",
+ "\n",
+ " #error message suggested that there is a string '.' ; ->locate and remove string\n",
+ " df = df[df['value'] != '.']\n",
+ " \n",
+ " df.value = df['value'].astype(float)\n",
+ " \n",
+ " return df\n",
+ " \n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "def moving_avs(dataframe):\n",
+ " \n",
+ " df=dataframe\n",
+ " \n",
+ " # make sure type is correct\n",
+ " df['value'] = df.value.astype(float)\n",
+ " \n",
+ " # calculate weekly moving average\n",
+ " weekly_ma = df['value'].rolling('7D').mean()\n",
+ " df['weekly_ma'] = weekly_ma\n",
+ "\n",
+ " # calculate quaterly moving average\n",
+ " yearly_ma = df['value'].rolling('365D').mean()\n",
+ " df['yearly_ma'] = yearly_ma\n",
+ " \n",
+ " return df"
+ ],
+ "metadata": {
+ "id": "R03eX0NTB65e"
+ },
+ "execution_count": null,
+ "outputs": []
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "#plot dataframe\n",
+ "import plotly.express as px\n",
+ "import plotly.graph_objs as go\n",
+ "import pandas as pd\n",
+ "\n",
+ "\n",
+ "def plotter(dataframe,symbol, moving=0,amount='', footnote=''):\n",
+ " \n",
+ " df=dataframe\n",
+ " \n",
+ " # plot the data\n",
+ " \n",
+ " \n",
+ " \n",
+ " if moving == 1:\n",
+ "\n",
+ " # create a new DataFrame with the moving averages\n",
+ "\n",
+ " df_ma = pd.concat([df['value'], df.weekly_ma, df.yearly_ma], axis=1)\n",
+ "\n",
+ " # Create the plot\n",
+ " fig = go.Figure()\n",
+ " fig.add_trace(go.Scatter(x=df_ma.index, y=df_ma['weekly_ma'], name='Weekly Moving Average', opacity=0.3))\n",
+ " fig.add_trace(go.Scatter(x=df_ma.index, y=df_ma['yearly_ma'], name='Yearly Moving Average'))\n",
+ "\n",
+ " # title and axis labels\n",
+ " fig.update_layout(title=symbol, xaxis_title='Date', yaxis_title=f'in {amount} (USD)', \n",
+ " legend_title='Moving Average', plot_bgcolor=' #cce6ff',paper_bgcolor=' #e6f2ff')\n",
+ "\n",
+ " # footnote\n",
+ " fig.add_annotation(xref='paper', yref='paper', x=-0.1, y=-0.17, text=footnote, showarrow=False, font=dict(\n",
+ " family='Arial',\n",
+ " size=9,\n",
+ " \n",
+ " ))\n",
+ "\n",
+ " \n",
+ " fig.show()\n",
+ " \n",
+ " else: \n",
+ "\n",
+ " fig = go.Figure() \n",
+ " fig.add_trace(go.Scatter(x=dataframe.index, y=dataframe.value, name='Global GDP'))\n",
+ " fig.update_layout(title=symbol, xaxis_title='Date', yaxis_title=f'in {amount} (USD)', \n",
+ " legend_title='symbol', plot_bgcolor=' #cce6ff',paper_bgcolor=' #e6f2ff')\n",
+ " fig.add_annotation(xref='paper', yref='paper', x=-0.1, y=-0.17, text=footnote, showarrow=False, font=dict(\n",
+ " family='Arial',\n",
+ " size=9,\n",
+ " \n",
+ " ))\n",
+ " fig.show()\n"
+ ],
+ "metadata": {
+ "id": "FBM5IVlG4rCI"
+ },
+ "execution_count": null,
+ "outputs": []
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "#alphavantage_get entries\n",
+ "#call alphavantage_get(symbol,dfrom,dto, intervel, api_key)\n",
+ "\n",
+ "#api key\n",
+ "api_key = av\n",
+ "\n",
+ "#symbol\n",
+ "symbols=['BRENT','ALL_COMMODITIES']\n",
+ "\n",
+ "# daily interval\n",
+ "interval = 'daily' \n",
+ "\n",
+ "#time period\n",
+ "start_date = '2005-01-01'\n",
+ "end_date = '2015-12-31'\n"
+ ],
+ "metadata": {
+ "id": "FZauzajf0xh6"
+ },
+ "execution_count": null,
+ "outputs": []
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "# get all_commodidities from alphavantage\n",
+ "comod = alphavantage_get(symbols[1], start_date, end_date, interval, api_key)\n",
+ "comod = moving_avs(comod)\n",
+ "amount=''\n",
+ "footnote='Source: International Monetary Fund (IMF Terms of Use), Global Price Index of All Commodities, retrieved from FRED, Federal Reserve Bank of St. Louiss; data accessed through AlphaVantage API.'\n",
+ "plotter(comod,'GLOBAL COMMODITIES',1,amount,footnote)\n"
+ ],
+ "metadata": {
+ "colab": {
+ "base_uri": "https://localhost:8080/",
+ "height": 542
+ },
+ "id": "YxTxPgmR4u35",
+ "outputId": "cbd6e1b1-57c8-46e8-8567-277dd3ff90b4"
+ },
+ "execution_count": null,
+ "outputs": [
+ {
+ "output_type": "display_data",
+ "data": {
+ "text/html": [
+ "\n",
+ "
\n", + " | value | \n", + "
---|---|
date | \n", + "\n", + " |
2005 | \n", + "48.136604 | \n", + "