(11)Python引领金融前沿:投资组合优化实战案例

1. 前言

本篇文章为 Python 对金融的投资组合优化的示例。投资组合优化是从一组可用的投资组合中选择最佳投资组合的过程,目的是最大限度地提高回报和降低风险。

投资组合优化是从一组可用的投资组合中选择最佳投资组合的过程,目的是最大限度地提高回报和降低风险。

本案例研究涵盖了我们在前几课中介绍的许多 Python 编程基础知识,例如获取真实世界的市场财务数据、使用 pandas 执行数据分析以及使用 Matplotlib、Seaborn 和 Plotly Express 可视化投资组合数据。

2. 导入库和数据集

在本课中,您将学习如何导入库(例如用于数值分析的 NumPy),并学习如何导入和使用 datetime。此外,您还将学习如何导入数据以执行库提供的一些操作。

在开始之前,我们需要定义以下术语

  • 打开:股票市场开盘时证券首次交易的价格。

  • :给定股票在常规交易时段内交易的最高价格。

  • :给定股票在常规交易时段内交易的最低价格。

  • 关闭:给定股票在常规交易时段交易的最后价格。

  • :开盘和收盘之间的交易股票数量。

  • 调整关闭:考虑股票分割和股息后调整后的股票收盘价。

另请注意,纽约证券交易所 (NYSE) 于美国东部时间上午 9:30 开市,上海证券交易所 (SSE) 于中国标准时间上午 9:30 开市。

# Import key librares and modules 
import pandas as pd
import numpy as np# Import datetime module that comes pre-installed in Python 
# datetime offers classes that work with date & time information
import datetime as dt# Use Pandas to read stock data (the csv file is included in the course package) 
stock_df = pd.read_csv('Amazon.csv')
stock_df.head(15)# Count the number of missing values in "stock_df" Pandas DataFrame
stock_df.isnull().sum()# Obtain information about the Pandas DataFrame such as data types, memory utilization..etc
stock_df.info()

3. 计算每日回报率

在这里插入图片描述

在这里插入图片描述

# Calculate the percentage daily return
stock_df['Daily Return'] = stock_df['Adj Close'].pct_change(1) * 100
stock_df

输出:
在这里插入图片描述

# Let's replace the first row with zeros instead of NaN
stock_df['Daily Return'].replace(np.nan, 0, inplace = True)
stock_df

在这里插入图片描述

# Use the describe() method to obtain a statistical summary about the data 
# Over the specified time period, the average adjusted close price for Amazon stock was $120.07 
# The maximum adjusted close price was $186.57
# The maximum volume of shares traded on one day were 311,346,000
stock_df.describe().round(2)

在这里插入图片描述

4. 为单只股票进行数据可视化:第一部分

在这里插入图片描述

Matplotlib 官方文档: https://matplotlib.org/
Seaborn 官方文档: https://seaborn.pydata.org/
Plotly 官方文档: https://plotly.com/python/

在这里插入图片描述

# Matplotlib is a comprehensive data visualization library in Python 
# Seaborn is a visualization library that sits on top of matplotlib and offers enhanced features 
# plotly.express module contains functions that can create interactive figures using a few lines of codeimport matplotlib.pyplot as plt!pip install seaborn
import seaborn as snsimport plotly.express as px# Plot a Line Plot Using Plotly Express
fig = px.line(title = 'Amazon.com, Inc. (AMZN) Adjusted Closing Price [$]')
fig.add_scatter(x = stock_df['Date'], y = stock_df['Adj Close'], name = 'Adj Close')stock_df# Define a function that performs interactive data visualization using Plotly Express
def plot_financial_data(df, title):fig = px.line(title = title)# For loop that plots all stock prices in the pandas dataframe df# Note that index starts with 1 because we want to skip the date columnfor i in df.columns[1:]:fig.add_scatter(x = df['Date'], y = df[i], name = i)fig.update_traces(line_width = 5)fig.update_layout({'plot_bgcolor': "white"})fig.show()# Plot High, Low, Open, Close and Adj Close
plot_financial_data(stock_df.drop(['Volume', 'Daily Return'], axis = 1), 'Amazon.com, Inc. (AMZN) Stock Price [$]')# Plot trading volume
plot_financial_data(stock_df.iloc[:,[0,5]], 'Amazon.com, Inc. (AMZN) Trading Volume')# Plot % Daily Returns
plot_financial_data(stock_df.iloc[:,[0,7]], 'Amazon.com, Inc. (AMZN) Percentage Daily Return [%]')

5. 为单只股票进行数据可视化:第二部分

# Define a function that classifies the returns based on the magnitude
# Feel free to change these numbers
def percentage_return_classifier(percentage_return):if percentage_return > -0.3 and percentage_return <= 0.3:return 'Insignificant Change'elif percentage_return > 0.3 and percentage_return <= 3:return 'Positive Change'elif percentage_return > -3 and percentage_return <= -0.3:return 'Negative Change'elif percentage_return > 3 and percentage_return <= 7:return 'Large Positive Change'elif percentage_return > -7 and percentage_return <= -3:return 'Large Negative Change'elif percentage_return > 7:return 'Bull Run'elif percentage_return <= -7:return 'Bear Sell Off'# Apply the function to the "Daily Return" Column and place the result in "Trend" column
stock_df['Trend'] = stock_df['Daily Return'].apply(percentage_return_classifier)
stock_df# Count distinct values in the Trend column
trend_summary = stock_df['Trend'].value_counts()
trend_summary# Plot a pie chart using Matplotlib Library
plt.figure(figsize = (8, 8))
trend_summary.plot(kind = 'pie', y = 'Trend');# Plot a pie chart using Matplotlib Library
plt.figure(figsize = (8, 8))
trend_summary.plot(kind = 'pie', y = 'Trend');

6. 为单只股票进行数据可视化:第三部分

在这里插入图片描述

# Let's plot a candlestick graph using Cufflinks library
# Cufflinks is a powerful Python library that connects Pandas and Plotly for generating plots using few lines of code
# Cufflinks allows for interactive data visualization
! pip install cufflinks
import cufflinks as cf
cf.go_offline() # Enabling offline mode for interactive data visualization locallystock_df# Set the date to be the index for the Pandas DataFrame
# This is critical to show the date on the x-axis when using cufflinks
stock_df.set_index(['Date'], inplace = True)
stock_df# Plot Candlestick figure using Cufflinks QuantFig module
figure = cf.QuantFig(stock_df, title = 'Amazon.com, Inc. (AMZN) Candlestick Chart', name = 'AMZN')
figure.add_sma(periods =[14, 21], column = 'Close', color = ['magenta', 'green'])
figure.iplot(theme = 'white', up_color = 'green', down_color = 'red')

7. 为多只股票进行数据可视化

# Let's read multiple stocks data contained in "stock_prices.csv" attached in the course package 
# The Appendix includes details on how to obtain this data using yfinance and Pandas Datareader 
# Note that yfinance and Pandas Datareader might experience outage in some geographical regions# We will focus our analysis on U.S. stocks, similar analysis could be performed on Asian, European or African stocks  
# AMZN: Amazon Inc. - Multinational tech company focusing on e-commerce, cloud computing, and artificial intelligence
# JPM: JPMorgan Chase and Co. - Multinational investment bank and financial services holding company
# META: Meta Platforms, formerly named Facebook Inc. - META owns Facebook, Instagram, and WhatsApp
# PG: Procter and Gamble (P&G) - Multinational consumer goods corporation
# GOOG: Google (Alphabet Inc.) - Multinational company that focuses on search engine tech, e-commerce, Cloud and AI 
# CAT: Caterpillar - World's largest construction-equipment manufacturer
# PFE: Pfizer Inc. - Multinational pharmaceutical and biotechnology corporation
# EXC: Exelon - An American Fortune 100 energy company 
# DE: Deere & Company (John Deere) - Manufactures agricultural machinery and heavy equipment
# JNJ: Johnson & Johnson - A multinational corporation that develops medical devices and pharmaceuticalsclose_price_df = pd.read_csv('stock_prices.csv')
close_price_df# The objective of this code cell is to calculate the percentage daily return
# We will perform this calculation on all stocks except for the first column which is "Date"
daily_returns_df = close_price_df.iloc[:, 1:].pct_change() * 100
daily_returns_df.replace(np.nan, 0, inplace = True)
daily_returns_df# Insert the date column at the start of the Pandas DataFrame (@ index = 0)
daily_returns_df.insert(0, "Date", close_price_df['Date'])
daily_returns_df# Plot closing prices using plotly Express. Note that we used the same pre-defined function "plot_financial_data"
plot_financial_data(close_price_df, 'Adjusted Closing Prices [$]')# Plot the stocks daily returns
plot_financial_data(daily_returns_df, 'Percentage Daily Returns [%]')# Plot histograms for stocks daily returns using plotly express
# Compare META to JNJ daily returns histograms
fig = px.histogram(daily_returns_df.drop(columns = ['Date']))
fig.update_layout({'plot_bgcolor': "white"})# Plot a heatmap showing the correlations between daily returns
# Strong positive correlations between Catterpillar and John Deere - both into heavy equipment and machinery
# META and Google - both into Tech and Cloud Computing
plt.figure(figsize = (10, 8))
sns.heatmap(daily_returns_df.drop(columns = ['Date']).corr(), annot = True);# Plot the Pairplot between stocks daily returns
sns.pairplot(daily_returns_df);# Function to scale stock prices based on their initial starting price
# The objective of this function is to set all prices to start at a value of 1 
def price_scaling(raw_prices_df):scaled_prices_df = raw_prices_df.copy()for i in raw_prices_df.columns[1:]:scaled_prices_df[i] = raw_prices_df[i]/raw_prices_df[i][0]return scaled_prices_dfprice_scaling(close_price_df)

8. 定义一个生成随机投资组合权重的函数

在这里插入图片描述

# Let's create an array that holds random portfolio weights
# Note that portfolio weights must add up to 1 
import randomdef generate_portfolio_weights(n):weights = []for i in range(n):weights.append(random.random())# let's make the sum of all weights add up to 1weights = weights/np.sum(weights)return weights# Call the function (Run this cell multiple times to generate different outputs)
weights = generate_portfolio_weights(4)
print(weights)

9. 进行资产配置并计算投资组合的日价值/回报率

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

# Let's define the "weights" list similar to the slides
weights = [0.032266, 0.094461, 0.117917, 0.132624, 0.145942, 0.128299, 0.10009, 0.007403, 0.088581, 0.152417]
weights# Let's display "close_price_df" Pandas DataFrame
close_price_df# Scale stock prices using the "price_scaling" function that we defined earlier (make all stock values start at 1)
portfolio_df = close_price_df.copy()
scaled_df = price_scaling(portfolio_df)
scaled_df# Use enumerate() method to obtain the stock names along with a counter "i" (0, 1, 2, 3,..etc.)
# This counter "i" will be used as an index to access elements in the "weights" list
initial_investment = 1000000
for i, stock in enumerate(scaled_df.columns[1:]):portfolio_df[stock] = weights[i] * scaled_df[stock]  * initial_investment
portfolio_df.round(1)# Assume that we have $1,000,000 that we would like to invest in one or more of the selected stocks
# Let's create a function that receives the following arguments: # (1) Stocks closing prices# (2) Random weights # (3) Initial investment amount
# The function will return a DataFrame that contains the following:# (1) Daily value (position) of each individual stock over the specified time period# (2) Total daily value of the portfolio # (3) Percentage daily return def asset_allocation(df, weights, initial_investment):portfolio_df = df.copy()# Scale stock prices using the "price_scaling" function that we defined earlier (Make them all start at 1)scaled_df = price_scaling(df)for i, stock in enumerate(scaled_df.columns[1:]):portfolio_df[stock] = scaled_df[stock] * weights[i] * initial_investment# Sum up all values and place the result in a new column titled "portfolio value [$]" # Note that we excluded the date column from this calculationportfolio_df['Portfolio Value [$]'] = portfolio_df[portfolio_df != 'Date'].sum(axis = 1, numeric_only = True)# Calculate the portfolio percentage daily return and replace NaNs with zerosportfolio_df['Portfolio Daily Return [%]'] = portfolio_df['Portfolio Value [$]'].pct_change(1) * 100 portfolio_df.replace(np.nan, 0, inplace = True)return portfolio_df# Now let's put this code in a function and generate random weights
# Let's obtain the number of stocks under consideration (note that we ignored the "Date" column) 
n = len(close_price_df.columns)-1# Let's generate random weights 
print('Number of stocks under consideration = {}'.format(n))
weights = generate_portfolio_weights(n).round(6)
print('Portfolio weights = {}'.format(weights))# Let's test out the "asset_allocation" function
portfolio_df = asset_allocation(close_price_df, weights, 1000000)
portfolio_df.round(2)# Plot the portfolio percentage daily return
plot_financial_data(portfolio_df[['Date', 'Portfolio Daily Return [%]']], 'Portfolio Percentage Daily Return [%]')# Plot each stock position in our portfolio over time
# This graph shows how our initial investment in each individual stock grows over time
plot_financial_data(portfolio_df.drop(['Portfolio Value [$]', 'Portfolio Daily Return [%]'], axis = 1), 'Portfolio positions [$]')# Plot the total daily value of the portfolio (sum of all positions)
plot_financial_data(portfolio_df[['Date', 'Portfolio Value [$]']], 'Total Portfolio Value [$]')

10. 定义“模拟”函数,该函数执行资产配置并计算关键的投资组合指标

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

# Let's define the simulation engine function 
# The function receives: # (1) portfolio weights# (2) initial investment amount
# The function performs asset allocation and calculates portfolio statistical metrics including Sharpe ratio
# The function returns: # (1) Expected portfolio return # (2) Expected volatility # (3) Sharpe ratio # (4) Return on investment # (5) Final portfolio value in dollarsdef simulation_engine(weights, initial_investment):# Perform asset allocation using the random weights (sent as arguments to the function)portfolio_df = asset_allocation(close_price_df, weights, initial_investment)# Calculate the return on the investment # Return on investment is calculated using the last final value of the portfolio compared to its initial valuereturn_on_investment = ((portfolio_df['Portfolio Value [$]'][-1:] - portfolio_df['Portfolio Value [$]'][0])/ portfolio_df['Portfolio Value [$]'][0]) * 100# Daily change of every stock in the portfolio (Note that we dropped the date, portfolio daily worth and daily % returns) portfolio_daily_return_df = portfolio_df.drop(columns = ['Date', 'Portfolio Value [$]', 'Portfolio Daily Return [%]'])portfolio_daily_return_df = portfolio_daily_return_df.pct_change(1) # Portfolio Expected Return formulaexpected_portfolio_return = np.sum(weights * portfolio_daily_return_df.mean() ) * 252# Portfolio volatility (risk) formula# The risk of an asset is measured using the standard deviation which indicates the dispertion away from the mean# The risk of a portfolio is not a simple sum of the risks of the individual assets within the portfolio# Portfolio risk must consider correlations between assets within the portfolio which is indicated by the covariance # The covariance determines the relationship between the movements of two random variables# When two stocks move together, they have a positive covariance when they move inversely, the have a negative covariance covariance = portfolio_daily_return_df.cov() * 252 expected_volatility = np.sqrt(np.dot(weights.T, np.dot(covariance, weights)))# Check out the chart for the 10-years U.S. treasury at https://ycharts.com/indicators/10_year_treasury_raterf = 0.03 # Try to set the risk free rate of return to 1% (assumption)# Calculate Sharpe ratiosharpe_ratio = (expected_portfolio_return - rf)/expected_volatility return expected_portfolio_return, expected_volatility, sharpe_ratio, portfolio_df['Portfolio Value [$]'][-1:].values[0], return_on_investment.values[0]# Let's test out the "simulation_engine" function and print out statistical metrics
# Define the initial investment amount
initial_investment = 1000000
portfolio_metrics = simulation_engine(weights, initial_investment)print('Expected Portfolio Annual Return = {:.2f}%'.format(portfolio_metrics[0] * 100))
print('Portfolio Standard Deviation (Volatility) = {:.2f}%'.format(portfolio_metrics[1] * 100))
print('Sharpe Ratio = {:.2f}'.format(portfolio_metrics[2]))
print('Portfolio Final Value = ${:.2f}'.format(portfolio_metrics[3]))
print('Return on Investment = {:.2f}%'.format(portfolio_metrics[4]))

11. 运行蒙特卡罗模拟

在这里插入图片描述

# Set the number of simulation runs
sim_runs = 10000
initial_investment = 1000000# Placeholder to store all weights
weights_runs = np.zeros((sim_runs, n))# Placeholder to store all Sharpe ratios
sharpe_ratio_runs = np.zeros(sim_runs)# Placeholder to store all expected returns
expected_portfolio_returns_runs = np.zeros(sim_runs)# Placeholder to store all volatility values
volatility_runs = np.zeros(sim_runs)# Placeholder to store all returns on investment
return_on_investment_runs = np.zeros(sim_runs)# Placeholder to store all final portfolio values
final_value_runs = np.zeros(sim_runs)for i in range(sim_runs):# Generate random weights weights = generate_portfolio_weights(n)# Store the weightsweights_runs[i,:] = weights# Call "simulation_engine" function and store Sharpe ratio, return and volatility# Note that asset allocation is performed using the "asset_allocation" function  expected_portfolio_returns_runs[i], volatility_runs[i], sharpe_ratio_runs[i], final_value_runs[i], return_on_investment_runs[i] = simulation_engine(weights, initial_investment)print("Simulation Run = {}".format(i))   print("Weights = {}, Final Value = ${:.2f}, Sharpe Ratio = {:.2f}".format(weights_runs[i].round(3), final_value_runs[i], sharpe_ratio_runs[i]))   print('\n')

12. 执行投资组合优化

在这里插入图片描述

# List all Sharpe ratios generated from the simulation
sharpe_ratio_runs# Return the index of the maximum Sharpe ratio (Best simulation run) 
sharpe_ratio_runs.argmax()# Return the maximum Sharpe ratio value
sharpe_ratio_runs.max()weights_runs# Obtain the portfolio weights that correspond to the maximum Sharpe ratio (Golden set of weights!)
weights_runs[sharpe_ratio_runs.argmax(), :]# Return Sharpe ratio, volatility corresponding to the best weights allocation (maximum Sharpe ratio)
optimal_portfolio_return, optimal_volatility, optimal_sharpe_ratio, highest_final_value, optimal_return_on_investment = simulation_engine(weights_runs[sharpe_ratio_runs.argmax(), :], initial_investment)print('Best Portfolio Metrics Based on {} Monte Carlo Simulation Runs:'.format(sim_runs))
print('  - Portfolio Expected Annual Return = {:.02f}%'.format(optimal_portfolio_return * 100))
print('  - Portfolio Standard Deviation (Volatility) = {:.02f}%'.format(optimal_volatility * 100))
print('  - Sharpe Ratio = {:.02f}'.format(optimal_sharpe_ratio))
print('  - Final Value = ${:.02f}'.format(highest_final_value))
print('  - Return on Investment = {:.02f}%'.format(optimal_return_on_investment))# Create a DataFrame that contains volatility, return, and Sharpe ratio for all simualation runs
sim_out_df = pd.DataFrame({'Volatility': volatility_runs.tolist(), 'Portfolio_Return': expected_portfolio_returns_runs.tolist(), 'Sharpe_Ratio': sharpe_ratio_runs.tolist() })
sim_out_df# Plot volatility vs. return for all simulation runs
# Highlight the volatility and return that corresponds to the highest Sharpe ratio
import plotly.graph_objects as go
fig = px.scatter(sim_out_df, x = 'Volatility', y = 'Portfolio_Return', color = 'Sharpe_Ratio', size = 'Sharpe_Ratio', hover_data = ['Sharpe_Ratio'] )
fig.update_layout({'plot_bgcolor': "white"})
fig.show()# Use this code if Sharpe ratio is negative
# fig = px.scatter(sim_out_df, x = 'Volatility', y = 'Portfolio_Return', color = 'Sharpe_Ratio', hover_data = ['Sharpe_Ratio'] )# Let's highlight the point with the highest Sharpe ratio
fig = px.scatter(sim_out_df, x = 'Volatility', y = 'Portfolio_Return', color = 'Sharpe_Ratio', size = 'Sharpe_Ratio', hover_data = ['Sharpe_Ratio'] )
fig.add_trace(go.Scatter(x = [optimal_volatility], y = [optimal_portfolio_return], mode = 'markers', name = 'Optimal Point', marker = dict(size=[40], color = 'red')))
fig.update_layout(coloraxis_colorbar = dict(y = 0.7, dtick = 5))
fig.update_layout({'plot_bgcolor': "white"})
fig.show()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/48718.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

单例模式_Golang

目录 一、单例模式 1.1 基本概念 1.2 使用场景 二、Golang实现 2.1 懒汉模式&#xff08;Lazy Loading&#xff09; 一、单例模式 1.1 基本概念 一个类只能生成一个实例&#xff0c;且该类能自行创建这个实例的一种模式,这个定义个人感觉可以拆的通俗一些,在项目的生命周…

电子电器架构 - SOA架构软件平台

电子电器架构 - SOA架构软件平台 我是穿拖鞋的汉子,魔都中坚持长期主义的汽车电子工程师。 老规矩,分享一段喜欢的文字,避免自己成为高知识低文化的工程师: 屏蔽力是信息过载时代一个人的特殊竞争力,任何消耗你的人和事,多看一眼都是你的不对。非必要不费力证明自己,无…

Spring通过工厂方法进行配置

在Spring的世界中&#xff0c; 我们通常会利用 xml配置文件 或者 annotation注解方式来配置bean实例&#xff01; 在第一种利用 xml配置文件 方式中&#xff0c; 还包括如下三小类 反射模式&#xff08;我们前面的所有配置都是这种模式&#xff09;工厂方法模式Factory Bean模…

【Spark官方文档部分翻译】RDD编程指南(RDD Programming Guide)

写在前面 内容如何选择 本翻译只翻译本人认为精华的部分&#xff0c;本人认为的Spark的一些核心理念&#xff0c;编程思想。一些特别基础的操作包括但不限于搭建环境就不在此赘述了。 配套版本 本系列基于Spark 3.3.1&#xff0c;Scala 2.12.10&#xff0c;进行翻译总结 原…

Linux+InternStudio 关卡(test)

任务地址&#xff1a; https://github.com/InternLM/Tutorial/blob/camp3/docs/L0/Linux/task.md 文档 https://github.com/InternLM/Tutorial/blob/camp3/docs/L0/Linux/readme.md 任务 ssh连接 端口映射 gradio页面 笔记&#xff1a; 1.端口映射阶段&#xff1a;输入密…

【BUG】已解决:ModuleNotFoundError: No module named ‘sklearn‘

已解决&#xff1a;ModuleNotFoundError: No module named ‘sklearn‘ 目录 已解决&#xff1a;ModuleNotFoundError: No module named ‘sklearn‘ 【常见模块错误】 【解决方案】 欢迎来到英杰社区https://bbs.csdn.net/topics/617804998 欢迎来到我的主页&#xff0c;我是…

视频点播项目

文章目录 视频点播技术栈与项目环境JsonCppMariaDBhttplib 工具类设计文件类Json类 数据管理模块视频信息管理&#xff08;数据表设计&#xff09;数据管理类设计 网络通信接口设计业务处理模块设计前端界面主页面播放页面 项目总结项目回顾项目结构关键技术点总结 视频点播 允…

亚马逊自发货erp,虚拟自动化发货功能以及1688订单采购

亚马逊自发货erp自动化功能&#xff0c;自动同步订单&#xff0c;1688订单同步。 大家好&#xff0c;今天分享一个非常实用并且节省时间的功能&#xff1a;自动化发货以及1688同步订单。 首先来看下自动化发货功能怎么操作。 →要在商品信息里面添加商品信息&#xff0c;上传…

风灵月影修改器未检测到游戏怎么回事?解决方法分享

当风灵月影修改器未检测到游戏进程时&#xff0c;可能是由以下几个原因导致的&#xff1a; 1. 游戏未启动&#xff1a; 最直接的原因就是游戏本身没有被启动&#xff0c;或者游戏还未完全加载完成&#xff0c;处于启动过程中的某个阶段&#xff0c;此时修改器可能检测不到游戏…

【总结】逻辑运算在Z3中运用+CTF习题

国际赛IrisCTF在前几天举办&#xff0c;遇到了一道有意思的题目&#xff0c;特来总结。 题目 附件如下&#xff1a;&#x1f4ce;babyrevjohnson.tar 解题过程 关键main函数分析如下&#xff1a; int __fastcall main(int argc, const char **argv, const char**envp){int v4…

关于adcoder和codeforce 如何安装翻译插件

首先在扩展当中下载插件篡改猴 其次&#xff0c;点击获取新的脚本 最后搜索 atcoder better 和 codeforce better 安装即可

【Spring Boot】网页五子棋项目实现,手把手带你全盘解析(长达两万3千字的干货,坐好了,要发车了......)

目录 网页五子棋项目一、项目核心流程二、 登录模块2.1 前端输入用户信息2.2 后端进行数据库查询用户信息 三、 游戏大厅模块3.1 前端通过Ajax请求用户数据&#xff0c;后端从Session中拿取并从数据库中查询后返回3.2 前后端建立WebSocket连接&#xff0c;并进行判断&#xff0…

如何处理 PostgreSQL 中死锁的情况?

&#x1f345;关注博主&#x1f397;️ 带你畅游技术世界&#xff0c;不错过每一次成长机会&#xff01;&#x1f4da;领书&#xff1a;PostgreSQL 入门到精通.pdf 文章目录 如何处理 PostgreSQL 中死锁的情况&#xff1f;一、认识死锁二、死锁的症状三、死锁的检测四、预防死锁…

【MySQL】:想学好数据库,不知道这些还想咋学

客户端—服务器 客户端是一个“客户端—服务器”结构的程序 C&#xff08;client&#xff09;—S&#xff08;server&#xff09; 客户端和服务器是两个独立的程序&#xff0c;这两个程序之间通过“网络”进行通信&#xff08;相当于是两种角色&#xff09; 客户端 主动发起网…

Java语言程序设计——篇六(1)

字符串 概述创建String类对象     字符串基本操作实战演练 字符串查找字符串转换为数组字符串比较实战演练 字符串的拆分与组合 概述 字符串 用一对双引号“”括起来的字符序列。Java语言中&#xff0c;字符串常量或变量均用类实现。 字符串有两大类&#xff1a; 1&…

设计模式学习[2]---策略模式+简单工厂回顾

文章目录 前言1.简单工厂模式回顾2.策略模式3.策略模式简单工厂的结合总结 前言 上一篇讲到简单工厂模式。 在我的理解中工厂的存在就是&#xff0c;为了实例化对象。根据不同条件实例化不同的对象的作用。 这篇博客写的策略模式&#xff0c;可以说是把这个根据不同情况实例化…

pyinstaller 打包基于PyQt5和PaddleOCR的项目为.exe

简介&#xff1a; 最近做了一个小项目&#xff0c;是基于PyQt5和PaddleOCR的。需要将其打包为.exe&#xff0c;然后打包过程中遇到了很多问题&#xff0c;也看了很多教程&#xff0c;方法千奇百怪的&#xff0c;最后也是一步一步给试出来了。记录一下&#xff0c;防止以后忘记…

华为路由器SSH登录实验

概念 SSH全称安全外壳&#xff08;Secure Shell&#xff09;协议&#xff0c;这个协议的目的就是为了取代缺乏机密性保障的远程管理协议&#xff0c;SSH基于TCP协议的加密通道&#xff0c;让客户端使用服务器的RSA公钥来验证SSHv2服务器的身份。 创建密钥对 在充当SSH服务器的…

C语言随机数的生成相关案例

随机数的方式&#xff1a; 1、设置种子&#xff1a;srand(初始值) 2、获取随机数&#xff1a;rand(); 引导案例&#xff1a; 通过for循环简单生成10个随机数 #include<stdio.h> #include<stdlib.h> //添加包含随机数的库函数 int main() {srand(1); …

嵌入式人工智能(15-基于树莓派4B的电机控制-直流电机TB6612)

电机是传动以及控制系统的重要组成部分&#xff0c;现在的电机已从过去简单的传动向复杂的控制转移&#xff0c;尤其是对电机的速度、位置、转矩的精确控制&#xff0c;本系列将介绍如何使用树莓派驱动并控制3种最为常见的控制电机&#xff1a;直流电机&#xff08;风扇&#x…