Power BI执行Python数据获取脚本时出现SyntaxError错误求助
问题:Power BI中Python脚本语法错误导致运行失败
我在Power BI中尝试运行一段用于从Yahoo Finance获取股票及加密货币历史数据的Python脚本,脚本内容如下:
import pandas as pd import time from datetime import datetime # Convert 'YYYY-MM-DD' to UNIX timestamp def date_to_unix(date_str): return int(time.mktime(time.strptime(date_str, "%Y-%m-%d"))) # Get the current date in 'YYYY-MM-DD' format current_date = datetime.now().strftime('%Y-%m-%d') # Define the start date for the data start_date = '2023-07-01' # Adjust this as needed period1 = date_to_unix(start_date) period2 = date_to_unix(current_date) # Read the CSV file to get the list of stock symbols and their types file_path = D:\Power BI\Market Dashboard\Source\trackers.csv' # Replace with the path to your CSV file symbols_df = pd.read_csv(file_path) trackers = symbols_df[['Symbol', 'Type']].to_dict(orient='records') # Initialize a list to hold all data data_frames = [] for tracker in trackers: symbol = tracker['Symbol'] type_of_asset = tracker['Type'] url = f'https://query1.finance.yahoo.com/v7/finance/download/{symbol}?period1={period1}&period2={period2}&interval=1d&events=history&includeAdjustedClose=true' try: # Fetch data from Yahoo Finance df = pd.read_csv(url) df['Symbol'] = symbol # Add a column for the stock symbol df['Type'] = type_of_asset # Add a column for the type (Stock or Crypto) data_frames.append(df) # Append the dataframe to the list print(f"Data for {symbol} downloaded successfully.") except Exception as e: print(f"Failed to download data for {symbol}: {e}") # Concatenate all dataframes into a single dataframe combined_data = pd.concat(data_frames, ignore_index=True) # Reorder columns for better readability combined_data = combined_data[['Symbol', 'Type', 'Date', 'Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume']] # Display the combined dataframe print(combined_data.head())
运行时触发语法错误,报错详情如下:
Details: "ADO.NET: Python script error. <pi> File "C:\Users\DELL\PythonScriptWrapper_f429c0b8-9848-4521-ac5f-5b633281c7f5\PythonScriptWrapper.PY", line 30 file_path = D:\Power BI\Market Dashboard\Source\trackers.csv' # Replace with the path to your CSV file ^ SyntaxError: invalid syntax
解决方案
问题出在脚本第30行的文件路径定义:字符串开头缺少单引号,导致Python无法识别这是合法的字符串值,触发语法错误。
你可以用以下三种方式修正该行:
- 补充开头的单引号,并转义路径中的反斜杠:
file_path = 'D:\\Power BI\\Market Dashboard\\Source\\trackers.csv' - 使用双引号包裹路径(同样需要转义反斜杠):
file_path = "D:\\Power BI\\Market Dashboard\\Source\\trackers.csv" - 使用原始字符串(在字符串前加
r,无需转义反斜杠):file_path = r'D:\Power BI\Market Dashboard\Source\trackers.csv'
修正后重新运行脚本即可解决该语法错误。
内容的提问来源于stack exchange,提问作者Ayaz
相关产品推荐
相关产品推荐

