Skip to content

Instantly share code, notes, and snippets.

@melvfnz
Last active February 22, 2023 01:34
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save melvfnz/e0ea10d3049b808da436edddf1225136 to your computer and use it in GitHub Desktop.
Save melvfnz/e0ea10d3049b808da436edddf1225136 to your computer and use it in GitHub Desktop.
buy_low_sell_high_trading_bot.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
get_ipython().system('python --version')
# In[2]:
import robin_stocks as r
import pandas as pd
from datetime import datetime
from config import *
import numpy as np
# In[3]:
r.login(rh_username,rh_password)
# In[4]:
my_stocks = r.build_holdings()
# In[5]:
df = pd.DataFrame(my_stocks)
# In[6]:
df
# In[7]:
df = df.T
df['ticker'] = df.index
df = df.reset_index(drop=True)
# In[8]:
df.to_csv('stocks.csv')
# In[9]:
cols = df.columns.drop(['id','type','name','pe_ratio','ticker'])
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# In[10]:
df.dtypes
# In[11]:
df_buy = df[(df['average_buy_price'] <= 25.000) & (df['quantity'] == 1.000000) & (df['percent_change'] <= -.50)]
df_sell = df[(df['quantity'] == 5.000000) & (df['percent_change'] >= .50)]
# In[12]:
df_buy
# In[13]:
df_sell
# In[14]:
tkr_buy_list = df_buy['ticker'].tolist()
# In[15]:
tkr_sell_list = df_sell['ticker'].tolist()
# In[16]:
print(f"{len(r.orders.get_all_open_orders())} open order")
# In[17]:
r.orders.cancel_all_open_orders()
# In[18]:
if len(tkr_sell_list) > 0:
for i in tkr_sell_list:
print(i)
print(r.orders.order_sell_market(i,4,timeInForce= 'gfd'))
else:
print('Nothing to sell right now!')
# In[19]:
if len(tkr_buy_list) > 0:
for i in tkr_buy_list:
test = r.orders.order_buy_market(i,4,timeInForce= 'gfd')
print(i)
print(test)
print(type(test))
else:
print('Nothing to buy right now!')
# In[ ]:
r.get_crypto_currency_pairs()
# In[ ]:
r.stocks.get_earnings('TSLA',info='report')
# In[ ]:
@LightAutumnMelancholy
Copy link

This serves as a nice example on how to get started. I've been thinking about taking a serialized data source, such as a stock prices from something like json, and trying out some different models to handle trades. If I simulate trading, I can see what I would have made or lost.

In short, you have sparked my creativity with your example, it was a good article.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment