Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # Function to prompt for Robinhood credentials
- get_credentials() {
- read -p "Enter your Robinhood username: " username
- read -s -p "Enter your Robinhood password: " password
- echo
- }
- # Create directory for the application
- APP_DIR="/opt/robinhood_spy"
- sudo mkdir -p "$APP_DIR"
- sudo chown $USER:$USER "$APP_DIR"
- # Update and install required packages
- sudo apt update
- sudo apt install -y python3-pip python3-venv screen
- # Create virtual environment and install dependencies
- python3 -m venv "$APP_DIR/venv"
- source "$APP_DIR/venv/bin/activate"
- pip install robin_stocks pandas matplotlib flask apscheduler
- # Create the main Python script
- cat << 'EOF' > "$APP_DIR/robinhood_spy.py"
- import robin_stocks.robinhood as rh
- import pandas as pd
- import matplotlib.pyplot as plt
- from flask import Flask, render_template
- import io
- import base64
- from apscheduler.schedulers.background import BackgroundScheduler
- import os
- import json
- app = Flask(__name__)
- # Global variables to store data
- holdings = {}
- price_history = {}
- def load_config():
- with open('config.json', 'r') as f:
- return json.load(f)
- def update_data():
- global holdings, price_history
- config = load_config()
- # Login to Robinhood
- rh.login(username=config['username'], password=config['password'])
- # Fetch account holdings
- holdings = rh.build_holdings()
- # Fetch historical price data for each stock
- for symbol in holdings.keys():
- price_history[symbol] = rh.get_stock_historicals(symbol, interval='day', span='year')
- # Logout after fetching data
- rh.logout()
- def create_graph(symbol):
- data = price_history[symbol]
- df = pd.DataFrame(data)
- df['begins_at'] = pd.to_datetime(df['begins_at'])
- df['close_price'] = df['close_price'].astype(float)
- plt.figure(figsize=(10, 5))
- plt.plot(df['begins_at'], df['close_price'])
- plt.title(f"{symbol} Price History")
- plt.xlabel("Date")
- plt.ylabel("Price")
- img = io.BytesIO()
- plt.savefig(img, format='png')
- img.seek(0)
- return base64.b64encode(img.getvalue()).decode()
- @app.route('/')
- def home():
- total_value = sum(float(stock['equity']) for stock in holdings.values())
- total_cost = sum(float(stock['average_buy_price']) * float(stock['quantity']) for stock in holdings.values())
- total_gain = total_value - total_cost
- graphs = {symbol: create_graph(symbol) for symbol in holdings.keys()}
- return render_template('portfolio.html',
- holdings=holdings,
- total_value=total_value,
- total_gain=total_gain,
- graphs=graphs)
- if __name__ == '__main__':
- # Schedule data updates every hour
- scheduler = BackgroundScheduler()
- scheduler.add_job(update_data, 'interval', hours=1)
- scheduler.start()
- # Initial data update
- update_data()
- # Run the Flask app
- app.run(host='0.0.0.0', port=5000)
- EOF
- # Create the HTML template
- mkdir -p "$APP_DIR/templates"
- cat << 'EOF' > "$APP_DIR/templates/portfolio.html"
- <!DOCTYPE html>
- <html>
- <head>
- <title>My Robinhood Portfolio</title>
- <style>
- table {
- border-collapse: collapse;
- width: 100%;
- }
- th, td {
- border: 1px solid black;
- padding: 8px;
- text-align: left;
- }
- </style>
- </head>
- <body>
- <h1>My Robinhood Portfolio</h1>
- <h2>Total Portfolio Value: ${{ "%.2f"|format(total_value) }}</h2>
- <h2>Total Gain/Loss: ${{ "%.2f"|format(total_gain) }}</h2>
- <table>
- <tr>
- <th>Symbol</th>
- <th>Quantity</th>
- <th>Average Buy Price</th>
- <th>Current Price</th>
- <th>Equity</th>
- <th>Percent Change</th>
- </tr>
- {% for symbol, data in holdings.items() %}
- <tr>
- <td>{{ symbol }}</td>
- <td>{{ data['quantity'] }}</td>
- <td>${{ data['average_buy_price'] }}</td>
- <td>${{ data['price'] }}</td>
- <td>${{ data['equity'] }}</td>
- <td>{{ data['percent_change'] }}%</td>
- </tr>
- {% endfor %}
- </table>
- <h2>Price History Graphs</h2>
- {% for symbol, graph in graphs.items() %}
- <h3>{{ symbol }}</h3>
- <img src="data:image/png;base64,{{ graph }}" alt="{{ symbol }} graph">
- {% endfor %}
- </body>
- </html>
- EOF
- # Get Robinhood credentials
- get_credentials
- # Save credentials to config file
- cat << EOF > "$APP_DIR/config.json"
- {
- "username": "$username",
- "password": "$password"
- }
- EOF
- # Create systemd service file
- cat << EOF | sudo tee /etc/systemd/system/robinhood_spy.service
- [Unit]
- Description=Robinhood Spy Service
- After=network.target
- [Service]
- ExecStart=$APP_DIR/venv/bin/python $APP_DIR/robinhood_spy.py
- WorkingDirectory=$APP_DIR
- User=$USER
- Group=$USER
- Restart=always
- [Install]
- WantedBy=multi-user.target
- EOF
- # Enable and start the service
- sudo systemctl enable robinhood_spy
- sudo systemctl start robinhood_spy
- # Create uninstall script
- cat << EOF > "$APP_DIR/uninstall.sh"
- #!/bin/bash
- sudo systemctl stop robinhood_spy
- sudo systemctl disable robinhood_spy
- sudo rm /etc/systemd/system/robinhood_spy.service
- sudo rm -rf $APP_DIR
- echo "Robinhood Spy has been uninstalled."
- EOF
- chmod +x "$APP_DIR/uninstall.sh"
- echo "Installation complete. The Robinhood Spy is now running as a service."
- echo "You can access the web interface at http://$(hostname -I | awk '{print $1}'):5000"
- echo "To view logs or manage the service, use:"
- echo " sudo journalctl -u robinhood_spy"
- echo " sudo systemctl stop robinhood_spy"
- echo " sudo systemctl start robinhood_spy"
- echo "To uninstall, run: $APP_DIR/uninstall.sh"
Add Comment
Please, Sign In to add comment