MtnMCG

Untitled

Aug 31st, 2024
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.83 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # Function to prompt for Robinhood credentials
  4. get_credentials() {
  5. read -p "Enter your Robinhood username: " username
  6. read -s -p "Enter your Robinhood password: " password
  7. echo
  8. }
  9.  
  10. # Create directory for the application
  11. APP_DIR="/opt/robinhood_spy"
  12. sudo mkdir -p "$APP_DIR"
  13. sudo chown $USER:$USER "$APP_DIR"
  14.  
  15. # Update and install required packages
  16. sudo apt update
  17. sudo apt install -y python3-pip python3-venv screen
  18.  
  19. # Create virtual environment and install dependencies
  20. python3 -m venv "$APP_DIR/venv"
  21. source "$APP_DIR/venv/bin/activate"
  22. pip install robin_stocks pandas matplotlib flask apscheduler
  23.  
  24. # Create the main Python script
  25. cat << 'EOF' > "$APP_DIR/robinhood_spy.py"
  26. import robin_stocks.robinhood as rh
  27. import pandas as pd
  28. import matplotlib.pyplot as plt
  29. from flask import Flask, render_template
  30. import io
  31. import base64
  32. from apscheduler.schedulers.background import BackgroundScheduler
  33. import os
  34. import json
  35.  
  36. app = Flask(__name__)
  37.  
  38. # Global variables to store data
  39. holdings = {}
  40. price_history = {}
  41.  
  42. def load_config():
  43. with open('config.json', 'r') as f:
  44. return json.load(f)
  45.  
  46. def update_data():
  47. global holdings, price_history
  48.  
  49. config = load_config()
  50.  
  51. # Login to Robinhood
  52. rh.login(username=config['username'], password=config['password'])
  53.  
  54. # Fetch account holdings
  55. holdings = rh.build_holdings()
  56.  
  57. # Fetch historical price data for each stock
  58. for symbol in holdings.keys():
  59. price_history[symbol] = rh.get_stock_historicals(symbol, interval='day', span='year')
  60.  
  61. # Logout after fetching data
  62. rh.logout()
  63.  
  64. def create_graph(symbol):
  65. data = price_history[symbol]
  66. df = pd.DataFrame(data)
  67. df['begins_at'] = pd.to_datetime(df['begins_at'])
  68. df['close_price'] = df['close_price'].astype(float)
  69.  
  70. plt.figure(figsize=(10, 5))
  71. plt.plot(df['begins_at'], df['close_price'])
  72. plt.title(f"{symbol} Price History")
  73. plt.xlabel("Date")
  74. plt.ylabel("Price")
  75.  
  76. img = io.BytesIO()
  77. plt.savefig(img, format='png')
  78. img.seek(0)
  79.  
  80. return base64.b64encode(img.getvalue()).decode()
  81.  
  82. @app.route('/')
  83. def home():
  84. total_value = sum(float(stock['equity']) for stock in holdings.values())
  85. total_cost = sum(float(stock['average_buy_price']) * float(stock['quantity']) for stock in holdings.values())
  86. total_gain = total_value - total_cost
  87.  
  88. graphs = {symbol: create_graph(symbol) for symbol in holdings.keys()}
  89.  
  90. return render_template('portfolio.html',
  91. holdings=holdings,
  92. total_value=total_value,
  93. total_gain=total_gain,
  94. graphs=graphs)
  95.  
  96. if __name__ == '__main__':
  97. # Schedule data updates every hour
  98. scheduler = BackgroundScheduler()
  99. scheduler.add_job(update_data, 'interval', hours=1)
  100. scheduler.start()
  101.  
  102. # Initial data update
  103. update_data()
  104.  
  105. # Run the Flask app
  106. app.run(host='0.0.0.0', port=5000)
  107. EOF
  108.  
  109. # Create the HTML template
  110. mkdir -p "$APP_DIR/templates"
  111. cat << 'EOF' > "$APP_DIR/templates/portfolio.html"
  112. <!DOCTYPE html>
  113. <html>
  114. <head>
  115. <title>My Robinhood Portfolio</title>
  116. <style>
  117. table {
  118. border-collapse: collapse;
  119. width: 100%;
  120. }
  121. th, td {
  122. border: 1px solid black;
  123. padding: 8px;
  124. text-align: left;
  125. }
  126. </style>
  127. </head>
  128. <body>
  129. <h1>My Robinhood Portfolio</h1>
  130. <h2>Total Portfolio Value: ${{ "%.2f"|format(total_value) }}</h2>
  131. <h2>Total Gain/Loss: ${{ "%.2f"|format(total_gain) }}</h2>
  132.  
  133. <table>
  134. <tr>
  135. <th>Symbol</th>
  136. <th>Quantity</th>
  137. <th>Average Buy Price</th>
  138. <th>Current Price</th>
  139. <th>Equity</th>
  140. <th>Percent Change</th>
  141. </tr>
  142. {% for symbol, data in holdings.items() %}
  143. <tr>
  144. <td>{{ symbol }}</td>
  145. <td>{{ data['quantity'] }}</td>
  146. <td>${{ data['average_buy_price'] }}</td>
  147. <td>${{ data['price'] }}</td>
  148. <td>${{ data['equity'] }}</td>
  149. <td>{{ data['percent_change'] }}%</td>
  150. </tr>
  151. {% endfor %}
  152. </table>
  153.  
  154. <h2>Price History Graphs</h2>
  155. {% for symbol, graph in graphs.items() %}
  156. <h3>{{ symbol }}</h3>
  157. <img src="data:image/png;base64,{{ graph }}" alt="{{ symbol }} graph">
  158. {% endfor %}
  159. </body>
  160. </html>
  161. EOF
  162.  
  163. # Get Robinhood credentials
  164. get_credentials
  165.  
  166. # Save credentials to config file
  167. cat << EOF > "$APP_DIR/config.json"
  168. {
  169. "username": "$username",
  170. "password": "$password"
  171. }
  172. EOF
  173.  
  174. # Create systemd service file
  175. cat << EOF | sudo tee /etc/systemd/system/robinhood_spy.service
  176. [Unit]
  177. Description=Robinhood Spy Service
  178. After=network.target
  179.  
  180. [Service]
  181. ExecStart=$APP_DIR/venv/bin/python $APP_DIR/robinhood_spy.py
  182. WorkingDirectory=$APP_DIR
  183. User=$USER
  184. Group=$USER
  185. Restart=always
  186.  
  187. [Install]
  188. WantedBy=multi-user.target
  189. EOF
  190.  
  191. # Enable and start the service
  192. sudo systemctl enable robinhood_spy
  193. sudo systemctl start robinhood_spy
  194.  
  195. # Create uninstall script
  196. cat << EOF > "$APP_DIR/uninstall.sh"
  197. #!/bin/bash
  198. sudo systemctl stop robinhood_spy
  199. sudo systemctl disable robinhood_spy
  200. sudo rm /etc/systemd/system/robinhood_spy.service
  201. sudo rm -rf $APP_DIR
  202. echo "Robinhood Spy has been uninstalled."
  203. EOF
  204.  
  205. chmod +x "$APP_DIR/uninstall.sh"
  206.  
  207. echo "Installation complete. The Robinhood Spy is now running as a service."
  208. echo "You can access the web interface at http://$(hostname -I | awk '{print $1}'):5000"
  209. echo "To view logs or manage the service, use:"
  210. echo " sudo journalctl -u robinhood_spy"
  211. echo " sudo systemctl stop robinhood_spy"
  212. echo " sudo systemctl start robinhood_spy"
  213. echo "To uninstall, run: $APP_DIR/uninstall.sh"
Add Comment
Please, Sign In to add comment