TypeError: ‘float’对象不可订阅,同时打印

huangapple go评论127阅读模式
英文:

TypeError: 'float' object is not subscriptable while printing

问题

  1. # 获取指定符号的当前余额
  2. symbols_to_check = ["USDT", "BNB", "BTC", "ETH"]
  3. balances = get_current_balances(symbols_to_check)
  4. print("当前余额:")
  5. for symbol in symbols_to_check:
  6. balance_info = balances.get(symbol, {"free": 0.0})
  7. print(f"{symbol}: 可用 - {balance_info['free']}")

出现以下错误:

  1. Traceback (most recent call last):
  2. File "main.py", line 83, in <module>
  3. print(f"{symbol}: 可用 - {balance_info['free']}")
  4. TypeError: 'float' object is not subscriptable

对于任何对代码结构感兴趣,以提供可能导致错误或更好的实现预测的提示的人,都欢迎,我对Python相当新,也不是最好的开发人员。

  1. <details>
  2. <summary>英文:</summary>

Get the current balances for the specified symbols

symbols_to_check = ["USDT", "BNB", "BTC", "ETH"]
balances = get_current_balances(symbols_to_check)
print("Current Balances:")
for symbol in symbols_to_check:
balance_info = balances.get(symbol, {"free": 0.0})
print(f"{symbol}: Free - {balance_info['free']}")

  1. Throws a following error:
  2. Traceback (most recent call last):
  3. File &quot;main.py&quot;, line 83, in &lt;module&gt;
  4. print(f&quot;{symbol}: Free - {balance_info[&#39;free&#39;]}&quot;)
  5. TypeError: &#39;float&#39; object is not subscriptable
  6. for anyone interested in the hole code structure to provide any tips that might lead to errors or better ideas to implement better predictions are welcome, i am pretty new to python and not the best developer overall.
  7. ```
  8. import pandas as pd
  9. import numpy as np
  10. import requests
  11. from binance.client import BinanceAPIException, Client
  12. from sklearn.model_selection import train_test_split
  13. from sklearn.preprocessing import MinMaxScaler
  14. import tensorflow as tf
  15. import schedule
  16. import time
  17. import itertools
  18. tf.config.list_physical_devices(&#39;GPU&#39;)
  19. # Define parameters
  20. api_key = &quot;YOUR_API_KEY&quot;
  21. api_secret = &quot;YOUR_SECRET_KEY&quot;
  22. base_url = &quot;https://api.binance.com&quot;
  23. symbols = [&quot;BTCUSDT&quot;, &quot;ETHUSDT&quot;, &quot;BNBUSDT&quot;]
  24. interval = &quot;1h&quot;
  25. limit = 1000
  26. paper_trading = False
  27. # Create a client object
  28. client = Client(api_key, api_secret)
  29. # Create an empty dictionary to store the profits and losses of each symbol
  30. profit_loss_dict = {}
  31. # Define a threshold for trading (can be adjusted)
  32. threshold = {&quot;BTCUSDT&quot;: 10, &quot;ETHUSDT&quot;: 8, &quot;BNBUSDT&quot;: 5}
  33. # Define the tickSize for each symbol
  34. tick_sizes = {&quot;BTCUSDT&quot;: 0.01, &quot;ETHUSDT&quot;: 0.01, &quot;BNBUSDT&quot;:0.1}
  35. # Define the minimum quantity for each symbol
  36. min_quantity = {&quot;BTCUSDT&quot;: 0.00036, &quot;ETHUSDT&quot;: 0.0059 , &quot;BNBUSDT&quot;: 0.045}
  37. # Define a flag to hold after a buy order is executed
  38. hold = False
  39. # Define a function to get the minimum quantity allowed for each symbol
  40. def get_min_quantity(symbol):
  41. return min_quantity.get(symbol, 0.01)
  42. # Modify the get_trimmed_price function to return a tuple (trimmed_price, min_qty)
  43. def get_trimmed_price(target_value, symbol):
  44. tick_size = tick_sizes.get(symbol, 0.01)
  45. trimmed_price = round(target_value / tick_size) * tick_size
  46. return trimmed_price, get_min_quantity(symbol)
  47. # Modify the get_current_balances function to return a dictionary with the actual balances
  48. def get_current_balances(symbols):
  49. try:
  50. # Use the Binance API to get the account information
  51. account_info = client.get_account()
  52. # Create an empty dictionary to store the balances for each symbol
  53. balances = {}
  54. # Find the balance for each specified symbol
  55. for symbol in symbols:
  56. # Find the balance for the specified symbol in the account_info list
  57. balance = next((item for item in account_info[&#39;balances&#39;] if item[&#39;asset&#39;] == symbol), None)
  58. # If the symbol is found, get the &#39;free&#39; value, otherwise set it to 0
  59. free_balance = float(balance[&#39;free&#39;]) if balance else 0.0
  60. balances[symbol] = free_balance
  61. return balances
  62. except Exception as e:
  63. print(f&quot;Error fetching balances: {e}&quot;)
  64. return {} # Return an empty dictionary if there is an error
  65. # Get the current balances for the specified symbols
  66. symbols_to_check = [&quot;USDT&quot;, &quot;BNB&quot;, &quot;BTC&quot;, &quot;ETH&quot;]
  67. balances = get_current_balances(symbols_to_check)
  68. print(&quot;Current Balances:&quot;)
  69. for symbol in symbols_to_check:
  70. balance_info = balances.get(symbol, {&quot;free&quot;: 0.0})
  71. print(f&quot;{symbol}: Free - {balance_info[&#39;free&#39;]}&quot;)
  72. # Define a function to get historical data for multiple symbols and save each one to a separate csv file
  73. def get_historical_data(symbols, interval, limit):
  74. # Create an empty list to store the dataframes
  75. dfs = []
  76. # Loop through the symbols
  77. for symbol in symbols:
  78. # Construct the url
  79. url = base_url + &quot;/api/v3/klines&quot;
  80. params = {&quot;symbol&quot;: symbol, &quot;interval&quot;: interval, &quot;limit&quot;: limit}
  81. # Send a get request and parse the response
  82. response = requests.get(url, params=params)
  83. data = response.json()
  84. # Convert the data to a dataframe
  85. df = pd.DataFrame(data, columns=[&quot;open_time&quot;, &quot;open&quot;, &quot;high&quot;, &quot;low&quot;, &quot;close&quot;, &quot;volume&quot;, &quot;close_time&quot;, &quot;quote_volume&quot;,&quot;trades&quot;, &quot;taker_base_volume&quot;, &quot;taker_quote_volume&quot;, &quot;ignore&quot;])
  86. # Convert the columns to numeric values
  87. df = df.apply(pd.to_numeric)
  88. # Convert the time columns to datetime format
  89. df[&quot;open_time&quot;] = pd.to_datetime(df[&quot;open_time&quot;], unit=&quot;ms&quot;)
  90. df[&quot;close_time&quot;] = pd.to_datetime(df[&quot;close_time&quot;], unit=&quot;ms&quot;)
  91. # Add a column for the symbol name
  92. df[&quot;symbol&quot;] = symbol
  93. # Add a column for the moving average
  94. df[&quot;moving_average&quot;] = np.nan
  95. # Append the dataframe to the list
  96. dfs.append(df)
  97. # Concatenate all the dataframes in the list
  98. df = pd.concat(dfs, ignore_index=True)
  99. # Save the dataframe to a csv file
  100. df.to_csv(f&quot;historical_data_{interval}.csv&quot;, index=False)
  101. # Return the dataframe
  102. return df
  103. # Define a function to fetch and update historical data
  104. def update_historical_data():
  105. global df # Use the global df variable
  106. # Get historical data for multiple symbols and save it to a csv file
  107. df = get_historical_data(symbols, interval, limit)
  108. # Schedule the update_historical_data function to run at the specified interval
  109. update_interval_hours = 1 # Set the update interval (in hours)
  110. schedule.every(update_interval_hours).hours.do(update_historical_data)
  111. # Define a function to get real-time data for one symbol
  112. def get_realtime_data(symbol):
  113. # Construct the url
  114. url = base_url + &quot;/api/v3/ticker/price&quot;
  115. params = {&quot;symbol&quot;: symbol}
  116. # Send a get request and parse the response
  117. response = requests.get(url, params=params)
  118. data = response.json()
  119. # Convert the data to a float value
  120. price = float(data[&quot;price&quot;])
  121. # Return the price
  122. return price
  123. # Check the shape of the dataframe and make sure it has enough rows (at least 250)
  124. # Create the MinMaxScaler in a global scope
  125. scaler = MinMaxScaler()
  126. # Define a function to create a neural network model for one symbol using historical data
  127. def create_model(df, symbol):
  128. global scaler # Use the global scaler variable
  129. # Filter the dataframe by the symbol name
  130. df_symbol = df[df[&quot;symbol&quot;] == symbol]
  131. # Select the features and the target
  132. X = df_symbol[[&quot;open&quot;, &quot;high&quot;, &quot;low&quot;, &quot;volume&quot;]].values
  133. y = df_symbol[&quot;close&quot;].values
  134. # Scale the features to a range of (0, 1)
  135. X = scaler.fit_transform(X)
  136. # Split the data into training and testing sets
  137. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  138. # Create a neural network model using Sequential
  139. model = tf.keras.Sequential([
  140. tf.keras.layers.Dense(64, activation=&#39;relu&#39;, input_shape=(X_train.shape[1],)),
  141. tf.keras.layers.Dense(32, activation=&#39;relu&#39;),
  142. tf.keras.layers.Dense(1) # Output layer, predicting the closing price
  143. ])
  144. # Compile the model
  145. model.compile(optimizer=&#39;adam&#39;, loss=&#39;mean_squared_error&#39;)
  146. # Train the model
  147. epochs = 50
  148. batch_size = 32
  149. model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2, verbose=0)
  150. # Evaluate the model
  151. loss = model.evaluate(X_test, y_test, verbose=0)
  152. print(f&quot;Model evaluation for {symbol}: Test loss: {loss}&quot;)
  153. # Return the model
  154. return model
  155. def update_model():
  156. global df, models, mean_reversion_models
  157. # Check if there is new data available (compare the number of rows with the previous number)
  158. if df is not None and df.shape[0] &gt;= 250: # Assuming 250 rows are needed to create a model
  159. # Loop through the symbols and update the models
  160. for symbol in symbols:
  161. if df[df[&quot;symbol&quot;] == symbol].shape[0] &gt;= 250:
  162. model = create_model(df, symbol)
  163. models[symbol] = model
  164. else:
  165. print(f&quot;Not enough data to update the model for {symbol}&quot;)
  166. else:
  167. print(&quot;Not enough data to update models.&quot;)
  168. # Schedule the update_model function to run every hour
  169. schedule.every(1).hour.do(update_model)
  170. risk_tolerance_percentage = 30 # Set your desired risk tolerance percentage here
  171. # Define a function to save the predicted prices with dates and times to a CSV file
  172. def save_predictions(predictions, symbols, datetimes):
  173. df = pd.DataFrame({&quot;symbol&quot;: symbols, &quot;predicted_price&quot;: predictions, &quot;datetime&quot;: datetimes})
  174. df.to_csv(&quot;predictions_main_py.csv&quot;, index=False)
  175. trade_status = {}
  176. # Create an empty dictionary to store the trimmed prices for each symbol
  177. trimmed_prices = {}
  178. def trade(model, symbol, paper_trading):
  179. global scaler, hold, tick_sizes, min_quantity, trimmed_prices, trade_status, balances
  180. # Get the current price
  181. current_price = get_realtime_data(symbol)
  182. # Add &#39;global balances&#39; statement to specify the global scope
  183. global balances
  184. if paper_trading:
  185. base_asset_balance = get_current_balances([&quot;USDT&quot;]).get(&quot;USDT&quot;, {}).get(&quot;free&quot;, 0.0)
  186. trading_asset_balance = 0.0 # Since we are paper trading, set the trading asset balance to 0
  187. else:
  188. balances = get_current_balances([symbol, &quot;USDT&quot;])
  189. base_asset_balance = balances.get(&quot;USDT&quot;, {}).get(&quot;free&quot;, 0.0)
  190. trading_asset_balance = balances.get(symbol, {}).get(&quot;free&quot;, 0.0)
  191. portfolio_value = base_asset_balance + trading_asset_balance * current_price
  192. # Trim the current price based on tickSize and store in the trimmed_prices dictionary
  193. trimmed_price, min_qty = get_trimmed_price((risk_tolerance_percentage / 100) * portfolio_value, symbol)
  194. trimmed_prices[symbol] = trimmed_price
  195. # Use the model to make predictions for the new data
  196. df_symbol = df[df[&quot;symbol&quot;] == symbol]
  197. X_last_row = df_symbol[[&quot;open&quot;, &quot;high&quot;, &quot;low&quot;, &quot;volume&quot;]].iloc[-1:].values
  198. X_last_row_scaled = scaler.transform(X_last_row)
  199. prediction = model.predict(X_last_row_scaled)[0][0]
  200. # Check if hold flag is True, and if yes, do not execute buy order
  201. if hold:
  202. _, trading_asset_balance = get_current_balances([symbol])[symbol][&quot;free&quot;]
  203. if trading_asset_balance &gt;= min_qty:
  204. print(f&quot;Holding {symbol} - waiting for sell order to be executed&quot;)
  205. else:
  206. print(f&quot;Holding {symbol} - Insufficient quantity to trade. Waiting for sell order to be executed.&quot;)
  207. return
  208. if trade_status.get(symbol) == &quot;BOUGHT&quot;:
  209. # If the trade status is &quot;BOUGHT&quot;, it means we already bought the asset and are waiting for a sell order.
  210. # Check if we have the minimum quantity to sell.
  211. _, trading_asset_balance = get_current_balances([symbol])[symbol][&quot;free&quot;]
  212. if trading_asset_balance &gt;= min_quantity[symbol]:
  213. print(f&quot;Holding {symbol} - Waiting for sell order to be executed.&quot;)
  214. else:
  215. print(f&quot;Holding {symbol} - Insufficient quantity to sell. Waiting for sell order to be executed.&quot;)
  216. else:
  217. if not paper_trading:
  218. # Calculate the trading quantity based on the position size and current price
  219. quantity = (risk_tolerance_percentage / 100) * portfolio_value / current_price
  220. # Round the quantity according to the tickSize for each symbol
  221. decimals = int(-np.log10(tick_sizes[symbol]))
  222. quantity = round(quantity, decimals)
  223. # Check the available balance for the trading asset
  224. _, trading_asset_balance = get_current_balances([symbol])[symbol][&quot;free&quot;]
  225. # Compare the quantity with the trading asset balance
  226. if quantity &gt; trading_asset_balance:
  227. # If the quantity exceeds the available balance, set it to the available balance
  228. quantity = trading_asset_balance
  229. # If the calculated quantity is less than the minimum quantity allowed, use the minimum allowed quantity
  230. if quantity &lt; min_quantity[symbol]:
  231. quantity = min_quantity[symbol]
  232. print(f&quot;Quantity is less than the minimum allowed for {symbol}. Using the minimum allowed quantity for the trade.&quot;)
  233. print(f&quot;Trading {symbol}:&quot;)
  234. print(f&quot; Quantity: {quantity}&quot;)
  235. print(f&quot; Tick Size: {tick_sizes[symbol]}&quot;)
  236. print(f&quot; Current Price: {current_price}&quot;)
  237. print(f&quot; Portfolio Value: {portfolio_value}&quot;)
  238. print(f&quot; Predicted Price for {symbol}: {prediction}, Current price: {current_price}&quot;)
  239. try:
  240. if prediction &lt; trimmed_prices[symbol]:
  241. # Place a market buy order using the client object
  242. order_buy = client.order_market_buy(symbol=symbol, quantity=quantity)
  243. print(order_buy)
  244. print(&quot;Market buy order executed.&quot;)
  245. # Set trade status to &quot;BOUGHT&quot; after executing the buy order
  246. trade_status[symbol] = &quot;BOUGHT&quot;
  247. # Set hold flag to True after executing the buy order to wait for the sell order
  248. hold = True
  249. else:
  250. print(f&quot;No Buy Signal for {symbol} at current price {current_price}&quot;)
  251. except BinanceAPIException as e:
  252. print(f&quot;Error: {e}&quot;)
  253. else:
  254. # Use the model to make predictions for the new data
  255. df_symbol = df[df[&quot;symbol&quot;] == symbol]
  256. X_last_row = df_symbol[[&quot;open&quot;, &quot;high&quot;, &quot;low&quot;, &quot;volume&quot;]].iloc[-1:].values
  257. X_last_row_scaled = scaler.transform(X_last_row)
  258. prediction = model.predict(X_last_row_scaled)[0][0]
  259. print(f&quot;Price prediction for {symbol}: {prediction}, Current price: {current_price}&quot;)
  260. # Add the SELL logic here
  261. if trade_status.get(symbol) == &quot;BOUGHT&quot; and prediction &gt; trimmed_prices[symbol]:
  262. try:
  263. # Place a market sell order using the client object
  264. order_sell = client.order_market_sell(symbol=symbol, quantity=min_quantity[symbol])
  265. print(order_sell)
  266. print(&quot;Market sell order executed.&quot;)
  267. # Reset trade status and hold flag after executing the sell order
  268. trade_status[symbol] = None
  269. hold = False
  270. except BinanceAPIException as e:
  271. print(f&quot;Error: {e}&quot;)
  272. # Define a function to save the profits and losses of trade dates for each symbol
  273. def save_profit_loss(profit_loss_dict):
  274. # Convert the dictionary to a dataframe
  275. df = pd.DataFrame.from_dict(profit_loss_dict, orient=&quot;index&quot;)
  276. # Add a column for the net profit or loss
  277. df[&quot;net&quot;] = df[&quot;profit&quot;] - df[&quot;loss&quot;]
  278. # Save the dataframe to a csv file
  279. df.to_csv(&quot;profit_loss.csv&quot;, index=True)
  280. # Return the dataframe
  281. return df
  282. # Initialize &quot;profit&quot; and &quot;loss&quot; keys in the profit_loss_dict for each symbol
  283. for symbol in symbols:
  284. profit_loss_dict[symbol] = {&quot;profit&quot;: 0, &quot;loss&quot;: 0}
  285. # Get the current balances for the specified symbols
  286. symbols_to_check = [&quot;USDT&quot;, &quot;BNB&quot;, &quot;BTC&quot;, &quot;ETH&quot;]
  287. balances = get_current_balances(symbols_to_check)
  288. print(&quot;Current Balances:&quot;)
  289. for symbol, balance_info in balances.items():
  290. print(f&quot;{symbol}: Free - {balance_info[&#39;free&#39;]}&quot;)
  291. # Call the update_historical_data function to initialize the df variable before creating the models and starting the trading loop
  292. update_historical_data()
  293. # Loop through the symbols and create a model for each one
  294. models = {}
  295. #mean_reversion_models = {} # Create a separate dictionary to store mean reversion models
  296. for symbol in symbols:
  297. # Create a neural network model using historical data
  298. if df.shape[0] &gt;= 250:
  299. model = create_model(df, symbol)
  300. models[symbol] = model
  301. else:
  302. print(f&quot;Not enough data to create a model for {symbol}&quot;)
  303. # Save the profit and loss to a csv file
  304. save_profit_loss(profit_loss_dict)
  305. print(df.shape)
  306. # The main trading loop
  307. while True:
  308. schedule.run_pending() # Check if the scheduled update_model function needs to run
  309. if df is not None: # Add this condition to avoid accessing shape of None
  310. # Get the current balances for the specified symbols
  311. balances = get_current_balances([&quot;USDT&quot;, &quot;BNB&quot;, &quot;BTC&quot;, &quot;ETH&quot;])
  312. print(&quot;Current Balances:&quot;)
  313. for symbol in symbols:
  314. trading_asset_balance = balances.get(symbol, 0.0)
  315. print(f&quot;{symbol}: Free - {trading_asset_balance}&quot;)
  316. for symbol in symbols:
  317. # Fetch the latest price data for the symbol
  318. current_price = get_realtime_data(symbol)
  319. # Fetch the portfolio value from the account for live or paper trading
  320. if paper_trading:
  321. base_asset_balance = balances.get(&quot;USDT&quot;, 0.0)
  322. trading_asset_balance = balances.get(symbol, 0.0)
  323. else:
  324. base_asset_balance = balances.get(&quot;USDT&quot;, 0.0)
  325. trading_asset_balance = balances.get(symbol, 0.0)
  326. # Calculate the portfolio value
  327. portfolio_value = base_asset_balance + trading_asset_balance * current_price
  328. # Calculate the quantity
  329. quantity = (risk_tolerance_percentage / 100) * portfolio_value / current_price
  330. # Round the quantity according to the tickSize for each symbol
  331. decimals = int(-np.log10(tick_sizes[symbol]))
  332. quantity = round(quantity, decimals)
  333. # Perform trading using updated models
  334. trade(models[symbol], symbol, paper_trading=False) # Set paper_trading=False for live trading
  335. # Delay between consecutive API requests to avoid rate limiting
  336. time.sleep(1)
  337. ```
  338. </details>
  339. # 答案1
  340. **得分**: -1
  341. ```python
  342. balance_info = balances.get(symbol, {"free": 0.0})
  343. print(f"{symbol}: Free - {balance_info['free']}")
  344. ```
  345. `balances`是一个字典,所以如果`symbol`在这个字典中,`balance_info`是这个符号下的余额**值**,因此在您当前的代码中是一个浮点数。在下一行中,您将`balance_info`视为字典,这会导致错误。您可能想要执行以下操作:
  346. ```python
  347. free_balance = float(balance['free']) if balance else 0.0
  348. balances[symbol] = {'free': free_balance} # 而不是 ... = free_balance
  349. ```
  350. 在您的获取当前余额函数中,这样在[symbol]键下实际上仍然有一个字典(而不是一个浮点数)。
  351. <details>
  352. <summary>英文:</summary>
  353. ```
  354. balance_info = balances.get(symbol, {&quot;free&quot;: 0.0})
  355. print(f&quot;{symbol}: Free - {balance_info[&#39;free&#39;]}&quot;)
  356. ```
  357. `balances` is a dictionary, so if `symbol` is inside this dictionary, `balance_info` is a **value** of the balance under this symbol, and thus in your current code - a float. In the next line you treat balance_info as a dictionary, which causes an error. You probably meant to do
  358. ```
  359. free_balance = float(balance[&#39;free&#39;]) if balance else 0.0
  360. balances[symbol] = {&#39;free&#39;: free_balance} # instead of ... = free_balance
  361. ```
  362. inside your get current balance function, so that under [symbol] key you actually still have a dictionary (rather than a float).
  363. </details>

huangapple
  • 本文由 发表于 2023年8月4日 07:38:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76832175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定