Giter VIP home page Giter VIP logo

chatgpt_trading_bot's Introduction

ChatGPT_Trading_Bot

This is the code for the "ChatGPT Trading Bot" Video by Siraj Raval on Youtube

Overview

This is the code for this video on Youtube by Siraj Raval on building a ChatGPT trading bot. First, a disclaimer - Do NOT invest any money in any type of trading bot or algorithmic engine that you are not willing to lose. I gave this trading bot $2000 because I was willing to lose $2000 to make a great video for my AI Wizards out there. The entire codebase is contained in a single iPython notebook file, first published by the FinRL team as an example. Inside the notebook, 5 steps are performed.

  1. Pull 30 days of trading data for (Insert your stock or crypto) with Yahoo Finance Downloader API
  2. Create a simulated trading environment using real trading data with FinRL
  3. Train an neural network to predict that Stock Price using reinforcement learning inside this simulation with FinRL
  4. Once trained, backtest the predictions on the past 30 days data to compute potential returns with FinRL
  5. If the expectd returns are above a certain threshold, buy, else hold. If they're below a certain threshold, sell. (using Alpaca API)

In order to have this Colab run automatically once a day, we can deploy it to a hosting platform like Vercel with a seperate file that repeatedly executes it.

alt text

Dependencies

Setup Instructions

  1. Download the iPython notebook in this repository and upload it to Colab to try it out.
  2. Setup a simple flask app.
  3. To set up a cron job for a Flask app deployed on Vercel that executes a Google Colab notebook at a given link every hour, you can use the built-in Vercel cron feature. Here are the steps to follow:
  4. In your Flask app, import the necessary modules to run the Colab notebook, such as gdown or pyngrok
  5. Create a new endpoint in your Flask app that triggers the execution of the Colab notebook, using the link to the notebook file.
  6. Go to the Vercel project settings for your app and navigate to the "Cron" tab.
  7. Create a new cron job that runs every hour by adding the endpoint you created in step 2 to the "Cron Job" field and select the frequency you want to run the job.

Here is a sample code snippet for step 2:

from flask import Flask, jsonify
import gdown
app = Flask(__name__)

@app.route('/run-colab')
def run_colab():
    gdown.download('https://drive.google.com/file/d/<colab_notebook_id>', 'colab.ipynb', quiet=False)
    return jsonify(message='colab notebook ran successfully')

Credits & More Resources

Credits for the notebook go to the AI4FinanceFoundation, and for the API go to Alpaca.

chatgpt_trading_bot's People

Contributors

llsourcell avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chatgpt_trading_bot's Issues

just editing error

The link for Colab is broken, it has your github link prefixed to the link. Just fyi

How was NVDA purchased by the bot trained on data from DOW30?

In your tutorial and notebook, you have trained on DOW30 stocks and in your final purchase you have used NVDA (Nvidia) stock. NVDA stock is not even part of DOW30. How can the model even learn about NVDA performance without even training on the its historical data? Can you please explain this?

im getting scalar error at df_summary

If using all scalar values, you must pass an index

ValueError Traceback (most recent call last)
in <cell line: 1>()
----> 1 df_summary = ensemble_agent.run_ensemble_strategy(A2C_model_kwargs,
2 PPO_model_kwargs,
3 DDPG_model_kwargs,
4 timesteps_dict)

5 frames
/usr/local/lib/python3.10/dist-packages/pandas/core/internals/construction.py in _extract_index(data)
654
655 if not indexes and not raw_lengths:
--> 656 raise ValueError("If using all scalar values, you must pass an index")
657
658 elif have_series:

ValueError: If using all scalar values, you must pass an index

Error on get df_sumary

On execute this code:

df_summary = ensemble_agent.run_ensemble_strategy(A2C_model_kwargs,
                                                 PPO_model_kwargs,
                                                 DDPG_model_kwargs,
                                                 timesteps_dict)

I get this error:

============Start Ensemble Strategy============
============================================
turbulence_threshold:  234.1933647436273
======Model training from:  2013-01-01 to  2022-05-02
======A2C Training========
{'n_steps': 5, 'ent_coef': 0.005, 'learning_rate': 0.0007}
Using cuda device
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[34], line 1
----> 1 df_summary = ensemble_agent.run_ensemble_strategy(A2C_model_kwargs,
      2                                                  PPO_model_kwargs,
      3                                                  DDPG_model_kwargs,
      4                                                  timesteps_dict)

File [~/.local/lib/python3.10/site-packages/finrl/agents/stablebaselines3/models.py:469](https://file+.vscode-resource.vscode-cdn.net/home/pczin/Documents/projects/ChatGPT_Trading_Bot/~/.local/lib/python3.10/site-packages/finrl/agents/stablebaselines3/models.py:469), in DRLEnsembleAgent.run_ensemble_strategy(self, A2C_model_kwargs, PPO_model_kwargs, DDPG_model_kwargs, timesteps_dict)
    465 print("======A2C Training========")
    466 model_a2c = self.get_model(
    467     "a2c", self.train_env, policy="MlpPolicy", model_kwargs=A2C_model_kwargs
    468 )
--> 469 model_a2c = self.train_model(
    470     model_a2c,
    471     "a2c",
    472     tb_log_name=f"a2c_{i}",
    473     iter_num=i,
    474     total_timesteps=timesteps_dict["a2c"],
    475 )  # 100_000
    477 print(
    478     "======A2C Validation from: ",
    479     validation_start_date,
    480     "to ",
    481     validation_end_date,
...
---> 76         obs, self.reset_infos[env_idx] = self.envs[env_idx].reset(seed=self._seeds[env_idx])
     77         self._save_obs(env_idx, obs)
     78     # Seeds are only used once

TypeError: StockTradingEnv.reset() got an unexpected keyword argument 'seed'

Any solution?

I get this error during Implement DRL Algorithms

======DDPG Validation from: 2021-10-04 to 2022-01-03
======Best Model Retraining from: 2010-01-01 to 2022-01-03
======Trading from: 2022-01-03 to 2022-04-04

ValueError Traceback (most recent call last)
in <cell line: 1>()
----> 1 df_summary = ensemble_agent.run_ensemble_strategy(A2C_model_kwargs,
2 PPO_model_kwargs,
3 DDPG_model_kwargs,
4 timesteps_dict)

5 frames
/usr/local/lib/python3.10/site-packages/pandas/core/internals/construction.py in _extract_index(data)
643
644 if not indexes and not raw_lengths:
--> 645 raise ValueError("If using all scalar values, you must pass an index")
646
647 if have_series:

ValueError: If using all scalar values, you must pass an index

Not a loop

This program only places SPY and NVDA order once. I believe it needs in a loop, BUY when it qualifies if(DRLEnsembleAGent.Sharpe > .4) and sell (If ticket is bought) at 1% or more profit of BUY price. Else keep looping.

7.2 BackTestPlot - Error

AttributeError Traceback (most recent call last)
in <cell line: 6>()
4 # Dow Jones Index: ^DJI
5 # NASDAQ 100: ^NDX
----> 6 backtest_plot(df_account_value,
7 baseline_ticker = '^DJI',
8 baseline_start = df_account_value.loc[0,'date'],

5 frames
/usr/local/lib/python3.10/dist-packages/pyfolio/timeseries.py in gen_drawdown_table(returns, top)
1006 df_drawdowns.loc[i, 'Peak date'] = (peak.to_pydatetime()
1007 .strftime('%Y-%m-%d'))
-> 1008 df_drawdowns.loc[i, 'Valley date'] = (valley.to_pydatetime()
1009 .strftime('%Y-%m-%d'))
1010 if isinstance(recovery, float):

AttributeError: 'numpy.int64' object has no attribute 'to_pydatetime'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.