{"name": "OldWang_Buy Updated with Munal.ipynb", "path": "OldWang_Buy Updated with Munal.ipynb", "last_modified": "2024-10-30T17:01:18.492247Z", "created": "2024-01-02T16:43:32.602088Z", "content": {"cells": [{"cell_type": "code", "execution_count": 1, "id": "dea6d4f3", "metadata": {"trusted": true}, "outputs": [{"name": "stdout", "output_type": "stream", "text": "Buying power before making trade: 14368.99\nTotal stock in pool: 62\nSelected stocks: 19\nASTE:\n  5-min price: $32.25\n  10-min price: $32.21\n  Previous close price: $31.55\n  Percentage change: 2.09%\nBURL:\n  5-min price: $257.69\n  10-min price: $257.67\n  Previous close price: $254.64\n  Percentage change: 1.32%\nCBU:\n  5-min price: $62.02\n  10-min price: $62.01\n  Previous close price: $60.68\n  Percentage change: 2.14%\nCEIX:\n  5-min price: $111.50\n  10-min price: $111.36\n  Previous close price: $110.47\n  Percentage change: 0.87%\nDAL:\n  5-min price: $58.77\n  10-min price: $58.74\n  Previous close price: $57.34\n  Percentage change: 2.49%\nEPC:\n  5-min price: $36.29\n  10-min price: $36.26\n  Previous close price: $35.44\n  Percentage change: 2.38%\nFWRD:\n  5-min price: $37.49\n  10-min price: $37.40\n  Previous close price: $36.99\n  Percentage change: 1.27%\nIBKR:\n  5-min price: $154.13\n  10-min price: $154.13\n  Previous close price: $152.91\n  Percentage change: 0.82%\nITW:\n  5-min price: $263.16\n  10-min price: $262.98\n  Previous close price: $255.96\n  Percentage change: 2.70%\nOGN:\n  5-min price: $18.05\n  10-min price: $18.04\n  Previous close price: $17.84\n  Percentage change: 1.16%\nPVH:\n  5-min price: $100.43\n  10-min price: $100.22\n  Previous close price: $98.87\n  Percentage change: 1.58%\nR:\n  5-min price: $148.65\n  10-min price: $148.58\n  Previous close price: $145.16\n  Percentage change: 2.69%\nROKU:\n  5-min price: $77.53\n  10-min price: $77.51\n  Previous close price: $76.40\n  Percentage change: 1.57%\nSNPS:\n  5-min price: $533.31\n  10-min price: $532.57\n  Previous close price: $529.21\n  Percentage change: 0.57%\nSRCL:\n  5-min price: $61.35\n  10-min price: $61.34\n  Previous close price: $61.04\n  Percentage change: 0.48%\nUMBF:\n  5-min price: $111.00\n  10-min price: $110.78\n  Previous close price: $106.70\n  Percentage change: 3.95%\nUNM:\n  5-min price: $64.19\n  10-min price: $64.15\n  Previous close price: $61.66\n  Percentage change: 4.09%\nWK:\n  5-min price: $80.58\n  10-min price: $80.57\n  Previous close price: $79.85\n  Percentage change: 0.71%\nYUMC:\n  5-min price: $44.78\n  10-min price: $44.78\n  Previous close price: $44.50\n  Percentage change: 0.56%\nToday's stock pick contains 18 stocks:\nMarket Optimism Factor: -0.14\nStock Pool Activity Coefficient: 0.24\nMultiplicative Factor: 42\nBuying power:\n3241\nAttempting to buy ASTE:\nFunds allocated: $180.1\nAttempting to buy BURL:\nFunds allocated: $180.1\nAttempting to buy CBU:\nFunds allocated: $180.1\nAttempting to buy DAL:\nFunds allocated: $180.1\nAttempting to buy EPC:\nFunds allocated: $180.1\nAttempting to buy FWRD:\nFunds allocated: $180.1\nAttempting to buy IBKR:\nFunds allocated: $180.1\nAttempting to buy ITW:\nFunds allocated: $180.1\nAttempting to buy OGN:\nFunds allocated: $180.1\nAttempting to buy PAG:\nFunds allocated: $180.1\nAttempting to buy PVH:\nFunds allocated: $180.1\nAttempting to buy R:\nFunds allocated: $180.1\nAttempting to buy ROKU:\nFunds allocated: $180.1\nAttempting to buy SRCL:\nFunds allocated: $180.1\nAttempting to buy UMBF:\nFunds allocated: $180.1\nAttempting to buy UNM:\nFunds allocated: $180.1\nAttempting to buy WK:\nFunds allocated: $180.1\nAttempting to buy YUMC:\nFunds allocated: $180.1\nBuying power after making trade: 11469.63\n"}], "source": "import robin_stocks.robinhood as rh\nimport pandas as pd\nimport requests\nfrom datetime import datetime\nimport yfinance as yf\nimport time \nimport math\nimport random\n\nusername ='liuweiwang0824@gmail.com'\npassword ='Umcqar45&M'\n\ndef login():\n    rh.login(username, password)\n\n\nlogin()\n\ndef open_market():\n    time_now = datetime.now().time()\n    market_open = datetime.time(9, 30, 0)\n    market_close = datetime.time(15, 59, 0)\n    return market_open < time_now < market_close\n\ndef get_cash():\n    rh.login(username, password)\n    rh_profile = rh.load_account_profile()\n    return float(rh_profile['portfolio_cash'])\nprint(f'Buying power before making trade: {get_cash()}')\n\ndef get_holdings_and_bought_price(stocks):\n    holdings = {stock: 0 for stock in stocks}\n    bought_price = {stock: 0 for stock in stocks}\n    rh_holdings = rh.account.build_holdings()\n    for stock in stocks:\n        holdings[stock] = int(float((rh_holdings.get(stock, {}).get('quantity', '0'))))\n        bought_price[stock] = float((rh_holdings.get(stock, {}).get('average_buy_price', '0')))\n    return holdings, bought_price\n\ntoday = datetime.today()\na, b, c = str(today.year), str(today.month), str(today.day)\n\nf1 = pd.read_csv(r'\\\\DESKTOP-RRDK2EH\\Server\\Users\\jizha\\Desktop\\seabridge_datapool1\\final_strategy_data_temporaly\\\\three_strategy_buy_point_' + a + '_' + b + '_' + c + '.csv')\n# \u79fb\u9664\u5e26\u6709\u70b9\uff08\".\"\uff09\u7684\u80a1\u7968\u4ee3\u7801\nticker_sum = f1['0'].tolist()\n\nticker_sum = [ticker for ticker in ticker_sum if \".\" not in ticker]\n#ticker_sum.remove('RTWG.L')\n#ticker_sum.remove('PPHC.L')\nprint(f\"Total stock in pool: {len(ticker_sum)}\")\n \n\ndef buy(stock, allowable_holdings):\n    rh.orders.order_buy_fractional_by_price(stock, allowable_holdings, timeInForce='gfd', extendedHours=False)\n \ndef get_yahoo_historical_prices_5min(stock):\n    data = yf.download(stock, interval='5m', period='2d', progress=False)\n    if len(data) < 3:  # Ensure we have enough data points\n        return None, None, None, None\n    current_price = data['Close'].iloc[-1]  # Last data point\n    price_5min = data['Close'].iloc[-2]  # Second last data point\n    price_10min = data['Close'].iloc[-3]  # Third last data point\n    \n    # Extracting the previous day's close\n    yesterday_data = data[data.index.date != data.index[-1].date()]\n    close_p = yesterday_data['Close'].iloc[-1] if not yesterday_data.empty else None\n\n    return current_price, price_5min, price_10min, close_p\ndef final_trade_stock_data(stocks):\n    final_data = {}\n    \n    for stock in stocks:\n        current_price, price_5min, price_10min, close_p = get_yahoo_historical_prices_5min(stock)\n        if current_price is None or price_5min is None or price_10min is None or close_p is None:\n            continue\n        \n        # Check if the stock meets the criteria\n        if price_5min > price_10min and current_price > close_p:\n            pct_change = ((current_price - close_p) / close_p) * 100\n            if 0 < pct_change <5:\n                final_data[stock] = {\n                    'current_price': current_price,\n                    'price_5min': price_5min,\n                    'price_10min': price_10min,\n                    'close_p': close_p,\n                    'pct_change': pct_change\n                }\n    \n    return final_data\n\n\nselected_stocks = final_trade_stock_data(ticker_sum)\n\nprint(f\"Selected stocks: {len(selected_stocks)}\")\nfor stock, data in selected_stocks.items():\n    print(f\"{stock}:\")\n    print(f\"  5-min price: ${data['price_5min']:.2f}\")\n    print(f\"  10-min price: ${data['price_10min']:.2f}\")\n    print(f\"  Previous close price: ${data['close_p']:.2f}\")\n    print(f\"  Percentage change: {data['pct_change']:.2f}%\")\n\n\ndef calculate_multiplicative_factor(change):\n#    \"\"\"\u6839\u636e\u5e02\u573a\u53d8\u5316\u8ba1\u7b97\u4e58\u6cd5\u56e0\u5b50\u3002\"\"\"\n    return 40 + 40 * abs(change) / 0.03\n    \ndef calculate_market_activity_coefficient(total_stocks, selected_stocks):\n    \"\"\"\u8ba1\u7b97\u5e02\u573a\u6d3b\u8dc3\u5ea6\u7cfb\u6570\"\"\"\n    ratio = selected_stocks / total_stocks\n    market_activity_coefficient = 0.6 / (1 + math.exp(-12 * (ratio - 0.5))) + 0.2\n    market_activity_coefficient=round(market_activity_coefficient,2)\n\n    return market_activity_coefficient\n \ndef calculate_total_buying_power(change, cash, total_stocks, selected_stocks):\n    market_activity_coefficient = calculate_market_activity_coefficient(total_stocks, selected_stocks)\n    print(f\"Stock Pool Activity Coefficient: {market_activity_coefficient}\")  # \u6253\u5370\u5e02\u573a\u6d3b\u8dc3\u7cfb\u6570\n\n    multiplicative_factor = calculate_multiplicative_factor(change)\n    multiplicative_factor=round(multiplicative_factor)\n    print(f\"Multiplicative Factor: {multiplicative_factor}\")  # \u6253\u5370\u4e58\u6cd5\u56e0\u5b50\n\n    adjustment_coefficient = 1 + change * multiplicative_factor\n    total_buying_power_adjusted = adjustment_coefficient * cash * market_activity_coefficient\n    total_buying_power_adjusted = max(0, total_buying_power_adjusted)\n    if total_buying_power_adjusted > cash:\n        total_buying_power_adjusted = cash\n    \n    return total_buying_power_adjusted\n\nstocks = final_trade_stock_data(ticker_sum)\nnum_of_stocks = len(stocks)\nprint(f\"Today's stock pick contains {num_of_stocks} stocks:\")\ndef get_stock_change(stock):\n    # \u4f7f\u7528yfinance\u83b7\u53d6\u80a1\u7968\u7684\u6700\u8fd1\u4e24\u5929\u7684\u6536\u76d8\u4ef7\u683c\n    data = yf.download(stock, period=\"2d\", progress=False)['Close']\n    if len(data) < 2:\n        return None, None\n    today_close, yesterday_close = data[-1], data[-2]\n    change_percentage = (today_close - yesterday_close) / yesterday_close * 100\n    return today_close, change_percentage\n\n# \u4fee\u6539\u6253\u5370\u80a1\u7968\u4fe1\u606f\u7684\u90e8\u5206\uff1a\nfor stock in stocks:\n    current_price, change_pct = get_stock_change(stock)\n    if current_price is None or change_pct is None:\n        print(f\"{stock}: Data not available\")\n        continue\n    #print(f\"{stock}: Current Price: ${current_price:.2f}, Change: {change_pct:.2f}%\")\n\nspy_current = yf.download(\"SPY\", period=\"1d\", progress=False)['Close'][-1]\nqqq_current = yf.download(\"QQQ\", period=\"1d\", progress=False)['Close'][-1]\nspy_previous_close = yf.download(\"SPY\", period=\"2d\", progress=False)['Close'][-2]\nqqq_previous_close = yf.download(\"QQQ\", period=\"2d\", progress=False)['Close'][-2]\nspy_change = (spy_current - spy_previous_close) / spy_previous_close\nqqq_change = (qqq_current - qqq_previous_close) / qqq_previous_close\naverage_change = (spy_change + qqq_change)  \n\n#print(f\"SPY Change: {spy_change*100:.2f}%\")\n#print(f\"QQQ Change: {qqq_change*100:.2f}%\")\nprint(f\"Market Optimism Factor: {average_change*100:.2f}\")  # \u6253\u5370SPY\u548cQQQ\u7684\u6da8\u8dcc\u767e\u5206\u6bd4\n\nstocks = final_trade_stock_data(ticker_sum)\n\nmyCash = get_cash()\ncash = calculate_total_buying_power(average_change, myCash, len(ticker_sum), len(stocks))\ncash = round(cash) - 1\nprint('Buying power:')\nprint(cash)\nif cash <= 0:\n    print(\"Insufficient buying power. No trades will be executed.\")\nelse:\n \n    trade_dict = {stock: 0 for stock in stocks}\n    price_dict = {stock: 0 for stock in stocks}\n    df_trades = pd.DataFrame(columns=stocks)\n    df_prices = pd.DataFrame(columns=stocks)\n\n    #prices = rh.stocks.get_latest_price(stocks)\n    holdings, bought_price = get_holdings_and_bought_price(stocks)\n    # Modify the check_purchase_successful function to check the holdings directly\n    def check_purchase_successful(stock):\n        holdings_after_purchase, _ = get_holdings_and_bought_price([stock])\n        return holdings_after_purchase[stock] > 0  # Check if we hold any of the stock\n\n    for stock in stocks:\n        allowable_holdings = round(cash / len(stocks), 1)\n        print(f\"Attempting to buy {stock}:\")\n        print(f\"Funds allocated: ${allowable_holdings}\")\n\n        # Place the market order\n        buy(stock, allowable_holdings)\n\n        # Pause for 3 seconds to allow the broker to process the order\n        time_to_sleep = random.uniform(5, 12)\n                                \n        time.sleep(time_to_sleep)\n\n        # Check if purchase was successful\n    #    attempts = 1\n    #    while not check_purchase_successful(stock) and attempts < 1:  # Limit to 2 attempts\n    #        print(f\"Purchase of {stock} failed. Retrying...\")\n    #        buy(stock, allowable_holdings)\n\n            # Pause for 3 seconds again\n    #        time.sleep(3)\n\n    #        attempts += 1\n\n     #   if attempts == 1:\n     #       print(f\"Failed to buy {stock} after 1 attempt.\")\n\n\n    #-----------#\n    time.sleep(time_to_sleep)\n\n    print(f'Buying power after making trade: {get_cash()}')\n\n\n#ToolBox\n#quantity = 11.11 # convert quantity to float once\n#s='A'   \n#rh.orders.order_sell_market(symbol=s, quantity=quantity, timeInForce='gfd')\n    "}, {"cell_type": "code", "execution_count": null, "id": "82fa9411", "metadata": {"trusted": true}, "outputs": [], "source": " import robin_stocks.robinhood as rh\nimport pandas as pd\nimport time\n\nusername = 'liuweiwang0824@gmail.com'\npassword = 'Umcqar45&M'\n\n# \u767b\u5f55\ndef login():\n    rh.login(username, password)\n\nlogin()\n\n# \u83b7\u53d6\u73b0\u91d1\u4f59\u989d\ndef get_cash():\n    rh_profile = rh.load_account_profile()\n    return float(rh_profile['portfolio_cash'])\n\n# \u4e70\u5165\u6307\u5b9a\u80a1\u7968\ndef buy(stock, allowable_holdings):\n    rh.orders.order_buy_fractional_by_price(stock, allowable_holdings, timeInForce='gfd', extendedHours=False)\n\n# \u8ba1\u7b97\u4e70\u5165\u6bcf\u53ea\u80a1\u7968\u7684\u91d1\u989d\ndef calculate_allowable_holdings(cash, stocks):\n    return round(cash / len(stocks), 2)\n\n# \u4e3b\u6d41\u7a0b\ndef main():\n    selected_stocks = ['BX', 'LOW', 'GRMN', 'AIG', 'AOS', 'WSM', 'LECO']\n    cash = get_cash()\n    allowable_cash = round(cash / 2, 2)  # \u4f7f\u7528\u8d2d\u4e70\u529b\u7684\u4e00\u534a\n    print(f'Buying power to be used: ${allowable_cash}')\n    \n    allowable_holdings = calculate_allowable_holdings(allowable_cash, selected_stocks)\n    print(f'Funds allocated per stock: ${allowable_holdings}')\n    \n    if allowable_holdings <= 0:\n        print(\"Insufficient buying power. No trades will be executed.\")\n        return\n    \n    for stock in selected_stocks:\n        print(f\"Attempting to buy {stock}:\")\n        buy(stock, allowable_holdings)\n        print(f\"Bought {stock} with ${allowable_holdings}\")\n        time.sleep(120)  # \u6bcf\u6b21\u4e70\u5165\u540e\u95f4\u96942\u5206\u949f\n    \n    print(f'Buying power after making trade: {get_cash()}')\n\nif __name__ == \"__main__\":\n    main()\n"}, {"cell_type": "code", "execution_count": null, "id": "26f2e861", "metadata": {"trusted": true}, "outputs": [], "source": "import robin_stocks.robinhood as rh\n\nusername = 'liuweiwang0824@gmail.com'\npassword = 'Umcqar45&M'\n\n# \u767b\u5f55\ndef login():\n    rh.login(username, password)\n\nlogin()\n\n# \u83b7\u53d6\u6307\u5b9a\u80a1\u7968\u7684\u6301\u4ed3\u6570\u91cf\ndef get_stock_holdings(stock):\n    rh_holdings = rh.account.build_holdings()\n    holdings = int(float(rh_holdings.get(stock, {}).get('quantity', '0')))\n    return holdings\n\n# \u4e3b\u6d41\u7a0b\ndef main(stock):\n    shares = get_stock_holdings(stock)\n    print(f'You hold {shares} shares of {stock}.')\n\nif __name__ == \"__main__\":\n    stock_to_check = 'BX'  # \u5728\u8fd9\u91cc\u66ff\u6362\u4e3a\u60a8\u60f3\u8981\u68c0\u67e5\u7684\u80a1\u7968\u4ee3\u7801\n    main(stock_to_check)\n"}, {"cell_type": "code", "execution_count": null, "id": "7f0cd31a", "metadata": {"trusted": true}, "outputs": [], "source": "import robin_stocks.robinhood as rh\nimport pandas as pd\nimport time\n\nusername = 'liuweiwang0824@gmail.com'\npassword = 'Umcqar45&M'\n\n# \u767b\u5f55\ndef login():\n    rh.login(username, password)\n\nlogin()\n\n# \u83b7\u53d6\u73b0\u91d1\u4f59\u989d\ndef get_cash():\n    rh_profile = rh.load_account_profile()\n    return float(rh_profile['portfolio_cash'])\n\n# \u4e70\u5165\u6307\u5b9a\u80a1\u7968\ndef buy(stock, allowable_holdings):\n    rh.orders.order_buy_fractional_by_price(stock, allowable_holdings, timeInForce='gfd', extendedHours=False)\n\n# \u83b7\u53d6\u6301\u4ed3\u548c\u4e70\u5165\u4ef7\u683c\ndef get_holdings_and_bought_price(stocks):\n    holdings = {stock: 0 for stock in stocks}\n    rh_holdings = rh.account.build_holdings()\n    for stock in stocks:\n        holdings[stock] = int(float(rh_holdings.get(stock, {}).get('quantity', '0')))\n    return holdings\n\n# \u8ba1\u7b97\u4e70\u5165\u6bcf\u53ea\u80a1\u7968\u7684\u91d1\u989d\ndef calculate_allowable_holdings(cash, stocks):\n    return round(cash / len(stocks), 2)\n\n# \u68c0\u67e5\u662f\u5426\u6210\u529f\u4e70\u5165\ndef check_purchase_successful(stock, initial_holdings):\n    current_holdings = get_holdings_and_bought_price([stock])\n    return current_holdings[stock] > initial_holdings[stock]\n\nticker = [\"APD\", \"GD\", \"MA\", \"MDLZ\", \"PG\", \"VRSN\"]\n# \u4e3b\u6d41\u7a0b\ndef main():\n    selected_stocks = tickers\n    cash = get_cash()\n    allowable_cash = round(cash / 1.5, 2)  # \u4f7f\u7528\u8d2d\u4e70\u529b\u7684\u4e00\u534a\n    print(f'Buying power to be used: ${allowable_cash}')\n    \n    allowable_holdings = calculate_allowable_holdings(allowable_cash, selected_stocks)\n    print(f'Funds allocated per stock: ${allowable_holdings}')\n    \n    if allowable_holdings <= 0:\n        print(\"Insufficient buying power. No trades will be executed.\")\n        return\n    \n    failed_purchases = []\n    for stock in selected_stocks:\n        print(f\"Attempting to buy {stock}:\")\n        initial_holdings = get_holdings_and_bought_price([stock])\n        success = False\n        for attempt in range(3):\n            buy(stock, allowable_holdings)\n            time.sleep(30)  # \u7b49\u5f8530\u79d2\u540e\u68c0\u67e5\u6301\u4ed3\n            if check_purchase_successful(stock, initial_holdings):\n                print(f\"Successfully bought {stock} with ${allowable_holdings} on attempt {attempt + 1}\")\n                success = True\n                break\n            else:\n                print(f\"Attempt {attempt + 1} to buy {stock} failed.\")\n        if not success:\n            failed_purchases.append(stock)\n            print(f\"Failed to buy {stock} after 3 attempts. Needs manual purchase.\")\n        time.sleep(90)  # \u6bcf\u6b21\u4e70\u5165\u540e\u95f4\u96942\u5206\u949f\uff08\u5305\u62ec30\u79d2\u68c0\u67e5\u65f6\u95f4\uff09\n    \n    print(f'Buying power after making trade: {get_cash()}')\n    if failed_purchases:\n        print(\"The following stocks need manual purchase:\")\n        for stock in failed_purchases:\n            print(stock)\n\nif __name__ == \"__main__\":\n    main()\n"}, {"cell_type": "code", "execution_count": null, "id": "7579bcea", "metadata": {"trusted": true}, "outputs": [], "source": "import robin_stocks.robinhood as rh\n\nusername = 'liuweiwang0824@gmail.com'\npassword = 'Umcqar45&M'\n\n# \u767b\u5f55\ndef login():\n    rh.login(username, password)\n\nlogin()\n\n# \u83b7\u53d6\u6307\u5b9a\u80a1\u7968\u7684\u6301\u4ed3\u6570\u91cf\ndef get_stock_holdings(stock):\n    rh_holdings = rh.account.build_holdings()\n    holdings = int(float(rh_holdings.get(stock, {}).get('quantity', '0')))\n    return holdings\n\n# \u4e3b\u6d41\u7a0b\ndef main(stock):\n    shares = get_stock_holdings(stock)\n    print(f'You hold {shares} shares of {stock}.')\n\nif __name__ == \"__main__\":\n    stock_to_check = 'AOS'  # \u5728\u8fd9\u91cc\u66ff\u6362\u4e3a\u60a8\u60f3\u8981\u68c0\u67e5\u7684\u80a1\u7968\u4ee3\u7801\n    main(stock_to_check)\n"}, {"cell_type": "code", "execution_count": null, "id": "71fd6081", "metadata": {"trusted": true}, "outputs": [], "source": ""}], "metadata": {"kernelspec": {"display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3"}, "language_info": {"codemirror_mode": {"name": "ipython", "version": 3}, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.9"}}, "nbformat": 4, "nbformat_minor": 5}, "format": "json", "mimetype": null, "size": 24028, "writable": true, "type": "notebook"}