Skip to content

Instantly share code, notes, and snippets.

@crapher
Created February 16, 2020 19:31
Show Gist options
  • Save crapher/294a90394d78cb0948b33f2628a034c4 to your computer and use it in GitHub Desktop.
Save crapher/294a90394d78cb0948b33f2628a034c4 to your computer and use it in GitHub Desktop.
Simple Bot Framework
from yahoo_fin import stock_info as si
import time
# Settings
ticker = "MSFT" # Ticker to follow
portfolio_cash = 10000 # Starting cash
portfolio_stocks = 0 # Starting stocks
commisions = 0.005 # Commissions
# Function implemented
def what_should_i_do(stock_price):
# (0, 0): Hold Position
# (1, X): Buy X Stocks
# (-1, X): Sell X Stocks
return (0, 0)
stock_price = si.get_live_price(ticker) # Current price
while True:
operation = what_should_i_do(stock_price) # Bot result
if operation[0] == 1: # Buy
if operation[1] * stock_price > portfolio_cash: # Is there enough cash
print("@ ERR There is not enough cash (trying to buy %d stocks @ %.2f)" % (operation[1], stock_price))
else:
portfolio_stocks += operation[1]
portfolio_cash -= (operation[1] * stock_price * (1 + commisions))
print("- BUY (%d stocks @ %.2f): Cash %.2f - Stocks %d" % (operation[1], stock_price, portfolio_cash, portfolio_stocks))
elif operation[0] == -1: # Sell
if portfolio_stocks < operation[1]: # Are there enough stocks
print("@ ERR. There are not enough stocks (trying to sell %.2f stocks @ %d)" % (operation[1], stock_price))
else:
portfolio_stocks -= operation[1]
portfolio_cash += (operation[1] * stock_price * (1 - commisions))
print("- SELL (%d stocks @ %.2f): Cash %.2f - Stocks %d" % (operation[1], stock_price, portfolio_cash, portfolio_stocks))
else:
print("- HOLD: Cash %.2f - Stocks %d" % (portfolio_cash, portfolio_stocks))
time.sleep(1)
stock = si.get_live_price(ticker) # Current price
@tinserrano
Copy link

Hola Diego! una pequeña consulta sobre el what_should_i_do. La condicion para HOLD, BUY, SELL se coloca luego del "(0,0):" ? estoy aprendiendo python y no entiendo la nomenclatura de esta funcion. Gracias!

@crapher
Copy link
Author

crapher commented Feb 21, 2020

Hola Tin, el primer valor de la tupla es lo que indica Hold, Buy o Sell

  • (0,0) Significa Hold (el segundo 0 no se usa para nada, lo puse para mantener la tupla con el mismo tamaño).
  • (1,X) Significa Comprar X Stocks.
  • (-1,X) Significa Vender X Stocks.

Por ejemplo

  • Si queres comprar 20 stocks deberias retornar (1,20) donde 1 indica comprar y 20 indica la cantidad de stocks
  • Si queres vender 5 stocks deberias retornar (-1,5) donde -1 indica vender y 5 indica la cantidad de stocks
    Slds
    Diego

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